text,length,is_long_context,metric_val,label_metric "TYPES: BEGIN OF t_input, row TYPE string, END OF t_input. * Input declaration DATA: lv_input TYPE TABLE OF t_input, wa_input LIKE LINE OF lv_input. * Assign with the puzzle input. lv_input = VALUE #( ( row = 'acc +15' ) ( row = 'jmp +461' ) ( row = 'acc +6' ) ( row = 'nop +445' ) ( row = 'jmp +324' ) ( row = 'jmp +253' ) ( row = 'acc -4' ) ( row = 'acc +22' ) ( row = 'acc +11' ) ( row = 'jmp +471' ) ( row = 'jmp +145' ) ( row = 'acc +19' ) ( row = 'jmp -7' ) ( row = 'jmp +431' ) ( row = 'nop +66' ) ( row = 'acc +48' ) ( row = 'jmp +409' ) ( row = 'jmp +514' ) ( row = 'jmp +1' ) ( row = 'acc +32' ) ( row = 'jmp +552' ) ( row = 'acc +21' ) ( row = 'jmp +317' ) ( row = 'nop +488' ) ( row = 'jmp +500' ) ( row = 'jmp +214' ) ( row = 'acc +41' ) ( row = 'jmp +17' ) ( row = 'acc +19' ) ( row = 'jmp +1' ) ( row = 'acc +28' ) ( row = 'jmp +74' ) ( row = 'acc +37' ) ( row = 'acc +46' ) ( row = 'acc -10' ) ( row = 'jmp +455' ) ( row = 'acc +33' ) ( row = 'jmp +585' ) ( row = 'acc -13' ) ( row = 'acc +18' ) ( row = 'jmp +19' ) ( row = 'jmp +601' ) ( row = 'acc +30' ) ( row = 'jmp +272' ) ( row = 'acc +18' ) ( row = 'acc +50' ) ( row = 'acc +1' ) ( row = 'acc +29' ) ( row = 'jmp +50' ) ( row = 'nop +573' ) ( row = 'jmp +562' ) ( row = 'nop +274' ) ( row = 'jmp +1' ) ( row = 'acc +6' ) ( row = 'jmp +1' ) ( row = 'jmp +64' ) ( row = 'jmp +1' ) ( row = 'acc +37' ) ( row = 'jmp +161' ) ( row = 'nop +549' ) ( row = 'acc +21' ) ( row = 'jmp +1' ) ( row = 'nop +325' ) ( row = 'jmp +331' ) ( row = 'acc +0' ) ( row = 'acc +25' ) ( row = 'jmp +431' ) ( row = 'nop +349' ) ( row = 'jmp +45' ) ( row = 'acc +37' ) ( row = 'acc +9' ) ( row = 'jmp +354' ) ( row = 'jmp +132' ) ( row = 'jmp +307' ) ( row = 'jmp +1' ) ( row = 'nop +465' ) ( row = 'jmp +386' ) ( row = 'acc +13' ) ( row = 'acc +20' ) ( row = 'jmp -20' ) ( row = 'acc -15' ) ( row = 'nop +158' ) ( row = 'jmp +415' ) ( row = 'acc +33' ) ( row = 'acc +40' ) ( row = 'acc +38' ) ( row = 'acc -2' ) ( row = 'jmp +81' ) ( row = 'acc +44' ) ( row = 'acc +9' ) ( row = 'acc +15' ) ( row = 'nop +139' ) ( row = 'jmp -18' ) ( row = 'nop +187' ) ( row = 'acc +47' ) ( row = 'acc +45' ) ( row = 'acc +40' ) ( row = 'jmp +456' ) ( row = 'acc +48' ) ( row = 'jmp +1' ) ( row = 'jmp -75' ) ( row = 'acc +11' ) ( row = 'acc -13' ) ( row = 'nop +222' ) ( row = 'jmp +202' ) ( row = 'acc +38' ) ( row = 'acc +31' ) ( row = 'acc -11' ) ( row = 'acc +1' ) ( row = 'jmp +431' ) ( row = 'acc +37' ) ( row = 'nop +195' ) ( row = 'jmp +118' ) ( row = 'acc -8' ) ( row = 'jmp +1' ) ( row = 'jmp +154' ) ( row = 'acc +7' ) ( row = 'acc +13' ) ( row = 'jmp +43' ) ( row = 'jmp +507' ) ( row = 'acc -2' ) ( row = 'acc +11' ) ( row = 'jmp +465' ) ( row = 'acc -12' ) ( row = 'nop -103' ) ( row = 'jmp +50' ) ( row = 'acc +2' ) ( row = 'nop +4' ) ( row = 'acc +46' ) ( row = 'acc +17' ) ( row = 'jmp +100' ) ( row = 'nop +149' ) ( row = 'jmp +397' ) ( row = 'nop -28' ) ( row = 'jmp +236' ) ( row = 'acc +0' ) ( row = 'nop +465' ) ( row = 'acc +19' ) ( row = 'acc -5' ) ( row = 'jmp +91' ) ( row = 'jmp +118' ) ( row = 'acc -3' ) ( row = 'nop +176' ) ( row = 'acc +8' ) ( row = 'jmp +24' ) ( row = 'jmp +235' ) ( row = 'acc -7' ) ( row = 'nop -1' ) ( row = 'nop +347' ) ( row = 'acc +33' ) ( row = 'jmp +165' ) ( row = 'acc -18' ) ( row = 'acc +9' ) ( row = 'acc -8' ) ( row = 'jmp +179' ) ( row = 'acc -3' ) ( row = 'acc +40' ) ( row = 'jmp +1' ) ( row = 'acc +5' ) ( row = 'jmp +475' ) ( row = 'jmp +70' ) ( row = 'acc +50' ) ( row = 'acc -1' ) ( row = 'acc -11' ) ( row = 'acc +43' ) ( row = 'jmp +283' ) ( row = 'nop +114' ) ( row = 'jmp +161' ) ( row = 'acc -19' ) ( row = 'acc +50' ) ( row = 'acc +47' ) ( row = 'acc +49' ) ( row = 'jmp +381' ) ( row = 'jmp +1' ) ( row = 'jmp -94' ) ( row = 'nop +373' ) ( row = 'acc +26' ) ( row = 'acc +7' ) ( row = 'jmp +41' ) ( row = 'acc -7' ) ( row = 'jmp +264' ) ( row = 'nop -40' ) ( row = 'acc +23' ) ( row = 'jmp -60' ) ( row = 'acc +15' ) ( row = 'acc +19' ) ( row = 'acc +39' ) ( row = 'acc -16' ) ( row = 'jmp +283' ) ( row = 'acc +4' ) ( row = 'jmp +258' ) ( row = 'acc +0' ) ( row = 'acc +38' ) ( row = 'acc -6' ) ( row = 'jmp +32' ) ( row = 'acc +33' ) ( row = 'jmp +1' ) ( row = 'acc -4' ) ( row = 'acc +17' ) ( row = 'jmp +149' ) ( row = 'acc -17' ) ( row = 'acc +39' ) ( row = 'nop +75' ) ( row = 'jmp -136' ) ( row = 'acc +6' ) ( row = 'acc +10' ) ( row = 'jmp +1' ) ( row = 'acc +9' ) ( row = 'jmp +390' ) ( row = 'jmp +363' ) ( row = 'acc +32' ) ( row = 'jmp +95' ) ( row = 'jmp -71' ) ( row = 'acc +12' ) ( row = 'jmp +86' ) ( row = 'acc +49' ) ( row = 'acc +2' ) ( row = 'acc +0' ) ( row = 'jmp +139' ) ( row = 'nop +363' ) ( row = 'acc +21' ) ( row = 'jmp +366' ) ( row = 'jmp +1' ) ( row = 'acc +16' ) ( row = 'acc -13' ) ( row = 'jmp +55' ) ( row = 'jmp -159' ) ( row = 'acc +46' ) ( row = 'acc +50' ) ( row = 'jmp +266' ) ( row = 'acc +2' ) ( row = 'jmp -180' ) ( row = 'jmp -181' ) ( row = 'acc +41' ) ( row = 'acc -3' ) ( row = 'nop -176' ) ( row = 'jmp +121' ) ( row = 'acc +23' ) ( row = 'jmp +281' ) ( row = 'acc +5' ) ( row = 'acc +14' ) ( row = 'acc -8' ) ( row = 'jmp +128' ) ( row = 'jmp +281' ) ( row = 'nop +81' ) ( row = 'jmp +1' ) ( row = 'acc +36' ) ( row = 'acc +34' ) ( row = 'jmp -176' ) ( row = 'acc +8' ) ( row = 'jmp +309' ) ( row = 'acc +11' ) ( row = 'nop -77' ) ( row = 'jmp -40' ) ( row = 'acc +0' ) ( row = 'acc +8' ) ( row = 'acc +14' ) ( row = 'jmp +296' ) ( row = 'nop +197' ) ( row = 'nop -124' ) ( row = 'acc +38' ) ( row = 'acc +9' ) ( row = 'jmp +310' ) ( row = 'jmp -183' ) ( row = 'jmp +353' ) ( row = 'acc +28' ) ( row = 'acc -18' ) ( row = 'nop +120' ) ( row = 'jmp -217' ) ( row = 'acc +49' ) ( row = 'acc +38' ) ( row = 'jmp -243' ) ( row = 'nop -68' ) ( row = 'acc +9' ) ( row = 'acc +15' ) ( row = 'nop +43' ) ( row = 'jmp -46' ) ( row = 'acc -4' ) ( row = 'jmp +262' ) ( row = 'jmp +176' ) ( row = 'nop -139' ) ( row = 'acc +38' ) ( row = 'acc +35' ) ( row = 'acc -8' ) ( row = 'jmp -225' ) ( row = 'acc +37' ) ( row = 'acc +49' ) ( row = 'acc +42' ) ( row = 'nop +278' ) ( row = 'jmp +264' ) ( row = 'acc -11' ) ( row = 'nop +291' ) ( row = 'acc +21' ) ( row = 'nop -221' ) ( row = 'jmp +80' ) ( row = 'acc +15' ) ( row = 'acc +13' ) ( row = 'acc +2' ) ( row = 'nop -40' ) ( row = 'jmp +309' ) ( row = 'acc -18' ) ( row = 'acc -5' ) ( row = 'acc +24' ) ( row = 'jmp -70' ) ( row = 'acc +12' ) ( row = 'jmp -261' ) ( row = 'acc +4' ) ( row = 'acc -2' ) ( row = 'acc +3' ) ( row = 'jmp +1' ) ( row = 'jmp +302' ) ( row = 'acc -7' ) ( row = 'jmp +1' ) ( row = 'acc +39' ) ( row = 'jmp +73' ) ( row = 'jmp +18' ) ( row = 'acc +3' ) ( row = 'jmp +277' ) ( row = 'acc +4' ) ( row = 'nop +125' ) ( row = 'nop -284' ) ( row = 'acc +41' ) ( row = 'jmp -312' ) ( row = 'acc +13' ) ( row = 'jmp -183' ) ( row = 'nop -35' ) ( row = 'jmp -137' ) ( row = 'jmp -76' ) ( row = 'acc +1' ) ( row = 'acc +31' ) ( row = 'acc +39' ) ( row = 'jmp +56' ) ( row = 'jmp +290' ) ( row = 'jmp +1' ) ( row = 'acc +12' ) ( row = 'nop +71' ) ( row = 'acc +43' ) ( row = 'jmp -296' ) ( row = 'jmp +68' ) ( row = 'acc -14' ) ( row = 'acc +35' ) ( row = 'nop -290' ) ( row = 'jmp -24' ) ( row = 'acc +39' ) ( row = 'acc -8' ) ( row = 'nop +110' ) ( row = 'jmp +1' ) ( row = 'jmp +78' ) ( row = 'acc +11' ) ( row = 'acc +9' ) ( row = 'acc -11' ) ( row = 'acc +50' ) ( row = 'jmp +167' ) ( row = 'acc +50' ) ( row = 'acc +19' ) ( row = 'acc +0' ) ( row = 'jmp -221' ) ( row = 'acc -4' ) ( row = 'acc -6' ) ( row = 'nop +11' ) ( row = 'acc +49' ) ( row = 'jmp -348' ) ( row = 'nop +197' ) ( row = 'acc +6' ) ( row = 'jmp -196' ) ( row = 'nop -155' ) ( row = 'jmp -76' ) ( row = 'acc +50' ) ( row = 'acc -8' ) ( row = 'jmp -89' ) ( row = 'acc +9' ) ( row = 'jmp +255' ) ( row = 'acc +25' ) ( row = 'jmp +199' ) ( row = 'jmp -35' ) ( row = 'acc +46' ) ( row = 'acc +25' ) ( row = 'jmp +1' ) ( row = 'acc +32' ) ( row = 'jmp -31' ) ( row = 'acc -3' ) ( row = 'acc -5' ) ( row = 'jmp +73' ) ( row = 'acc +7' ) ( row = 'acc +22' ) ( row = 'acc -15' ) ( row = 'jmp +145' ) ( row = 'nop -97' ) ( row = 'acc +47' ) ( row = 'acc +22' ) ( row = 'jmp -110' ) ( row = 'acc +44' ) ( row = 'acc +4' ) ( row = 'jmp -383' ) ( row = 'acc +34' ) ( row = 'jmp +1' ) ( row = 'jmp +16' ) ( row = 'nop -128' ) ( row = 'acc +43' ) ( row = 'jmp -34' ) ( row = 'nop +95' ) ( row = 'acc +3' ) ( row = 'jmp +4' ) ( row = 'acc +13' ) ( row = 'acc -2' ) ( row = 'jmp -90' ) ( row = 'acc +39' ) ( row = 'jmp +187' ) ( row = 'acc +24' ) ( row = 'acc +23' ) ( row = 'acc +42' ) ( row = 'jmp -11' ) ( row = 'jmp -281' ) ( row = 'jmp +1' ) ( row = 'acc +25' ) ( row = 'jmp -157' ) ( row = 'acc +3' ) ( row = 'acc -3' ) ( row = 'nop -24' ) ( row = 'acc -13' ) ( row = 'jmp -46' ) ( row = 'acc +10' ) ( row = 'acc +16' ) ( row = 'nop -7' ) ( row = 'jmp -289' ) ( row = 'nop -408' ) ( row = 'acc -5' ) ( row = 'acc +23' ) ( row = 'nop +91' ) ( row = 'jmp -234' ) ( row = 'acc +0' ) ( row = 'acc +4' ) ( row = 'acc +15' ) ( row = 'acc -15' ) ( row = 'jmp -367' ) ( row = 'acc +32' ) ( row = 'acc -9' ) ( row = 'acc +13' ) ( row = 'jmp -194' ) ( row = 'acc +38' ) ( row = 'nop +126' ) ( row = 'acc +1' ) ( row = 'nop +124' ) ( row = 'jmp -275' ) ( row = 'acc -14' ) ( row = 'acc +26' ) ( row = 'jmp +55' ) ( row = 'jmp -388' ) ( row = 'acc +3' ) ( row = 'acc +8' ) ( row = 'acc +31' ) ( row = 'acc +34' ) ( row = 'jmp -372' ) ( row = 'acc +45' ) ( row = 'jmp -115' ) ( row = 'acc -6' ) ( row = 'acc +47' ) ( row = 'acc -17' ) ( row = 'acc +29' ) ( row = 'jmp -438' ) ( row = 'acc +33' ) ( row = 'jmp -113' ) ( row = 'jmp -301' ) ( row = 'jmp -396' ) ( row = 'acc +46' ) ( row = 'jmp -284' ) ( row = 'acc -14' ) ( row = 'acc +11' ) ( row = 'acc +20' ) ( row = 'nop -356' ) ( row = 'jmp -445' ) ( row = 'acc +20' ) ( row = 'acc -6' ) ( row = 'acc -8' ) ( row = 'jmp +134' ) ( row = 'nop +54' ) ( row = 'acc +33' ) ( row = 'jmp +1' ) ( row = 'acc +3' ) ( row = 'jmp +108' ) ( row = 'acc +14' ) ( row = 'nop +67' ) ( row = 'nop -66' ) ( row = 'acc +45' ) ( row = 'jmp +117' ) ( row = 'acc +45' ) ( row = 'acc +42' ) ( row = 'acc +25' ) ( row = 'acc -18' ) ( row = 'jmp -354' ) ( row = 'acc +8' ) ( row = 'jmp -240' ) ( row = 'nop -373' ) ( row = 'acc -8' ) ( row = 'jmp +72' ) ( row = 'jmp -95' ) ( row = 'jmp -350' ) ( row = 'jmp -62' ) ( row = 'acc +6' ) ( row = 'acc -18' ) ( row = 'jmp +108' ) ( row = 'acc +14' ) ( row = 'acc +11' ) ( row = 'nop -164' ) ( row = 'acc +4' ) ( row = 'jmp +6' ) ( row = 'acc +24' ) ( row = 'acc +11' ) ( row = 'acc -7' ) ( row = 'acc +27' ) ( row = 'jmp -171' ) ( row = 'acc +23' ) ( row = 'acc +36' ) ( row = 'acc +20' ) ( row = 'acc +42' ) ( row = 'jmp -51' ) ( row = 'acc +28' ) ( row = 'acc +10' ) ( row = 'jmp -218' ) ( row = 'nop +63' ) ( row = 'jmp -294' ) ( row = 'acc -10' ) ( row = 'nop +44' ) ( row = 'jmp +43' ) ( row = 'jmp -444' ) ( row = 'acc +20' ) ( row = 'acc +39' ) ( row = 'acc +29' ) ( row = 'jmp -507' ) ( row = 'jmp -265' ) ( row = 'jmp -471' ) ( row = 'nop +17' ) ( row = 'acc +39' ) ( row = 'acc +4' ) ( row = 'jmp -54' ) ( row = 'acc +1' ) ( row = 'nop -448' ) ( row = 'acc -18' ) ( row = 'acc +3' ) ( row = 'jmp -495' ) ( row = 'acc +17' ) ( row = 'acc +16' ) ( row = 'jmp +6' ) ( row = 'acc +6' ) ( row = 'acc +0' ) ( row = 'jmp +1' ) ( row = 'acc -15' ) ( row = 'jmp -317' ) ( row = 'jmp -77' ) ( row = 'acc +4' ) ( row = 'acc +30' ) ( row = 'acc -3' ) ( row = 'jmp -187' ) ( row = 'acc -11' ) ( row = 'nop -189' ) ( row = 'nop -488' ) ( row = 'jmp -140' ) ( row = 'acc +50' ) ( row = 'jmp -142' ) ( row = 'nop -211' ) ( row = 'jmp -166' ) ( row = 'acc -12' ) ( row = 'acc +7' ) ( row = 'acc +32' ) ( row = 'acc +40' ) ( row = 'jmp -384' ) ( row = 'jmp -186' ) ( row = 'nop -261' ) ( row = 'acc +32' ) ( row = 'acc +19' ) ( row = 'acc +44' ) ( row = 'jmp +16' ) ( row = 'acc +15' ) ( row = 'acc +30' ) ( row = 'nop -476' ) ( row = 'acc +9' ) ( row = 'jmp -299' ) ( row = 'acc -17' ) ( row = 'acc -17' ) ( row = 'acc -4' ) ( row = 'acc +44' ) ( row = 'jmp -133' ) ( row = 'jmp -58' ) ( row = 'acc +21' ) ( row = 'acc +4' ) ( row = 'acc -19' ) ( row = 'jmp -170' ) ( row = 'acc +32' ) ( row = 'acc -3' ) ( row = 'jmp -363' ) ( row = 'acc +48' ) ( row = 'acc +9' ) ( row = 'acc +48' ) ( row = 'jmp +5' ) ( row = 'acc +30' ) ( row = 'acc +40' ) ( row = 'jmp -450' ) ( row = 'jmp -282' ) ( row = 'jmp -388' ) ( row = 'acc +12' ) ( row = 'jmp -361' ) ( row = 'acc -6' ) ( row = 'jmp -237' ) ( row = 'acc +27' ) ( row = 'acc +16' ) ( row = 'acc -19' ) ( row = 'acc -5' ) ( row = 'jmp -145' ) ( row = 'acc +38' ) ( row = 'jmp -565' ) ( row = 'nop -341' ) ( row = 'jmp +11' ) ( row = 'acc +22' ) ( row = 'nop -219' ) ( row = 'jmp -597' ) ( row = 'acc +33' ) ( row = 'jmp -572' ) ( row = 'jmp -292' ) ( row = 'acc +7' ) ( row = 'acc -14' ) ( row = 'acc +33' ) ( row = 'jmp -432' ) ( row = 'acc +47' ) ( row = 'jmp -41' ) ( row = 'nop -306' ) ( row = 'jmp -85' ) ( row = 'jmp +1' ) ( row = 'nop -215' ) ( row = 'acc +30' ) ( row = 'acc +9' ) ( row = 'jmp -71' ) ( row = 'acc +42' ) ( row = 'acc +49' ) ( row = 'jmp -553' ) ( row = 'acc +28' ) ( row = 'acc +43' ) ( row = 'jmp +1' ) ( row = 'jmp -147' ) ( row = 'acc +44' ) ( row = 'acc +26' ) ( row = 'nop -176' ) ( row = 'jmp -582' ) ( row = 'acc +7' ) ( row = 'acc -14' ) ( row = 'acc +16' ) ( row = 'acc +34' ) ( row = 'jmp +1' ) ). TYPES: BEGIN OF t_checklist, instruction_index TYPE i, END OF t_checklist. DATA: lv_cur_position TYPE i VALUE 1, lv_accumulator TYPE i VALUE 0, lt_checklist TYPE TABLE OF t_checklist, lv_prefix TYPE string, wa_checklist LIKE LINE OF lt_checklist. DO. READ TABLE lv_input INTO wa_input INDEX lv_cur_position. IF line_exists( lt_checklist[ instruction_index = lv_cur_position ] ). EXIT. ELSE. "" Store the instruction as executed. wa_checklist-instruction_index = lv_cur_position. APPEND wa_checklist TO lt_checklist. ENDIF. SPLIT wa_input-row AT ' ' INTO TABLE DATA(lv_instruction). READ TABLE lv_instruction INTO DATA(lv_operation) INDEX 1. READ TABLE lv_instruction INTO DATA(lv_argument) INDEX 2. CASE lv_operation. WHEN 'jmp'. "" Jump to a position lv_prefix = lv_argument+0(1). REPLACE '+' WITH '' INTO lv_argument. REPLACE '-' WITH '' INTO lv_argument. CONDENSE lv_argument NO-GAPS. CASE lv_prefix. WHEN '+'. lv_cur_position = lv_cur_position + lv_argument. "" Adds the argument number WHEN '-'. lv_cur_position = lv_cur_position - lv_argument. "" Subs the argument number ENDCASE. WHEN 'acc'. "" Add / Sub value to the accumulator and goes to the next line lv_prefix = lv_argument+0(1). REPLACE '+' WITH '' INTO lv_argument. REPLACE '-' WITH '' INTO lv_argument. CONDENSE lv_argument NO-GAPS. CASE lv_prefix. WHEN '+'. lv_accumulator = lv_accumulator + lv_argument. "" Adds the argument number WHEN '-'. lv_accumulator = lv_accumulator - lv_argument. "" Subs the argument number ENDCASE. lv_cur_position = lv_cur_position + 1. WHEN 'nop'. "" No Operation, just go to the next line. lv_cur_position = lv_cur_position + 1. ENDCASE. ENDDO. WRITE: 'Result accumulator: ' && lv_accumulator. ",7064,True,2655.060763865732,median "//// Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the ""License""); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. //// = Layouts Ralph Goers ; Gary Gregory An Appender uses a Layout to format a LogEvent into a form that meets the needs of whatever will be consuming the log event. In Log4j 1.x and Logback Layouts were expected to transform an event into a String. In Log4j 2 Layouts return a byte array. This allows the result of the Layout to be useful in many more types of Appenders. However, this means you need to configure most Layouts with a https://docs.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html[`Charset`] to ensure the byte array contains correct values. The root class for layouts that use a Charset is `org.apache.logging.log4j.core.layout.AbstractStringLayout` where the default is UTF-8. Each layout that extends `AbstractStringLayout` can provide its own default. See each layout below. A custom character encoder was added to Log4j 2.4.1 for the ISO-8859-1 and US-ASCII charsets, to bring some of the performance improvements built-in to Java 8 to Log4j for use on Java 7. For applications that log only ISO-8859-1 characters, specifying this charset will improve performance significantly. [#CSVLayouts] == CSV Layouts As of Log4j 2.11.0, CSV support has moved from the existing module `logj-core` to the new module `log4j-csv`. This layout creates https://en.wikipedia.org/wiki/Comma-separated_values[Comma Separated Value (CSV)] records and requires https://commons.apache.org/proper/commons-csv/[Apache Commons CSV] 1.4. The CSV layout can be used in two ways: First, using `CsvParameterLayout` to log event parameters to create a custom database, usually to a logger and file appender uniquely configured for this purpose. Second, using `CsvLogEventLayout` to log events to create a database, as an alternative to using a full DBMS or using a JDBC driver that supports the CSV format. The `CsvParameterLayout` converts an event's parameters into a CSV record, ignoring the message. To log CSV records, you can use the usual Logger methods `info()`, `debug()`, and so on: [source,java] ---- logger.info(""Ignored"", value1, value2, value3); ---- Which will create the CSV record: .... value1, value2, value3 .... Alternatively, you can use a `ObjectArrayMessage`, which only carries parameters: [source,java] ---- logger.info(new ObjectArrayMessage(value1, value2, value3)); ---- The layouts `CsvParameterLayout` and `CsvLogEventLayout` are configured with the following parameters: .CsvParameterLayout and CsvLogEventLayout [cols=""1m,1,4""] |=== |Parameter Name |Type |Description |format |String |One of the predefined formats: `Default`, `Excel`, `MySQL`, `RFC4180`, `TDF`. See https://commons.apache.org/proper/commons-csv/archives/1.4/apidocs/org/apache/commons/csv/CSVFormat.Predefined.html[CSVFormat.Predefined]. |delimiter |Character |Sets the delimiter of the format to the specified character. |escape |Character |Sets the escape character of the format to the specified character. |quote |Character |Sets the quoteChar of the format to the specified character. |quoteMode |String |Sets the output quote policy of the format to the specified value. One of: `ALL`, `MINIMAL`, `NON_NUMERIC`, `NONE`. |nullString |String |Writes null as the given nullString when writing records. |recordSeparator |String |Sets the record separator of the format to the specified String. |charset |Charset |The output Charset. |header |Sets the header to include when the stream is opened. |Desc. |footer |Sets the footer to include when the stream is closed. |Desc. |=== Logging as a CSV events looks like this: [source,java] ---- logger.debug(""one={}, two={}, three={}"", 1, 2, 3); ---- Produces a CSV record with the following fields: 1. Time Nanos 2. Time Millis 3. Level 4. Thread ID 5. Thread Name 6. Thread Priority 7. Formatted Message 8. Logger FQCN 9. Logger Name 10. Marker 11. Thrown Proxy 12. Source 13. Context Map 14. Context Stack .... 0,1441617184044,DEBUG,main,""one=1, two=2, three=3"",org.apache.logging.log4j.spi.AbstractLogger,,,,org.apache.logging.log4j.core.layout.CsvLogEventLayoutTest.testLayout(CsvLogEventLayoutTest.java:98),{},[] .... Additional link:../runtime-dependencies.html[runtime dependencies] are required for using CSV layouts. [#GELFLayout] == GELF Layout Lays out events in the Graylog Extended Log Format (GELF) 1.1. This layout compresses JSON to GZIP or ZLIB (the `compressionType`) if log event data is larger than 1024 bytes (the `compressionThreshold`). This layout does not implement chunking. Configure as follows to send to a Graylog 2.x server with UDP: [source,xml] ---- ---- Configure as follows to send to a Graylog 2.x server with TCP: [source,xml] ---- ---- .GelfLayout Parameters [cols=""1m,1,4""] |=== |Parameter Name |Type |Description |host |String |The value of the `host` property (optional, defaults to local host name). |compressionType |`GZIP`, `ZLIB` or `OFF` |Compression to use (optional, defaults to `GZIP`) |compressionThreshold |int |Compress if data is larger than this number of bytes (optional, defaults to 1024) |includeStacktrace |boolean |Whether to include full stacktrace of logged Throwables (optional, default to true). If set to false, only the class name and message of the https://docs.oracle.com/javase/6/docs/api/java/lang/Throwable.html[Throwable] will be included. |includeThreadContext |boolean |Whether to include thread context as additional fields (optional, default to true). |includeNullDelimiter |boolean |Whether to include NULL byte as delimiter after each event (optional, default to false). Useful for Graylog GELF TCP input. Cannot be used with compression. |=== To include any custom field in the output, use following syntax: [source,xml] ---- ---- Custom fields are included in the order they are declared. The values support link:lookups.html[lookups]. See also: * The http://docs.graylog.org/en/latest/pages/gelf.html#gelf[GELF specification] [#HTMLLayout] == HTML Layout The HtmlLayout generates an HTML page and adds each LogEvent to a row in a table. .HtmlLayout Parameters [cols=""1m,1,4""] |=== |Parameter Name |Type |Description |charset |String |The character set to use when converting the HTML String to a byte array. The value must be a valid http://docs.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html[Charset]. If not specified, this layout uses UTF-8. |contentType |String |The value to assign to the Content-Type header. The default is ""text/html"". |locationInfo |boolean a|[[HtmlLocationInfo]] If true, the filename and line number will be included in the HTML output. The default value is false. Generating link:#LocationInformation[location information] is an expensive operation and may impact performance. Use with caution. |title |String |A String that will appear as the HTML title. |fontName |String |The `font-family` to use. The default is ""arial,sans-serif"". |fontSize |String |The `font-size` to use. The default is ""small"". |=== [#JSONLayout] == JSON Layout Appends a series of JSON events as strings serialized as bytes. === Complete well-formed JSON vs. fragment JSON If you configure `complete=""true""`, the appender outputs a well-formed JSON document. By default, with `complete=""false""`, you should include the output as an _external file_ in a separate file to form a well-formed JSON document. If `complete=""false""`, the appender does not write the JSON open array character ""["" at the start of the document, ""]"" and the end, nor comma "","" between records. Log event follows this pattern: [source,json] ---- { ""instant"" : { ""epochSecond"" : 1493121664, ""nanoOfSecond"" : 118000000 }, ""thread"" : ""main"", ""level"" : ""INFO"", ""loggerName"" : ""HelloWorld"", ""marker"" : { ""name"" : ""child"", ""parents"" : [ { ""name"" : ""parent"", ""parents"" : [ { ""name"" : ""grandparent"" } ] } ] }, ""message"" : ""Hello, world!"", ""thrown"" : { ""commonElementCount"" : 0, ""message"" : ""error message"", ""name"" : ""java.lang.RuntimeException"", ""extendedStackTrace"" : [ { ""class"" : ""logtest.Main"", ""method"" : ""main"", ""file"" : ""Main.java"", ""line"" : 29, ""exact"" : true, ""location"" : ""classes/"", ""version"" : ""?"" } ] }, ""contextStack"" : [ ""one"", ""two"" ], ""endOfBatch"" : false, ""loggerFqcn"" : ""org.apache.logging.log4j.spi.AbstractLogger"", ""contextMap"" : { ""bar"" : ""BAR"", ""foo"" : ""FOO"" }, ""threadId"" : 1, ""threadPriority"" : 5, ""source"" : { ""class"" : ""logtest.Main"", ""method"" : ""main"", ""file"" : ""Main.java"", ""line"" : 29 } } ---- If `complete=""false""`, the appender does not write the JSON open array character ""["" at the start of the document, ""]"" and the end, nor comma "","" between records. === Pretty vs. compact JSON By default, the JSON layout is not compact (a.k.a. not ""pretty"") with `compact=""false""`, which means the appender uses end-of-line characters and indents lines to format the text. If `compact=""true""`, then no end-of-line or indentation is used. Message content may contain, of course, escaped end-of-lines. .JsonLayout Parameters [cols=""1m,1,4""] |=== |Parameter Name |Type |Description |charset |String |The character set to use when converting to a byte array. The value must be a valid http://docs.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html[Charset]. If not specified, UTF-8 will be used. |compact |boolean |If true, the appender does not use end-of-lines and indentation. Defaults to false. |eventEol |boolean |If true, the appender appends an end-of-line after each record. Defaults to false. Use with eventEol=true and compact=true to get one record per line. |complete |boolean |If true, the appender includes the JSON header and footer, and comma between records. Defaults to false. |properties |boolean |If true, the appender includes the thread context map in the generated JSON. Defaults to false. |propertiesAsList |boolean |If true, the thread context map is included as a list of map entry objects, where each entry has a ""key"" attribute (whose value is the key) and a ""value"" attribute (whose value is the value). Defaults to false, in which case the thread context map is included as a simple map of key-value pairs. |locationInfo |boolean a| If true, the appender includes the location information in the generated JSON. Defaults to false. Generating link:#LocationInformation[location information] is an expensive operation and may impact performance. Use with caution. |includeStacktrace |boolean |If true, include full stacktrace of any logged https://docs.oracle.com/javase/6/docs/api/java/lang/Throwable.html[Throwable] (optional, default to true). |stacktraceAsString |boolean |Whether to format the stacktrace as a string, and not a nested object (optional, defaults to false). |includeNullDelimiter |boolean |Whether to include NULL byte as delimiter after each event (optional, default to false). |objectMessageAsJsonObject |boolean |If true, ObjectMessage is serialized as JSON object to the ""message"" field of the output log. Defaults to false. |=== To include any custom field in the output, use following syntax: [source,xml] ---- ---- Custom fields are always last, in the order they are declared. The values support link:lookups.html[lookups]. Additional link:../runtime-dependencies.html[runtime dependencies] are required for using JsonLayout. [#PatternLayout] == Pattern Layout A flexible layout configurable with pattern string. The goal of this class is to format a LogEvent and return the results. The format of the result depends on the _conversion pattern_. The conversion pattern is closely related to the conversion pattern of the printf function in C. A conversion pattern is composed of literal text and format control expressions called _conversion specifiers_. _Note that any literal text, including *Special Characters*, may be included in the conversion pattern._ Special Characters include *\\t*, *\\n*, *\\r*, *\\f*. Use *\\\\* to insert a single backslash into the output. Each conversion specifier starts with a percent sign (%) and is followed by optional _format modifiers_ and a _conversion character_. The conversion character specifies the type of data, e.g. category, priority, date, thread name. The format modifiers control such things as field width, padding, left and right justification. The following is a simple example. Let the conversion pattern be *""%-5p [%t]: %m%n""* and assume that the Log4j environment was set to use a PatternLayout. Then the statements .... Logger logger = LogManager.getLogger(""MyLogger""); logger.debug(""Message 1""); logger.warn(""Message 2""); .... would yield the output .... DEBUG [main]: Message 1 WARN [main]: Message 2 .... Note that there is no explicit separator between text and conversion specifiers. The pattern parser knows when it has reached the end of a conversion specifier when it reads a conversion character. In the example above the conversion specifier *%-5p* means the priority of the logging event should be left justified to a width of five characters. If the pattern string does not contain a specifier to handle a Throwable being logged, parsing of the pattern will act as if the ""%xEx"" specifier had be added to the end of the string. To suppress formatting of the Throwable completely simply add ""%ex{0}"" as a specifier in the pattern string. .PatternLayout Parameters [cols=""1m,1,4""] |=== |Parameter Name |Type |Description |charset |String |The character set to use when converting the syslog String to a byte array. The String must be a valid http://docs.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html[Charset]. If not specified, this layout uses the platform default character set. |pattern |String |A composite pattern string of one or more conversion patterns from the table below. Cannot be specified with a PatternSelector. |patternSelector |PatternSelector |A component that analyzes information in the LogEvent and determines which pattern should be used to format the event. The pattern and patternSelector parameters are mutually exclusive. |replace |RegexReplacement |Allows portions of the resulting String to be replaced. If configured, the replace element must specify the regular expression to match and the substitution. This performs a function similar to the RegexReplacement converter but applies to the whole message while the converter only applies to the String its pattern generates. |alwaysWriteExceptions |boolean |If `true` (it is by default) exceptions are always written even if the pattern contains no exception conversions. This means that if you do not include a way to output exceptions in your pattern, the default exception formatter will be added to the end of the pattern. Setting this to `false` disables this behavior and allows you to exclude exceptions from your pattern output. |header |String |The optional header string to include at the top of each log file. |footer |String |The optional footer string to include at the bottom of each log file. |disableAnsi |boolean |If `true` (default is false), do not output ANSI escape codes. |noConsoleNoAnsi |boolean |If `true` (default is false) and `System.console()` is null, do not output ANSI escape codes. |=== .RegexReplacement Parameters |=== |Parameter Name |Type |Description |regex |String |A Java-compliant regular expression to match in the resulting string. See https://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html[Pattern]. |replacement |String |The string to replace any matched sub-strings with. |=== [#Patterns] === Patterns The conversions that are provided with Log4j are: [cols=""1,3a""] |=== |Conversion Pattern |Description |*c*{precision} + *logger*{precision} |Outputs the name of the logger that published the logging event. The logger conversion specifier can be optionally followed by _precision specifier_, which consists of a decimal integer, or a pattern starting with a decimal integer. When the precision specifier is an integer value, it reduces the size of the logger name. If the number is positive, the layout prints the corresponding number of rightmost logger name components. If negative, the layout removes the corresponding number of leftmost logger name components. If the precision contains any non-integer characters, then the layout abbreviates the name based on the pattern. If the precision integer is less than one, the layout still prints the right-most token in full. By default, the layout prints the logger name in full. !=== !Conversion Pattern !Logger Name !Result !%c{1} !org.apache.commons.Foo !Foo !%c{2} !org.apache.commons.Foo !commons.Foo !%c{10} !org.apache.commons.Foo !org.apache.commons.Foo !%c{-1} !org.apache.commons.Foo !apache.commons.Foo !%c{-2} !org.apache.commons.Foo !commons.Foo !%c{-10} !org.apache.commons.Foo !org.apache.commons.Foo !%c{1.} !org.apache.commons.Foo !o.a.c.Foo !%c{1.1.~.~} !org.apache.commons.test.Foo !o.a.~.~.Foo !%c{.} !org.apache.commons.test.Foo !....Foo !=== |[[PatternClass]] *C*{precision} + *class*{precision} |Outputs the fully qualified class name of the caller issuing the logging request. This conversion specifier can be optionally followed by _precision specifier_, that follows the same rules as the logger name converter. Generating the class name of the caller (link:#LocationInformation[location information]) is an expensive operation and may impact performance. Use with caution. |*d*{pattern} + *date*{pattern} |Outputs the date of the logging event. The date conversion specifier may be followed by a set of braces containing a date and time pattern string per https://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html[`SimpleDateFormat`]. The predefined formats are `DEFAULT`, `ABSOLUTE`, `COMPACT`, `DATE`, `ISO8601`, and `ISO8601_BASIC`. You can also use a set of braces containing a time zone id per https://docs.oracle.com/javase/6/docs/api/java/util/TimeZone.html#getTimeZone(java.lang.String)[java.util.TimeZone.getTimeZone]. If no date format specifier is given then the DEFAULT format is used. [cols="","",options=""header"",] !=== !Pattern !Example !%d{DEFAULT} !2012-11-02 14:34:02,123 !%d{DEFAULT_MICROS} !2012-11-02 14:34:02,123456 !%d{DEFAULT_NANOS} !2012-11-02 14:34:02,123456789 !%d{ISO8601} !2012-11-02T14:34:02,781 !%d{ISO8601_BASIC} !20121102T143402,781 !%d{ABSOLUTE} !14:34:02,781 !%d{ABSOLUTE_MICROS} !14:34:02,123456 !%d{ABSOLUTE_NANOS} !14:34:02,123456789 !%d{DATE} !02 Nov 2012 14:34:02,781 !%d{COMPACT} !20121102143402781 !%d{HH:mm:ss,SSS} !14:34:02,123 !%d{HH:mm:ss,nnnn} to %d{HH:mm:ss,nnnnnnnnn} !14:34:02,1234 to 14:34:02,123456789 !%d{dd MMM yyyy HH:mm:ss,SSS} !02 Nov 2012 14:34:02,123 !%d{dd MMM yyyy HH:mm:ss,nnnn} to %d{dd MMM yyyy HH:mm:ss,nnnnnnnnn} !02 Nov 2012 14:34:02,1234 to 02 Nov 2012 14:34:02,123456789 !%d{HH:mm:ss}{GMT+0} !18:34:02 !%d{UNIX} !1351866842 !%d{UNIX_MILLIS} !1351866842781 !=== %d{UNIX} outputs the UNIX time in seconds. %d{UNIX_MILLIS} outputs the UNIX time in milliseconds. The UNIX time is the difference, in seconds for UNIX and in milliseconds for UNIX_MILLIS, between the current time and midnight, January 1, 1970 UTC. While the time unit is milliseconds, the granularity depends on the operating system (http://msdn.microsoft.com/en-us/windows/hardware/gg463266.aspx[Windows]). This is an efficient way to output the event time because only a conversion from long to String takes place, there is no Date formatting involved. Log4j 2.11 adds limited support for timestamps more precise than milliseconds when running on Java 9. Note that not all https://docs.oracle.com/javase/9/docs/api/java/time/format/DateTimeFormatter.html[DateTimeFormatter] formats are supported. Only timestamps in the formats mentioned in the table above may use the ""nano-of-second"" pattern letter `n` instead of the ""fraction-of-second"" pattern letter `S`. Users may revert back to a millisecond-precision clock when running on Java 9 by setting system property `log4j2.Clock` to `SystemMillisClock`. |*enc*{_pattern_}{[HTML\\|XML\\|JSON\\|CRLF]} + *encode*{_pattern_}{[HTML\\|XML\\|JSON\\|CRLF]} |Encodes and escapes special characters suitable for output in specific markup languages. By default, this encodes for HTML if only one option is specified. The second option is used to specify which encoding format should be used. This converter is particularly useful for encoding user provided data so that the output data is not written improperly or insecurely. A typical usage would encode the message `%enc{%m}` but user input could come from other locations as well, such as the MDC `%enc{%mdc{key}}` Using the HTML encoding format, the following characters are replaced: !=== !Character !Replacement !'\\r', '\\n' !Converted into escaped strings ""\\\\r"" and ""\\\\n"" respectively !&, <, >, "", ', / !Replaced with the corresponding HTML entity !=== Using the XML encoding format, this follows the escaping rules specified by https://www.w3.org/TR/xml/[the XML specification]: !=== !Character !Replacement !&, <, >, "", ' !Replaced with the corresponding XML entity !=== Using the JSON encoding format, this follows the escaping rules specified by https://www.ietf.org/rfc/rfc4627.txt[RFC 4627 section 2.5]: !=== !Character !Replacement !U+0000 - U+001F !\\u0000 - \\u001F !Any other control characters !Encoded into its `\\uABCD` equivalent escaped code point !"" !\\"" !\\ !\\\\ !=== For example, the pattern `{""message"": ""%enc{%m}{JSON}""}` could be used to output a valid JSON document containing the log message as a string value. Using the CRLF encoding format, the following characters are replaced: !=== !Character !Replacement !'\\r', '\\n' !Converted into escaped strings ""\\\\r"" and ""\\\\n"" respectively !=== |*equals*{pattern}{test}{substitution} + *equalsIgnoreCase*{pattern}{test}{substitution} |Replaces occurrences of 'test', a string, with its replacement 'substitution' in the string resulting from evaluation of the pattern. For example, ""%equals{[%marker]}{[]}\\{}"" will replace '[]' strings produces by events without markers with an empty string. The pattern can be arbitrarily complex and in particular can contain multiple conversion keywords. |**ex**\\|**exception**\\|*throwable* + { +   [ ""none"" +    \\| ""full"" +    \\| depth +    \\| ""short"" +    \\| ""short.className"" +    \\| ""short.fileName"" +    \\| ""short.lineNumber"" +    \\| ""short.methodName"" +    \\| ""short.message"" +    \\| ""short.localizedMessage""] + } +   {filters(package,package,...)} +   {suffix(_pattern_)} +   {separator(_separator_)} |Outputs the Throwable trace bound to the logging event, by default this will output the full trace as one would normally find with a call to `Throwable.printStackTrace()`. You can follow the throwable conversion word with an option in the form `%throwable{option}`. `%throwable{short}` outputs the first line of the Throwable. `%throwable{short.className}` outputs the name of the class where the exception occurred. `%throwable{short.methodName}` outputs the method name where the exception occurred. `%throwable{short.fileName}` outputs the name of the class where the exception occurred. `%throwable{short.lineNumber}` outputs the line number where the exception occurred. `%throwable{short.message}` outputs the message. `%throwable{short.localizedMessage}` outputs the localized message. `%throwable{n}` outputs the first n lines of the stack trace. Specifying `%throwable{none}` or `%throwable{0}` suppresses output of the exception. Use `{filters(packages)}` where _packages_ is a list of package names to suppress matching stack frames from stack traces. Use `{suffix(pattern)}` to add the output of _pattern_ at the end of each stack frames. Use a `{separator(...)}` as the end-of-line string. For example: `separator(\\|)`. The default value is the `line.separator` system property, which is operating system dependent. |[[PatternFile]] *F* + *file* |Outputs the file name where the logging request was issued. Generating the file information (link:#LocationInformation[location information]) is an expensive operation and may impact performance. Use with caution. |*highlight*{pattern}{style} |Adds ANSI colors to the result of the enclosed pattern based on the current event's logging level. (See Jansi link:#enable-jansi[configuration].) The default colors for each level are: !=== !Level !ANSI color !FATAL !Bright red !ERROR !Bright red !WARN !Yellow !INFO !Green !DEBUG !Cyan !TRACE !Black (looks dark grey) !=== The color names are ANSI names defined in the link:../log4j-core/apidocs/org/apache/logging/log4j/core/pattern/AnsiEscape.html[`AnsiEscape`] class. The color and attribute names and are standard, but the exact shade, hue, or value. .Color table !=== !Intensity Code !0 !1 !2 !3 !4 !5 !6 !7 !Normal !Black !Red !Green !Yellow !Blue !Magenta !Cyan !White !Bright !Black !Red !Green !Yellow !Blue !Magenta !Cyan !White !=== You can use the default colors with: .... %highlight{%d [%t] %-5level: %msg%n%throwable} .... You can override the default colors in the optional {style} option. For example: .... %highlight{%d [%t] %-5level: %msg%n%throwable}{FATAL=white, ERROR=red, WARN=blue, INFO=black, DEBUG=green, TRACE=blue} .... You can highlight only the a portion of the log event: .... %d [%t] %highlight{%-5level: %msg%n%throwable} .... You can style one part of the message and highlight the rest the log event: .... %style{%d [%t]}{black} %highlight{%-5level: %msg%n%throwable} .... You can also use the STYLE key to use a predefined group of colors: .... %highlight{%d [%t] %-5level: %msg%n%throwable}{STYLE=Logback} .... The STYLE value can be one of: * Default: see above * Logback: !=== !Level !ANSI color !FATAL !Blinking bright red !ERROR !Bright red !WARN !Red !INFO !Blue !DEBUG !Normal !TRACE !Normal !=== |[[PatternMap]] *K*{key} + *map*{key} + *MAP*{key} |Outputs the entries in a link:../log4j-api/apidocs/org/apache/logging/log4j/message/MapMessage.html[MapMessage], if one is present in the event. The *K* conversion character can be followed by the key for the map placed between braces, as in *%K{clientNumber}* where `clientNumber` is the key. The value in the Map corresponding to the key will be output. If no additional sub-option is specified, then the entire contents of the Map key value pair set is output using a format {{key1,val1},{key2,val2}} |[[PatternLocation]] *l* + *location* |Outputs location information of the caller which generated the logging event. The location information depends on the JVM implementation but usually consists of the fully qualified name of the calling method followed by the callers source the file name and line number between parentheses. Generating link:#LocationInformation[location information] is an expensive operation and may impact performance. Use with caution. |[[PatternLine]] *L* + *line* |Outputs the line number from where the logging request was issued. Generating line number information (link:#LocationInformation[location information]) is an expensive operation and may impact performance. Use with caution. |[[PatternMessage]] *m*{nolookups}{ansi} + *msg*{nolookups}{ansi} + *message*{nolookups}{ansi} |Outputs the application supplied message associated with the logging event. Add `{ansi}` to render messages with ANSI escape codes (requires JAnsi, see link:#enable-jansi[configuration].) The default syntax for embedded ANSI codes is: .... @\\|code(,code)* text\\|@ .... For example, to render the message `""Hello""` in green, use: .... @\\|green Hello\\|@ .... To render the message `""Hello""` in bold and red, use: .... @\\|bold,red Warning!\\|@ .... You can also define custom style names in the configuration with the syntax: .... %message{ansi}{StyleName=value(,value)*( StyleName=value(,value)*)*}%n .... For example: .... %message{ansi}{WarningStyle=red,bold KeyStyle=white ValueStyle=blue}%n .... The call site can look like this: .... logger.info(""@\\|KeyStyle {}\\|@ = @\\|ValueStyle {}\\|@"", entry.getKey(), entry.getValue()); .... Use `{nolookups}` to log messages like `""${date:YYYY-MM-dd}""` without using any lookups. Normally calling `logger.info(""Try ${date:YYYY-MM-dd}"")` would replace the date template `${date:YYYY-MM-dd}` with an actual date. Using `nolookups` disables this feature and logs the message string untouched. |[[PatternMethod]] *M* + *method* |Outputs the method name where the logging request was issued. Generating the method name of the caller (link:#LocationInformation[location information]) is an expensive operation and may impact performance. Use with caution. |[[PatternMarker]] *marker* |The full name of the marker, including parents, if one is present. |[[PatternMarkerSimpleName]] *markerSimpleName* |The simple name of the marker (not including parents), if one is present. |[[PatternMaxLength]] *maxLen* + *maxLength* |Outputs the result of evaluating the pattern and truncating the result. If the length is greater than 20, then the output will contain a trailing ellipsis. If the provided length is invalid, a default value of 100 is used. Example syntax: `%maxLen{%p: %c{1} - %m%notEmpty{ =>%ex{short}}}{160}` will be limited to 160 characters with a trailing ellipsis. Another example: `%maxLen{%m}{20}` will be limited to 20 characters and no trailing ellipsis. |[[PatternNewLine]] *n* |Outputs the platform dependent line separator character or characters. This conversion character offers practically the same performance as using non-portable line separator strings such as ""\\n"", or ""\\r\\n"". Thus, it is the preferred way of specifying a line separator. |[[NanoTime]] *N* + *nano* |Outputs the result of `System.nanoTime()` at the time the log event was created. |[[Process_ID]] *pid*{[defaultValue]} + *processId*{[defaultValue]} |Outputs the process ID if supported by the underlying platform. An optional default value may be specified to be shown if the platform does not support process IDs. |[[VariablesNotEmpty]] *variablesNotEmpty*{pattern} + *varsNotEmpty*{pattern} + *notEmpty*{pattern} |Outputs the result of evaluating the pattern if and only if all variables in the pattern are not empty. For example: .... %notEmpty{[%marker]} .... |[[PatternLevel]] **p**\\|*level*{__level__=_label_, __level__=_label_, ...} **p**\\|*level*{length=_n_} **p**\\|*level*{lowerCase=__true__\\|_false_} |Outputs the level of the logging event. You provide a level name map in the form ""level=value, level=value"" where level is the name of the Level and value is the value that should be displayed instead of the name of the Level. For example: .... %level{WARN=Warning, DEBUG=Debug, ERROR=Error, TRACE=Trace, INFO=Info} .... Alternatively, for the compact-minded: .... %level{WARN=W, DEBUG=D, ERROR=E, TRACE=T, INFO=I} .... More succinctly, for the same result as above, you can define the length of the level label: .... %level{length=1} .... If the length is greater than a level name length, the layout uses the normal level name. You can combine the two kinds of options: .... %level{ERROR=Error, length=2} .... This give you the `Error` level name and all other level names of length 2. Finally, you can output lower-case level names (the default is upper-case): .... %level{lowerCase=true} .... |[[PatternRelative]] *r* + *relative* |Outputs the number of milliseconds elapsed since the JVM was started until the creation of the logging event. |[[PatternReplace]] *replace*{pattern}{regex}{substitution} |Replaces occurrences of 'regex', a regular expression, with its replacement 'substitution' in the string resulting from evaluation of the pattern. For example, ""%replace{%msg}{\\s}\\{}"" will remove all spaces contained in the event message. The pattern can be arbitrarily complex and in particular can contain multiple conversion keywords. For instance, ""%replace{%logger %msg}{\\.}{/}"" will replace all dots in the logger or the message of the event with a forward slash. |[[PatternException]] **rEx**\\|**rException**\\|*rThrowable* +   { +     [""none"" \\| ""short"" \\| ""full"" \\| depth] +     [,filters(package,package,...)] +     [,separator(_separator_)] +   } +   {ansi( +     Key=Value,Value,... +     Key=Value,Value,... +     ...) +   } +   {suffix(_pattern_)} + |The same as the %throwable conversion word but the stack trace is printed starting with the first exception that was thrown followed by each subsequent wrapping exception. The throwable conversion word can be followed by an option in the form `%rEx{short}` which will only output the first line of the Throwable or `%rEx{n}` where the first n lines of the stack trace will be printed. Specifying `%rEx{none}` or `%rEx{0}` will suppress printing of the exception. Use `filters(packages)` where _packages_ is a list of package names to suppress matching stack frames from stack traces. Use a `separator` string to separate the lines of a stack trace. For example: `separator(\\|)`. The default value is the `line.separator` system property, which is operating system dependent. Use `rEx{suffix(pattern)` to add the output of _pattern_ to the output only when there is a throwable to print. |[[PatternSequenceNumber]] *sn* + *sequenceNumber* |Includes a sequence number that will be incremented in every event. The counter is a static variable so will only be unique within applications that share the same converter Class object. |[[PatternStyle]] *style*{pattern}{ANSI style} |Uses ANSI escape sequences to style the result of the enclosed pattern. The style can consist of a comma separated list of style names from the following table. (See Jansi link:#enable-jansi[configuration].) !=== !Style Name !Description !Normal !Normal display !Bright !Bold !Dim !Dimmed or faint characters !Underline !Underlined characters !Blink !Blinking characters !Reverse !Reverse video !Hidden ! !Black or FG_Black !Set foreground color to black !Red or FG_Red !Set foreground color to red !Green or FG_Green !Set foreground color to green !Yellow or FG_Yellow !Set foreground color to yellow !Blue or FG_Blue !Set foreground color to blue !Magenta or FG_Magenta !Set foreground color to magenta !Cyan or FG_Cyan !Set foreground color to cyan !White or FG_White !Set foreground color to white !Default or FG_Default !Set foreground color to default (white) !BG_Black !Set background color to black !BG_Red !Set background color to red !BG_Green !Set background color to green !BG_Yellow !Set background color to yellow !BG_Blue !Set background color to blue !BG_Magenta !Set background color to magenta !BG_Cyan !Set background color to cyan !BG_White !Set background color to white !=== For example: .... %style{%d{ISO8601}}{black} %style{[%t]}{blue} %style{%-5level:}{yellow} %style{%msg%n%throwable}{green} .... You can also combine styles: .... %d %highlight{%p} %style{%logger}{bright,cyan} %C{1.} %msg%n .... You can also use `%` with a color like `%black`, `%blue`, `%cyan`, and so on. For example: .... %black{%d{ISO8601}} %blue{[%t]} %yellow{%-5level:} %green{%msg%n%throwable} .... |[[PatternThreadId]] *T* + *tid* + *threadId* |Outputs the ID of the thread that generated the logging event. |[[PatternThreadName]] *t* + *tn* + *thread* + *threadName* |Outputs the name of the thread that generated the logging event. |[[PatternThreadPriority]] *tp* + *threadPriority* |Outputs the priority of the thread that generated the logging event. |[[PatternLoggerFqcn]] *fqcn* |Outputs the fully qualified class name of the logger. |[[EndOfBatch]] *endOfBatch* |Outputs the EndOfBatch status of the logging event, as ""true"" or ""false"". |[[PatternNDC]] *x* + *NDC* |Outputs the Thread Context Stack (also known as the Nested Diagnostic Context or NDC) associated with the thread that generated the logging event. |[[PatternMDC]] *X*{key[,key2...]} + *mdc*{key[,key2...]} + *MDC*{key[,key2...]} |Outputs the Thread Context Map (also known as the Mapped Diagnostic Context or MDC) associated with the thread that generated the logging event. The *X* conversion character can be followed by one or more keys for the map placed between braces, as in *%X{clientNumber}* where `clientNumber` is the key. The value in the MDC corresponding to the key will be output. If a list of keys are provided, such as *%X{name, number}*, then each key that is present in the ThreadContext will be output using the format {name=val1, number=val2}. The key/value pairs will be printed in the order they appear in the list. If no sub-options are specified then the entire contents of the MDC key value pair set is output using a format {key1=val1, key2=val2}. The key/value pairs will be printed in sorted order. See the link:../log4j-api/apidocs/org/apache/logging/log4j/ThreadContext.html[ThreadContext] class for more details. |[[PatternUUID]] *u*{""RANDOM"" \\| ""TIME""} + *uuid* |Includes either a random or a time-based UUID. The time-based UUID is a Type 1 UUID that can generate up to 10,000 unique ids per millisecond, will use the MAC address of each host, and to try to insure uniqueness across multiple JVMs and/or ClassLoaders on the same host a random number between 0 and 16,384 will be associated with each instance of the UUID generator Class and included in each time-based UUID generated. Because time-based UUIDs contain the MAC address and timestamp they should be used with care as they can cause a security vulnerability. |[[PatternExtendedException]] **xEx**\\|**xException**\\|*xThrowable* +   { +     [""none"" \\| ""short"" \\| ""full"" \\| depth] +     [,filters(package,package,...)] +     [,separator(_separator_)] +   } +   {ansi( +     Key=Value,Value,... +     Key=Value,Value,... +     ...) +   } +   {suffix(_pattern_)} + |The same as the %throwable conversion word but also includes class packaging information. At the end of each stack element of the exception, a string containing the name of the jar file that contains the class or the directory the class is located in and the ""Implementation-Version"" as found in that jar's manifest will be added. If the information is uncertain, then the class packaging data will be preceded by a tilde, i.e. the '~' character. The throwable conversion word can be followed by an option in the form `%xEx{short}` which will only output the first line of the Throwable or `%xEx{n}` where the first n lines of the stack trace will be printed. Specifying `%xEx{none}` or `%xEx{0}` will suppress printing of the exception. Use `filters(packages)` where _packages_ is a list of package names to suppress matching stack frames from stack traces. Use a `separator` string to separate the lines of a stack trace. For example: `separator(\\|)`. The default value is the `line.separator` system property, which is operating system dependent. The `ansi` option renders stack traces with ANSI escapes code using the JAnsi library. (See link:#enable-jansi[configuration].) Use `{ansi}` to use the default color mapping. You can specify your own mappings with `key=value` pairs. The keys are: * Prefix * Name * NameMessageSeparator * Message * At * CauseLabel * Text * More * Suppressed * StackTraceElement.ClassName * StackTraceElement.ClassMethodSeparator * StackTraceElement.MethodName * StackTraceElement.NativeMethod * StackTraceElement.FileName * StackTraceElement.LineNumber * StackTraceElement.Container * StackTraceElement.ContainerSeparator * StackTraceElement.UnknownSource * ExtraClassInfo.Inexact * ExtraClassInfo.Container * ExtraClassInfo.ContainerSeparator * ExtraClassInfo.Location * ExtraClassInfo.Version The values are names from JAnsi's https://fusesource.github.io/jansi/documentation/api/org/fusesource/jansi/AnsiRenderer.Code.html[Code] class like `blue`, `bg_red`, and so on (Log4j ignores case.) The special key `StyleMapName` can be set to one of the following predefined maps: `Spock`, `Kirk`. As with %throwable, the *%xEx{suffix(_pattern_)* conversion will add the output of _pattern_ to the output only if there is a throwable to print. |[[PatternPercentLiteral]] *%* |The sequence %% outputs a single percent sign. |=== By default the relevant information is output as is. However, with the aid of format modifiers it is possible to change the minimum field width, the maximum field width and justification. The optional format modifier is placed between the percent sign and the conversion character. The first optional format modifier is the _left justification flag_ which is just the minus (-) character. Then comes the optional _minimum field width_ modifier. This is a decimal constant that represents the minimum number of characters to output. If the data item requires fewer characters, it is padded on either the left or the right until the minimum width is reached. The default is to pad on the left (right justify) but you can specify right padding with the left justification flag. The padding character is space. If the data item is larger than the minimum field width, the field is expanded to accommodate the data. The value is never truncated. This behavior can be changed using the _maximum field width_ modifier which is designated by a period followed by a decimal constant. If the data item is longer than the maximum field, then the extra characters are removed from the _beginning_ of the data item and not from the end. For example, it the maximum field width is eight and the data item is ten characters long, then the first two characters of the data item are dropped. This behavior deviates from the printf function in C where truncation is done from the end. Truncation from the end is possible by appending a minus character right after the period. In that case, if the maximum field width is eight and the data item is ten characters long, then the last two characters of the data item are dropped. Below are various format modifier examples for the category conversion specifier. .Pattern Converters |=== |Format modifier |left justify |minimum width |maximum width |comment |%20c |false |20 |none |Left pad with spaces if the category name is less than 20 characters long. |%-20c |true |20 |none |Right pad with spaces if the category name is less than 20 characters long. |%.30c |NA |none |30 |Truncate from the beginning if the category name is longer than 30 characters. |%20.30c |false |20 |30 |Left pad with spaces if the category name is shorter than 20 characters. However, if category name is longer than 30 characters, then truncate from the beginning. |%-20.30c |true |20 |30 |Right pad with spaces if the category name is shorter than 20 characters. However, if category name is longer than 30 characters, then truncate from the beginning. |%-20.-30c |true |20 |30 |Right pad with spaces if the category name is shorter than 20 characters. However, if category name is longer than 30 characters, then truncate from the end. |=== [#enable-jansi] === ANSI Styling on Windows ANSI escape sequences are supported natively on many platforms but are not by default on Windows. To enable ANSI support add the http://jansi.fusesource.org/[Jansi] jar to your application and set property `log4j.skipJansi` to `false`. This allows Log4j to use Jansi to add ANSI escape codes when writing to the console. NOTE: Prior to Log4j 2.10, Jansi was enabled by default. The fact that Jansi requires native code means that Jansi can only be loaded by a single class loader. For web applications this means the Jansi jar has to be in the web container's classpath. To avoid causing problems for web applications, Log4j will no longer automatically try to load Jansi without explicit configuration from Log4j 2.10 onward. === Example Patterns ==== Filtered Throwables This example shows how to filter out classes from unimportant packages in stack traces. [source,xml] ---- org.junit,org.apache.maven,sun.reflect,java.lang.reflect ... ---- The result printed to the console will appear similar to: .... Exception java.lang.IllegalArgumentException: IllegalArgument at org.apache.logging.log4j.core.pattern.ExtendedThrowableTest.testException(ExtendedThrowableTest.java:72) [test-classes/:?] ... suppressed 26 lines at $Proxy0.invoke(Unknown Source)} [?:?] ... suppressed 3 lines Caused by: java.lang.NullPointerException: null pointer at org.apache.logging.log4j.core.pattern.ExtendedThrowableTest.testException(ExtendedThrowableTest.java:71) ~[test-classes/:?] ... 30 more .... ==== ANSI Styled The log level will be highlighted according to the event's log level. All the content that follows the level will be bright green. [source,xml] ---- %d %highlight{%p} %style{%C{1.} [%t] %m}{bold,green}%n ---- === Pattern Selectors The PatternLayout can be configured with a PatternSelector to allow it to choose a pattern to use based on attributes of the log event or other factors. A PatternSelector will normally be configured with a defaultPattern attribute, which is used when other criteria don't match, and a set of PatternMatch elements that identify the various patterns that can be selected. [#MarkerPatternSelector] ==== MarkerPatternSelector The MarkerPatternSelector selects patterns based on the Marker included in the log event. If the Marker in the log event is equal to or is an ancestor of the name specified on the PatternMatch key attribute, then the pattern specified on that PatternMatch element will be used. [source,xml] ---- ---- [#ScriptPatternSelector] ==== ScriptPatternSelector The ScriptPatternSelector executes a script as descibed in the link:../configuration.html#Scripts[Scripts] section of the Configuration chapter. The script is passed all the properties configured in the Properties section of the configuration, the StrSubstitutor used by the Confguration in the ""substitutor"" vairables, and the log event in the ""logEvent"" variable, and is expected to return the value of the PatternMatch key that should be used, or null if the default pattern should be used. [source,xml] ---- ---- [#RFC5424Layout] == RFC5424 Layout As the name implies, the Rfc5424Layout formats LogEvents in accordance with http://tools.ietf.org/html/rfc5424[RFC 5424], the enhanced Syslog specification. Although the specification is primarily directed at sending messages via Syslog, this format is quite useful for other purposes since items are passed in the message as self-describing key/value pairs. .Rfc5424Layout Parameters [cols=""1m,1,4""] |=== |Parameter Name |Type |Description |appName |String |The value to use as the APP-NAME in the RFC 5424 syslog record. |charset |String |The character set to use when converting the syslog String to a byte array. The String must be a valid http://docs.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html[Charset]. If not specified, the default system Charset will be used. |enterpriseNumber |integer |The IANA enterprise number as described in http://tools.ietf.org/html/rfc5424#section-7.2.2[RFC 5424] |exceptionPattern |String |One of the conversion specifiers from PatternLayout that defines which ThrowablePatternConverter to use to format exceptions. Any of the options that are valid for those specifiers may be included. The default is to not include the Throwable from the event, if any, in the output. |facility |String |The facility is used to try to classify the message. The facility option must be set to one of ""KERN"", ""USER"", ""MAIL"", ""DAEMON"", ""AUTH"", ""SYSLOG"", ""LPR"", ""NEWS"", ""UUCP"", ""CRON"", ""AUTHPRIV"", ""FTP"", ""NTP"", ""AUDIT"", ""ALERT"", ""CLOCK"", ""LOCAL0"", ""LOCAL1"", ""LOCAL2"", ""LOCAL3"", ""LOCAL4"", ""LOCAL5"", ""LOCAL6"", or ""LOCAL7"". These values may be specified as upper or lower case characters. |format |String |If set to ""RFC5424"" the data will be formatted in accordance with RFC 5424. Otherwise, it will be formatted as a BSD Syslog record. Note that although BSD Syslog records are required to be 1024 bytes or shorter the SyslogLayout does not truncate them. The RFC5424Layout also does not truncate records since the receiver must accept records of up to 2048 bytes and may accept records that are longer. |id |String |The default structured data id to use when formatting according to RFC 5424. If the LogEvent contains a StructuredDataMessage the id from the Message will be used instead of this value. |includeMDC |boolean |Indicates whether data from the ThreadContextMap will be included in the RFC 5424 Syslog record. Defaults to true. |loggerFields |List of KeyValuePairs |Allows arbitrary PatternLayout patterns to be included as specified ThreadContext fields; no default specified. To use, include a nested element, containing one or more elements. Each must have a key attribute, which specifies the key name which will be used to identify the field within the MDC Structured Data element, and a value attribute, which specifies the PatternLayout pattern to use as the value. |mdcExcludes |String |A comma separated list of mdc keys that should be excluded from the LogEvent. This is mutually exclusive with the mdcIncludes attribute. This attribute only applies to RFC 5424 syslog records. |mdcIncludes |String |A comma separated list of mdc keys that should be included in the FlumeEvent. Any keys in the MDC not found in the list will be excluded. This option is mutually exclusive with the mdcExcludes attribute. This attribute only applies to RFC 5424 syslog records. |mdcRequired |String |A comma separated list of mdc keys that must be present in the MDC. If a key is not present a LoggingException will be thrown. This attribute only applies to RFC 5424 syslog records. |mdcPrefix |String |A string that should be prepended to each MDC key in order to distinguish it from event attributes. The default string is ""mdc:"". This attribute only applies to RFC 5424 syslog records. |mdcId |String |A required MDC ID. This attribute only applies to RFC 5424 syslog records. |messageId |String |The default value to be used in the MSGID field of RFC 5424 syslog records. |newLine |boolean |If true, a newline will be appended to the end of the syslog record. The default is false. |newLineEscape |String |String that should be used to replace newlines within the message text. |=== [#SerializedLayout] == Serialized Layout The SerializedLayout simply serializes the LogEvent into a byte array using Java Serialization. The SerializedLayout accepts no parameters. This layout is deprecated since version 2.9. Java Serialization has inherent security weaknesses, using this layout is no longer recommended. An alternative layout containing the same information is link:#JSONLayout[JsonLayout], configured with `properties=""true""`. [#SyslogLayout] == Syslog Layout The SyslogLayout formats the LogEvent as BSD Syslog records matching the same format used by Log4j 1.2. .SyslogLayout Parameters [cols=""1m,1,4""] |=== |Parameter Name |Type |Description |charset |String |The character set to use when converting the syslog String to a byte array. The String must be a valid http://docs.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html[Charset]. If not specified, this layout uses UTF-8. |facility |String |The facility is used to try to classify the message. The facility option must be set to one of ""KERN"", ""USER"", ""MAIL"", ""DAEMON"", ""AUTH"", ""SYSLOG"", ""LPR"", ""NEWS"", ""UUCP"", ""CRON"", ""AUTHPRIV"", ""FTP"", ""NTP"", ""AUDIT"", ""ALERT"", ""CLOCK"", ""LOCAL0"", ""LOCAL1"", ""LOCAL2"", ""LOCAL3"", ""LOCAL4"", ""LOCAL5"", ""LOCAL6"", or ""LOCAL7"". These values may be specified as upper or lower case characters. |newLine |boolean |If true, a newline will be appended to the end of the syslog record. The default is false. |newLineEscape |String |String that should be used to replace newlines within the message text. |=== [#XMLLayout] == XML Layout Appends a series of `Event` elements as defined in the log4j.dtd. === Complete well-formed XML vs. fragment XML If you configure `complete=""true""`, the appender outputs a well-formed XML document where the default namespace is the Log4j namespace `""http://logging.apache.org/log4j/2.0/events""`. By default, with `complete=""false""`, you should include the output as an _external entity_ in a separate file to form a well-formed XML document, in which case the appender uses `namespacePrefix` with a default of `""log4j""`. A well-formed XML document follows this pattern: [source,xml] ---- Hello, world! one two ---- If `complete=""false""`, the appender does not write the XML processing instruction and the root element. === Marker Markers are represented by a `Marker` element within the `Event` element. The `Marker` element appears only when a marker is used in the log message. The name of the marker's parent will be provided in the `parent` attribute of the `Marker` element. === Pretty vs. compact XML By default, the XML layout is not compact (a.k.a. not ""pretty"") with `compact=""false""`, which means the appender uses end-of-line characters and indents lines to format the XML. If `compact=""true""`, then no end-of-line or indentation is used. Message content may contain, of course, end-of-lines. .XmlLayout Parameters [cols=""1m,1,4""] |=== |Parameter Name |Type |Description |charset |String |The character set to use when converting to a byte array. The value must be a valid https://docs.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html[Charset]. If not specified, UTF-8 will be used. |compact |boolean |If true, the appender does not use end-of-lines and indentation. Defaults to false. |complete |boolean |If true, the appender includes the XML header and footer. Defaults to false. |properties |boolean |If true, the appender includes the thread context map in the generated XML. Defaults to false. |locationInfo |boolean a|If true, the appender includes the location information in the generated XML. Defaults to false. Generating link:#LocationInformation[location information] is an expensive operation and may impact performance. Use with caution. |includeStacktrace |boolean |If true, include full stacktrace of any logged https://docs.oracle.com/javase/6/docs/api/java/lang/Throwable.html[Throwable] (optional, default to true). |stacktraceAsString |boolean |Whether to format the stacktrace as a string, and not a nested object (optional, defaults to false). |includeNullDelimiter |boolean |Whether to include NULL byte as delimiter after each event (optional, default to false). |=== To include any custom field in the output, use following syntax: [source,xml] ---- ---- Custom fields are always last, in the order they are declared. The values support link:lookups.html[lookups]. Additional link:../runtime-dependencies.html[runtime dependencies] are required for using XmlLayout. [#YamlLayout] == YAML Layout Appends a series of YAML events as strings serialized as bytes. A YAML log event follows this pattern: [source,yaml] ---- --- instant: epochSecond: 1493121664 nanoOfSecond: 118000000 thread: ""main"" level: ""INFO"" loggerName: ""HelloWorld"" marker: name: ""child"" parents: - name: ""parent"" parents: - name: ""grandparent"" message: ""Hello, world!"" thrown: commonElementCount: 0 message: ""error message"" name: ""java.lang.RuntimeException"" extendedStackTrace: - class: ""logtest.Main"" method: ""main"" file: ""Main.java"" line: 29 exact: true location: ""classes/"" version: ""?"" contextStack: - ""one"" - ""two"" endOfBatch: false loggerFqcn: ""org.apache.logging.log4j.spi.AbstractLogger"" contextMap: bar: ""BAR"" foo: ""FOO"" threadId: 1 threadPriority: 5 source: class: ""logtest.Main"" method: ""main"" file: ""Main.java"" line: 29 ---- .YamlLayout Parameters [cols=""1m,1,4""] |=== |Parameter Name |Type |Description |charset |String |The character set to use when converting to a byte array. The value must be a valid https://docs.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html[Charset]. If not specified, UTF-8 will be used. |properties |boolean |If true, the appender includes the thread context map in the generated YAML. Defaults to false. |locationInfo |boolean a| If true, the appender includes the location information in the generated YAML. Defaults to false. Generating link:#LocationInformation[location information] is an expensive operation and may impact performance. Use with caution. |includeStacktrace |boolean |If true, include full stacktrace of any logged https://docs.oracle.com/javase/6/docs/api/java/lang/Throwable.html[Throwable] (optional, default to true). |stacktraceAsString |boolean |Whether to format the stacktrace as a string, and not a nested object (optional, defaults to false). |includeNullDelimiter |boolean |Whether to include NULL byte as delimiter after each event (optional, default to false). |=== To include any custom field in the output, use following syntax: [source,xml] ---- ---- Custom fields are always last, in the order they are declared. The values support link:lookups.html[lookups]. Additional link:../runtime-dependencies.html[runtime dependencies] are required for using YamlLayout. [#LocationInformation] == Location Information If one of the layouts is configured with a location-related attribute like HTML link:#HtmlLocationInfo[locationInfo], or one of the patterns link:#PatternClass[%C or %class], link:#PatternFile[%F or %file], link:#PatternLocation[%l or %location], link:#PatternLine[%L or %line], link:#PatternMethod[%M or %method], Log4j will take a snapshot of the stack, and walk the stack trace to find the location information. This is an expensive operation: 1.3 - 5 times slower for synchronous loggers. Synchronous loggers wait as long as possible before they take this stack snapshot. If no location is required, the snapshot will never be taken. However, asynchronous loggers need to make this decision before passing the log message to another thread; the location information will be lost after that point. The link:../performance.html#asyncLoggingWithLocation[performance impact] of taking a stack trace snapshot is even higher for asynchronous loggers: logging with location is 30-100 times slower than without location. For this reason, asynchronous loggers and asynchronous appenders do not include location information by default. You can override the default behaviour in your logger or asynchronous appender configuration by specifying `includeLocation=""true""`. ",16325,True,3073.30374029097,median "class ZSAPLINK_INTERFACE definition public inheriting from ZSAPLINK create public . public section. type-pools ABAP . type-pools SEOR . type-pools SEOS . type-pools SEOT . methods CHECKEXISTS redefinition . methods CREATEIXMLDOCFROMOBJECT redefinition . methods CREATEOBJECTFROMIXMLDOC redefinition . protected section. methods DELETEOBJECT redefinition . methods GETOBJECTTYPE redefinition . private section. constants XML_KEY_METHOD type STRING value 'method' ##NO_TEXT. constants XML_KEY_PARAMETER type STRING value 'parameter' ##NO_TEXT. constants XML_KEY_EXCEPTION type STRING value 'exception' ##NO_TEXT. constants XML_KEY_EVENTS type STRING value 'events' ##NO_TEXT. constants XML_KEY_ATTRIBUTE type STRING value 'attribute' ##NO_TEXT. constants XML_KEY_TYPEUSAGE type STRING value 'typeUsage' ##NO_TEXT. constants XML_KEY_TYPES type STRING value 'types' ##NO_TEXT. constants XML_KEY_INCLUDE type STRING value 'include' ##NO_TEXT. methods EXPORT_INTERFACES importing !CLASSKEY type SEOCLSKEY exporting !RC type SYSUBRC changing !ROOTNODE type ref to IF_IXML_ELEMENT . methods IMPORT_METHODS changing !CH_METHODS type SEOO_METHODS_R !CH_PARAMETERS type SEOS_PARAMETERS_R !CH_EXCEPS type SEOS_EXCEPTIONS_R . methods IMPORT_ATTRIBUTES changing !CH_ATTRIBUTES type SEOO_ATTRIBUTES_R raising ZCX_SAPLINK . methods IMPORT_INTERFACES changing !CH_COMPRISINGS type SEOR_COMPRISINGS_R . methods IMPORT_TYPES changing !CH_TYPEUSAGES type SEOT_TYPEPUSAGES_R !CH_TYPES type SEOO_TYPES_R . methods IMPORT_EVENTS changing !CH_EVENTS type SEOO_EVENTS_R !CH_PARAMETERS type SEOS_PARAMETERS_R . methods EXPORT_METHODS importing !INTFDESCR type ref to CL_ABAP_INTFDESCR !CLASSNAME type SEOCLSNAME changing !RC type SYSUBRC !ROOTNODE type ref to IF_IXML_ELEMENT . methods EXPORT_EVENTS importing !CLASSKEY type SEOCLSKEY changing !RC type SYSUBRC !ROOTNODE type ref to IF_IXML_ELEMENT . methods EXPORT_ATTRIBUTES importing !INTFDESCR type ref to CL_ABAP_INTFDESCR changing !RC type SYSUBRC !ROOTNODE type ref to IF_IXML_ELEMENT . methods EXPORT_TYPES importing !CLASSKEY type SEOCLSKEY changing !RC type SYSUBRC !ROOTNODE type ref to IF_IXML_ELEMENT . methods EXPORT_TYPEGROUPS importing !CLASSKEY type SEOCLSKEY changing !RC type SYSUBRC !ROOTNODE type ref to IF_IXML_ELEMENT . ENDCLASS. CLASS ZSAPLINK_INTERFACE 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. | *\\---------------------------------------------------------------------/ *Plugin created by Thomas Ritter *Based on work done by: Michael Yakovlev, Edward Herrmann *and other SAPlink contributors data intkey type SEOCLSKEY. data not_active TYPE char1. intkey-clsName = objname. CALL FUNCTION 'SEO_INTERFACE_EXISTENCE_CHECK' EXPORTING intkey = intkey IMPORTING not_active = not_active EXCEPTIONS * NOT_SPECIFIED = 1 NOT_EXISTING = 2 * IS_CLASS = 3 * NO_TEXT = 4 * INCONSISTENT = 5 * OTHERS = 6 . IF sy-subrc <> 2. 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. | *\\---------------------------------------------------------------------/ *Plugin created by Thomas Ritter *Based on work done by: Michael Yakovlev, Edward Herrmann *and other SAPlink contributors data intfsection type ref to if_ixml_element. data rootnode type ref to if_ixml_element. data _classname type seoclsname. data rc type sysubrc. data intfdescr type ref to cl_abap_intfdescr. data typedescr type ref to cl_abap_typedescr. data classkey type seoclskey. data intproperties type vseointerf. data _objtype type string. _classname = objname. classkey-clsname = objname. _objtype = getobjecttype( ). rootnode = xmldoc->create_element( _objtype ). call function 'SEO_INTERFACE_GET' EXPORTING intkey = classkey version = '1' IMPORTING interface = intproperties EXCEPTIONS not_existing = 1 deleted = 2 is_class = 3 model_only = 4 others = 5. if sy-subrc <> 0. case sy-subrc. when 1. raise exception type zcx_SAPlink exporting textid = zcx_SAPlink=>not_found. when 2. raise exception type zcx_SAPlink exporting textid = zcx_SAPlink=>error_message msg = 'interface deleted'. when 3. raise exception type zcx_SAPlink exporting textid = zcx_SAPlink=>error_message msg = 'classes not supported'. when 4. raise exception type zcx_SAPlink exporting textid = zcx_SAPlink=>error_message msg = 'interface is modeled only'. endcase. endif. setattributesfromstructure( node = rootnode structure = intproperties ). try. call method cl_abap_intfdescr=>describe_by_name EXPORTING p_name = objname RECEIVING p_descr_ref = typedescr EXCEPTIONS type_not_found = 1. if sy-subrc = 0. intfdescr ?= typedescr. endif. catch cx_root. raise exception type zcx_SAPlink exporting textid = zcx_SAPlink=>system_error. endtry. *Add included interfaces to the xml document CALL METHOD ME->EXPORT_INTERFACES EXPORTING CLASSKEY = classkey IMPORTING RC = rc CHANGING ROOTNODE = rootnode. *Add types to the xml document CALL METHOD me->EXPORT_TYPES EXPORTING CLASSKEY = classkey CHANGING RC = rc ROOTNODE = rootnode. *Add typegroups to the xml document CALL METHOD me->EXPORT_TYPEGROUPS EXPORTING CLASSKEY = classkey CHANGING RC = rc ROOTNODE = rootnode. *Add events to the xml document CALL METHOD me->EXPORT_EVENTS EXPORTING CLASSKEY = classkey CHANGING RC = rc ROOTNODE = rootnode. *Add attributes to the xml document CALL METHOD me->EXPORT_ATTRIBUTES EXPORTING INTFDESCR = intfdescr CHANGING RC = rc ROOTNODE = rootnode. *Add methods to the xml document CALL METHOD me->EXPORT_METHODS EXPORTING INTFDESCR = intfdescr CLASSNAME = _CLASSNAME CHANGING RC = rc ROOTNODE = rootnode. * append root node to xmldoc rc = xmldoc->append_child( rootnode ). ixmldocument = xmldoc. 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. | *\\---------------------------------------------------------------------/ *Plugin created by Thomas Ritter *Based on work done by: Michael Yakovlev, Edward Herrmann *and other SAPlink contributors data rootnode type ref to if_ixml_element. data classkey type seoclskey. data not_active type boolean. data _devclass type devclass. data _objtype type string. data checkexists type flag. data: e_corrnr type TRKORR, e_devclass type DEVCLASS, e_version type SEOVERSION, e_genflag type GENFLAG, e_authority_check type SEOX_BOOLEAN, e_overwrite type SEOX_BOOLEAN. data: i_korrnr type trkorr. data: ch_interface type VSEOINTERF, ch_comprisings type SEOR_COMPRISINGS_R, ch_attributes type SEOO_ATTRIBUTES_R, ch_methods type SEOO_METHODS_R, ch_events type SEOO_EVENTS_R, ch_parameters type SEOS_PARAMETERS_R, ch_exceps type SEOS_EXCEPTIONS_R, ch_typeusages type SEOT_TYPEPUSAGES_R, ch_types type SEOO_TYPES_R. call function 'SEO_BUFFER_INIT'. e_devclass = devclass. _objtype = getobjecttype( ). e_overwrite = overwrite. _devclass = devclass. _objtype = getobjecttype( ). xmldoc = ixmldocument. rootnode = xmldoc->find_from_name( _objtype ). call method getstructurefromattributes EXPORTING node = rootnode CHANGING structure = ch_interface. 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. if sy-subrc <> 0. case sy-subrc. when 1. 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. *Add attributes to new interface call method import_attributes CHANGING ch_attributes = ch_attributes. *Add includes call method import_interfaces CHANGING ch_comprisings = ch_comprisings. *Add types and type groups call method import_types CHANGING ch_types = ch_types ch_typeusages = ch_typeusages. *Add events and event parameters call method import_events CHANGING ch_events = ch_events ch_parameters = ch_parameters. *Add methods, method parameters and method exceptions call method import_methods CHANGING ch_methods = ch_methods ch_parameters = ch_parameters ch_exceps = ch_exceps. *Create the interface CALL FUNCTION 'SEO_INTERFACE_CREATE_COMPLETE' EXPORTING CORRNR = e_corrnr DEVCLASS = e_devclass VERSION = e_version GENFLAG = e_genflag AUTHORITY_CHECK = e_authority_check OVERWRITE = e_overwrite * SUPPRESS_REFACTORING_SUPPORT = SEOX_TRUE IMPORTING KORRNR = i_korrnr * TABLES * CLASS_DESCRIPTIONS = * COMPONENT_DESCRIPTIONS = * SUBCOMPONENT_DESCRIPTIONS = CHANGING INTERFACE = ch_interface COMPRISINGS = ch_comprisings ATTRIBUTES = ch_attributes METHODS = ch_methods EVENTS = ch_events PARAMETERS = ch_parameters EXCEPS = ch_exceps * ALIASES = TYPEPUSAGES = ch_typeusages * CLSDEFERRDS = * INTDEFERRDS = TYPES = ch_types EXCEPTIONS EXISTING = 1 IS_CLASS = 2 DB_ERROR = 3 COMPONENT_ERROR = 4 NO_ACCESS = 5 OTHER = 6 OTHERS = 7. case sy-subrc. when '0'. ** i guess if we made it this far, we will assume ** successful install name = objname. when '1'. RAISE EXCEPTION TYPE zcx_SAPlink EXPORTING textid = zcx_SAPlink=>existing. when others. raise exception type zcx_SAPlink exporting textid = zcx_SAPlink=>system_error. endcase. 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. | *\\---------------------------------------------------------------------/ *Plugin created by Thomas Ritter *Based on work done by: Michael Yakovlev, Edward Herrmann *and other SAPlink contributors DATA clskey TYPE seoclskey. clskey-clsname = objname. CALL FUNCTION 'SEO_INTERFACE_GET' EXPORTING INTKEY = clskey VERSION = SEOC_VERSION_INACTIVE STATE = '0' EXCEPTIONS NOT_EXISTING = 1 DELETED = 2 IS_CLASS = 3 MODEL_ONLY = 4 OTHERS = 5. IF SY-SUBRC <> 0. RAISE EXCEPTION TYPE zcx_SAPlink EXPORTING textid = zcx_SAPlink=>error_message msg = 'interface not deleted'. ENDIF. CALL FUNCTION 'SEO_INTERFACE_DELETE_W_DEPS' EXPORTING intkey = clskey save = ' ' EXCEPTIONS not_existing = 1 is_class = 2 not_deleted = 3 db_error = 4 OTHERS = 5. IF sy-subrc <> 0. CASE sy-subrc. WHEN 1. RAISE EXCEPTION TYPE zcx_SAPlink EXPORTING textid = zcx_SAPlink=>not_found. WHEN 2. RAISE EXCEPTION TYPE zcx_SAPlink EXPORTING textid = zcx_SAPlink=>error_message msg = 'class not supported'. WHEN 3. RAISE EXCEPTION TYPE zcx_SAPlink EXPORTING textid = zcx_SAPlink=>error_message msg = 'interface not deleted'. WHEN OTHERS. RAISE EXCEPTION TYPE zcx_SAPlink EXPORTING textid = zcx_SAPlink=>system_error. ENDCASE. ENDIF. CALL FUNCTION 'SEO_CLIF_SAVE_ALL' EXPORTING CIFKEY = clskey * CHANGING * CORRNR = corrnr EXCEPTIONS NOT_EXISTING = 1 NOTHING_TO_DO = 2 ACCESS_ERROR = 3 DB_ERROR = 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 EXPORT_ATTRIBUTES. */---------------------------------------------------------------------\\ *| 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. | *\\---------------------------------------------------------------------/ *Plugin created by Thomas Ritter *Based on work done by: Michael Yakovlev, Edward Herrmann *and other SAPlink contributors data: attribkey type seocmpkey, attribdescr type abap_attrdescr, attribnode type ref to if_ixml_element, attribproperties type vseoattrib, _otrguid type sotr_conc, otrnode type ref to if_ixml_element. attribkey-clsname = objname. loop at intfdescr->attributes into attribdescr where is_inherited = abap_false. attribnode = xmldoc->create_element( XML_KEY_ATTRIBUTE ). attribkey-cmpname = attribdescr-name. call function 'SEO_ATTRIBUTE_GET' EXPORTING attkey = attribkey IMPORTING attribute = attribproperties. * include OTR if necessary (for exception classes) if attribproperties-type = 'SOTR_CONC' and attribproperties-attvalue is not initial. _otrguid = attribproperties-attvalue+1(32). otrnode = createnodefromotr( _otrguid ). if otrnode is bound. rc = attribnode->append_child( otrnode ). endif. endif. * append attribute node to parent node setattributesfromstructure( node = attribnode structure = attribproperties ). rc = rootnode->append_child( attribnode ). endloop. endmethod. method EXPORT_EVENTS. */---------------------------------------------------------------------\\ *| 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. | *\\---------------------------------------------------------------------/ *Plugin created by Thomas Ritter *Based on work done by: Michael Yakovlev, Edward Herrmann *and other SAPlink contributors DATA: events TYPE SEOO_EVENTS_R, wa_event LIKE LINE OF events, eventkey type SEOCMPKEY, eventparams type seos_parameters_r, wa_params type seos_parameter_r, event_node TYPE REF TO if_ixml_element, parameternode type ref to if_ixml_element. CALL FUNCTION 'SEO_EVENT_READ_ALL' EXPORTING cifkey = classkey version = 1 IMPORTING events = events EXCEPTIONS clif_not_existing = 1 OTHERS = 2. IF sy-subrc <> 0. ENDIF. LOOP AT events INTO wa_event. eventkey-clsname = wa_event-clsname. eventkey-cmpname = wa_event-CMPNAME. event_node = xmldoc->create_element( XML_KEY_EVENTS ). setattributesfromstructure( node = event_node structure = wa_event ). CALL FUNCTION 'SEO_EVENT_SIGNATURE_GET' EXPORTING EVTKEY = eventkey IMPORTING PARAMETERS = eventparams. * event parameters loop at eventParams into wa_params. parameternode = xmldoc->create_element( XML_KEY_PARAMETER ). setattributesfromstructure( node = parameternode structure = wa_params ). rc = event_node->append_child( parameternode ). ENDLOOP. rc = rootnode->append_child( event_node ). ENDLOOP. endmethod. method EXPORT_INTERFACES. */---------------------------------------------------------------------\\ *| 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. | *\\---------------------------------------------------------------------/ *Plugin created by Thomas Ritter *Based on work done by: Michael Yakovlev, Edward Herrmann *and other SAPlink contributors DATA: it_vseocompri type table of VSEOCOMPRI, wa_vseocompri like line of it_vseocompri, implementingNode TYPE REF TO if_ixml_element, objname type VRSD-OBJNAME. objname = classkey. CALL FUNCTION 'SVRS_GET_VERSION_INTF_40' EXPORTING * DESTINATION = OBJECT_NAME = objname VERSNO = '00000' * IV_NO_RELEASE_TRANSFORMATION = * IMPORTING * INFO_LINE = TABLES * VSMODISRC = * PSEOALIASES = * PVSEOATTRIB = PVSEOCOMPRI = it_vseocompri * PVSEOEVENT = * PVSEOEXCEP = * PVSEOINTERF = * PSMODILOG = * PVSEOMETHOD = * PVSEOPARAM = * PPOOL_SOURCE = * PSOURCE = * PTRDIR = * TYPE_TAB = * PSEOTYPEPLS = EXCEPTIONS NO_VERSION = 1 SYSTEM_FAILURE = 2 COMMUNICATION_FAILURE = 3 OTHERS = 4 . IF SY-SUBRC <> 0. ENDIF. LOOP AT it_vseocompri INTO wa_vseocompri. implementingNode = xmldoc->create_element( XML_KEY_INCLUDE ). setattributesfromstructure( node = implementingNode structure = wa_vseocompri ). rc = rootnode->append_child( implementingNode ). ENDLOOP. endmethod. method EXPORT_METHODS. */---------------------------------------------------------------------\\ *| 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. | *\\---------------------------------------------------------------------/ *Plugin created by Thomas Ritter *Based on work done by: Michael Yakovlev, Edward Herrmann *and other SAPlink contributors data: methoddescr type abap_methdescr, methodkey type seocpdkey, clsmethkey type seocmpkey, methodproperties type vseomethod, paramdescr type abap_parmdescr, paramproperties type vseoparam, paramkey type seoscokey, exceptionlist type seos_exceptions_r, anexception type vseoexcep, exceptionnode type ref to if_ixml_element, parameternode type ref to if_ixml_element, methodnode type ref to if_ixml_element. loop at intfdescr->methods into methoddescr where not ( is_inherited = 'X' and is_redefined is initial ). methodkey-clsname = classname. methodkey-cpdname = methoddescr-name. clsmethkey-clsname = classname. clsmethkey-cmpname = methoddescr-name. clear methodproperties. call function 'SEO_METHOD_GET' EXPORTING mtdkey = clsmethkey IMPORTING method = methodproperties EXCEPTIONS not_existing = 1. if sy-subrc = 0. methodnode = xmldoc->create_element( XML_KEY_METHOD ). setattributesfromstructure( node = methodnode structure = methodproperties ). *add method parameters only when not an alias if methoddescr-alias_for eq ''. loop at methoddescr-parameters into paramdescr. clear paramproperties. parameternode = xmldoc->create_element( XML_KEY_PARAMETER ). paramkey-cmpname = clsmethkey-cmpname. paramkey-sconame = paramdescr-name. paramkey-clsname = objname. call function 'SEO_PARAMETER_GET' EXPORTING parkey = paramkey version = '1' IMPORTING parameter = paramproperties. setattributesfromstructure( node = parameternode structure = paramproperties ). rc = methodnode->append_child( parameternode ). endloop. endif. *add method exceptions call function 'SEO_METHOD_SIGNATURE_GET' EXPORTING mtdkey = clsmethkey version = '1' IMPORTING exceps = exceptionlist. loop at exceptionlist into anexception. exceptionnode = xmldoc->create_element( XML_KEY_EXCEPTION ). setattributesfromstructure( node = exceptionnode structure = anexception ). rc = methodnode->append_child( exceptionnode ). endloop. endif. ""method found rc = rootnode->append_child( methodnode ). endloop. endmethod. method EXPORT_TYPEGROUPS. */---------------------------------------------------------------------\\ *| 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. | *\\---------------------------------------------------------------------/ *Plugin created by Thomas Ritter *Based on work done by: Michael Yakovlev, Edward Herrmann *and other SAPlink contributors data: forwarddeclarationlist type seot_typepusages_r, forwarddeclaration type ref to if_ixml_element, forwarddeclarationrow type seot_typepusage_r. call function 'SEO_TYPEPUSAGE_READ_ALL' EXPORTING cifkey = classkey version = '1' IMPORTING typepusages = forwarddeclarationlist. *comment rrq old way....forwardDeclarations the only attribute *set was the ""TypeGroup"" *the new way....the entire structure is passed as in node typeUsage LOOP AT forwarddeclarationlist INTO forwarddeclarationrow. forwarddeclaration = xmldoc->create_element( XML_KEY_TYPEUSAGE ). setattributesfromstructure( node = forwarddeclaration structure = forwarddeclarationrow ). rc = rootnode->append_child( forwarddeclaration ). ENDLOOP. endmethod. method EXPORT_TYPES. */---------------------------------------------------------------------\\ *| 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. | *\\---------------------------------------------------------------------/ *Plugin created by Thomas Ritter *Based on work done by: Michael Yakovlev, Edward Herrmann *and other SAPlink contributors data: types type seoo_types_r, wa_type like line of types, types_node type ref to if_ixml_element. call function 'SEO_TYPE_READ_ALL' EXPORTING cifkey = classkey version = 1 IMPORTING types = types EXCEPTIONS clif_not_existing = 1 others = 2. if sy-subrc <> 0. endif. loop at types into wa_type. types_node = xmldoc->create_element( XML_KEY_TYPES ). setattributesfromstructure( node = types_node structure = wa_type ). rc = rootnode->append_child( types_node ). endloop. 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. | *\\---------------------------------------------------------------------/ *Plugin created by Thomas Ritter *Based on work done by: Michael Yakovlev, Edward Herrmann *and other SAPlink contributors objecttype = 'INTF'. ""Interface endmethod. method IMPORT_ATTRIBUTES. */---------------------------------------------------------------------\\ *| 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. | *\\---------------------------------------------------------------------/ *Plugin created by Thomas Ritter *Based on work done by: Michael Yakovlev, Edward Herrmann *and other SAPlink contributors data: otrConcept type SOTR_TEXT-CONCEPT, wa_attributes like line of ch_attributes, filter type ref to if_ixml_node_filter, iterator type ref to if_ixml_node_iterator, node type ref to if_ixml_element, otrnode type ref to if_ixml_element. filter = xmldoc->create_filter_name( XML_KEY_ATTRIBUTE ). iterator = xmldoc->create_iterator_filtered( filter ). node ?= iterator->get_next( ). WHILE node IS NOT INITIAL. * create OTR texts if necessary (for exception classes) clear otrConcept. otrnode = node->find_from_name( 'sotr' ). IF otrnode IS NOT INITIAL. me->createotrfromnode( exporting node = otrnode importing concept = otrConcept ). ENDIF. clear wa_attributes. * create attribute CALL METHOD getstructurefromattributes EXPORTING node = node CHANGING structure = wa_attributes. wa_attributes-version = '0'. * ewH:issue33-->6.40 and above, must create new concept if otrConcept is not initial. concatenate `'` otrConcept `'` into wa_attributes-attvalue. endif. append wa_attributes to ch_attributes. node ?= iterator->get_next( ). ENDWHILE. endmethod. method IMPORT_EVENTS. */---------------------------------------------------------------------\\ *| 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. | *\\---------------------------------------------------------------------/ *Plugin created by Thomas Ritter *Based on work done by: Michael Yakovlev, Edward Herrmann *and other SAPlink contributors data: event_filter type ref to if_ixml_node_filter, parameter_filter type ref to if_ixml_node_filter, event_iterator type ref to if_ixml_node_iterator, parameter_iterator type ref to if_ixml_node_iterator, event_node type ref to if_ixml_element, parameter_node type ref to if_ixml_element, wa_events like line of ch_events, wa_parameters like line of ch_parameters. event_filter = xmldoc->create_filter_name( XML_KEY_EVENTS ). event_iterator = xmldoc->create_iterator_filtered( event_filter ). event_node ?= event_iterator->get_next( ). WHILE event_node IS NOT INITIAL. CLEAR wa_events. CALL METHOD getstructurefromattributes EXPORTING node = event_node CHANGING structure = wa_events. append wa_events to ch_events. parameter_filter = event_node->create_filter_name( XML_KEY_PARAMETER ). parameter_iterator = event_node->create_iterator_filtered( parameter_filter ). parameter_node ?= parameter_iterator->get_next( ). WHILE parameter_node IS NOT INITIAL. CLEAR wa_parameters. CALL METHOD getstructurefromattributes EXPORTING node = parameter_node CHANGING structure = wa_parameters. append wa_parameters to ch_parameters. parameter_node ?= parameter_iterator->get_next( ). endwhile. event_node ?= event_iterator->get_next( ). ENDWHILE. endmethod. method IMPORT_INTERFACES. */---------------------------------------------------------------------\\ *| 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. | *\\---------------------------------------------------------------------/ *Plugin created by Thomas Ritter *Based on work done by: Michael Yakovlev, Edward Herrmann *and other SAPlink contributors data: filter type ref to if_ixml_node_filter, iterator type ref to if_ixml_node_iterator, node type ref to if_ixml_element, wa_comprisings like line of ch_comprisings. filter = xmldoc->create_filter_name( XML_KEY_INCLUDE ). iterator = xmldoc->create_iterator_filtered( filter ). node ?= iterator->get_next( ). WHILE node IS NOT INITIAL. CLEAR wa_comprisings. CALL METHOD getstructurefromattributes EXPORTING node = node CHANGING structure = wa_comprisings. wa_comprisings-version = '0'. append wa_comprisings to ch_comprisings. node ?= iterator->get_next( ). ENDWHILE. endmethod. method IMPORT_METHODS. */---------------------------------------------------------------------\\ *| 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. | *\\---------------------------------------------------------------------/ *Plugin created by Thomas Ritter *Based on work done by: Michael Yakovlev, Edward Herrmann *and other SAPlink contributors data: filter type ref to if_ixml_node_filter, filter2 type ref to if_ixml_node_filter, iterator type ref to if_ixml_node_iterator, iterator2 type ref to if_ixml_node_iterator, node type ref to if_ixml_element, node2 type ref to if_ixml_element, wa_parameters like line of ch_parameters, wa_methods like line of ch_methods, wa_exceps like line of ch_exceps. *Add methods to new interface filter = xmldoc->create_filter_name( XML_KEY_METHOD ). iterator = xmldoc->create_iterator_filtered( filter ). node ?= iterator->get_next( ). WHILE node IS NOT INITIAL. CLEAR wa_methods. CALL METHOD getstructurefromattributes EXPORTING node = node CHANGING structure = wa_methods. *Add parameters filter2 = node->create_filter_name( XML_KEY_PARAMETER ). iterator2 = node->create_iterator_filtered( filter2 ). node2 ?= iterator2->get_next( ). WHILE node2 IS NOT INITIAL. CLEAR wa_parameters. CALL METHOD getstructurefromattributes EXPORTING node = node2 CHANGING structure = wa_parameters. append wa_parameters to ch_parameters. node2 ?= iterator2->get_next( ). ENDWHILE. *Add exceptions filter2 = node->create_filter_name( XML_KEY_EXCEPTION ). iterator2 = node->create_iterator_filtered( filter2 ). node2 ?= iterator2->get_next( ). WHILE node2 IS NOT INITIAL. CALL METHOD getstructurefromattributes EXPORTING node = node2 CHANGING structure = wa_exceps. append wa_exceps to ch_exceps. node2 ?= iterator2->get_next( ). ENDWHILE. append wa_methods to ch_methods. node ?= iterator->get_next( ). endwhile. endmethod. method IMPORT_TYPES. */---------------------------------------------------------------------\\ *| 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. | *\\---------------------------------------------------------------------/ *Plugin created by Thomas Ritter *Based on work done by: Michael Yakovlev, Edward Herrmann *and other SAPlink contributors data: filter type ref to if_ixml_node_filter, iterator type ref to if_ixml_node_iterator, node type ref to if_ixml_element, wa_types like line of ch_types, wa_typeusages like line of ch_typeusages. filter = xmldoc->create_filter_name( XML_KEY_TYPES ). iterator = xmldoc->create_iterator_filtered( filter ). node ?= iterator->get_next( ). WHILE node IS NOT INITIAL. CLEAR wa_types. CALL METHOD getstructurefromattributes EXPORTING node = node CHANGING structure = wa_types. wa_types-version = '0'. append wa_types to ch_types. node ?= iterator->get_next( ). ENDWHILE. *ewH: for version 0.1.3, we will continue to generate both nodes * in order for upgradeability of SAPlink itself. For version * 2.0, forwardDeclaration node generations will be deprecated. filter = xmldoc->create_filter_name( XML_KEY_TYPEUSAGE ). iterator = xmldoc->create_iterator_filtered( filter ). node ?= iterator->get_next( ). WHILE node IS NOT INITIAL. CALL METHOD getstructurefromattributes EXPORTING node = node CHANGING structure = wa_typeUsages. APPEND wa_typeusages TO ch_typeusages. node ?= iterator->get_next( ). ENDWHILE. endmethod. ENDCLASS. ",9110,False,2131.4692231921576,median "// ================================================================================================= // // Starling Framework // Copyright Gamua GmbH. All Rights Reserved. // // This program is free software. You can redistribute and/or modify it // in accordance with the terms of the accompanying license agreement. // // ================================================================================================= package starling.core { import flash.display.Shape; import flash.display.Sprite; import flash.display.Stage3D; import flash.display.StageAlign; import flash.display.StageScaleMode; import flash.display3D.Context3D; import flash.display3D.Context3DProfile; import flash.events.ErrorEvent; import flash.events.Event; import flash.events.KeyboardEvent; import flash.events.MouseEvent; import flash.events.TouchEvent; import flash.geom.Matrix; import flash.geom.Point; import flash.geom.Rectangle; import flash.system.Capabilities; import flash.text.TextField; import flash.text.TextFieldAutoSize; import flash.text.TextFormat; import flash.text.TextFormatAlign; import flash.ui.Mouse; import flash.ui.Multitouch; import flash.ui.MultitouchInputMode; import flash.utils.getTimer; import flash.utils.setTimeout; import starling.rendering.VertexData; import starling.animation.Juggler; import starling.display.DisplayObject; import starling.display.Stage; import starling.events.EventDispatcher; import starling.events.ResizeEvent; import starling.events.TouchPhase; import starling.events.TouchProcessor; import starling.rendering.Painter; import starling.textures.TextureSmoothing; import starling.utils.Align; import starling.utils.Color; import starling.utils.MatrixUtil; import starling.utils.Pool; import starling.utils.RectangleUtil; import starling.utils.SystemUtil; /** Dispatched when a new render context is created. The 'data' property references the context. */ [Event(name=""context3DCreate"", type=""starling.events.Event"")] /** Dispatched when the root class has been created. The 'data' property references that object. */ [Event(name=""rootCreated"", type=""starling.events.Event"")] /** Dispatched when a fatal error is encountered. The 'data' property contains an error string. */ [Event(name=""fatalError"", type=""starling.events.Event"")] /** Dispatched when the display list is about to be rendered. This event provides the last * opportunity to make changes before the display list is rendered. */ [Event(name=""render"", type=""starling.events.Event"")] /** The Starling class represents the core of the Starling framework. * *

The Starling framework makes it possible to create 2D applications and games that make * use of the Stage3D architecture introduced in Flash Player 11. It implements a display tree * system that is very similar to that of conventional Flash, while leveraging modern GPUs * to speed up rendering.

* *

The Starling class represents the link between the conventional Flash display tree and * the Starling display tree. To create a Starling-powered application, you have to create * an instance of the Starling class:

* *
var starling:Starling = new Starling(Game, stage);
* *

The first parameter has to be a Starling display object class, e.g. a subclass of * starling.display.Sprite. In the sample above, the class ""Game"" is the * application root. An instance of ""Game"" will be created as soon as Starling is initialized. * The second parameter is the conventional (Flash) stage object. Per default, Starling will * display its contents directly below the stage.

* *

It is recommended to store the Starling instance as a member variable, to make sure * that the Garbage Collector does not destroy it. After creating the Starling object, you * have to start it up like this:

* *
starling.start();
* *

It will now render the contents of the ""Game"" class in the frame rate that is set up for * the application (as defined in the Flash stage).

* * Context3D Profiles * *

Stage3D supports different rendering profiles, and Starling works with all of them. The * last parameter of the Starling constructor allows you to choose which profile you want. * The following profiles are available:

* *
    *
  • BASELINE_CONSTRAINED: provides the broadest hardware reach. If you develop for the * browser, this is the profile you should test with.
  • *
  • BASELINE: recommend for any mobile application, as it allows Starling to use a more * memory efficient texture type (RectangleTextures). It also supports more complex * AGAL code.
  • *
  • BASELINE_EXTENDED: adds support for textures up to 4096x4096 pixels. This is * especially useful on mobile devices with very high resolutions.
  • *
  • STANDARD_CONSTRAINED, STANDARD, STANDARD_EXTENDED: each provide more AGAL features, * among other things. Most Starling games will not gain much from them.
  • *
* *

The recommendation is to deploy your app with the profile ""auto"" (which makes Starling * pick the best available of those), but to test it in all available profiles.

* * Accessing the Starling object * *

From within your application, you can access the current Starling object anytime * through the static method Starling.current. It will return the active Starling * instance (most applications will only have one Starling object, anyway).

* * Viewport * *

The area the Starling content is rendered into is, per default, the complete size of the * stage. You can, however, use the ""viewPort"" property to change it. This can be useful * when you want to render only into a part of the screen, or if the player size changes. For * the latter, you can listen to the RESIZE-event dispatched by the Starling * stage.

* * Native overlay * *

Sometimes you will want to display native Flash content on top of Starling. That's what the * nativeOverlay property is for. It returns a Flash Sprite lying directly * on top of the Starling content. You can add conventional Flash objects to that overlay.

* *

Beware, though, that conventional Flash content on top of 3D content can lead to * performance penalties on some (mobile) platforms. For that reason, always remove all child * objects from the overlay when you don't need them any longer.

* * Multitouch * *

Starling supports multitouch input on devices that provide it. During development, * where most of us are working with a conventional mouse and keyboard, Starling can simulate * multitouch events with the help of the ""Shift"" and ""Ctrl"" (Mac: ""Cmd"") keys. Activate * this feature by enabling the simulateMultitouch property.

* * Skipping Unchanged Frames * *

It happens surprisingly often in an app or game that a scene stays completely static for * several frames. So why redraw the stage at all in those situations? That's exactly the * point of the skipUnchangedFrames-property. If enabled, static scenes are * recognized as such and the back buffer is simply left as it is. On a mobile device, the * impact of this feature can't be overestimated! There's simply no better way to enhance * battery life. Make it a habit to always activate it; look at the documentation of the * corresponding property for details.

* * Handling a lost render context * *

On some operating systems and under certain conditions (e.g. returning from system * sleep), Starling's stage3D render context may be lost. Starling will try to recover * from a lost context automatically; to be able to do this, it will cache textures in * RAM. This will take up quite a bit of extra memory, though, which might be problematic * especially on mobile platforms. To avoid the higher memory footprint, it's recommended * to load your textures with Starling's ""AssetManager""; it is smart enough to recreate a * texture directly from its origin.

* *

In case you want to react to a context loss manually, Starling dispatches an event with * the type ""Event.CONTEXT3D_CREATE"" when the context is restored, and textures will execute * their root.onRestore callback, to which you can attach your own logic. * Refer to the ""Texture"" class for more information.

* * Sharing a 3D Context * *

Per default, Starling handles the Stage3D context itself. If you want to combine * Starling with another Stage3D engine, however, this may not be what you want. In this case, * you can make use of the shareContext property:

* *
    *
  1. Manually create and configure a context3D object that both frameworks can work with * (ideally through RenderUtil.requestContext3D and * context.configureBackBuffer).
  2. *
  3. Initialize Starling with the stage3D instance that contains that configured context. * This will automatically enable shareContext.
  4. *
  5. Call start() on your Starling instance (as usual). This will make * Starling queue input events (keyboard/mouse/touch).
  6. *
  7. Create a game loop (e.g. using the native ENTER_FRAME event) and let it * call Starling's nextFrame as well as the equivalent method of the other * Stage3D engine. Surround those calls with context.clear() and * context.present().
  8. *
* *

The Starling wiki contains a tutorial with more * information about this topic.

* * @see starling.utils.AssetManager * @see starling.textures.Texture * */ public class Starling extends EventDispatcher { /** The version of the Starling framework. */ public static const VERSION:String = ""2.7""; // members private var _stage:Stage; // starling.display.stage! private var _rootClass:Class; private var _root:DisplayObject; private var _juggler:Juggler; private var _painter:Painter; private var _touchProcessor:TouchProcessor; private var _defaultTextureSmoothing:String; private var _antiAliasing:int; private var _frameTimestamp:Number; private var _frameID:uint; private var _leftMouseDown:Boolean; private var _statsDisplay:StatsDisplay; private var _statsDisplayAlign:Object; private var _started:Boolean; private var _rendering:Boolean; private var _supportHighResolutions:Boolean; private var _supportBrowserZoom:Boolean; private var _skipUnchangedFrames:Boolean; private var _showStats:Boolean; private var _supportsCursor:Boolean; private var _multitouchEnabled:Boolean; private var _viewPort:Rectangle; private var _previousViewPort:Rectangle; private var _clippedViewPort:Rectangle; private var _nativeStage:flash.display.Stage; private var _nativeStageEmpty:Boolean; private var _nativeOverlay:Sprite; private static var sCurrent:Starling; private static var sAll:Vector. = new []; // construction /** Creates a new Starling instance. * @param rootClass A subclass of 'starling.display.DisplayObject'. It will be created * as soon as initialization is finished and will become the first child * of the Starling stage. Pass null if you don't want to * create a root object right away. (You can use the * rootClass property later to make that happen.) * @param stage The Flash (2D) stage. * @param viewPort A rectangle describing the area into which the content will be * rendered. Default: stage size * @param stage3D The Stage3D object into which the content will be rendered. If it * already contains a context, sharedContext will be set * to true. Default: the first available Stage3D. * @param renderMode The Context3D render mode that should be requested. * Use this parameter if you want to force ""software"" rendering. * @param profile The Context3D profile that should be requested. * *
    *
  • If you pass a profile String, this profile is enforced.
  • *
  • Pass an Array of profiles to make Starling pick the first * one that works (starting with the first array element).
  • *
  • Pass the String ""auto"" to make Starling pick the best available * profile automatically.
  • *
*/ public function Starling(rootClass:Class, stage:flash.display.Stage, viewPort:Rectangle=null, stage3D:Stage3D=null, renderMode:String=""auto"", profile:Object=""auto"") { if (stage == null) throw new ArgumentError(""Stage must not be null""); if (viewPort == null) viewPort = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); if (stage3D == null) stage3D = stage.stage3Ds[0]; // TODO it might make sense to exchange the 'renderMode' and 'profile' parameters. SystemUtil.initialize(); sAll.push(this); makeCurrent(); _rootClass = rootClass; _viewPort = viewPort; _previousViewPort = new Rectangle(); _stage = new Stage(viewPort.width, viewPort.height, stage.color); _nativeOverlay = new Sprite(); _nativeStage = stage; _nativeStage.addChild(_nativeOverlay); _touchProcessor = new TouchProcessor(_stage); _touchProcessor.discardSystemGestures = !SystemUtil.isDesktop; _juggler = new Juggler(); _antiAliasing = 0; _defaultTextureSmoothing = TextureSmoothing.BILINEAR; _supportHighResolutions = false; _painter = new Painter(stage3D); _frameTimestamp = getTimer() / 1000.0; _frameID = 1; _supportsCursor = Mouse.supportsCursor || Capabilities.os.indexOf(""Windows"") == 0; _statsDisplayAlign = {}; // register appropriate touch/mouse event handlers setMultitouchEnabled(Multitouch.inputMode == MultitouchInputMode.TOUCH_POINT, true); // make the native overlay behave just like one would expect intuitively nativeOverlayBlocksTouches = true; // all other modes are problematic in Starling, so we force those here stage.scaleMode = StageScaleMode.NO_SCALE; stage.align = StageAlign.TOP_LEFT; // register other event handlers stage.addEventListener(Event.ENTER_FRAME, onEnterFrame, false, 0, true); stage.addEventListener(KeyboardEvent.KEY_DOWN, onKey, false, 0, true); stage.addEventListener(KeyboardEvent.KEY_UP, onKey, false, 0, true); stage.addEventListener(Event.RESIZE, onResize, false, 0, true); stage.addEventListener(Event.MOUSE_LEAVE, onMouseLeave, false, 0, true); stage.addEventListener(Event.ACTIVATE, onActivate, false, 0, true); stage3D.addEventListener(Event.CONTEXT3D_CREATE, onContextCreated, false, 10, true); stage3D.addEventListener(ErrorEvent.ERROR, onStage3DError, false, 10, true); var runtimeVersion:int = parseInt(SystemUtil.version.split("","").shift()); if (runtimeVersion < 19) { var runtime:String = SystemUtil.isAIR ? ""Adobe AIR"" : ""Flash Player""; stopWithFatalError( ""Your "" + runtime + "" installation is outdated. "" + ""This software requires at least version 19.""); } else if (_painter.shareContext) { setTimeout(initialize, 1); // we don't call it right away, because Starling should // behave the same way with or without a shared context } else { _painter.requestContext3D(renderMode, profile); } } /** Disposes all children of the stage and the render context; removes all registered * event listeners. */ public function dispose():void { stop(true); _nativeStage.removeEventListener(Event.ENTER_FRAME, onEnterFrame, false); _nativeStage.removeEventListener(KeyboardEvent.KEY_DOWN, onKey, false); _nativeStage.removeEventListener(KeyboardEvent.KEY_UP, onKey, false); _nativeStage.removeEventListener(Event.RESIZE, onResize, false); _nativeStage.removeEventListener(Event.MOUSE_LEAVE, onMouseLeave, false); _nativeStage.removeEventListener(Event.BROWSER_ZOOM_CHANGE, onBrowserZoomChange, false); _nativeStage.removeChild(_nativeOverlay); stage3D.removeEventListener(Event.CONTEXT3D_CREATE, onContextCreated, false); stage3D.removeEventListener(Event.CONTEXT3D_CREATE, onContextRestored, false); stage3D.removeEventListener(ErrorEvent.ERROR, onStage3DError, false); for each (var touchEventType:String in getTouchEventTypes(_multitouchEnabled)) _nativeStage.removeEventListener(touchEventType, onTouch, false); _touchProcessor.dispose(); _stage.dispose(); _painter.dispose(); var index:int = sAll.indexOf(this); if (index != -1) sAll.removeAt(index); if (sCurrent == this) sCurrent = null; } // functions private function initialize():void { makeCurrent(); updateViewPort(true); // ideal time: after viewPort setup, before root creation dispatchEventWith(Event.CONTEXT3D_CREATE, false, context); initializeRoot(); _frameTimestamp = getTimer() / 1000.0; } private function initializeRoot():void { if (_root == null && _rootClass != null) { _root = new _rootClass() as DisplayObject; if (_root == null) throw new Error(""Invalid root class: "" + _rootClass); _stage.addChildAt(_root, 0); dispatchEventWith(starling.events.Event.ROOT_CREATED, false, _root); } } /** Calls advanceTime() (with the time that has passed since the last frame) * and render(). */ public function nextFrame():void { var now:Number = getTimer() / 1000.0; var passedTime:Number = now - _frameTimestamp; _frameTimestamp = now; // to avoid overloading time-based animations, the maximum delta is truncated. if (passedTime > 1.0) passedTime = 1.0; // after about 25 days, 'getTimer()' will roll over. A rare event, but still ... if (passedTime < 0.0) passedTime = 1.0 / _nativeStage.frameRate; advanceTime(passedTime); render(); } /** Dispatches ENTER_FRAME events on the display list, advances the Juggler * and processes touches. */ public function advanceTime(passedTime:Number):void { if (!contextValid) return; makeCurrent(); _touchProcessor.advanceTime(passedTime); _stage.advanceTime(passedTime); _juggler.advanceTime(passedTime); } /** Renders the complete display list. Before rendering, the context is cleared; afterwards, * it is presented (to avoid this, enable shareContext). * *

This method also dispatches an Event.RENDER-event on the Starling * instance. That's the last opportunity to make changes before the display list is * rendered.

*/ public function render():void { if (!contextValid) return; makeCurrent(); updateViewPort(); var doRedraw:Boolean = _stage.requiresRedraw || mustAlwaysRender; if (doRedraw) { dispatchEventWith(starling.events.Event.RENDER); var shareContext:Boolean = _painter.shareContext; var scaleX:Number = _viewPort.width / _stage.stageWidth; var scaleY:Number = _viewPort.height / _stage.stageHeight; var stageColor:uint = _stage.color; _painter.nextFrame(); _painter.pixelSize = 1.0 / contentScaleFactor; _painter.state.setProjectionMatrix( _viewPort.x < 0 ? -_viewPort.x / scaleX : 0.0, _viewPort.y < 0 ? -_viewPort.y / scaleY : 0.0, _clippedViewPort.width / scaleX, _clippedViewPort.height / scaleY, _stage.stageWidth, _stage.stageHeight, _stage.cameraPosition); if (!shareContext) _painter.clear(stageColor, Color.getAlpha(stageColor)); _stage.render(_painter); VertexData.starling_internal::unassignDomainMemory(); _painter.finishFrame(); _painter.frameID = ++_frameID; if (!shareContext) _painter.present(); } else dispatchEventWith(starling.events.Event.SKIP_FRAME); if (_statsDisplay) _statsDisplay.drawCount = _painter.drawCount; } private function updateViewPort(forceUpdate:Boolean=false):void { // the last set viewport is stored in a variable; that way, people can modify the // viewPort directly (without a copy) and we still know if it has changed. if (forceUpdate || !RectangleUtil.compare(_viewPort, _previousViewPort)) { _previousViewPort.setTo(_viewPort.x, _viewPort.y, _viewPort.width, _viewPort.height); // Constrained mode requires that the viewport is within the native stage bounds; // thus, we use a clipped viewport when configuring the back buffer. (In baseline // mode, that's not necessary, but it does not hurt either.) updateClippedViewPort(); updateStatsDisplayPosition(); var contentScaleFactor:Number = _supportHighResolutions ? _nativeStage.contentsScaleFactor : 1.0; if (_supportBrowserZoom) contentScaleFactor *= _nativeStage.browserZoomFactor; _painter.configureBackBuffer(_clippedViewPort, contentScaleFactor, _antiAliasing, true, _supportBrowserZoom); setRequiresRedraw(); } } private function updateClippedViewPort():void { var stageBounds:Rectangle = Pool.getRectangle(0, 0, _nativeStage.stageWidth, _nativeStage.stageHeight); _clippedViewPort = RectangleUtil.intersect(_viewPort, stageBounds, _clippedViewPort); if (_clippedViewPort.width < 32) _clippedViewPort.width = 32; if (_clippedViewPort.height < 32) _clippedViewPort.height = 32; Pool.putRectangle(stageBounds); } private function updateNativeOverlay():void { _nativeOverlay.x = _viewPort.x; _nativeOverlay.y = _viewPort.y; _nativeOverlay.scaleX = _viewPort.width / _stage.stageWidth; _nativeOverlay.scaleY = _viewPort.height / _stage.stageHeight; } /** Stops Starling right away and displays an error message on the native overlay. * This method will also cause Starling to dispatch a FATAL_ERROR event. */ public function stopWithFatalError(message:String):void { var background:Shape = new Shape(); background.graphics.beginFill(0x0, 0.8); background.graphics.drawRect(0, 0, _stage.stageWidth, _stage.stageHeight); background.graphics.endFill(); var textField:TextField = new TextField(); var textFormat:TextFormat = new TextFormat(""Verdana"", 14, 0xFFFFFF); textFormat.align = TextFormatAlign.CENTER; textField.defaultTextFormat = textFormat; textField.wordWrap = true; textField.width = _stage.stageWidth * 0.75; textField.autoSize = TextFieldAutoSize.CENTER; textField.text = message; textField.x = (_stage.stageWidth - textField.width) / 2; textField.y = (_stage.stageHeight - textField.height) / 2; textField.background = true; textField.backgroundColor = 0x550000; updateNativeOverlay(); nativeOverlay.addChild(background); nativeOverlay.addChild(textField); stop(true); trace(""[Starling]"", message); dispatchEventWith(starling.events.Event.FATAL_ERROR, false, message); } /** Make this Starling instance the current one. */ public function makeCurrent():void { sCurrent = this; } /** As soon as Starling is started, it will queue input events (keyboard/mouse/touch); * furthermore, the method nextFrame will be called once per Flash Player * frame. (Except when shareContext is enabled: in that case, you have to * call that method manually.) */ public function start():void { _started = _rendering = true; _frameTimestamp = getTimer() / 1000.0; } /** Stops all logic and input processing, effectively freezing the app in its current state. * Per default, rendering will continue: that's because the classic display list * is only updated when stage3D is. (If Starling stopped rendering, conventional Flash * contents would freeze, as well.) * *

However, if you don't need classic Flash contents, you can stop rendering, too. * On some mobile systems (e.g. iOS), you are even required to do so if you have * activated background code execution.

*/ public function stop(suspendRendering:Boolean=false):void { _started = false; _rendering = !suspendRendering; } /** Makes sure that the next frame is actually rendered. * *

When skipUnchangedFrames is enabled, some situations require that you * manually force a redraw, e.g. when a RenderTexture is changed. This method is the * easiest way to do so; it's just a shortcut to stage.setRequiresRedraw(). *

*/ public function setRequiresRedraw():void { _stage.setRequiresRedraw(); } // event handlers private function onStage3DError(event:ErrorEvent):void { if (event.errorID == 3702) { var mode:String = Capabilities.playerType == ""Desktop"" ? ""renderMode"" : ""wmode""; stopWithFatalError(""Context3D not available! Possible reasons: wrong "" + mode + "" or missing device support.""); } else stopWithFatalError(""Stage3D error: "" + event.text); } private function onContextCreated(event:Event):void { stage3D.removeEventListener(Event.CONTEXT3D_CREATE, onContextCreated); stage3D.addEventListener(Event.CONTEXT3D_CREATE, onContextRestored, false, 10, true); trace(""[Starling] Context ready. Display Driver:"", context.driverInfo); initialize(); } private function onContextRestored(event:Event):void { trace(""[Starling] Context restored.""); updateViewPort(true); _painter.setupContextDefaults(); dispatchEventWith(Event.CONTEXT3D_CREATE, false, context); } private function onEnterFrame(event:Event):void { // On mobile, the native display list is only updated on stage3D draw calls. // Thus, we render even when Starling is paused. if (!shareContext) { if (_started) nextFrame(); else if (_rendering) render(); } updateNativeOverlay(); } private function onActivate(event:Event):void { // with 'skipUnchangedFrames' enabled, a forced redraw is required when the app // is restored on some platforms (namely Windows with BASELINE_CONSTRAINED profile // and some Android versions). setTimeout(setRequiresRedraw, 100); } private function onKey(event:KeyboardEvent):void { if (!_started) return; var keyEvent:starling.events.KeyboardEvent = new starling.events.KeyboardEvent( event.type, event.charCode, event.keyCode, event.keyLocation, event.ctrlKey, event.altKey, event.shiftKey); makeCurrent(); _stage.dispatchEvent(keyEvent); if (keyEvent.isDefaultPrevented()) event.preventDefault(); } private function onResize(event:Event):void { var stageWidth:int = event.target.stageWidth; var stageHeight:int = event.target.stageHeight; if (contextValid) dispatchResizeEvent(); else addEventListener(Event.CONTEXT3D_CREATE, dispatchResizeEvent); function dispatchResizeEvent():void { // on Android, the context is not valid while we're resizing. To avoid problems // with user code, we delay the event dispatching until it becomes valid again. makeCurrent(); removeEventListener(Event.CONTEXT3D_CREATE, dispatchResizeEvent); _stage.dispatchEvent(new ResizeEvent(Event.RESIZE, stageWidth, stageHeight)); } } private function onBrowserZoomChange(event:Event):void { _painter.refreshBackBufferSize( _nativeStage.contentsScaleFactor * _nativeStage.browserZoomFactor); } private function onMouseLeave(event:Event):void { _touchProcessor.enqueueMouseLeftStage(); } private function onTouch(event:Event):void { if (!_started) return; var globalX:Number; var globalY:Number; var touchID:int; var phase:String; var pressure:Number = 1.0; var width:Number = 1.0; var height:Number = 1.0; // figure out general touch properties if (event is MouseEvent) { var mouseEvent:MouseEvent = event as MouseEvent; globalX = mouseEvent.stageX; globalY = mouseEvent.stageY; touchID = 0; // MouseEvent.buttonDown returns true for both left and right button (AIR supports // the right mouse button). We only want to react on the left button for now, // so we have to save the state for the left button manually. if (event.type == MouseEvent.MOUSE_DOWN) _leftMouseDown = true; else if (event.type == MouseEvent.MOUSE_UP) _leftMouseDown = false; } else { var touchEvent:TouchEvent = event as TouchEvent; // On a system that supports both mouse and touch input, the primary touch point // is dispatched as mouse event as well. Since we don't want to listen to that // event twice, we ignore the primary touch in that case. if (_supportsCursor && touchEvent.isPrimaryTouchPoint) return; else { globalX = touchEvent.stageX; globalY = touchEvent.stageY; touchID = touchEvent.touchPointID; pressure = touchEvent.pressure; width = touchEvent.sizeX; height = touchEvent.sizeY; } } // figure out touch phase switch (event.type) { case TouchEvent.TOUCH_BEGIN: phase = TouchPhase.BEGAN; break; case TouchEvent.TOUCH_MOVE: phase = TouchPhase.MOVED; break; case TouchEvent.TOUCH_END: phase = TouchPhase.ENDED; break; case MouseEvent.MOUSE_DOWN: phase = TouchPhase.BEGAN; break; case MouseEvent.MOUSE_UP: phase = TouchPhase.ENDED; break; case MouseEvent.MOUSE_MOVE: phase = (_leftMouseDown ? TouchPhase.MOVED : TouchPhase.HOVER); break; } // move position into viewport bounds globalX = _stage.stageWidth * (globalX - _viewPort.x) / _viewPort.width; globalY = _stage.stageHeight * (globalY - _viewPort.y) / _viewPort.height; // enqueue touch in touch processor _touchProcessor.enqueue(touchID, phase, globalX, globalY, pressure, width, height); // allow objects that depend on mouse-over state to be updated immediately if (event.type == MouseEvent.MOUSE_UP && _supportsCursor) _touchProcessor.enqueue(touchID, TouchPhase.HOVER, globalX, globalY); } private function hitTestNativeOverlay(localX:Number, localY:Number):Boolean { if (_nativeOverlay.numChildren) { var globalPos:Point = Pool.getPoint(); var matrix:Matrix = Pool.getMatrix( _nativeOverlay.scaleX, 0, 0, _nativeOverlay.scaleY, _nativeOverlay.x, _nativeOverlay.y); MatrixUtil.transformCoords(matrix, localX, localY, globalPos); var result:Boolean = _nativeOverlay.hitTestPoint(globalPos.x, globalPos.y, true); Pool.putPoint(globalPos); Pool.putMatrix(matrix); return result; } else return false; } private function setMultitouchEnabled(value:Boolean, forceUpdate:Boolean=false):void { if (forceUpdate || value != _multitouchEnabled) { var oldEventTypes:Array = getTouchEventTypes(_multitouchEnabled); var newEventTypes:Array = getTouchEventTypes(value); for each (var oldEventType:String in oldEventTypes) _nativeStage.removeEventListener(oldEventType, onTouch); for each (var newEventType:String in newEventTypes) _nativeStage.addEventListener(newEventType, onTouch, false, 0, true); _touchProcessor.cancelTouches(); _multitouchEnabled = value; } } private function getTouchEventTypes(multitouchEnabled:Boolean):Array { var types:Array = []; if (multitouchEnabled) types.push(TouchEvent.TOUCH_BEGIN, TouchEvent.TOUCH_MOVE, TouchEvent.TOUCH_END); if (!multitouchEnabled || _supportsCursor) types.push(MouseEvent.MOUSE_DOWN, MouseEvent.MOUSE_MOVE, MouseEvent.MOUSE_UP); return types; } private function get mustAlwaysRender():Boolean { // On mobile, and in some browsers with the ""baselineConstrained"" profile, the // standard display list is only rendered after calling ""context.present()"". // In such a case, we cannot omit frames if there is any content on the stage. if (!_skipUnchangedFrames || _painter.shareContext) return true; else if (SystemUtil.isDesktop && profile != Context3DProfile.BASELINE_CONSTRAINED) return false; else { // Rendering can be skipped when both this and previous frame are empty. var nativeStageEmpty:Boolean = isNativeDisplayObjectEmpty(_nativeStage); var mustAlwaysRender:Boolean = !nativeStageEmpty || !_nativeStageEmpty; _nativeStageEmpty = nativeStageEmpty; return mustAlwaysRender; } } // properties /** Indicates if this Starling instance is started. */ public function get isStarted():Boolean { return _started; } /** The default juggler of this instance. Will be advanced once per frame. */ public function get juggler():Juggler { return _juggler; } /** The painter, which is used for all rendering. The same instance is passed to all * rendermethods each frame. */ public function get painter():Painter { return _painter; } /** The render context of this instance. */ public function get context():Context3D { return _painter.context; } /** Indicates if multitouch simulation with ""Shift"" and ""Ctrl""/""Cmd""-keys is enabled. * @default false */ public function get simulateMultitouch():Boolean { return _touchProcessor.simulateMultitouch; } public function set simulateMultitouch(value:Boolean):void { _touchProcessor.simulateMultitouch = value; } /** Indicates if Stage3D render methods will report errors. It's recommended to activate * this when writing custom rendering code (shaders, etc.), since you'll get more detailed * error messages. However, it has a very negative impact on performance, and it prevents * ATF textures from being restored on a context loss. Never activate for release builds! * * @default false */ public function get enableErrorChecking():Boolean { return _painter.enableErrorChecking; } public function set enableErrorChecking(value:Boolean):void { _painter.enableErrorChecking = value; } /** The anti-aliasing level. 0 - none, 16 - maximum. @default 0 */ public function get antiAliasing():int { return _antiAliasing; } public function set antiAliasing(value:int):void { if (_antiAliasing != value) { _antiAliasing = value; if (contextValid) updateViewPort(true); } } /** The default texture smoothing. This value will be used as the default value when * creating 'MeshStyle', 'FragmentFilter' or 'FilterEffect'. * Changing it won't have any impact on the existing meshes & filters. * @default ""bilinear"" */ public function get defaultTextureSmoothing():String { return _defaultTextureSmoothing; } public function set defaultTextureSmoothing(value:String):void { if (!TextureSmoothing.isValid(value)) throw new ArgumentError(""Invalid texture smoothing: "" + value); _defaultTextureSmoothing = value; } /** The viewport into which Starling contents will be rendered. */ public function get viewPort():Rectangle { return _viewPort; } public function set viewPort(value:Rectangle):void { _viewPort.copyFrom(value); } /** The ratio between viewPort width and stage width. Useful for choosing a different * set of textures depending on the display resolution. */ public function get contentScaleFactor():Number { return (_viewPort.width * _painter.backBufferScaleFactor) / _stage.stageWidth; } /** A Flash Sprite placed directly on top of the Starling content. Use it to display native * Flash components. */ public function get nativeOverlay():Sprite { return _nativeOverlay; } /** If enabled, touches or mouse events on the native overlay won't be propagated to * Starling. @default true */ public function get nativeOverlayBlocksTouches():Boolean { return _touchProcessor.occlusionTest != null; } public function set nativeOverlayBlocksTouches(value:Boolean):void { if (value != this.nativeOverlayBlocksTouches) _touchProcessor.occlusionTest = value ? hitTestNativeOverlay : null; } /** Indicates if a small statistics box (with FPS, memory usage and draw count) is * displayed. * *

When the box turns dark green, more than 50% of the frames since the box' last * update could skip rendering altogether. This will only happen if the property * skipUnchangedFrames is enabled.

* *

Beware that the memory usage should be taken with a grain of salt. The value is * determined via System.totalMemory and does not take texture memory * into account. It is recommended to use Adobe Scout for reliable and comprehensive * memory analysis.

*/ public function get showStats():Boolean { return _showStats; } public function set showStats(value:Boolean):void { _showStats = value; if (value) { showStatsAt(_statsDisplayAlign.horizontal || ""left"", _statsDisplayAlign.vertical || ""top""); } else if (_statsDisplay) { _statsDisplay.removeFromParent(); } } /** Displays the statistics box at a certain position. */ public function showStatsAt(horizontalAlign:String=""left"", verticalAlign:String=""top"", scale:Number=1):void { _showStats = true; _statsDisplayAlign.horizontal = horizontalAlign; _statsDisplayAlign.vertical = verticalAlign; if (context == null) { // Starling is not yet ready - we postpone this until it's initialized. addEventListener(starling.events.Event.ROOT_CREATED, onRootCreated); } else { if (_statsDisplay == null) { _statsDisplay = new StatsDisplay(); _statsDisplay.touchable = false; } _stage.addChild(_statsDisplay); _statsDisplay.scaleX = _statsDisplay.scaleY = scale; _statsDisplay.showSkipped = _skipUnchangedFrames; updateClippedViewPort(); updateStatsDisplayPosition(); } function onRootCreated():void { if (_showStats) showStatsAt(horizontalAlign, verticalAlign, scale); removeEventListener(starling.events.Event.ROOT_CREATED, onRootCreated); } } private function updateStatsDisplayPosition():void { if (!_showStats || _statsDisplay == null) return; // The stats display must always be visible, i.e. inside the clipped viewPort. // So we take viewPort clipping into account when calculating its position. var horizontalAlign:String = _statsDisplayAlign.horizontal; var verticalAlign:String = _statsDisplayAlign.vertical; var scaleX:Number = _viewPort.width / _stage.stageWidth; var scaleY:Number = _viewPort.height / _stage.stageHeight; var clipping:Rectangle = Pool.getRectangle( _viewPort.x < 0 ? -_viewPort.x / scaleX : 0.0, _viewPort.y < 0 ? -_viewPort.y / scaleY : 0.0, _clippedViewPort.width / scaleX, _clippedViewPort.height / scaleY); if (horizontalAlign == Align.LEFT) _statsDisplay.x = clipping.x; else if (horizontalAlign == Align.RIGHT) _statsDisplay.x = clipping.right - _statsDisplay.width; else if (horizontalAlign == Align.CENTER) _statsDisplay.x = (clipping.right - _statsDisplay.width) / 2; else throw new ArgumentError(""Invalid horizontal alignment: "" + horizontalAlign); if (verticalAlign == Align.TOP) _statsDisplay.y = clipping.y; else if (verticalAlign == Align.BOTTOM) _statsDisplay.y = clipping.bottom - _statsDisplay.height; else if (verticalAlign == Align.CENTER) _statsDisplay.y = (clipping.bottom - _statsDisplay.height) / 2; else throw new ArgumentError(""Invalid vertical alignment: "" + verticalAlign); Pool.putRectangle(clipping); } /** The Starling stage object, which is the root of the display tree that is rendered. */ public function get stage():Stage { return _stage; } /** The Flash Stage3D object Starling renders into. */ public function get stage3D():Stage3D { return _painter.stage3D; } /** The Flash (2D) stage object Starling renders beneath. */ public function get nativeStage():flash.display.Stage { return _nativeStage; } /** The instance of the root class provided in the constructor. Available as soon as * the event 'ROOT_CREATED' has been dispatched. */ public function get root():DisplayObject { return _root; } /** The class that will be instantiated by Starling as the 'root' display object. * Must be a subclass of 'starling.display.DisplayObject'. * *

If you passed null as first parameter to the Starling constructor, * you can use this property to set the root class at a later time. As soon as the class * is instantiated, Starling will dispatch a ROOT_CREATED event.

* *

Beware: you cannot change the root class once the root object has been * instantiated.

*/ public function get rootClass():Class { return _rootClass; } public function set rootClass(value:Class):void { if (_rootClass != null && _root != null) throw new Error(""Root class may not change after root has been instantiated""); else if (_rootClass == null) { _rootClass = value; if (context) initializeRoot(); } } /** Indicates if another Starling instance (or another Stage3D framework altogether) * uses the same render context. If enabled, Starling will not execute any destructive * context operations (e.g. not call 'configureBackBuffer', 'clear', 'present', etc. * This has to be done manually, then. @default false */ public function get shareContext():Boolean { return _painter.shareContext; } public function set shareContext(value:Boolean):void { if (!value) _previousViewPort.setEmpty(); // forces back buffer update _painter.shareContext = value; } /** The Context3D profile of the current render context, or null * if the context has not been created yet. */ public function get profile():String { return _painter.profile; } /** Indicates that if the device supports HiDPI screens Starling will attempt to allocate * a larger back buffer than indicated via the viewPort size. Note that this is used * on Desktop only; mobile AIR apps still use the ""requestedDisplayResolution"" parameter * the application descriptor XML. @default false */ public function get supportHighResolutions():Boolean { return _supportHighResolutions; } public function set supportHighResolutions(value:Boolean):void { if (_supportHighResolutions != value) { _supportHighResolutions = value; if (contextValid) updateViewPort(true); } } /** If enabled, the Stage3D back buffer will change its size according to the browser zoom * value - similar to what's done when ""supportHighResolutions"" is enabled. The resolution * is updated on the fly when the zoom factor changes. Only relevant for the browser plugin. * @default false */ public function get supportBrowserZoom():Boolean { return _supportBrowserZoom; } public function set supportBrowserZoom(value:Boolean):void { if (_supportBrowserZoom != value) { _supportBrowserZoom = value; if (contextValid) updateViewPort(true); if (value) _nativeStage.addEventListener( Event.BROWSER_ZOOM_CHANGE, onBrowserZoomChange, false, 0, true); else _nativeStage.removeEventListener( Event.BROWSER_ZOOM_CHANGE, onBrowserZoomChange, false); } } /** When enabled, Starling will skip rendering the stage if it hasn't changed since the * last frame. This is great for apps that remain static from time to time, since it will * greatly reduce power consumption. You should activate this whenever possible! * *

The reason why it's disabled by default is just that it causes problems with Render- * and VideoTextures. When you use those, you either have to disable this property * temporarily, or call setRequiresRedraw() (ideally on the stage) whenever * those textures are changing. Otherwise, the changes won't show up.

* * @default false */ public function get skipUnchangedFrames():Boolean { return _skipUnchangedFrames; } public function set skipUnchangedFrames(value:Boolean):void { _skipUnchangedFrames = value; _nativeStageEmpty = false; // required by 'mustAlwaysRender' if (_statsDisplay) _statsDisplay.showSkipped = value; } /** The TouchProcessor is passed all mouse and touch input and is responsible for * dispatching TouchEvents to the Starling display tree. If you want to handle these * types of input manually, pass your own custom subclass to this property. */ public function get touchProcessor():TouchProcessor { return _touchProcessor; } public function set touchProcessor(value:TouchProcessor):void { if (value == null) throw new ArgumentError(""TouchProcessor must not be null""); else if (value != _touchProcessor) { _touchProcessor.dispose(); _touchProcessor = value; } } /** When enabled, all touches that start very close to the screen edges are discarded. * On mobile, such touches often indicate swipes that are meant to use OS features. * Per default, margins of 15 points at the top, bottom, and left side of the screen are * checked. Call starling.touchProcessor.setSystemGestureMargins() to adapt * the margins in each direction. @default true on mobile, false on desktop */ public function get discardSystemGestures():Boolean { return _touchProcessor.discardSystemGestures; } public function set discardSystemGestures(value:Boolean):void { _touchProcessor.discardSystemGestures = value; } /** The number of frames that have been rendered since this instance was created. */ public function get frameID():uint { return _frameID; } /** Indicates if the Context3D object is currently valid (i.e. it hasn't been lost or * disposed). */ public function get contextValid():Boolean { return _painter.contextValid; } // static properties /** The currently active Starling instance. */ public static function get current():Starling { return sCurrent; } /** All Starling instances.

CAUTION: not a copy, but the actual object! Do not modify!

*/ public static function get all():Vector. { return sAll; } /** The render context of the currently active Starling instance. */ public static function get context():Context3D { return sCurrent ? sCurrent.context : null; } /** The default juggler of the currently active Starling instance. */ public static function get juggler():Juggler { return sCurrent ? sCurrent._juggler : null; } /** The painter used for all rendering of the currently active Starling instance. */ public static function get painter():Painter { return sCurrent ? sCurrent._painter : null; } /** The contentScaleFactor of the currently active Starling instance. */ public static function get contentScaleFactor():Number { return sCurrent ? sCurrent.contentScaleFactor : 1.0; } /** Indicates if multitouch input should be supported. You can enable or disable * multitouch at any time; just beware that any current touches will be cancelled. */ public static function get multitouchEnabled():Boolean { var enabled:Boolean = Multitouch.inputMode == MultitouchInputMode.TOUCH_POINT; var outOfSync:Boolean = false; for each (var star:Starling in sAll) if (star._multitouchEnabled != enabled) outOfSync = true; if (outOfSync) trace(""[Starling] Warning: multitouch settings are out of sync. Always set "" + ""'Starling.multitouchEnabled' instead of 'Multitouch.inputMode'.""); return enabled; } public static function set multitouchEnabled(value:Boolean):void { var wasEnabled:Boolean = Multitouch.inputMode == MultitouchInputMode.TOUCH_POINT; Multitouch.inputMode = value ? MultitouchInputMode.TOUCH_POINT : MultitouchInputMode.NONE; var isEnabled:Boolean = Multitouch.inputMode == MultitouchInputMode.TOUCH_POINT; if (wasEnabled != isEnabled) { for each (var star:Starling in sAll) star.setMultitouchEnabled(isEnabled); } } /** The number of frames that have been rendered since the current instance was created. */ public static function get frameID():uint { return sCurrent ? sCurrent._frameID : 0; } } } import flash.display.DisplayObject; import flash.display.DisplayObjectContainer; // put here to avoid naming conflicts function isNativeDisplayObjectEmpty(object:DisplayObject):Boolean { if (object == null) return true; else if (object is DisplayObjectContainer) { var container:DisplayObjectContainer = object as DisplayObjectContainer; var numChildren:int = container.numChildren; for (var i:int=0; ity_post_data . METHODS set_only_favorites IMPORTING iv_only_favorites TYPE abap_bool. METHODS get_only_favorites RETURNING VALUE(rv_result) TYPE abap_bool. PROTECTED SECTION. PRIVATE SECTION. TYPES: BEGIN OF ty_overview, favorite TYPE string, ""! True for offline, false for online repo type TYPE string, key TYPE zif_abapgit_persistence=>ty_value, name TYPE string, url TYPE string, package TYPE devclass, branch TYPE string, created_by TYPE xubname, created_at TYPE string, deserialized_by TYPE xubname, deserialized_at TYPE string, write_protected TYPE abap_bool, END OF ty_overview, ty_overviews TYPE STANDARD TABLE OF ty_overview WITH NON-UNIQUE DEFAULT KEY. CONSTANTS: BEGIN OF c_action, select TYPE string VALUE 'select', apply_filter TYPE string VALUE 'apply_filter', END OF c_action . DATA: mv_order_descending TYPE abap_bool, mv_filter TYPE string, mv_time_zone TYPE timezone, mt_col_spec TYPE zif_abapgit_definitions=>ty_col_spec_tt, mt_overview TYPE ty_overviews. METHODS: render_text_input IMPORTING iv_name TYPE string iv_label TYPE string iv_value TYPE string OPTIONAL iv_max_length TYPE string OPTIONAL !iv_autofocus TYPE abap_bool DEFAULT abap_false RETURNING VALUE(ri_html) TYPE REF TO zif_abapgit_html, apply_filter CHANGING ct_overview TYPE ty_overviews, map_repo_list_to_overview RETURNING VALUE(rt_overview) TYPE ty_overviews RAISING zcx_abapgit_exception, render_table_header IMPORTING ii_html TYPE REF TO zif_abapgit_html, render_table IMPORTING ii_html TYPE REF TO zif_abapgit_html it_overview TYPE ty_overviews RAISING zcx_abapgit_exception, render_table_body IMPORTING ii_html TYPE REF TO zif_abapgit_html it_repo_list TYPE ty_overviews RAISING zcx_abapgit_exception, render_header_bar IMPORTING ii_html TYPE REF TO zif_abapgit_html, apply_order_by CHANGING ct_overview TYPE ty_overviews, _add_column IMPORTING iv_tech_name TYPE string OPTIONAL iv_display_name TYPE string OPTIONAL iv_css_class TYPE string OPTIONAL iv_add_tz TYPE abap_bool OPTIONAL iv_title TYPE string OPTIONAL iv_allow_order_by TYPE any OPTIONAL. METHODS render_scripts RETURNING VALUE(ri_html) TYPE REF TO zif_abapgit_html RAISING zcx_abapgit_exception. METHODS shorten_repo_url IMPORTING iv_full_url TYPE string iv_max_length TYPE i DEFAULT 60 RETURNING VALUE(rv_shortened) TYPE string. METHODS render_actions IMPORTING ii_html TYPE REF TO zif_abapgit_html. METHODS column IMPORTING iv_content TYPE string OPTIONAL iv_css_class TYPE string OPTIONAL RETURNING VALUE(rv_html) TYPE string. METHODS action_link IMPORTING iv_content TYPE string RETURNING VALUE(rv_html) TYPE string. ENDCLASS. CLASS zcl_abapgit_gui_page_repo_over IMPLEMENTATION. METHOD apply_filter. IF mv_filter IS NOT INITIAL. DELETE ct_overview WHERE key NS mv_filter AND name NS mv_filter AND url NS mv_filter AND package NS mv_filter AND branch NS mv_filter AND created_by NS mv_filter AND created_at NS mv_filter AND deserialized_by NS mv_filter AND deserialized_at NS mv_filter. ENDIF. ENDMETHOD. METHOD apply_order_by. DATA: lt_sort TYPE abap_sortorder_tab, ls_sort LIKE LINE OF lt_sort. ls_sort-name = 'FAVORITE'. ls_sort-descending = abap_true. ls_sort-astext = abap_true. INSERT ls_sort INTO TABLE lt_sort. IF mv_order_by IS NOT INITIAL. ls_sort-name = mv_order_by. ls_sort-descending = mv_order_descending. ls_sort-astext = abap_true. INSERT ls_sort INTO TABLE lt_sort. ENDIF. SORT ct_overview BY (lt_sort). ENDMETHOD. METHOD constructor. super->constructor( ). mv_order_by = |NAME|. mv_only_favorites = iv_only_favorites. CALL FUNCTION 'GET_SYSTEM_TIMEZONE' IMPORTING timezone = mv_time_zone EXCEPTIONS customizing_missing = 1 OTHERS = 2. ASSERT sy-subrc = 0. ENDMETHOD. METHOD map_repo_list_to_overview. DATA: ls_overview LIKE LINE OF rt_overview, lv_date TYPE d, lv_time TYPE t, lt_repo_obj_list TYPE zif_abapgit_repo_srv=>ty_repo_list. FIELD-SYMBOLS LIKE LINE OF lt_repo_obj_list. IF mv_only_favorites = abap_true. lt_repo_obj_list = zcl_abapgit_repo_srv=>get_instance( )->list_favorites( ). ELSE. lt_repo_obj_list = zcl_abapgit_repo_srv=>get_instance( )->list( ). ENDIF. LOOP AT lt_repo_obj_list ASSIGNING . CLEAR: ls_overview. ls_overview-favorite = zcl_abapgit_persistence_user=>get_instance( )->is_favorite_repo( ->ms_data-key ). ls_overview-type = ->ms_data-offline. ls_overview-key = ->ms_data-key. ls_overview-name = ->get_name( ). ls_overview-url = ->ms_data-url. ls_overview-package = ->ms_data-package. ls_overview-branch = ->ms_data-branch_name. ls_overview-created_by = ->ms_data-created_by. ls_overview-write_protected = ->ms_data-local_settings-write_protected. IF ->ms_data-created_at IS NOT INITIAL. CONVERT TIME STAMP ->ms_data-created_at TIME ZONE mv_time_zone INTO DATE lv_date TIME lv_time. ls_overview-created_at = |{ lv_date DATE = USER } { lv_time TIME = USER }|. ENDIF. ls_overview-deserialized_by = ->ms_data-deserialized_by. IF ->ms_data-deserialized_at IS NOT INITIAL. CONVERT TIME STAMP ->ms_data-deserialized_at TIME ZONE mv_time_zone INTO DATE lv_date TIME lv_time. ls_overview-deserialized_at = |{ lv_date DATE = USER } { lv_time TIME = USER }|. ENDIF. INSERT ls_overview INTO TABLE rt_overview. ENDLOOP. ENDMETHOD. METHOD render_header_bar. DATA: lv_new_toggle_favorites TYPE abap_bool, lv_icon_class TYPE string. ii_html->add( |
| ). ii_html->add( |
| ). ii_html->add( render_text_input( iv_name = |filter| iv_label = |Filter: | iv_value = mv_filter iv_autofocus = abap_true ) ). ii_html->add( || ). ii_html->add( |
| ). lv_new_toggle_favorites = boolc( NOT mv_only_favorites = abap_true ). "" render icon for current state but filter value for new state IF mv_only_favorites = abap_true. lv_icon_class = `blue`. ELSE. lv_icon_class = `grey`. ENDIF. ii_html->add( ii_html->a( iv_txt = | Only Favorites| iv_act = |{ zif_abapgit_definitions=>c_action-toggle_favorites }?favorites={ lv_new_toggle_favorites }| ) ). ii_html->add( `|` ). ii_html->add( ii_html->a( iv_txt = ' Detail' iv_act = |gHelper.toggleRepoListDetail()| iv_typ = zif_abapgit_html=>c_action_type-onclick ) ). render_actions( ii_html = ii_html ). ii_html->add( |
| ). ENDMETHOD. METHOD render_scripts. CREATE OBJECT ri_html TYPE zcl_abapgit_html. ri_html->set_title( cl_abap_typedescr=>describe_by_object_ref( me )->get_relative_name( ) ). ri_html->add( 'setInitialFocus(""filter"");' ). ri_html->add( 'var gHelper = new RepoOverViewHelper();' ). ENDMETHOD. METHOD render_table. ii_html->add( |
| ). ii_html->add( || ). render_table_header( ii_html ). render_table_body( ii_html = ii_html it_repo_list = it_overview ). ii_html->add( |
| ). ii_html->add( |
| ). ENDMETHOD. METHOD render_table_body. DATA: lv_type_icon TYPE string, lv_favorite_icon TYPE string, lv_favorite_class TYPE string, lv_text TYPE string, lv_lock TYPE string, lv_toggle_favorite_link TYPE string, lv_repo_go_link TYPE string, lv_remote_icon_link TYPE string. FIELD-SYMBOLS: LIKE LINE OF it_repo_list. ii_html->add( '' ). LOOP AT it_repo_list ASSIGNING . IF -type = abap_true. lv_type_icon = 'plug/darkgrey'. ELSE. lv_type_icon = 'cloud-upload-alt/darkgrey'. ENDIF. IF -favorite = abap_true. lv_favorite_icon = 'star/blue'. lv_favorite_class = 'favorite'. ELSE. lv_favorite_icon = 'star/grey'. lv_favorite_class = ''. ENDIF. ii_html->add( |-key }"" data-offline=""{ -type }"">| ). lv_toggle_favorite_link = ii_html->a( iv_act = |{ zif_abapgit_definitions=>c_action-repo_toggle_fav }?key={ -key }| iv_txt = ii_html->icon( iv_name = lv_favorite_icon iv_class = 'pad-sides' iv_hint = 'Click to toggle favorite' ) ). ii_html->add( column( iv_content = lv_toggle_favorite_link iv_css_class = 'wmin' ) ). CLEAR lv_lock. IF -write_protected = abap_true. lv_lock = ii_html->icon( iv_name = 'lock/grey70' iv_class = 'm-em5-sides' iv_hint = 'Locked from pulls' ). ENDIF. ii_html->add( column( iv_content = ii_html->icon( lv_type_icon ) iv_css_class = 'wmin' ) ). ii_html->add( column( iv_content = ii_html->a( iv_txt = -name iv_act = |{ c_action-select }?key={ -key }| ) && lv_lock ) ). ii_html->add( column( iv_content = zcl_abapgit_gui_chunk_lib=>render_package_name( iv_package = -package iv_suppress_title = boolc( NOT mv_only_favorites = abap_true ) )->render( ) ) ). IF -type = abap_false. lv_remote_icon_link = ii_html->a( iv_txt = ii_html->icon( iv_name = 'edit-solid' iv_class = 'pad-sides' iv_hint = 'Change remote' ) iv_act = |{ zif_abapgit_definitions=>c_action-repo_remote_settings }?| && |key={ -key }| iv_class = |remote_repo| ). lv_text = shorten_repo_url( -url ) && lv_remote_icon_link. ii_html->add( column( iv_content = |{ ii_html->a( iv_txt = lv_text iv_title = -url iv_act = |{ zif_abapgit_definitions=>c_action-url }?url={ -url }| ) }| ) ). ELSE. ii_html->add( column( ) ). ENDIF. IF -branch IS INITIAL. ii_html->add( column( iv_content = | | ) ). ELSE. ii_html->add( column( iv_content = zcl_abapgit_gui_chunk_lib=>render_branch_name( iv_branch = -branch iv_repo_key = -key )->render( ) ) ). ENDIF. ii_html->add( column( iv_content = zcl_abapgit_gui_chunk_lib=>render_user_name( iv_username = -deserialized_by iv_suppress_title = boolc( NOT mv_only_favorites = abap_true ) )->render( ) iv_css_class = 'ro-detail' ) ). ii_html->add( column( iv_content = -deserialized_at iv_css_class = 'ro-detail' ) ). ii_html->add( column( iv_content = zcl_abapgit_gui_chunk_lib=>render_user_name( iv_username = -created_by iv_suppress_title = boolc( NOT mv_only_favorites = abap_true ) )->render( ) iv_css_class = 'ro-detail' ) ). ii_html->add( column( iv_content = -created_at iv_css_class = 'ro-detail' ) ). ii_html->add( column( iv_content = |{ -key }| iv_css_class = 'ro-detail' ) ). "" the link is clicked in javascript lv_repo_go_link = ii_html->a( iv_txt = `` iv_act = |{ c_action-select }?key={ -key }| iv_class = 'hidden' ). ii_html->add( column( iv_content = |›{ lv_repo_go_link }| iv_css_class = 'ro-go' ) ). ii_html->add( `` ). ENDLOOP. ii_html->add( || ). IF mv_only_favorites = abap_true. ii_html->add( `` ). ii_html->add( `(Only favorites are shown. ` ). ii_html->add( ii_html->a( iv_txt = |Show All| iv_act = |{ zif_abapgit_definitions=>c_action-toggle_favorites }?favorites={ abap_false }| ) ). ii_html->add( `)` ). ENDIF. ENDMETHOD. METHOD render_actions. CONSTANTS: lc_separator TYPE string VALUE `|`, lc_dummy_key TYPE string VALUE `?key=#`, lc_offline_class TYPE string VALUE `action_offline_repo`, lc_online_class TYPE string VALUE `action_online_repo`, lc_action_class TYPE string VALUE `action_link`. DATA: lv_settings_link TYPE string, lv_check_link TYPE string, lv_stage_link TYPE string, lv_patch_link TYPE string, lv_diff_link TYPE string, lv_pull_link TYPE string. DATA: lv_zip_import_link TYPE string, lv_zip_export_link TYPE string. ii_html->add( |
| ). lv_pull_link = ii_html->a( iv_txt = |Pull| iv_act = |{ zif_abapgit_definitions=>c_action-git_reset }{ lc_dummy_key }| iv_class = |{ lc_action_class } { lc_online_class }| ). ii_html->add( action_link( lv_pull_link && lc_separator ) ). lv_stage_link = ii_html->a( iv_txt = |Stage| iv_act = |{ zif_abapgit_definitions=>c_action-go_stage }{ lc_dummy_key }| iv_class = |{ lc_action_class } { lc_online_class } | ). ii_html->add( action_link( lv_stage_link && lc_separator ) ). lv_patch_link = ii_html->a( iv_txt = |Patch| iv_act = |{ zif_abapgit_definitions=>c_action-go_patch }{ lc_dummy_key }| iv_class = |{ lc_action_class } { lc_online_class } | ). ii_html->add( action_link( lv_patch_link && lc_separator ) ). lv_diff_link = ii_html->a( iv_txt = |Diff| iv_act = |{ zif_abapgit_definitions=>c_action-go_repo_diff }{ lc_dummy_key }| iv_class = |{ lc_action_class } { lc_online_class }| ). ii_html->add( action_link( lv_diff_link && lc_separator ) ). lv_check_link = ii_html->a( iv_txt = |Check| iv_act = |{ zif_abapgit_definitions=>c_action-repo_code_inspector }{ lc_dummy_key }| iv_class = |{ lc_action_class }| ). ii_html->add( action_link( lv_check_link && lc_separator ) ). lv_zip_import_link = ii_html->a( iv_txt = |Import| iv_act = |{ zif_abapgit_definitions=>c_action-zip_import }{ lc_dummy_key }| iv_class = |{ lc_action_class } { lc_offline_class }| ). ii_html->add( action_link( lv_zip_import_link && lc_separator ) ). lv_zip_export_link = ii_html->a( iv_txt = |Export| iv_act = |{ zif_abapgit_definitions=>c_action-zip_export }{ lc_dummy_key }| iv_class = |{ lc_action_class } { lc_offline_class }| ). ii_html->add( action_link( lv_zip_export_link && lc_separator ) ). lv_settings_link = ii_html->a( iv_txt = |Settings| iv_act = |{ zif_abapgit_definitions=>c_action-repo_settings }{ lc_dummy_key }| iv_class = |{ lc_action_class }| ). ii_html->add( action_link( lv_settings_link ) ). ii_html->add( |
| ). ENDMETHOD. METHOD shorten_repo_url. DATA lv_new_length TYPE i. DATA lv_length_to_truncate_to TYPE i. rv_shortened = iv_full_url. REPLACE FIRST OCCURRENCE OF 'https://' IN rv_shortened WITH ''. REPLACE FIRST OCCURRENCE OF 'http://' IN rv_shortened WITH ''. IF rv_shortened CP '*.git'. lv_new_length = strlen( rv_shortened ) - 4. rv_shortened = rv_shortened(lv_new_length). ENDIF. IF strlen( rv_shortened ) > iv_max_length. lv_length_to_truncate_to = iv_max_length - 3. rv_shortened = rv_shortened(lv_length_to_truncate_to) && `...`. ENDIF. ENDMETHOD. METHOD render_table_header. CLEAR mt_col_spec. _add_column( iv_tech_name = 'FAVORITE' iv_css_class = 'wmin' iv_allow_order_by = abap_false ). _add_column( iv_tech_name = 'TYPE' iv_css_class = 'wmin' iv_allow_order_by = abap_false ). _add_column( iv_tech_name = 'NAME' iv_display_name = 'Name' iv_allow_order_by = abap_true ). _add_column( iv_tech_name = 'PACKAGE' iv_display_name = 'Package' iv_css_class = 'package' iv_allow_order_by = abap_true ). _add_column( iv_tech_name = 'URL' iv_display_name = 'Remote' iv_allow_order_by = abap_true ). _add_column( iv_tech_name = 'BRANCH' iv_display_name = 'Branch' iv_allow_order_by = abap_true ). _add_column( iv_tech_name = 'DESERIALIZED_BY' iv_display_name = 'Deserialized by' iv_css_class = 'ro-detail' iv_allow_order_by = abap_true ). _add_column( iv_tech_name = 'DESERIALIZED_AT' iv_display_name = 'Deserialized at' iv_css_class = 'ro-detail' iv_allow_order_by = abap_true ). _add_column( iv_tech_name = 'CREATED_BY' iv_display_name = 'Created by' iv_css_class = 'ro-detail' iv_allow_order_by = abap_true ). _add_column( iv_tech_name = 'CREATED_AT' iv_display_name = 'Created at' iv_css_class = 'ro-detail' iv_add_tz = abap_true iv_allow_order_by = abap_true ). _add_column( iv_tech_name = 'KEY' iv_display_name = 'Key' iv_css_class = 'ro-detail' iv_allow_order_by = abap_true ). _add_column( iv_tech_name = 'GO' iv_css_class = 'ro-go' iv_allow_order_by = abap_false ). ii_html->add( || ). ii_html->add( || ). ii_html->add( zcl_abapgit_gui_chunk_lib=>render_order_by_header_cells( it_col_spec = mt_col_spec iv_order_by = mv_order_by iv_order_descending = mv_order_descending ) ). ii_html->add( '' ). ii_html->add( '' ). ENDMETHOD. METHOD render_text_input. DATA lv_attrs TYPE string. CREATE OBJECT ri_html TYPE zcl_abapgit_html. IF iv_value IS NOT INITIAL. lv_attrs = | value=""{ iv_value }""|. ENDIF. IF iv_max_length IS NOT INITIAL. lv_attrs = lv_attrs && | maxlength=""{ iv_max_length }""|. ENDIF. IF iv_autofocus = abap_true. lv_attrs = lv_attrs && | autofocus|. ENDIF. ri_html->add( || ). ri_html->add( || ). ENDMETHOD. METHOD set_filter. FIELD-SYMBOLS: LIKE LINE OF it_postdata. READ TABLE it_postdata ASSIGNING INDEX 1. IF sy-subrc = 0. FIND FIRST OCCURRENCE OF REGEX `filter=(.*)` IN SUBMATCHES mv_filter. ENDIF. mv_filter = condense( mv_filter ). ENDMETHOD. METHOD set_order_by. mv_order_by = iv_order_by. ENDMETHOD. METHOD set_order_direction. mv_order_descending = iv_order_descending. ENDMETHOD. METHOD zif_abapgit_gui_renderable~render. mt_overview = map_repo_list_to_overview( ). apply_order_by( CHANGING ct_overview = mt_overview ). apply_filter( CHANGING ct_overview = mt_overview ). CREATE OBJECT ri_html TYPE zcl_abapgit_html. render_header_bar( ri_html ). zcl_abapgit_exit=>get_instance( )->wall_message_list( ri_html ). render_table( ii_html = ri_html it_overview = mt_overview ). register_deferred_script( render_scripts( ) ). ENDMETHOD. METHOD _add_column. FIELD-SYMBOLS LIKE LINE OF mt_col_spec. APPEND INITIAL LINE TO mt_col_spec ASSIGNING . -display_name = iv_display_name. -tech_name = iv_tech_name. -title = iv_title. -css_class = iv_css_class. -add_tz = iv_add_tz. -allow_order_by = iv_allow_order_by. ENDMETHOD. METHOD column. IF iv_css_class IS NOT INITIAL. rv_html = || && iv_content && ||. ELSE. rv_html = || && iv_content && ||. ENDIF. ENDMETHOD. METHOD action_link. rv_html = || && iv_content && ||. ENDMETHOD. METHOD set_only_favorites. mv_only_favorites = iv_only_favorites. ENDMETHOD. METHOD get_only_favorites. rv_result = mv_only_favorites. ENDMETHOD. ENDCLASS. ",5993,False,1275.7551432651271,median "class ZCL_EXCEL definition public create public . public section. *""* public components of class ZCL_EXCEL *""* do not include other source files here!!! interfaces ZIF_EXCEL_BOOK_PROPERTIES . interfaces ZIF_EXCEL_BOOK_PROTECTION . interfaces ZIF_EXCEL_BOOK_VBA_PROJECT . data LEGACY_PALETTE type ref to ZCL_EXCEL_LEGACY_PALETTE read-only . data SECURITY type ref to ZCL_EXCEL_SECURITY . data USE_TEMPLATE type XFELD . methods ADD_NEW_AUTOFILTER importing !IO_SHEET type ref to ZCL_EXCEL_WORKSHEET returning value(RO_AUTOFILTER) type ref to ZCL_EXCEL_AUTOFILTER raising ZCX_EXCEL . methods ADD_NEW_DRAWING importing !IP_TYPE type ZEXCEL_DRAWING_TYPE default ZCL_EXCEL_DRAWING=>TYPE_IMAGE !IP_TITLE type CLIKE optional returning value(EO_DRAWING) type ref to ZCL_EXCEL_DRAWING . methods ADD_NEW_RANGE returning value(EO_RANGE) type ref to ZCL_EXCEL_RANGE . methods ADD_NEW_STYLE importing !IP_GUID type ZEXCEL_CELL_STYLE optional returning value(EO_STYLE) type ref to ZCL_EXCEL_STYLE . methods ADD_NEW_WORKSHEET importing !IP_TITLE type ZEXCEL_SHEET_TITLE optional returning value(EO_WORKSHEET) type ref to ZCL_EXCEL_WORKSHEET raising ZCX_EXCEL . methods ADD_STATIC_STYLES . methods CONSTRUCTOR . methods DELETE_WORKSHEET importing !IO_WORKSHEET type ref to ZCL_EXCEL_WORKSHEET raising ZCX_EXCEL . methods DELETE_WORKSHEET_BY_INDEX importing !IV_INDEX type NUMERIC . methods DELETE_WORKSHEET_BY_NAME importing !IV_TITLE type CLIKE . methods GET_ACTIVE_SHEET_INDEX returning value(R_ACTIVE_WORKSHEET) type ZEXCEL_ACTIVE_WORKSHEET . methods GET_ACTIVE_WORKSHEET returning value(EO_WORKSHEET) type ref to ZCL_EXCEL_WORKSHEET . methods GET_AUTOFILTERS_REFERENCE returning value(RO_AUTOFILTERS) type ref to ZCL_EXCEL_AUTOFILTERS . methods GET_DEFAULT_STYLE returning value(EP_STYLE) type ZEXCEL_CELL_STYLE . methods GET_DRAWINGS_ITERATOR importing !IP_TYPE type ZEXCEL_DRAWING_TYPE returning value(EO_ITERATOR) type ref to CL_OBJECT_COLLECTION_ITERATOR . methods GET_NEXT_TABLE_ID returning value(EP_ID) type I . methods GET_RANGES_ITERATOR returning value(EO_ITERATOR) type ref to CL_OBJECT_COLLECTION_ITERATOR . methods GET_STATIC_CELLSTYLE_GUID importing !IP_CSTYLE_COMPLETE type ZEXCEL_S_CSTYLE_COMPLETE !IP_CSTYLEX_COMPLETE type ZEXCEL_S_CSTYLEX_COMPLETE returning value(EP_GUID) type ZEXCEL_CELL_STYLE . methods GET_STYLES_ITERATOR returning value(EO_ITERATOR) type ref to CL_OBJECT_COLLECTION_ITERATOR . methods GET_STYLE_INDEX_IN_STYLES importing !IP_GUID type ZEXCEL_CELL_STYLE returning value(EP_INDEX) type SYTABIX raising ZCX_EXCEL . methods GET_STYLE_TO_GUID importing !IP_GUID type ZEXCEL_CELL_STYLE returning value(EP_STYLEMAPPING) type ZEXCEL_S_STYLEMAPPING raising ZCX_EXCEL . methods GET_THEME exporting !EO_THEME type ref to ZCL_EXCEL_THEME . methods GET_WORKSHEETS_ITERATOR returning value(EO_ITERATOR) type ref to CL_OBJECT_COLLECTION_ITERATOR . methods GET_WORKSHEETS_NAME returning value(EP_NAME) type ZEXCEL_WORKSHEETS_NAME . methods GET_WORKSHEETS_SIZE returning value(EP_SIZE) type I . methods GET_WORKSHEET_BY_INDEX importing !IV_INDEX type NUMERIC returning value(EO_WORKSHEET) type ref to ZCL_EXCEL_WORKSHEET . methods GET_WORKSHEET_BY_NAME importing !IP_SHEET_NAME type ZEXCEL_SHEET_TITLE returning value(EO_WORKSHEET) type ref to ZCL_EXCEL_WORKSHEET . methods SET_ACTIVE_SHEET_INDEX importing !I_ACTIVE_WORKSHEET type ZEXCEL_ACTIVE_WORKSHEET raising ZCX_EXCEL . methods SET_ACTIVE_SHEET_INDEX_BY_NAME importing !I_WORKSHEET_NAME type ZEXCEL_WORKSHEETS_NAME . methods SET_DEFAULT_STYLE importing !IP_STYLE type ZEXCEL_CELL_STYLE raising ZCX_EXCEL . methods SET_THEME importing !IO_THEME type ref to ZCL_EXCEL_THEME . protected section. data WORKSHEETS type ref to ZCL_EXCEL_WORKSHEETS . private section. constants VERSION type CHAR10 value '7.0.6'. ""#EC NOTEXT data AUTOFILTERS type ref to ZCL_EXCEL_AUTOFILTERS . data CHARTS type ref to ZCL_EXCEL_DRAWINGS . data DEFAULT_STYLE type ZEXCEL_CELL_STYLE . *""* private components of class ZCL_EXCEL *""* do not include other source files here!!! data DRAWINGS type ref to ZCL_EXCEL_DRAWINGS . data RANGES type ref to ZCL_EXCEL_RANGES . data STYLES type ref to ZCL_EXCEL_STYLES . data T_STYLEMAPPING1 type ZEXCEL_T_STYLEMAPPING1 . data T_STYLEMAPPING2 type ZEXCEL_T_STYLEMAPPING2 . data THEME type ref to ZCL_EXCEL_THEME . methods GET_STYLE_FROM_GUID importing !IP_GUID type ZEXCEL_CELL_STYLE returning value(EO_STYLE) type ref to ZCL_EXCEL_STYLE . methods STYLEMAPPING_DYNAMIC_STYLE importing !IP_STYLE type ref to ZCL_EXCEL_STYLE returning value(EO_STYLE2) type ZEXCEL_S_STYLEMAPPING . ENDCLASS. CLASS ZCL_EXCEL IMPLEMENTATION. METHOD add_new_autofilter. * Check for autofilter reference: new or overwrite; only one per sheet ro_autofilter = autofilters->add( io_sheet ) . ENDMETHOD. method ADD_NEW_DRAWING. * Create default blank worksheet CREATE OBJECT eo_drawing EXPORTING ip_type = ip_type ip_title = ip_title. CASE ip_type. WHEN 'image'. drawings->add( eo_drawing ). WHEN 'chart'. charts->add( eo_drawing ). ENDCASE. endmethod. method ADD_NEW_RANGE. * Create default blank range CREATE OBJECT eo_range. ranges->add( eo_range ). endmethod. method ADD_NEW_STYLE. * Start of deletion # issue 139 - Dateretention of cellstyles * CREATE OBJECT eo_style. * styles->add( eo_style ). * End of deletion # issue 139 - Dateretention of cellstyles * Start of insertion # issue 139 - Dateretention of cellstyles * Create default style CREATE OBJECT eo_style EXPORTING ip_guid = ip_guid. styles->add( eo_style ). DATA: style2 TYPE zexcel_s_stylemapping. * Copy to new representations style2 = stylemapping_dynamic_style( eo_style ). INSERT style2 INTO TABLE t_stylemapping1. INSERT style2 INTO TABLE t_stylemapping2. * End of insertion # issue 139 - Dateretention of cellstyles endmethod. method ADD_NEW_WORKSHEET. * Create default blank worksheet CREATE OBJECT eo_worksheet EXPORTING ip_excel = me ip_title = ip_title. worksheets->add( eo_worksheet ). worksheets->active_worksheet = worksheets->size( ). endmethod. METHOD add_static_styles. "" # issue 139 FIELD-SYMBOLS: LIKE LINE OF t_stylemapping1, LIKE LINE OF t_stylemapping2. DATA: style TYPE REF TO zcl_excel_style. LOOP AT me->t_stylemapping1 ASSIGNING WHERE added_to_iterator IS INITIAL. READ TABLE me->t_stylemapping2 ASSIGNING WITH TABLE KEY guid = -guid. CHECK sy-subrc = 0. "" Should always be true since these tables are being filled parallel style = me->add_new_style( -guid ). zcl_excel_common=>recursive_struct_to_class( EXPORTING i_source = -complete_style i_sourcex = -complete_stylex CHANGING e_target = style ). ENDLOOP. ENDMETHOD. method CONSTRUCTOR. DATA: lo_style TYPE REF TO zcl_excel_style. * Inizialize instance objects CREATE OBJECT security. CREATE OBJECT worksheets. CREATE OBJECT ranges. CREATE OBJECT styles. CREATE OBJECT drawings EXPORTING ip_type = zcl_excel_drawing=>type_image. CREATE OBJECT charts EXPORTING ip_type = zcl_excel_drawing=>type_chart. CREATE OBJECT legacy_palette. CREATE OBJECT autofilters. me->zif_excel_book_protection~initialize( ). me->zif_excel_book_properties~initialize( ). me->add_new_worksheet( ). me->add_new_style( ). "" Standard style lo_style = me->add_new_style( ). "" Standard style with fill gray125 lo_style->fill->filltype = zcl_excel_style_fill=>c_fill_pattern_gray125. endmethod. METHOD delete_worksheet. DATA: lo_worksheet TYPE REF TO zcl_excel_worksheet, l_size TYPE i, lv_errormessage TYPE string. l_size = get_worksheets_size( ). IF l_size = 1. "" Only 1 worksheet left --> check whether this is the worksheet to be deleted lo_worksheet = me->get_worksheet_by_index( 1 ). IF lo_worksheet = io_worksheet. lv_errormessage = 'Deleting last remaining worksheet is not allowed'(002). RAISE EXCEPTION TYPE zcx_excel EXPORTING error = lv_errormessage. ENDIF. ENDIF. me->worksheets->remove( io_worksheet ). ENDMETHOD. METHOD delete_worksheet_by_index. DATA: lo_worksheet TYPE REF TO zcl_excel_worksheet, lv_errormessage TYPE string. lo_worksheet = me->get_worksheet_by_index( iv_index ). IF lo_worksheet IS NOT BOUND. lv_errormessage = 'Worksheet not existing'(001). RAISE EXCEPTION TYPE zcx_excel EXPORTING error = lv_errormessage. ENDIF. me->delete_worksheet( lo_worksheet ). ENDMETHOD. METHOD delete_worksheet_by_name. DATA: lo_worksheet TYPE REF TO zcl_excel_worksheet, lv_errormessage TYPE string. lo_worksheet = me->get_worksheet_by_name( iv_title ). IF lo_worksheet IS NOT BOUND. lv_errormessage = 'Worksheet not existing'(001). RAISE EXCEPTION TYPE zcx_excel EXPORTING error = lv_errormessage. ENDIF. me->delete_worksheet( lo_worksheet ). ENDMETHOD. method GET_ACTIVE_SHEET_INDEX. r_active_worksheet = me->worksheets->active_worksheet. endmethod. method GET_ACTIVE_WORKSHEET. eo_worksheet = me->worksheets->get( me->worksheets->active_worksheet ). endmethod. method GET_AUTOFILTERS_REFERENCE. ro_autofilters = autofilters. endmethod. method GET_DEFAULT_STYLE. ep_style = me->default_style. endmethod. method GET_DRAWINGS_ITERATOR. CASE ip_type. WHEN zcl_excel_drawing=>type_image. eo_iterator = me->drawings->get_iterator( ). WHEN zcl_excel_drawing=>type_chart. eo_iterator = me->charts->get_iterator( ). WHEN OTHERS. ENDCASE. endmethod. method GET_NEXT_TABLE_ID. DATA: lo_worksheet TYPE REF TO zcl_excel_worksheet, lo_iterator TYPE REF TO cl_object_collection_iterator, lv_tables_count TYPE i. lo_iterator = me->get_worksheets_iterator( ). WHILE lo_iterator->if_object_collection_iterator~has_next( ) EQ abap_true. lo_worksheet ?= lo_iterator->if_object_collection_iterator~get_next( ). lv_tables_count = lo_worksheet->get_tables_size( ). ADD lv_tables_count TO ep_id. ENDWHILE. ADD 1 TO ep_id. endmethod. method GET_RANGES_ITERATOR. eo_iterator = me->ranges->get_iterator( ). endmethod. METHOD get_static_cellstyle_guid. "" # issue 139 DATA: style LIKE LINE OF me->t_stylemapping1. READ TABLE me->t_stylemapping1 INTO style WITH TABLE KEY dynamic_style_guid = style-guid "" no dynamic style --> look for initial guid here complete_style = ip_cstyle_complete complete_stylex = ip_cstylex_complete. IF sy-subrc <> 0. style-complete_style = ip_cstyle_complete. style-complete_stylex = ip_cstylex_complete. * CALL FUNCTION 'GUID_CREATE' "" del issue #379 - function is outdated in newer releases * IMPORTING * ev_guid_16 = style-guid. style-guid = zcl_excel_obsolete_func_wrap=>guid_create( ). "" ins issue #379 - replacement for outdated function call INSERT style INTO TABLE me->t_stylemapping1. INSERT style INTO TABLE me->t_stylemapping2. ENDIF. ep_guid = style-guid. ENDMETHOD. method GET_STYLES_ITERATOR. eo_iterator = me->styles->get_iterator( ). endmethod. METHOD get_style_from_guid. DATA: lo_style TYPE REF TO zcl_excel_style, lo_iterator TYPE REF TO cl_object_collection_iterator. lo_iterator = styles->get_iterator( ). WHILE lo_iterator->has_next( ) = abap_true. lo_style ?= lo_iterator->get_next( ). IF lo_style->get_guid( ) = ip_guid. eo_style = lo_style. RETURN. ENDIF. ENDWHILE. ENDMETHOD. method GET_STYLE_INDEX_IN_STYLES. DATA: index TYPE syindex. DATA: lo_iterator TYPE REF TO cl_object_collection_iterator, lo_style TYPE REF TO zcl_excel_style. CHECK ip_guid IS NOT INITIAL. lo_iterator = me->get_styles_iterator( ). WHILE lo_iterator->has_next( ) = 'X'. ADD 1 TO index. lo_style ?= lo_iterator->get_next( ). IF lo_style->get_guid( ) = ip_guid. ep_index = index. EXIT. ENDIF. ENDWHILE. IF ep_index IS INITIAL. RAISE EXCEPTION TYPE zcx_excel EXPORTING error = 'Index not found'. else. SUBTRACT 1 from ep_index. "" In excel list starts with ""0"" ENDIF. endmethod. METHOD get_style_to_guid. DATA: lo_style TYPE REF TO zcl_excel_style. "" # issue 139 READ TABLE me->t_stylemapping2 INTO ep_stylemapping WITH TABLE KEY guid = ip_guid. IF sy-subrc <> 0. RAISE EXCEPTION TYPE zcx_excel EXPORTING error = 'GUID not found'. ENDIF. IF ep_stylemapping-dynamic_style_guid IS NOT INITIAL. lo_style = me->get_style_from_guid( ip_guid ). zcl_excel_common=>recursive_class_to_struct( EXPORTING i_source = lo_style CHANGING e_target = ep_stylemapping-complete_style e_targetx = ep_stylemapping-complete_stylex ). ENDIF. ENDMETHOD. method GET_THEME. eo_theme = theme. endmethod. method GET_WORKSHEETS_ITERATOR. eo_iterator = me->worksheets->get_iterator( ). endmethod. method GET_WORKSHEETS_NAME. ep_name = me->worksheets->name. endmethod. METHOD get_worksheets_size. ep_size = me->worksheets->size( ). ENDMETHOD. METHOD get_worksheet_by_index. DATA: lv_index TYPE zexcel_active_worksheet. lv_index = iv_index. eo_worksheet = me->worksheets->get( lv_index ). ENDMETHOD. METHOD get_worksheet_by_name. DATA: lv_index TYPE zexcel_active_worksheet, l_size TYPE i. l_size = get_worksheets_size( ). DO l_size TIMES. lv_index = sy-index. eo_worksheet = me->worksheets->get( lv_index ). IF eo_worksheet->get_title( ) = ip_sheet_name. RETURN. ENDIF. ENDDO. CLEAR eo_worksheet. ENDMETHOD. METHOD set_active_sheet_index. DATA: lo_worksheet TYPE REF TO zcl_excel_worksheet, lv_errormessage TYPE string. *--------------------------------------------------------------------* * Check whether worksheet exists *--------------------------------------------------------------------* lo_worksheet = me->get_worksheet_by_index( i_active_worksheet ). IF lo_worksheet IS NOT BOUND. lv_errormessage = 'Worksheet not existing'(001). RAISE EXCEPTION TYPE zcx_excel EXPORTING error = lv_errormessage. ENDIF. me->worksheets->active_worksheet = i_active_worksheet. ENDMETHOD. METHOD set_active_sheet_index_by_name. DATA: ws_it TYPE REF TO cl_object_collection_iterator, ws TYPE REF TO zcl_excel_worksheet, lv_title TYPE zexcel_sheet_title, count TYPE i VALUE 1. ws_it = me->worksheets->get_iterator( ). WHILE ws_it->if_object_collection_iterator~has_next( ) = abap_true. ws ?= ws_it->if_object_collection_iterator~get_next( ). lv_title = ws->get_title( ). IF lv_title = i_worksheet_name. me->worksheets->active_worksheet = count. EXIT. ENDIF. count = count + 1. ENDWHILE. ENDMETHOD. method SET_DEFAULT_STYLE. me->default_style = ip_style. endmethod. method SET_THEME. theme = io_theme. endmethod. method STYLEMAPPING_DYNAMIC_STYLE. "" # issue 139 eo_style2-dynamic_style_guid = ip_style->get_guid( ). eo_style2-guid = eo_style2-dynamic_style_guid. eo_style2-added_to_iterator = abap_true. * don't care about attributes here, since this data may change * dynamically endmethod. METHOD zif_excel_book_properties~initialize. DATA: lv_timestamp TYPE timestampl. me->zif_excel_book_properties~application = 'Microsoft Excel'. me->zif_excel_book_properties~appversion = '12.0000'. GET TIME STAMP FIELD lv_timestamp. me->zif_excel_book_properties~created = lv_timestamp. me->zif_excel_book_properties~creator = sy-uname. me->zif_excel_book_properties~description = zcl_excel=>version. me->zif_excel_book_properties~modified = lv_timestamp. me->zif_excel_book_properties~lastmodifiedby = sy-uname. ENDMETHOD. method ZIF_EXCEL_BOOK_PROTECTION~INITIALIZE. me->zif_excel_book_protection~protected = zif_excel_book_protection=>c_unprotected. me->zif_excel_book_protection~lockrevision = zif_excel_book_protection=>c_unlocked. me->zif_excel_book_protection~lockstructure = zif_excel_book_protection=>c_unlocked. me->zif_excel_book_protection~lockwindows = zif_excel_book_protection=>c_unlocked. CLEAR me->zif_excel_book_protection~workbookpassword. CLEAR me->zif_excel_book_protection~revisionspassword. endmethod. method ZIF_EXCEL_BOOK_VBA_PROJECT~SET_CODENAME. me->zif_excel_book_vba_project~codename = ip_codename. endmethod. method ZIF_EXCEL_BOOK_VBA_PROJECT~SET_CODENAME_PR. me->zif_excel_book_vba_project~codename_pr = ip_codename_pr. endmethod. method ZIF_EXCEL_BOOK_VBA_PROJECT~SET_VBAPROJECT. me->zif_excel_book_vba_project~vbaproject = ip_vbaproject. endmethod. ENDCLASS. ",4649,False,874.4029499128022,median "//////////////////////////////////////////////////////////////////////////////// // // 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 // // No warranty of merchantability or fitness of any kind. // Use this software at your own risk. // //////////////////////////////////////////////////////////////////////////////// package actionScripts.utils { import flash.display.DisplayObject; import flash.events.Event; import flash.geom.Point; import flash.system.Capabilities; import mx.collections.ArrayCollection; import mx.collections.ICollectionView; import mx.collections.IList; import mx.collections.Sort; import mx.collections.SortField; import mx.controls.Alert; import mx.core.FlexGlobals; import mx.core.UIComponent; import mx.events.CloseEvent; import mx.events.ToolTipEvent; import mx.managers.PopUpManager; import mx.resources.ResourceManager; import mx.utils.UIDUtil; import actionScripts.events.GlobalEventDispatcher; import actionScripts.events.ProjectEvent; import actionScripts.factory.FileLocation; import actionScripts.locator.IDEModel; import actionScripts.plugin.actionscript.as3project.vo.AS3ProjectVO; import actionScripts.plugin.actionscript.as3project.vo.SWFOutputVO; import actionScripts.plugin.groovy.grailsproject.vo.GrailsProjectVO; import actionScripts.plugin.haxe.hxproject.vo.HaxeOutputVO; import actionScripts.plugin.haxe.hxproject.vo.HaxeProjectVO; import actionScripts.plugin.java.javaproject.vo.JavaProjectVO; import actionScripts.plugin.ondiskproj.vo.OnDiskProjectVO; import actionScripts.plugin.settings.SettingsView; import actionScripts.ui.IContentWindow; import actionScripts.ui.IFileContentWindow; import actionScripts.ui.menu.vo.MenuItem; import actionScripts.ui.menu.vo.ProjectMenuTypes; import actionScripts.ui.tabview.CloseTabEvent; import actionScripts.valueObjects.ConstantsCoreVO; import actionScripts.valueObjects.DataHTMLType; import actionScripts.valueObjects.FileWrapper; import actionScripts.valueObjects.ProjectReferenceVO; import actionScripts.valueObjects.ProjectVO; import actionScripts.valueObjects.ResourceVO; import actionScripts.valueObjects.SDKReferenceVO; import actionScripts.valueObjects.SDKTypes; import components.popup.ModifiedFileListPopup; import components.renderers.CustomToolTipGBA; import components.views.splashscreen.SplashScreen; import feathers.data.ArrayCollection; //import flash.filesystem.File; public class UtilsCore { public static var wrappersFoundThroughFindingAWrapper:Vector.; private static var model:IDEModel = IDEModel.getInstance(); /** * Get data agent error type */ public static function getDataType(value:String):DataHTMLType { var dataType:DataHTMLType = new DataHTMLType(); var message:String; // true if it's a login agent call if ((value.indexOf(""/Grails4NotesBroker/admin/auth"") != -1) || (value.indexOf(""Please Login"") != -1)) { // error is a login error var indexToStart:int = value.indexOf("""", indexToStart)); else message = ""Please, check your username or password.""; dataType.message = message; dataType.type = DataHTMLType.LOGIN_ERROR; dataType.isError = true; } else if ((value.toLowerCase().indexOf(""authenticated"") != -1) || (value.toLowerCase().indexOf(""welcome to grails"") != -1)) { dataType.isError = false; dataType.type = DataHTMLType.LOGIN_SUCCESS; } else { dataType.message = ""Your session has expired. Please, re-login.""; dataType.type = DataHTMLType.SESSION_ERROR; dataType.isError = true; } return dataType; } /** * Checks through opened project list against * a given path value * @return * BOOL */ public static function checkProjectIfAlreadyOpened(value:String):Boolean { for each (var file:ProjectVO in model.projects) { if (file.folderLocation.fileBridge.nativePath == value) { return true; } } return false; } /** * Creates custom tooltip */ public static function createCustomToolTip(event:ToolTipEvent):void { var cTT : CustomToolTipGBA = new CustomToolTipGBA(); event.toolTip = cTT; } /** * Checks content of files to determine between * binary and text */ public static function isBinary(fileContent:String):Boolean { return (/[\\x00-\\x08\\x0E-\\x1F]/.test(fileContent)); } /** * Positions the toolTip */ public static function positionTip(event:ToolTipEvent):void { var tmpPoint : Point = getContentToGlobalXY( event.currentTarget as UIComponent ); event.toolTip.y = tmpPoint.y + 20; //event.toolTip.x = event.toolTip.x - 20; event.toolTip.x = ( event.currentTarget as UIComponent ).mouseX; } /** * Determines if a project is AIR type */ public static function isAIR(project:AS3ProjectVO):Boolean { // giving precedence to the as3proj value if (project.swfOutput.platform == SWFOutputVO.PLATFORM_AIR || project.swfOutput.platform == SWFOutputVO.PLATFORM_MOBILE) return true; if (project.targets.length > 0) { // considering that application descriptor file should exists in the same // root where application source file is exist var appFileName:String = project.targets[0].fileBridge.name.split(""."")[0]; if (project.targets[0].fileBridge.parent.fileBridge.resolvePath(""application.xml"").fileBridge.exists) return true; else if (project.targets[0].fileBridge.parent.fileBridge.resolvePath(appFileName +""-app.xml"").fileBridge.exists) return true; } if (project.isLibraryProject && project.testMovie == AS3ProjectVO.TEST_MOVIE_AIR) return true; return false; } /** * Determines if a project is mobile type */ public static function isMobile(project:AS3ProjectVO):Boolean { // giving precedence to the as3proj value if (project.swfOutput.platform == SWFOutputVO.PLATFORM_MOBILE) return true; if (project.isLibraryProject) { if (project.buildOptions.additional && project.buildOptions.additional.indexOf(""airmobile"") != -1) return true; } else if (project.sourceFolder && project.sourceFolder.fileBridge.exists) { var appFileName:String = project.targets[0].fileBridge.name.split(""."")[0]; var descriptor:FileLocation = project.sourceFolder.fileBridge.resolvePath(appFileName +""-app.xml""); if (descriptor.fileBridge.exists) { var descriptorData:XML = XML(descriptor.fileBridge.read()); var tmpNameSearchString:String = """"; for each (var i:XML in descriptorData.children()) { tmpNameSearchString += i.localName()+"" ""; } return (tmpNameSearchString.indexOf(""android"") != -1) || (tmpNameSearchString.indexOf(""iPhone"") != -1); } } return false; } /** * Determines if a project is Lime type */ public static function isLime(project:HaxeProjectVO):Boolean { return project.haxeOutput.platform == HaxeOutputVO.PLATFORM_LIME; } /** * Getting a component co-ordinate * in respect of global stage */ public static function getContentToGlobalXY(dObject:UIComponent):Point { var thisHolderPoint : Point = UIComponent(dObject.owner).contentToGlobal( new Point( dObject.x, dObject.y ) ); var newP : Point = FlexGlobals.topLevelApplication.globalToContent( thisHolderPoint ); return newP; } public static function fixSlashes(path:String):String { if (!path) return null; //path = path.replace(/\\//g, IDEModel.getInstance().fileCore.separator); if (ConstantsCoreVO.IS_MACOS) path = path.replace(/\\\\/g, model.fileCore.separator); return path; } public static function convertString(path:String):String { if (!ConstantsCoreVO.IS_MACOS) { path= path.split("" "").join(""^ ""); path= path.split(""("").join(""^(""); path= path.split("")"").join(""^)""); path= path.split(""&"").join(""^&""); } else { path= path.split("" "").join(""\\\\ ""); path= path.split(""("").join(""\\\\(""); path= path.split("")"").join(""\\\\)""); path= path.split(""&"").join(""\\\\&""); } return path; } public static function getUserDefinedSDK(searchByValue:String, searchByField:String):SDKReferenceVO { for each (var i:SDKReferenceVO in model.userSavedSDKs) { if (!ConstantsCoreVO.IS_MACOS) searchByValue = searchByValue.replace(/(\\/)/g, ""\\\\""); if (i[searchByField] == searchByValue) { return i; } } // if not found return null; } public static function sortCollection(collection:mx.collections.ArrayCollection, fields:Array):void { var sortFields:Array = []; fields.forEach(function(field:String, index:int, arr:Array):void { if (field != """") { sortFields.push(new SortField(field, true)); } }); collection.sort = new Sort(sortFields); collection.refresh(); } /** * Returns project based on its path */ public static function getProjectByPath(value:String):ProjectVO { for each (var project:ProjectVO in model.projects) { if (project.folderLocation.fileBridge.nativePath == value) { return project; } } return null; } /** * Returns project if given path match any project's path */ public static function getProjectByAnyFilePath(value:String):ProjectVO { for each (var project:ProjectVO in model.projects) { if (value.toLowerCase().indexOf(project.folderLocation.fileBridge.nativePath.toLowerCase()) != -1) { return project; } } return null; } /** * Returns project based on its name */ public static function getProjectByName(projectName:String):ProjectVO { for each (var project:ProjectVO in model.projects) { if (project.projectName == projectName) { return project; } } return null; } /** * Returns projectVO against fileWrapper */ public static function getProjectFromProjectFolder(projectFolder:FileWrapper):ProjectVO { if (!projectFolder) return null; for each (var p:ProjectVO in model.projects) { if (p.folderPath == projectFolder.projectReference.path) return p; } return null; } /** * Returns the probable SDK against a project */ public static function getCurrentSDK(pvo:AS3ProjectVO):FileLocation { return pvo.buildOptions.customSDK ? pvo.buildOptions.customSDK : model.defaultSDK; } /** * Returns path reference separated with * file separator */ public static function getPackageReferenceByProjectPath(classPaths:Vector., filePath:String=null, fileWrapper:FileWrapper=null, fileLocation:FileLocation=null, appendProjectNameAsPrefix:Boolean=true):String { var path:String = getPathStringByProjectPath(classPaths, filePath, fileWrapper, fileLocation, appendProjectNameAsPrefix); var pattern:RegExp = new RegExp(ConstantsCoreVO.IS_MACOS ? model.fileCore.separator : ""\\\\"" + model.fileCore.separator, ""g""); path = path.replace(pattern, "".""); return path; } /** * Returns dotted package references * against a project path */ public static function getPathStringByProjectPath(classPaths:Vector., filePath:String=null, fileWrapper:FileWrapper=null, fileLocation:FileLocation=null, appendProjectNameAsPrefix:Boolean=true):String { if (fileWrapper) { filePath = fileWrapper.nativePath; } else if (fileLocation) { filePath = fileLocation.fileBridge.nativePath; } var separator:String = model.fileCore.separator; var classPathCount:int = classPaths.length; var projectPathSplit:Array = null; for (var i:int = 0; i < classPathCount; i++) { var location:FileLocation = classPaths[i]; if (filePath.indexOf(location.fileBridge.nativePath) > -1) { projectPathSplit = location.fileBridge.nativePath.split(separator); filePath = filePath.replace(location.fileBridge.nativePath, """"); break; } } //var projectPathSplit:Array = projectPath.split(separator); //filePath = filePath.replace(projectPath, """"); if (appendProjectNameAsPrefix && projectPathSplit) { return projectPathSplit[projectPathSplit.length-1] + filePath.split(separator).join(model.fileCore.separator); } return filePath.split(separator).join(model.fileCore.separator); } /** * Fine a fileWrapper object * by a fileLocation object */ public static function findFileWrapperAgainstFileLocation(current:FileWrapper, target:FileLocation):FileWrapper { // Recurse-find filewrapper child for each (var child:FileWrapper in current.children) { if (target.fileBridge.nativePath == child.nativePath || target.fileBridge.nativePath.indexOf(child.nativePath + target.fileBridge.separator) == 0) { if (wrappersFoundThroughFindingAWrapper) wrappersFoundThroughFindingAWrapper.push(child); if (target.fileBridge.nativePath == child.nativePath) { return child; } if (child.children) { return findFileWrapperAgainstFileLocation(child, target); } } } return current; } /** * Find a fileWrapper object * against a project object */ public static function findFileWrapperAgainstProject(current:FileWrapper, project:ProjectVO, orInFileWrapper:FileWrapper=null):FileWrapper { var projectChildren:FileWrapper = project ? project.projectFolder : orInFileWrapper; // Probable termination if (!projectChildren) return current; // Recurse-find filewrapper child wrappersFoundThroughFindingAWrapper = new Vector.(); for each (var ownerWrapper:FileWrapper in projectChildren.children) { if (current.file.fileBridge.nativePath == ownerWrapper.nativePath || current.file.fileBridge.nativePath.indexOf(ownerWrapper.nativePath + current.file.fileBridge.separator) == 0) { wrappersFoundThroughFindingAWrapper.push(ownerWrapper); if (current.file.fileBridge.nativePath == ownerWrapper.nativePath) { return ownerWrapper; } if (ownerWrapper.children && ownerWrapper.children.length > 0) { var tmpMultiReturn:FileWrapper = findFileWrapperAgainstFileLocation(ownerWrapper, current.file); if (tmpMultiReturn != ownerWrapper) return tmpMultiReturn; } } } return current; } /** * Another way of finding fileWrapper * inside the project hierarchy */ public static function findFileWrapperInDepth(wrapper:FileWrapper, searchPath:String, project:ProjectVO=null):FileWrapper { var projectChildren:FileWrapper = project ? project.projectFolder : wrapper; for each (var child:FileWrapper in projectChildren.children) { if (searchPath == child.nativePath || searchPath.indexOf(child.nativePath + child.file.fileBridge.separator) == 0) { wrappersFoundThroughFindingAWrapper.push(child); if (searchPath == child.nativePath) { return child; } if (child.children && child.children.length > 0) return findFileWrapperInDepth(child, searchPath); } } return wrapper; } public static function findDominoFileWrapperInDepth(wrapper:FileWrapper, searchPath:String):FileWrapper { //Alert.show(""searchPath:""+searchPath); for each (var child:FileWrapper in wrapper.children) { if (searchPath == child.nativePath || searchPath.indexOf(child.nativePath + child.file.fileBridge.separator) == 0) { wrappersFoundThroughFindingAWrapper.push(child); if (searchPath == child.nativePath) { return child; } if (child.children && child.children.length > 0) return findFileWrapperInDepth(child, searchPath); } if(child.children && child.children.length > 0){ if(endsWith(child.nativePath,""nsfs"")|| endsWith(child.nativePath,""nsf-moonshine"")||endsWith(child.nativePath,""odp"")){ findDominoFileWrapperInDepth(child, searchPath); } // } } return wrapper; } public static function endsWith(str:String, ending:String):Boolean { var index:int = str.lastIndexOf(ending) return index > -1 && index == str.length - ending.length; } /** * Finding fileWrapper by its UDID */ public static function findFileWrapperIndexByID(wrapperToSearch:FileWrapper, searchIn:ICollectionView):int { var uidToSearch:String = UIDUtil.getUID(wrapperToSearch); for (var i:String in searchIn) { if (UIDUtil.getUID(searchIn[i]) == uidToSearch) return int(i); } return -1; } /** * Validate a given path compared with a project's * default source path and class path */ public static function validatePathAgainstSources(project:ProjectVO, wrapperToCompare:FileWrapper):Boolean { var pathToCompare:String = wrapperToCompare.nativePath + project.folderLocation.fileBridge.separator; // if no sourceFolder exists at all let add file anywhere if (!project[""sourceFolder""]) { return true; } if (project.hasOwnProperty(""classpaths"") && project[""classpaths""]) { var classPaths:Vector. = project[""classpaths""]; var hasPath:Boolean = classPaths.some(function(item:FileLocation, index:int, vector:Vector.):Boolean{ return pathToCompare.indexOf(item.fileBridge.nativePath) != -1; }); if (hasPath) { return true; } } if (pathToCompare.indexOf(project[""sourceFolder""].fileBridge.nativePath + project.folderLocation.fileBridge.separator) == -1) { return false; } return true; } /** * Checks if code-completion requisite FlexJS * available or not and returns */ public static function checkCodeCompletionFlexJSSDK():String { var hasFlex:Boolean = false; var FLEXJS_NAME_PREFIX:String = ""Apache Flex (FlexJS) ""; var path:String; var bestVersionValue:int = 0; for each (var i:SDKReferenceVO in model.userSavedSDKs) { var sdkName:String = i.name; if (sdkName.indexOf(FLEXJS_NAME_PREFIX) != -1) { var sdkVersion:String = sdkName.substr(FLEXJS_NAME_PREFIX.length, sdkName.indexOf("" "", FLEXJS_NAME_PREFIX.length) - FLEXJS_NAME_PREFIX.length); var versionParts:Array = sdkVersion.split(""-"")[0].split("".""); var major:int = 0; var minor:int = 0; var revision:int = 0; if (versionParts.length >= 3) { major = parseInt(versionParts[0], 10); minor = parseInt(versionParts[1], 10); revision = parseInt(versionParts[2], 10); } //FlexJS 0.7.0 is the minimum version supported by the //language server. this may change in the future. if (major > 0 || minor >= 7) { //convert the three parts of the version number //into a single value to compare to other versions. var currentValue:int = major * 1e6 + minor * 1000 + revision; if(bestVersionValue < currentValue) { //pick the newest available version of FlexJS //to power the language server. hasFlex = true; path = i.path; bestVersionValue = currentValue; model.isCodeCompletionJavaPresent = true; } } } } return path; } /** * Returns BOOL if version is newer than * given version * * Basically requires for FlexJS version check where * 0.8.0 added new compiler argument which do not works * in older versions */ public static function isNewerVersionSDKThan(olderVersion:int, sdkPath:String):Boolean { if (!sdkPath) return false; // we need some extra work to determine if FlexJS version is lower than 0.8.0 // to ensure addition of new compiler argument '-compiler.targets' // which do not works with SDK < 0.8.0 var sdkFullName:String; for each (var project:SDKReferenceVO in model.userSavedSDKs) { if (sdkPath == project.path) { sdkFullName = project.name; break; } } if (!sdkFullName) return false; var flexJSPrefixName:String = ""Apache Flex (FlexJS) ""; var royalePrefixName:String = ""Apache Royale ""; var isValidSdk:Boolean = false; if (sdkFullName.indexOf(flexJSPrefixName) > -1) { isValidSdk = true; } else if (sdkFullName.indexOf(royalePrefixName) > -1) { return true; } if (isValidSdk) { var sdkNamePrefixLength:int = flexJSPrefixName.length; var sdkVersion:String = sdkFullName.substr(sdkNamePrefixLength, sdkFullName.indexOf("" "", sdkNamePrefixLength) - sdkNamePrefixLength); var versionParts:Array = sdkVersion.split(""-"")[0].split("".""); var major:int = 0; var minor:int = 0; if (versionParts.length >= 3) { major = parseInt(versionParts[0], 10); minor = parseInt(versionParts[1], 10); } if (major > 0 || minor > olderVersion) { return true; } } return false; } /** * Sets requisite flags based on application file's tag * Required - AS3ProjectVO */ public static function checkIfRoyaleApplication(project:AS3ProjectVO):void { if (project.isRoyale) return; // probable termination if (project.targets.length == 0 || !project.targets[0].fileBridge.exists) return; var mainAppContent:String = project.targets[0].fileBridge.read() as String; var isBasicApp:Boolean = mainAppContent.indexOf(""js:Application"") > -1; var isMdlApp:Boolean = mainAppContent.indexOf(""mdl:Application"") > -1; var isJewelApp:Boolean = mainAppContent.indexOf(""j:Application"") > -1; var isMXApp:Boolean = mainAppContent.indexOf(""mx:Application"") > -1; var hasExpressNamespace:Boolean = mainAppContent.indexOf(""library://ns.apache.org/royale/express"") > -1; var hasRoyaleNamespace:Boolean = mainAppContent.indexOf(""library://ns.apache.org/royale/basic"") > -1 || hasExpressNamespace; var hasFlexJSNamespace:Boolean = mainAppContent.indexOf(""library://ns.apache.org/flexjs/basic"") > -1; var hasJewelNamespace:Boolean = mainAppContent.indexOf(""library://ns.apache.org/royale/jewel"") > -1; var hasMXNamespace:Boolean = mainAppContent.indexOf(""library://ns.apache.org/royale/mx"") > -1; var isRoyaleModule:Boolean = mainAppContent.indexOf(""s:Module"") > -1 || mainAppContent.indexOf(""mx:Module"") || mainAppContent.indexOf(""js:UIModule""); var isRoyaleNamespace:Boolean = hasRoyaleNamespace || hasJewelNamespace || hasMXNamespace || hasExpressNamespace; if ((isBasicApp || isMdlApp || isJewelApp || isMXApp || isRoyaleModule) && (hasFlexJSNamespace || isRoyaleNamespace)) { // FlexJS Application project.isFlexJS = true; project.isRoyale = isRoyaleNamespace; // FlexJS MDL applicaiton project.isMDLFlexJS = isMdlApp; } else { project.isFlexJS = project.isMDLFlexJS = project.isRoyale = false; } } /** * Returns possible Java exeuctable in system */ public static function getExecutableJavaLocation():FileLocation { var executableFile:FileLocation; var separator:String = model.fileCore.separator; if (ConstantsCoreVO.IS_MACOS) { if (model.javaPathForTypeAhead && model.javaPathForTypeAhead.fileBridge.exists) { executableFile = new FileLocation(model.javaPathForTypeAhead.fileBridge.nativePath.concat(separator, ""bin"", separator, ""java"")); } else { executableFile = new FileLocation(separator.concat(""usr"", separator, ""bin"", separator, ""java"")); } } else { if (model.javaPathForTypeAhead && model.javaPathForTypeAhead.fileBridge.exists) { executableFile = new FileLocation(model.javaPathForTypeAhead.fileBridge.nativePath.concat(separator, ""bin"", separator, ""javaw.exe"")); if (!executableFile.fileBridge.exists) { executableFile = new FileLocation(model.javaPathForTypeAhead.fileBridge.nativePath.concat(separator, ""javaw.exe"")); } // in case of user setup by 'javaPath/bin' } else { var javaFolder:String = Capabilities.supports64BitProcesses ? ""Program Files (x86)"" : ""Program Files""; var tmpJavaLocation:FileLocation = new FileLocation(""C:"".concat(separator, javaFolder, separator, ""Java"")); if (tmpJavaLocation.fileBridge.exists) { var javaFiles:Array = tmpJavaLocation.fileBridge.getDirectoryListing(); for each (var j:Object in javaFiles) { if (j.nativePath.indexOf(""jre"") != -1) { executableFile = new FileLocation(j.nativePath + separator + ""bin"" + separator + ""javaw.exe""); break; } } } } } // finally return executableFile; } /** * Closes all the opened editors relative to a certain project path */ public static function closeAllRelativeEditors(projectOrWrapper:Object, isSkipSaveConfirmation:Boolean=false, completionHandler:Function=null, isCloseWhenDone:Boolean=true, exceptEditor:IContentWindow=null):void { var projectReferencePath:String; var editorsCount:int = model.editors.length; var hasChangesEditors:mx.collections.ArrayCollection = new mx.collections.ArrayCollection(); var editorsToClose:Array = []; // closes all opened file editor instances belongs to the deleted project // closing is IMPORTANT // if projectOrWrapper==null, it'll close all opened editors irrespective of // any particular project (example usage in 'Close All' option in File menu) if (projectOrWrapper) { if (projectOrWrapper is ProjectVO) { projectReferencePath = (projectOrWrapper as ProjectVO).folderLocation.fileBridge.nativePath; } else if (projectOrWrapper is FileWrapper && (projectOrWrapper as FileWrapper).projectReference) { projectReferencePath = (projectOrWrapper as FileWrapper).projectReference.path; } } for (var i:int = 0; i < editorsCount; i++) { if (model.editors[i] == exceptEditor) { continue; } if ((model.editors[i] is IFileContentWindow) && model.editors[i].currentFile && (!projectReferencePath || (model.editors[i].hasOwnProperty(""projectPath"") && model.editors[i].projectPath == projectReferencePath))) { var editor:IContentWindow = model.editors[i]; if (editor) { editorsToClose.push(editor); if (!isSkipSaveConfirmation && editor.isChanged()) { hasChangesEditors.addItem({file:editor, isSelected:true}); } } } else if (model.editors[i] is SettingsView && model.editors[i].associatedData && (!projectReferencePath || ProjectVO(model.editors[i].associatedData).folderLocation.fileBridge.nativePath == projectReferencePath)) { editorsToClose.push(model.editors[i]); if (!isSkipSaveConfirmation && model.editors[i].isChanged()) { hasChangesEditors.addItem({file:model.editors[i], isSelected:true}); } } else if (model.editors[i].hasOwnProperty(""label"") && ConstantsCoreVO.NON_CLOSEABLE_TABS.indexOf(model.editors[i].label) == -1) { if (!isSkipSaveConfirmation && model.editors[i].isChanged()) { hasChangesEditors.addItem({file:model.editors[i], isSelected:true}); } else if (projectOrWrapper == null && completionHandler == null && model.editors[i] != SplashScreen) { editorsToClose.push(model.editors[i]); } } } // check if the editors has any changes if (!isSkipSaveConfirmation && hasChangesEditors.length > 0) { var modListPopup:ModifiedFileListPopup = PopUpManager.createPopUp(FlexGlobals.topLevelApplication as DisplayObject, ModifiedFileListPopup, true) as ModifiedFileListPopup; modListPopup.collection = hasChangesEditors; modListPopup.addEventListener(CloseEvent.CLOSE, onModListClosed); PopUpManager.centerPopUp(modListPopup); } else { onModListClosed(null); } /* * @local */ function onModListClosed(event:CloseEvent):void { if (event) event.target.removeEventListener(CloseEvent.CLOSE, onModListClosed); // in case we just want save process to the unsaved editors // but not to close the editors when done // default - true if (isCloseWhenDone) { // close all the tabs without waiting for anything further for each (var j:IContentWindow in editorsToClose) { GlobalEventDispatcher.getInstance().dispatchEvent( new CloseTabEvent(CloseTabEvent.EVENT_CLOSE_TAB, j as DisplayObject, true) ); } } // notify the caller if (completionHandler != null) completionHandler(); } } /** * Parse all acceptable files in a given project */ public static function parseFilesList(flexCollection:IList=null, feathersCollection:feathers.data.ArrayCollection=null, project:ProjectVO=null, readableExtensions:Array=null, isSourceFolderOnly:Boolean=false):void { if (project) { if (isSourceFolderOnly && (project as AS3ProjectVO).sourceFolder) { // lets search for the probable existing fileWrapper object // instead of creating a new one - that could be expensive var sourceWrapper:FileWrapper = findFileWrapperAgainstFileLocation(project.projectFolder, (project as AS3ProjectVO).sourceFolder); if (sourceWrapper) { initiateFilesParsingByPath(sourceWrapper.file.fileBridge.nativePath); return; } } initiateFilesParsingByPath(project.projectFolder.nativePath); } else { for each (var i:ProjectVO in model.projects) { initiateFilesParsingByPath(i.projectFolder.nativePath); } } /* * @local */ function initiateFilesParsingByPath(value:String):void { var tmpFSP:FileSystemParser = new FileSystemParser(); tmpFSP.addEventListener(FileSystemParser.EVENT_PARSE_COMPLETED, onFilesListParseCompleted); tmpFSP.parseFilesPaths(value, """", readableExtensions); } function onFilesListParseCompleted(event:Event):void { event.currentTarget.removeEventListener(FileSystemParser.EVENT_PARSE_COMPLETED, onFilesListParseCompleted); var parsedFilesList:Array = (event.target as FileSystemParser).resultsArrayFormat; var fileCount:int = parsedFilesList.length; var separator:String = model.fileCore.separator; var tmpNameLabel:String; var tmpNameExtension:String; for each (var i:String in parsedFilesList) { //var resource:ResourceVO = ResourceVO(parsedFilesList.getItemAt(i)); //resources.add(resource); if (i != """") { tmpNameLabel = i.substr(i.lastIndexOf(separator)+1, i.length); tmpNameExtension = tmpNameLabel.substr(tmpNameLabel.lastIndexOf(""."")+1, tmpNameLabel.length); if (!readableExtensions || (readableExtensions && isAcceptableResource(tmpNameExtension, readableExtensions))) { if (flexCollection) flexCollection.addItem({name:tmpNameLabel, extension: tmpNameExtension, resourcePath: i}); if (feathersCollection) feathersCollection.add({name:tmpNameLabel, extension: tmpNameExtension, resourcePath: i}); } } } } } /** * Returns menu options on current * recent opened projects */ public static function getRecentProjectsMenu():MenuItem { var openRecentLabel:String = ResourceManager.getInstance().getString('resources','OPEN_RECENT_PROJECTS'); var openProjectMenu:MenuItem = new MenuItem(openRecentLabel); openProjectMenu.parents = [""File"", openRecentLabel]; openProjectMenu.items = new Vector.(); for each (var i:ProjectReferenceVO in model.recentlyOpenedProjects) { if (i.name) { var menuItem:MenuItem = new MenuItem(i.name, null, null, ""eventOpenRecentProject""); menuItem.data = i; openProjectMenu.items.push(menuItem); } } openProjectMenu.items.sort(menuComparer); return openProjectMenu; } /** * Returns menu options on current * recent opened projects */ public static function getRecentFilesMenu():MenuItem { var openRecentLabel:String = ResourceManager.getInstance().getString('resources','OPEN_RECENT_FILES'); var openFileMenu:MenuItem = new MenuItem(openRecentLabel); openFileMenu.parents = [""File"", openRecentLabel]; openFileMenu.items = new Vector.(); for each (var i:ProjectReferenceVO in model.recentlyOpenedFiles) { if (i.name) { var menuItem:MenuItem = new MenuItem(i.name, null, null, ""eventOpenRecentFile""); menuItem.data = i; openFileMenu.items.push(menuItem); } } openFileMenu.items.sort(menuComparer); return openFileMenu; } /** * Set project menu type based on possible field */ public static function setProjectMenuType(value:ProjectVO):void { var currentMenuType:String; // the type-check ordering are important if (value is AS3ProjectVO) { if ((value as AS3ProjectVO).isFlexJS || (value as AS3ProjectVO).isRoyale || (value as AS3ProjectVO).isMDLFlexJS) { currentMenuType = ProjectMenuTypes.JS_ROYALE; } else if ((value as AS3ProjectVO).isLibraryProject) { currentMenuType = ProjectMenuTypes.LIBRARY_FLEX_AS; } else if ((value as AS3ProjectVO).isPrimeFacesVisualEditorProject) { currentMenuType = ProjectMenuTypes.VISUAL_EDITOR_PRIMEFACES; }else if ((value as AS3ProjectVO).isDominoVisualEditorProject) { currentMenuType = ProjectMenuTypes.VISUAL_EDITOR_DOMINO; } else if ((value as AS3ProjectVO).isVisualEditorProject) { currentMenuType = ProjectMenuTypes.VISUAL_EDITOR_FLEX; } else if ((value as AS3ProjectVO).isActionScriptOnly) { currentMenuType = ProjectMenuTypes.PURE_AS; } else { currentMenuType = ProjectMenuTypes.FLEX_AS; } } else if (value is GrailsProjectVO) { currentMenuType = ProjectMenuTypes.GRAILS; } else if (value is JavaProjectVO) { currentMenuType = ProjectMenuTypes.JAVA; } else if (value is HaxeProjectVO) { currentMenuType = ProjectMenuTypes.HAXE; } else if (value is OnDiskProjectVO) { currentMenuType = ProjectMenuTypes.ON_DISK; } if (!value.menuType) { value.menuType = currentMenuType; } else if (value.menuType && value.menuType.indexOf(currentMenuType) == -1) { value.menuType += "",""+ currentMenuType; } // version-control check if (!value.hasVersionControlType) { // git check GlobalEventDispatcher.getInstance().dispatchEvent(new ProjectEvent(ProjectEvent.CHECK_GIT_PROJECT, value)); // svn check GlobalEventDispatcher.getInstance().dispatchEvent(new ProjectEvent(ProjectEvent.CHECK_SVN_PROJECT, value)); } } /** * Returns encoded string to run on Windows' shell */ public static function getEncodedForShell(value:String, forceOSXEncode:Boolean=false, forceWindowsEncode:Boolean=false):String { var tmpValue:String = """"; if (ConstantsCoreVO.IS_MACOS || forceOSXEncode) { // @note // in case of /bash one should send the value surrounded by $'' // i.e. $' +encodedValue+ ' tmpValue = value.replace(/(\\\\)/g, '\\\\\\\\""'); tmpValue = value.replace(/("")/g, '\\\\""'); tmpValue = value.replace(/(')/g, ""\\\\'""); } else if (!ConstantsCoreVO.IS_MACOS || forceWindowsEncode) { for (var i:int; i < value.length; i++) { tmpValue += ""^""+ value.charAt(i); } } return tmpValue; } /** * Reads through project configuration and * returns the project name */ public static function getProjectNameFromConfiguration(file:FileLocation=null, path:String=null):String { if (!file && !path) return null; if (!file && path) file = new FileLocation(path); var configurationXML:XML = new XML(file.fileBridge.read() as String); if (file.fileBridge.extension == ""project"") { // flash-builder projec return String(configurationXML.name); } else { // moonshine projects return file.fileBridge.nameWithoutExtension; } return null; } public static function getConsolePath():String { var separator:String = model.fileCore.separator; if (!ConstantsCoreVO.IS_MACOS) { // in windows return ""c:"".concat(separator, ""Windows"", separator, ""System32"", separator, ""cmd.exe""); } else { // in mac return separator.concat(""bin"", separator, ""bash""); } } public static function isMavenAvailable():Boolean { if (!model.mavenPath || model.mavenPath == """") { return false; } var component:Object = model.flexCore.getComponentByType(SDKTypes.MAVEN); if (component && component.pathValidation) { return model.fileCore.isPathExists(model.mavenPath + model.fileCore.separator + component.pathValidation); } return true; } public static function isGradleAvailable():Boolean { if (!model.gradlePath || model.gradlePath == """") { return false; } var component:Object = model.flexCore.getComponentByType(SDKTypes.GRADLE); if (component && component.pathValidation) { return model.fileCore.isPathExists(model.gradlePath + model.fileCore.separator + component.pathValidation); } return true; } public static function isGrailsAvailable():Boolean { if (!model.grailsPath || model.grailsPath == """") { return false; } var component:Object = model.flexCore.getComponentByType(SDKTypes.GRAILS); if (component && component.pathValidation) { return model.fileCore.isPathExists(model.grailsPath + model.fileCore.separator + component.pathValidation); } return true; } public static function isNodeAvailable():Boolean { if (!model.nodePath || model.nodePath == """") { return false; } var component:Object = model.flexCore.getComponentByType(SDKTypes.NODEJS); if (component && component.pathValidation) { if (model.fileCore.isPathExists(model.nodePath + model.fileCore.separator + component.pathValidation)) return true; else if (model.fileCore.isPathExists(model.nodePath + model.fileCore.separator + ""node"")) return true; return false; } return true; } public static function isHaxeAvailable():Boolean { if (!model.haxePath || model.haxePath == """") { return false; } //TODO: use path validation with SDKTypes var haxeName:String = ConstantsCoreVO.IS_MACOS ? ""haxe"" : ""haxe.exe""; return model.fileCore.isPathExists(model.haxePath + model.fileCore.separator + haxeName); } public static function isNekoAvailable():Boolean { if (!model.nekoPath || model.nekoPath == """") { return false; } //TODO: use path validation with SDKTypes var nekoName:String = ConstantsCoreVO.IS_MACOS ? ""neko"" : ""neko.exe""; return model.fileCore.isPathExists(model.nekoPath + model.fileCore.separator + nekoName); } public static function getMavenBinPath():String { if (!model.mavenPath || model.mavenPath == """") { return null; } var separator:String = model.fileCore.separator; var mavenLocation:FileLocation = new FileLocation(model.mavenPath); var mavenBin:String = ""bin"" + separator; if (mavenLocation.fileBridge.nativePath.lastIndexOf(model.fileCore.separator +""bin"") > -1) { mavenBin = """"; } if (!mavenLocation.fileBridge.exists) { return null; } else if (!ConstantsCoreVO.IS_MACOS) { return mavenLocation.resolvePath(mavenBin + ""mvn.cmd"").fileBridge.nativePath; } else { return UtilsCore.convertString(mavenLocation.resolvePath(mavenBin + ""mvn"").fileBridge.nativePath); } return null; } public static function getGradleBinPath():String { if (!model.gradlePath || model.gradlePath == """") { return null; } var gradleLocation:FileLocation = new FileLocation(model.gradlePath); var gradleBin:String = ""bin"" + model.fileCore.separator; if (gradleLocation.fileBridge.nativePath.lastIndexOf(model.fileCore.separator +""bin"") > -1) { gradleBin = """"; } if (!gradleLocation.fileBridge.exists) { return null; } else if (!ConstantsCoreVO.IS_MACOS) { return gradleLocation.resolvePath(gradleBin + ""gradle.bat"").fileBridge.nativePath; } else { return UtilsCore.convertString(gradleLocation.resolvePath(gradleBin + ""gradle"").fileBridge.nativePath); } return null; } public static function getGrailsBinPath():String { if (!model.grailsPath || model.grailsPath == """") { return null; } var separator:String = model.fileCore.separator; var grailsLocation:FileLocation = new FileLocation(model.grailsPath); var grailsBin:String = ""bin"" + separator; if (grailsLocation.fileBridge.nativePath.lastIndexOf(model.fileCore.separator +""bin"") > -1) { grailsBin = """"; } if (!grailsLocation.fileBridge.exists) { return null; } else if (!ConstantsCoreVO.IS_MACOS) { return grailsLocation.resolvePath(grailsBin + ""grails.bat"").fileBridge.nativePath; } else { return UtilsCore.convertString(grailsLocation.resolvePath(grailsBin + ""grails"").fileBridge.nativePath); } return null; } public static function getNodeBinPath():String { if (!model.nodePath || model.nodePath == """") { return null; } var nodeLocation:FileLocation = new FileLocation(model.nodePath); if (!nodeLocation.fileBridge.exists) { return null; } else if (!ConstantsCoreVO.IS_MACOS) { return nodeLocation.resolvePath(""node.exe"").fileBridge.nativePath; } else { if (nodeLocation.resolvePath(""node"").fileBridge.exists) { return UtilsCore.convertString(nodeLocation.resolvePath(""node"").fileBridge.nativePath); } else if (nodeLocation.resolvePath(""bin/node"").fileBridge.exists) { return UtilsCore.convertString(nodeLocation.resolvePath(""bin/node"").fileBridge.nativePath); } } return null; } public static function isDefaultSDKAvailable():Boolean { if (!model.defaultSDK || !model.defaultSDK.fileBridge.exists) { return false; } return true; } public static function isJavaForTypeaheadAvailable():Boolean { if (!model.javaPathForTypeAhead || !model.javaPathForTypeAhead.fileBridge.exists) { return false; } var component:Object = model.flexCore.getComponentByType(SDKTypes.OPENJAVA); if (component && component.pathValidation) { return model.javaPathForTypeAhead.fileBridge.resolvePath(component.pathValidation).fileBridge.exists; } return true; } public static function isJava8Present():Boolean { if (model.java8Path && model.java8Path.fileBridge.exists) { return true; } return false; } public static function isAntAvailable():Boolean { if (!model.antHomePath || !model.antHomePath.fileBridge.exists) { return false; } var component:Object = model.flexCore.getComponentByType(SDKTypes.ANT); if (component && component.pathValidation) { return model.antHomePath.fileBridge.resolvePath(component.pathValidation).fileBridge.exists; } return true; } public static function isSVNPresent():Boolean { if (!model.svnPath || !model.fileCore.isPathExists(model.svnPath)) { return false; } var component:Object = model.flexCore.getComponentByType(SDKTypes.SVN); if (component && component.pathValidation) { return model.flexCore.isValidExecutableBy(SDKTypes.SVN, model.svnPath, component.pathValidation); } return true; } public static function isGitPresent():Boolean { if (!model.gitPath || !model.fileCore.isPathExists(model.gitPath)) { return false; } var component:Object = model.flexCore.getComponentByType(SDKTypes.GIT); if (component && component.pathValidation) { return model.flexCore.isValidExecutableBy(SDKTypes.GIT, model.gitPath, component.pathValidation); } return true; } public static function isVagrantAvailable():Boolean { if (!model.vagrantPath || !model.fileCore.isPathExists(model.vagrantPath)) { return false; } var component:Object = model.flexCore.getComponentByType(SDKTypes.VAGRANT); if (component && component.pathValidation) { return model.flexCore.isValidExecutableBy(SDKTypes.VAGRANT, model.vagrantPath, component.pathValidation); } return false; } public static function getVagrantBinPath():String { if (!model.vagrantPath || !model.fileCore.isPathExists(model.vagrantPath)) { return null; } var vagrantExecutable:String = ConstantsCoreVO.IS_MACOS ? ""vagrant"" : ""vagrant.exe""; if (model.fileCore.isPathExists([model.vagrantPath, vagrantExecutable].join(model.fileCore.separator))) { return [model.vagrantPath, vagrantExecutable].join(model.fileCore.separator); } if (model.fileCore.isPathExists([model.vagrantPath, ""bin"", vagrantExecutable].join(model.fileCore.separator))) { return [model.vagrantPath, ""bin"", vagrantExecutable].join(model.fileCore.separator); } return null; } public static function isMacPortsAvailable():Boolean { if (!model.macportsPath || !model.fileCore.isPathExists(model.macportsPath)) { return false; } var component:Object = model.flexCore.getComponentByType(SDKTypes.MACPORTS); if (component && component.pathValidation) { return model.flexCore.isValidExecutableBy(SDKTypes.MACPORTS, model.macportsPath, component.pathValidation); } return false; } public static function getMacPortsBinPath():String { if (!model.macportsPath || !model.fileCore.isPathExists(model.macportsPath)) { return null; } var mportsExecutable:String = ""port""; if (model.fileCore.isPathExists([model.macportsPath, mportsExecutable].join(model.fileCore.separator))) { return [model.macportsPath, mportsExecutable].join(model.fileCore.separator); } if (model.fileCore.isPathExists([model.macportsPath, ""bin"", mportsExecutable].join(model.fileCore.separator))) { return [model.macportsPath, ""bin"", mportsExecutable].join(model.fileCore.separator); } return null; } public static function isNotesDominoAvailable():Boolean { if (!model.notesPath || !model.fileCore.isPathExists(model.notesPath)) { return false; } var component:Object = model.flexCore.getComponentByType(SDKTypes.NOTES); if (component && component.pathValidation) { return model.fileCore.resolvePath(model.notesPath +""/""+ component.pathValidation).fileBridge.exists; //return model.flexCore.isValidExecutableBy(SDKTypes.NOTES, model.notesPath, component.pathValidation); } return true; } public static function getLineBreakEncoding():String { return (ConstantsCoreVO.IS_MACOS ? ""\\n"" : ""\\r\\n""); } public static function getVisualEditorSourceFile(fw:FileWrapper):FileLocation { var as3ProjectVO:AS3ProjectVO = UtilsCore.getProjectFromProjectFolder(fw) as AS3ProjectVO; if (as3ProjectVO && as3ProjectVO.isVisualEditorProject) { var veSourcePathFile:String = fw.file.fileBridge.nativePath .replace(as3ProjectVO.sourceFolder.fileBridge.nativePath, as3ProjectVO.visualEditorSourceFolder.fileBridge.nativePath) .replace(/.mxml$|.xhtml$|.form/, "".xml""); return new FileLocation(veSourcePathFile); } return null; } private static function parseChildrens(value:FileWrapper, collection:IList, readableExtensions:Array=null):void { if (!value) return; var extension:String = value.file.fileBridge.extension; if (!value.file.fileBridge.isDirectory && (extension != null) && isAcceptableResource(extension)) { collection.addItem(new ResourceVO(value.file.fileBridge.name, value)); return; } if ((value.children is Array) && (value.children as Array).length > 0) { for each (var c:FileWrapper in value.children) { extension = c.file.fileBridge.extension; if (!c.file.fileBridge.isDirectory && (extension != null) && isAcceptableResource(extension, readableExtensions)) { collection.addItem(new ResourceVO(c.file.fileBridge.name, c)); } else if (c.file.fileBridge.isDirectory) { parseChildrens(c, collection, readableExtensions); } } } } private static function isAcceptableResource(extension:String, readableExtensions:Array=null):Boolean { readableExtensions ||= ConstantsCoreVO.READABLE_FILES; return readableExtensions.some( function isValidExtension(item:Object, index:int, arr:Array):Boolean { return item == extension; }); } private static function menuComparer(itemA:MenuItem, itemB:MenuItem):Number { if (itemA.label.toLowerCase() < itemB.label.toLowerCase()) return -1; else if (itemA.label.toLowerCase() > itemB.label.toLowerCase()) return 1; else return 0; } } }",12458,False,2216.5185816314297,median ":toc: :toclevels: 4 :sectnums: = MLPerf Training Rules Version 1.0 March 25, 2021 == Overview This document describes how to implement the MLPerf Training Suite using an ML framework and how to use that implementation to measure the performance of an ML software framework or hardware. There are seperate rules for the submission, review, and publication process for all MLPerf benchmarks https://github.com/mlperf/policies/blob/master/submission_rules.adoc[here]. The MLPerf name and logo are trademarks. In order to refer to a result using the MLPerf name, the result must conform to the letter and spirit of the rules specified in this document. The MLPerf organization reserves the right to solely determine if a use of its name or logo is acceptable. === Definitions (read this section carefully) The following definitions are used throughout this document: _Performance_ always refers to execution speed. _Quality_ always refers to a model’s ability to produce “correct” outputs. A _system_ consists of a defined set of hardware resources such as processors, memories, disks, and interconnect. It also includes specific versions of all software such as operating system, compilers, libraries, and drivers that significantly influences the running time of a benchmark, excluding the ML framework. A _framework_ is a specific version of a software library or set of related libraries, possibly with associated offline compiler, for training ML models using a system. Examples include specific versions of Caffe2, MXNet, PaddlePaddle, pyTorch, or TensorFlow. A _benchmark_ is an abstract problem that can be solved using ML by training a model based on a specific dataset or simulation environment to a target quality level. A _suite_ is a specific set of benchmarks. A _division_ is a set of rules for implementing benchmarks from a suite to produce a class of comparable results. A _reference implementation_ is a specific implementation of a benchmark provided by the MLPerf organization. A _benchmark implementation_ is an implementation of a benchmark in a particular framework by a user under the rules of a specific division. A _submission implementation set_ is a set of benchmark implementations for one or more benchmarks from a suite under the rules of a specific division using the same framework. A _run_ is a complete execution of an implementation on a system, training a model from initialization to the quality target. A _run result_ is the wallclock time required for a run. A _reference result_ is the result provided by the MLPerf organization for each reference implementation A _benchmark result_ is the mean of a benchmark-specific number of run results, dropping the highest and lowest results. The result is then normalized to the reference result for that benchmark. Normalization is of the form (reference result / benchmark result) such that a better benchmark result produces a higher number. A _submission result set_ is a one benchmark result for each benchmark implementation in a submission implementation set. A _submission_ is a submission implementation set and a corresponding submission result set. A _custom summary result_ is the weighted geometric mean of an arbitrary set of results from a specific submission. MLPerf endorses this methodology for computing custom summary results but does not endorse any official summary result. == General rules The following rules apply to all benchmark implementations. === Strive to be fair Benchmarking should be conducted to measure the framework and system performance as fairly as possible. Ethics and reputation matter. === System and framework must be consistent The same system and framework must be used for a submission result set. Note that the reference implementations do not all use the same framework. === Benchmark detection is not allowed The framework and system should not detect and behave differently for benchmarks. === Pre-training is not allowed Unless part of the definition of a benchmark, the implementation should not encode any information about the content of the dataset or a successful model’s state in any form. High-level statistical information about the dataset, such as distribution of sizes, may be used. For benchmarks which are defined as starting from a fixed set of weights, such as a checkpoint or backbone, the implementation should start from the weights provided in the benchmark reference definition, or if that is not posssible, provide information and code sufficient for reproducing how those starting weights were obtained. For v0.7, sets of weights used in v0.6 are allowed. == Benchmarks The benchmark suite consists of the benchmarks shown in the following table. |=== |Area|Problem |Dataset |Vision |Image classification |ImageNet | |Image segmentation (medical) |KiTS19 | |Object detection (light weight) |COCO | |Object detection (heavy weight) |COCO |Language |Speech recognition |LibriSpeech | |NLP |Wikipedia 2020/01/01 |Commerce |Recommendation |1TB Click Logs |Research |Reinforcement learning |Go |=== The MLPerf organization provides a reference implementation of each benchmark, which includes the following elements: Code that implements the model in a framework. A plain text “README.md” file that describes: * Problem ** Dataset/Environment ** Publication/Attribution ** Data preprocessing ** Training and test data separation ** Training data order ** Test data order ** Simulation environment (RL models only) ** Steps necessary for reproducing the initial set of weights, if an initial set of non-standard weights is used. For v0.7, weights from v0.6 may be used without this information. ** Publication/Attribution ** List of layers ** Weight and bias initialization ** Loss function ** Optimizer * Quality ** Quality metric ** Quality target ** Evaluation frequency (training items between quality evaluations) ** Evaluation thoroughness (test items per quality evaluation) * Directions ** Steps to configure machine ** Steps to download and verify data ** Steps to run and time A “download_dataset” script that downloads the dataset. A “verify_dataset” script that verifies the dataset against the checksum. A “run_and_time” script that executes the benchmark and reports the wall-clock time. == Divisions There are two divisions of the benchmark suite, the Closed division and the Open division. === Closed Division The Closed division requires using the same preprocessing, model, training method, and quality target as the reference implementation. The closed division models and quality targets are: |=== |Area |Problem |Model |Target |Vision |Image classification |ResNet-50 v1.5 |75.90% classification | |Image segmentation (medical) |U-Net3D |0.908 Mean DICE score | |Object detection (light weight) |SSD |23.0% mAP | |Object detection (heavy weight) |Mask R-CNN |0.377 Box min AP and 0.339 Mask min AP |Language | Speech recognition | RNN-T | 0.058 Word Error Rate | |NLP |BERT |0.720 Mask-LM accuracy |Commerce |Recommendation |DLRM |0.8025 AUC |Research |Reinforcement learning |Mini Go (based on Alpha Go paper) |50% win rate vs. checkpoint |=== Closed division benchmarks must be referred to using the benchmark name plus the term Closed, e.g. “for the Image Classification Closed benchmark, the system achieved a result of 7.2.” === Open Division The Open division allows using arbitrary training data, preprocessing, model, and/or training method. However, the Open division still requires using supervised or reinforcement machine learning in which a model is iteratively improved based on training data, simulation, or self-play. Open division benchmarks must be referred to using the benchmark name plus the term Open, e.g. “for the Image Classification Open benchmark, the system achieved a result of 7.2.” == Basics === Random numbers CLOSED: Random numbers must be generated using stock random number generators. Random number generators may be seeded from the following sources: * Clock * System source of randomness, e.g. /dev/random or /dev/urandom * Another random number generator initialized with an allowed seed Random number generators may be initialized repeatedly in multiple processes or threads. For a single run, the same seed may be shared across multiple processes or threads. OPEN: Any random number generation may be used. === Numerical formats CLOSED: The numerical formats fp64, fp32, tf32, fp16, bfloat16, Graphcore FLOAT 16.16, int8, uint8, int4, and uint4 are pre-approved for use. Additional formats require explicit approval. Scaling may be added where required to compensate for different precision. Reference Convergence Points must be obtained using FP32 precision, or FP32 emulation with explanation of the methodology for emulation. OPEN: Any format and scaling may be used. === Epoch numbering Epochs should always be numbered from 1. === Result rounding Public results should be rounded normally. == Data Set === Data State at Start of Run CLOSED: Each reference implementation includes a script to download the input dataset and script to verify the dataset using a checksum. The data must then be preprocessed in a manner consistent with the reference implementation, excepting any transformations that must be done for each run (e.g. random transformations). The data may also be reformatted for the target system provided that the reformatting does not introduce new information or introduce duplicate copies of data. OPEN: Any public dataset may be used for training the model, however the evaluation data must be drawn from the benchmark dataset in a manner consistent with the reference. You must flush the cache or restart the system prior to benchmarking. Data can start on any durable storage system such as local disks and cloud storage systems. This explicitly excludes RAM. === Preprocessing During the Run Only preprocessing that must be done for each run (e.g. random transformations) must be timed. CLOSED: The same preprocessing steps as the reference implementation must be used. OPEN: Any preprocessing steps are allowed for training data. However, each datum must be preprocessed individually in a manner that is not influenced by any other data. The evaluation data must be preprocessed in a manner consistent with reference. === Data Representation CLOSED: Images must have the same size as in the reference implementation. Mathematically equivalent padding of images is allowed. CLOSED: For benchmarks with sequence inputs, you may choose a length N and either truncate all examples to length N or throw out all examples which exceed length N. This must be done uniformly for all examples. This may only be done on the training set and not the evaluation set. CLOSED: Two ways to represent the Mask R-CNN mask are permitted. One is a polygon and the other is a scalable bitmask. OPEN: The closed division data representations restrictions only apply at the start of the run. Data may be represented in an arbitrary fashion during the run. === Other Uses of Data Input encoding data, such as language vocabulary, or the set of possible labels may used during pre-processing or execution without counting as ""touching the training data"" for timing purposes. === Training and Test Sets CLOSED: If applicable, the dataset must be separated into training and test sets in the same manner as the reference implementation. OPEN: If applicable, the test dataset must be extracted in the same manner as the reference implementation. The training data set may not contain data that appears in the test set. === Training Data Order CLOSED: the training and test data must be traversed in the same conceptual order as the reference implementation. For instance, the data might be traversed sequentially or randomly with uniform distribution. Batch size, shard size, and the random number generator will affect order. Where data pipelines randomly order data, arbitrary sharding, batching, and packing are allowed provided that (1) the data is still overall randomly ordered and not ordered to improve convergence and (2) each datum still appears exactly once. OPEN: The training data may be traversed in any order. The test data must be traversed in the same order as the reference implementation. == RL Environment CLOSED: The implementation must use the same RL algorithm and simulator or game as the reference implementation, with the same parameters. OPEN: The implementation may use a different RL algorithm but must use the same simulator or game with the same parameters. If the reference implementation generates all data online, the Open division implementation must also generate all data online. It is allowed and encouraged to parallelize and otherwise optimize (e.g. by implementing in a compiled language) the RL environment provided that the semantics are preserved. == Model CLOSED: The benchmark implementation must use the same model as the reference implementation, as defined by the remainder of this section. OPEN: The benchmark implementation may use a different model. === Graph Definition CLOSED: Each of the current frameworks has a graph that describes the operations performed during the forward propagation of training. The frameworks automatically infer and execute the corresponding back-propagation computations from this graph. Benchmark implementations must use the same graph as the reference implementation. === Weight and Bias Initialization CLOSED: Weights and biases must be initialized using the same constant or random value distribution as the reference implementation, unless a pre-trained set of weights, such as a checkpoint or backbone, is used by the reference. OPEN: Weights and biases must be initialized using a consistent constant or random value distribution. === Graph Execution CLOSED: Frameworks are free to optimize the non-weight parts of the computation graph provided that the changes are mathematically equivalent. So optimizations and graph / code transformations of the flavor of dead code elimination, common subexpression elimination, loop-invariant code motion, and recomputation of node state are entirely allowed. OPEN: Frameworks are free to alter the graph. == Training Loop === Hyperparameters CLOSED: By default, the hyperparameters must be the same as the reference. Hyperparameters include the optimizer used and values like the regularization norms and weight decays. The implementation of the optimizer must match the optimizer specified in the Appendex: Allowed Optimizer. The Appendex lists which optimizers in the popular deep learning frameworks are compliant by default. If a submission uses an alternate implementation, the submitter must describe the optimizer's equation and demonstrate equivalence with the approved optimizers on that list. The following table lists the tunable hyperparameters for each allowed model,optimizer combination. The value of each tunable hyperparameter must meet the listed constraint. The MLPerf verifier scripts checks all hyperparameters except those with names marked with asterisks. If a hyperparameter is marked with one asterisk, it must be checked manually. If a hyperparameter is marked with two asterisks, it is also not logged and it must be checked manually in the code. If the verifier and the constraints in this table differ, the verifier (specifically, the version on the date of submission unless otherwise decided by the review committee) is the source of truth. |=== |Model |Optimizer |Name |Constraint |Definition |Reference Code |bert |lamb |global_batch_size |unconstrained |The glboal batch size for training. |--train_batch_size |bert |lamb |opt_base_learning_rate |unconstrained |The base learning rate. |--learning_rate |bert |lamb |opt_epsilon |unconstrained |adam epsilon |link:https://github.com/mlperf/training/blob/fb058e3849c25f6c718434e60906ea3b0cb0f67d/language_model/tensorflow/bert/optimization.py#L75[reference code] |bert |lamb |opt_learning_rate_training_steps |unconstrained |Step at which your reach the lowest learning late |link:https://github.com/mlperf/training/blob/master/language_model/tensorflow/bert/run_pretraining.py#L64[reference code] |bert |lamb |opt_learning_rate_warmup_steps |unconstrained |""num_warmup_steps"" |link:https://github.com/mlperf/training/blob/master/language_model/tensorflow/bert/optimization.py#L34[reference code] |bert |lamb |num_warmup_steps |unconstrained |Number of steps for linear warmup. |--num_warmup_steps |bert |lamb |start_warmup_step |unconstrained |--start_warmup_step |--start_warmup_step |bert |lamb |opt_lamb_beta_1 |unconstrained |adam beta1 |link:https://github.com/mlperf/training/blob/fb058e3849c25f6c718434e60906ea3b0cb0f67d/language_model/tensorflow/bert/optimization.py#L73[reference code] |bert |lamb |opt_lamb_beta_2 |unconstrained |adam beta2 |link:https://github.com/mlperf/training/blob/fb058e3849c25f6c718434e60906ea3b0cb0f67d/language_model/tensorflow/bert/optimization.py#L74[reference code] |bert |lamb |opt_lamb_weight_decay_rate |unconstrained |Weight decay |link:https://github.com/mlperf/training/blob/fb058e3849c25f6c718434e60906ea3b0cb0f67d/language_model/tensorflow/bert/optimization.py#L72[reference code] |dlrm |sgd |global_batch_size |unconstrained |global batch size | |dlrm |sgd |opt_base_learning_rate |unconstrained |base learning rate, this should be the learning rate after warm up and before decay |link:https://github.com/facebookresearch/dlrm/blob/master/dlrm_s_pytorch.py#L492[reference code] |dlrm |sgd |opt_learning_rate_warmup_steps |unconstrained |Number to steps go from 0 to sgd_opt_base_learning_rate with a linear warmup |See PR (From Intel and NV, TODO Link) |dlrm |sgd |lr_decay_start_steps |unconstrained |step at which you start poly decay |See PR (From Intel and NV, TODO Link) |dlrm |sgd |sgd_opt_base_learning_rate |unconstrained |learning rate at the start of poly decay |See PR (From Intel and NV, TODO Link) |dlrm |sgd |sgd_opt_learning_rate_decay_poly_power |2 |power of the poly decay |See PR (From Intel and NV, TODO Link) |dlrm |sgd |sgd_opt_learning_rate_decay_steps |unconstrained |the step at which you reach the end learning rate |See PR (From Intel and NV, TODO Link) |maskrcnn |sgd |global_batch_size |arbitrary constant |global version of reference SOLVER.IMS_PER_BATCH |link:https://github.com/mlperf/training/blob/00570abf77d351e474d57830014f6a3e501dece1/object_detection/pytorch/maskrcnn_benchmark/data/build.py#L112[reference code] |maskrcnn |sgd |opt_learning_rate_decay_factor$$*$$ |fixed to reference (0.1) |learning rate decay factor |link:https://github.com/mlperf/training/blob/00570abf77d351e474d57830014f6a3e501dece1/object_detection/pytorch/maskrcnn_benchmark/solver/build.py#L13[reference code] |maskrcnn |sgd |opt_learning_rate_decay_steps$$*$$ |(60000, 80000) * (1 + K / 10) * 16 / global_batch_size where K is integer |Steps at which learning rate is decayed |link:https://github.com/mlperf/training/blob/00570abf77d351e474d57830014f6a3e501dece1/object_detection/pytorch/maskrcnn_benchmark/solver/build.py#L26[reference code] |maskrcnn |sgd |opt_base_learning_rate |0.02 * K for any integer K |base learning rate, this should be the learning rate after warm up and before decay |link:https://github.com/mlperf/training/blob/00570abf77d351e474d57830014f6a3e501dece1/object_detection/pytorch/maskrcnn_benchmark/solver/build.py#L12[reference code] |maskrcnn |sgd |max_image_size$$*$$ |fixed to reference |Maximum size of the longer side |link:https://github.com/mlperf/training/blob/00570abf77d351e474d57830014f6a3e501dece1/object_detection/pytorch/maskrcnn_benchmark/data/transforms/build.py#L8[reference code] |maskrcnn |sgd |min_image_size$$*$$ |fixed to reference |Maximum size of the shorter side |link:https://github.com/mlperf/training/blob/00570abf77d351e474d57830014f6a3e501dece1/object_detection/pytorch/maskrcnn_benchmark/data/transforms/build.py#L7[reference code] |maskrcnn |sgd |num_image_candidates$$*$$ |1000 or 1000 * batches per chip |tunable number of region proposals for given batch size |link:https://github.com/mlperf/training/blob/00570abf77d351e474d57830014f6a3e501dece1/object_detection/pytorch/maskrcnn_benchmark/modeling/rpn/inference.py#L183[reference code] |maskrcnn |sgd |opt_learning_rate_warmup_factor |unconstrained |the constant factor applied at learning rate warm up |link:https://github.com/mlperf/training/blob/00570abf77d351e474d57830014f6a3e501dece1/object_detection/pytorch/maskrcnn_benchmark/solver/build.py#L28[reference code] |maskrcnn |sgd |opt_learning_rate_warmup_steps |unconstrained |number of steps for learning rate to warm up |link:https://github.com/mlperf/training/blob/00570abf77d351e474d57830014f6a3e501dece1/object_detection/pytorch/maskrcnn_benchmark/solver/build.py#L29[reference code] |maskrcnn |sgd |num_image_candidates$$*$$ |(1000 or 2000) or (1000 * batches per chip) |tunable number of region proposals for given batch size |link:https://github.com/mlperf/training/blob/00570abf77d351e474d57830014f6a3e501dece1/object_detection/pytorch/maskrcnn_benchmark/modeling/rpn/inference.py#L183[reference code] |minigo |sgd |train_batch_size |integer > 0 |Batch size to use for training |link:https://github.com/mlperf/training/blob/00570abf77d351e474d57830014f6a3e501dece1/reinforcement/tensorflow/minigo/dual_net.py#L47[reference code] |minigo |sgd |lr_boundaries |unconstrained |The number of steps at which the learning rate will decay |link:https://github.com/mlperf/training/blob/00570abf77d351e474d57830014f6a3e501dece1/reinforcement/tensorflow/minigo/dual_net.py#L67[reference code] |minigo |sgd |lr_rates |unconstrained |The different learning rates |link:https://github.com/mlperf/training/blob/00570abf77d351e474d57830014f6a3e501dece1/reinforcement/tensorflow/minigo/dual_net.py#L70[reference code] |minigo |sgd |actual_selfplay_games_per_generation |integer >= 8192 (min_selfplay_games_per_generation) |""NOT A HYPERPARAMETER, CANNOT BE 'BORROWED' during review"" Implicit (LOG ONLY) - total number of games played per epoch; many parameters can impact this, varies per iteration |N/A |minigo |sgd |min_selfplay_games_per_generation$$*$$ |fixed to reference (8192) |Minimum number of games to play for each training iteration |link:https://github.com/mlperf/training/blob/00570abf77d351e474d57830014f6a3e501dece1/reinforcement/tensorflow/minigo/ml_perf/train_loop.py#L51[reference code] |resnet |lars |lars_opt_base_learning_rate |arbitrary constant |Base ""plr"" in the PR linked. |link:https://github.com/mlperf/training/pull/342/files#[reference code] |resnet |lars |lars_opt_end_learning_rate$$*$$ |fixed to reference |end learning rate for polynomial decay, implied mathemetically from other HPs |N/A |resnet |lars |lars_opt_learning_rate_decay_poly_power$$*$$ |fixed to reference |power of polynomial decay, no link needed since not tunable |N/A |resnet |lars |lars_epsilon$$*$$ |Fixed to reference |epsilon in reference |link:https://github.com/mlperf/training/pull/342/files#diff-b7db7d58acb8134acb65b4d1d60b8e90R49[reference code] |resnet |lars |lars_opt_learning_rate_warmup_epochs |arbitrary constant |w_epochs in PR |link:https://github.com/mlperf/training/pull/342/files#[reference code] |resnet |lars |lars_opt_momentum | 0.9 for batch<32k, otherwise arbitrary constant |momentum in reference |link:https://github.com/mlperf/training/pull/342/files#diff-b7db7d58acb8134acb65b4d1d60b8e90R49[reference code] |resnet |lars |lars_opt_weight_decay |(0.0001 * 2 ^ N) where N is any integer |weight_decay in reference |link:https://github.com/mlperf/training/pull/342/files#diff-b7db7d58acb8134acb65b4d1d60b8e90R49[reference code] |resnet |lars |lars_opt_learning_rate_decay_steps |unconstrained |num_epochs in reference |link:https://github.com/mlperf/training/blob/master/image_classification/tensorflow/official/resnet/resnet_run_loop.py[reference code] |resnet |lars |global_batch_size |unconstrained |global batch size in reference |link:https://github.com/mlperf/training/blob/00570abf77d351e474d57830014f6a3e501dece1/image_classification/tensorflow/official/utils/arg_parsers/parsers.py#L158[reference code] |resnet |lars |label smoothing$$*$$$$*$$ |0 or 0.1 | TODO |TODO |resnet |lars |truncated norm initialization$$*$$$$*$$ |boolean | TODO |TODO |resnet |sgd |global_batch_size |arbitrary constant |reference --batch_size |See LARS |resnet |sgd |sgd_opt_base_learning_rate |0.001 * k where is an integer |the learning rate |See LARS |resnet |sgd |sgd_opt_end_learning_rate |10^-4 |end learning rate for polynomial decay, implied mathemetically from other HPs |See LARS |resnet |sgd |sgd_opt_learning_rate_decay_poly_power |2 |power of polynomial decay, no link needed since not tunable |See LARS |resnet |sgd |sgd_opt_learning_rate_decay_steps |integer >= 0 |num_epochs in reference |See LARS |resnet |sgd |sgd_opt_weight_decay |(0.0001 * 2 ^ N) where N is any integer |Weight decay, same as LARS. |See LARS |resnet |sgd |sgd_opt_momentum |0.9 |Momentum for SGD. |See LARS |resnet |sgd |model_bn_span |arbitrary constant |number of samples whose statistics a given BN layer uses to normalize a training minibatch (may be just the portion of global_batch_size per device, but also may be aggregated over several devices) |See LARS |resnet |sgd |opt_learning_rate_warmup_epochs |integer >= 0 |number of epochs needed for learning rate warmup |See LARS |resnet |sgd |label smoothing$$*$$$$*$$ |0 or 0.1 | TODO |TODO |resnet |sgd |truncated norm initialization$$*$$$$*$$ |boolean | TODO |TODO |resnet |lars/sgd |opt_name |""lars"" or ""sgd"" |The optimizer that was used. | |rnnt |lamb |global_batch_size |unconstrained |reference --batch_size |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L270-L271[reference code] |rnnt |lamb |opt_name |""lamb"" |The optimizer that was used. |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L357[reference code] |rnnt |lamb |opt_base_learning_rate |unconstrained |base learning rate, this should be the learning rate after warm up and before decay |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L358[reference code] |rnnt |lamb |opt_lamb_epsilon |1e-9 |LAMB epsilon |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L359[reference code] |rnnt |lamb |opt_lamb_learning_rate_decay_poly_power |unconstrained |Exponential decay rate |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L360[reference code] |rnnt |lamb |opt_lamb_learning_rate_hold_epochs |unconstrained |Number of epochs when LR schedule keeps the base learning rate value |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L362[reference code] |rnnt |lamb |opt_learning_rate_warmup_epochs |unconstrained |Number of epochs when LR linearly increases from 0 to base learning rate |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L361[reference code] |rnnt |lamb |opt_weight_decay |1e-3 |L2 weight decay |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L372[reference code] |rnnt |lamb |opt_lamb_beta_1 |unconstrained |LAMB beta 1 |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L363[reference code] |rnnt |lamb |opt_lamb_beta_2 |unconstrained |LAMB beta 2 |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L364[reference code] |rnnt |lamb |opt_gradient_clip_norm |1 or inf |Gradients are clipped above this norm threshold. |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L365[reference code] |rnnt |lamb |opt_gradient_accumulation_steps |unconstrained |Numer of fwd/bwd steps between optimizer step. |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L222[reference code] |rnnt |lamb |opt_learning_rate_alt_decay_func |True |whether to use alternative learning rate decay function |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/common/optimizers.py#L20-L49[reference code] |rnnt |lamb |opt_learning_rate_alt_warmup_func |True |whether to use alternative learning rate warmup function |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L367[reference code] |rnnt |lamb |opt_lamb_learning_rate_min |1e-5 |LR schedule doesn't set LR values below this threshold |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L368[reference code] |rnnt |lamb |train_samples |unconstrained |Number of training samples after filtering out samples longer than data_train_max_duration |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L337[reference code] |rnnt |lamb |eval_samples |2703 |Number of evaluation samples |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L338[reference code] |rnnt |lamb |data_train_max_duration |unconstrained |Samples longer than this number of seconds are not included to training dataset |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L252-L253[reference code] |rnnt |lamb |data_train_num_buckets |unconstrained |Training dataset is split to this number of buckets |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L293[reference code] |rnnt |lamb |data_train_speed_perturbation_min |0.85 |Input audio is resampled to a random rample rate not less than this fraction of original sample rate. |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L256-L257[reference code] |rnnt |lamb |data_train_speed_perturbation_max |1.15 |Input audio is resampled to a random rample rate not greater than this fraction of original sample rate. |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L254-L255[reference code] |rnnt |lamb |data_spec_augment_freq_n |2 |Number of masks for frequency bands |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L258-L259[reference code] |rnnt |lamb |data_spec_augment_freq_min |0 |Minimum number of frequencies in a single mask |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L260-L261[reference code] |rnnt |lamb |data_spec_augment_freq_max |20 |Maximum number of frequencies in a single mask |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L262-L263[reference code] |rnnt |lamb |data_spec_augment_time_n |10 |Number of masks for time band |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L264-L265[reference code] |rnnt |lamb |data_spec_augment_time_min |0 |Minimum number of masked time steps as a fraction of all steps |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L266-L267[reference code] |rnnt |lamb |data_spec_augment_time_max |0.03 |Maximum number of masked time steps as a fraction of all steps |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L268-L269[reference code] |rnnt |lamb |model_eval_ema_factor |unconstrained |Smoothing factor for Exponential Moving Average |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L395[reference code] |rnnt |lamb |model_weights_initialization_scale |unconstrained |After random initialization of weight and bias tensors, all are scaled with this factorAfter random initialization of weight and bias tensors, all are scaled with this factor |See link:https://github.com/mwawrzos/training/blob/2126999a1ffff542064bb3208650a1e673920dcf/rnn_speech_recognition/pytorch/train.py#L342[reference code] |ssd |sgd |global_batch_size |arbitrary constant |reference --batch-size |link:https://github.com/mlperf/training/blob/master/single_stage_detector/ssd/train.py#L23[reference code] |ssd |sgd |model_bn_span |integer >= 1 |number of samples whose statistics a given BN layer uses to normalize a training minibatch (may be just the portion of global_batch_size per device, but also may be aggregated over several devices) |link:https://github.com/mlperf/training/blob/master/single_stage_detector/ssd/train.py#L335[reference code] |ssd |sgd |opt_learning_rate_warmup_factor |Integer >= 0 |the constant factor applied at learning rate warm up |link:https://github.com/mlperf/training/blob/master/single_stage_detector/ssd/train.py#L45[reference code] |ssd |sgd |opt_learning_rate_warmup_steps |integer >= 1 |number of steps for learning rate to warm up |link:https://github.com/mlperf/training/blob/master/single_stage_detector/ssd/train.py#L43[reference code] |ssd |sgd |opt_weight_decay |arbitrary constant |L2 weight decay |link:https://github.com/mlperf/training/blob/master/single_stage_detector/ssd/train.py#L40[reference code] |ssd |sgd |opt_base_learning_rate |unconstrained |base learning rate, this should be the learning rate after warm up and before decay |link:https://github.com/mlperf/training/blob/master/single_stage_detector/ssd/train.py#L47[reference code] |ssd |sgd |max_samples |1 or 50 |maximum number of samples attempted when generating a training patch for a given IoU choice |link:https://github.com/mlperf/training/pull/367/commits/e6fbbb323adb7d1521cc5b7d7371f2e4461ece59#diff-591431110d6b55f5afe595b96253fddbR111[reference code] |ssd |sgd |opt_learning_rate_decay_boundary_epochs |[40, 50] * (1 + k/10) for some integer k |Epochs at which the learning rate decays |link:https://github.com/mlperf/training/blob/e6fbbb323adb7d1521cc5b7d7371f2e4461ece59/single_stage_detector/ssd/train.py#L48[reference code] |unet3d |sgd |global_batch_size |unconstrained |global batch size |reference --batch_size |unet3d |sgd |opt_base_learning_rate |unconstrained |base learning rate |reference --learning_rate |unet3d |sgd |opt_momentum |unconstrained |SGD momentum |reference --momentum |unet3d |sgd |opt_learning_rate_warmup_steps |unconstrained |number of epochs needed for learning rate warmup|reference --lr_warmup_epochs |unet3d |sgd |opt_initial_learning_rate |unconstrained |initial learning rate (for LR warm up) |reference --init_learning_rate |unet3d |sgd |opt_learning_rate_decay_steps |unconstrained |epochs at which the learning rate decays |reference --lr_decay_epochs |unet3d |sgd |opt_learning_rate_decay_factor |unconstrained |factor used for learning rate decay |reference --lr_decay_factor |unet3d |sgd |opt_weight_decay |unconstrained |L2 weight decay |reference --weight_decay |unet3d |sgd |training_oversampling |fixed to reference |training oversampling |reference --oversampling |unet3d |sgd |training_input_shape |fixed to reference |training input shape |reference --input_shape |unet3d |sgd |evaluation_overlap |fixed to reference |evaluation sliding window overlap |reference --overlap |unet3d |sgd |evaluation_input_shape |fixed to reference |evaluation input shape |reference --val_input_shape |unet3d |sgd |data_train_samples |fixed to reference |number of training samples | N/A |unet3d |sgd |data_eval_samples |fixed to reference |number of evaluation samples | N/A |=== OPEN: Hyperparameters and optimizer may be freely changed. === Hyperparameter Borrowing Submitters are expected to use their best efforts to submit with optimal hyperparameters for their system. The intent of Hyperparameter Borrowing is to allow a submitter to update their submission to reflect what they would have submitted had they known about more optimal hyperparameters before submitting, without knowing any other info (ie the performance of other submissions). During the review period as described in the Submission Rules, a submitter may replace the hyperparameters, once per benchmark entry, in their implementation of a benchmark with hyperparameters from another submitter's implementation of the same benchmark. By default, they may change batch size (local batch size, global batch size, batchnorm span), but must replace all other hyperparameters as a group. With evidence that the resulting model, using the same batch size as the other submitter's implementation, converges worse in terms of epochs required, the submitter may make a minimum number of additional hyperparameter changes for the purpose of improving convergence and achieving comparable, but not better, convergence in epochs compared to the other submitter's implementation, but preserving any difference in convergence that may exist due to precision choices. In this situation, the other submitter's implementation is considered the reference, and the new submitter must match the convergence behavior of the other submitter in a similar way as we compare any submission to the reference. A resubmission of a benchmark with borrowed hyperparameters must use the same software (with the exceptions listed in the Software Adoption section of this document), system and system configuration (accelerators, NICs etc) as the original submission. The largest scale submission for a benchmark from a given system may be resubmitted with borrowed hyperparameters using a change of scale on that system, but only if the new scale is either larger, or enables the resubmission to achieve a faster run result. In addition, the new scale must not be larger than the largest scale used in an original submission of at least one of the benchmarks on that system in this round. === Loss function CLOSED: The same loss function used in the reference implementation must be used. OPEN: Any loss function may be used. Do not confuse the loss function with target quality measure. === Quality measure Each run must reach a target quality level on the reference implementation quality measure. By default, the time to evaluate the quality is included in the wallclock time. However, if the reference implementation generates timestamped checkpoints and evaluates the quality after the clock has been stopped, then an implementation may either perform evaluation on-the-clock or generate timestamped checkpoints, evaluate them after the clock has been stopped, and update the clock stopped time to the timestamp of the first passing checkpoint. The checkpoint timestamp may be any time after the last weight value included in the checkpoint is updated. CLOSED: The same quality measure as the reference implementation must be used. The quality measure must be evaluated at the same frequency (in terms of number of training items between test sets) and at least as thoroughly (in terms of number of tests per set) as in the reference implementation. Where applicable, the required evaluation point may be rounded up to the nearest batch size. Typically, a test consists of comparing the output of one forward pass through the network with the desired output from the test set. |=== |Area |Problem |Model|Evaluation frequency |Vision |Image classification |Resnet-50 v1.5|Every 4 epochs with offset 0 or 1 or 2 or 3 | |Image segmentation (medical) |U-Net3D | Starting at `CEILING(1000*168/samples_per_epoch)` epochs, then every `CEILING(20*168/samples_per_epoch)` epochs. Where `samples_per_epoch` is the number of samples processed in a given epoch assuming that in the case of uneven batches the last batch is padded, e.g. `CEILING(168/global_batch_size) * global_batch_size`. | |Object detection (light weight) |SSD|Fixed at epochs=40, 50, 55, 60, 65, 70, 75, 80 | |Object detection (heavy weight) |Mask R-CNN|Every 1 epoch |Language|Speech recognition |RNN-T|Every 1 epoch | |NLP |BERT| eval_interval_samples=FLOOR(0.05*(230.23*GBS+3000000), 25000), skipping 0 |Commerce|Recommendation |DLRM|Every 102400 samples |Research|Reinforcement learning |Mini Go|Every 1 epoch |=== OPEN: An arbitrary stopping criteria may be used, including but not limited to the closed quality measure, a different quality measure, the number of epochs, or a fixed time. However, the reported results must include the geometric mean of the final quality as measured by the closed quality measure. Check points can be created at the discretion of submitter. No check points are required to be produced or retained. === Equivalence exceptions The CLOSED division allows limited exemptions to mathematical equivalence between implementations for pragmatic purposes, including: * Different methods can be used to add color jitter as long as the methods are of a similar distribution and magnitude to the reference. * If data set size is not evenly divisible by batch size, one of several techniques may be used. The last batch in an epoch may be composed of the remaining samples in the epoch, may be padded, or may be a mixed batch composed of samples from the end of one epoch and the start of the next. If the mixed batch technique is used, quality for the ending epoch must be evaluated after the mixed batch. If the padding technique is used, the first batch may be padded instead of the last batch. * Values introduced for padding purposes may be reflected in batch norm computations. * Adam optimizer implementations may use the very small value epsilon to maintain mathematical stability in slightly different ways, provided that methods are reviewed and approved in advance. One such method involves squaring the value of epsilon and moving epsilon inside the square root in the parameter update equation. * Distributed batch normalization is allowed. Additional exemptions need to be explicitly requested and approved in advance. In general, exemptions may be approved for techniques that are common industry practice, introduce small differences that would be difficult to engineer around relative to their significance, and do not substantially decrease the required computation. Over time, MLPerf should seek to help the industry converge on standards and remove exemptions. The OPEN division does not restrict mathematical equivalence. == Software Adoption == For a given round of MLPerf, the ""canonical version"" of a software component shall be defined as the public version as of 14 days before submission. If the software is open source, the canonical version shall be the one compiled with the default compilation options. If a system software provider submits with a component whose version is other than the canonical version, then other submitters using the same component are allowed to update their submission to use that version. Those other submitters must resubmit with the updated system software before the resubmission deadline during the review period. Software adoption applies only to system software, only to the version used by the software provider’s submission, and explicitly does not cover benchmark implementations. Benchmark implementations should be borrowed as a whole only if the software provider’s submission introduces new APIs. [#section-run-results] == Run Results A run result consists of a wall-clock timing measurement for a contiguous period that includes model initialization in excess of a maximum initialization time, any data preprocessing required to be on the clock, using the dataset to train the model, and quality evaluation unless specified otherwise for the benchmark. Prior to starting the clock, a system may use a maximum of 20 minutes of model initialization time. Model initialization time begins when the system first begins to construct or execute the model. This maximum initialization time is intended to ensure that model initialization is not disproportionate on large systems intended to run much larger models, and may be adjusted in the future with sufficient evidence. The clock must start before any part of the system touches the dataset or when the maximum model initialization time is exceeded. The clock may be stopped as soon as any part of the system determines target accuracy has been reached. The clock may not be paused during the run. == Benchmark Results Each benchmark result is based on a set of run results. The number of results for each benchmark is based on a combination of the variance of the benchmark result, the cost of each run, and the likelihood of convergence. |=== |Area|Problem |Minimum Number of Runs |Vision |Image classification |5 | |Image segmentation (medical) | 40 | |Object detection (light weight) |5 | |Object detection (heavy weight) |5 |Language |NLP |10 | |Speech recognition |10 |Commerce |Recommendation |5 |Research |Reinforcement learning |10 |=== Each benchmark result is computed by dropping the fastest and slowest runs, then taking the mean of the remaining times. For this purpose, a single non-converging run may be treated as the slowest run and dropped. A benchmark result is invalid if there is more than one non-converging run. In the case of UNET3D, due to large variance, 40 runs are required. Out of the 40 runs, the 4 fastest and 4 slowest are dropped. There can be maximum of 4 non-converging runs. A run is classified as non-converged if the target quality metric is not reached within `CEILING(10000*168/samples_in_epoch)` epochs. Each benchmark result should be normalized by dividing the reference result for the corresponding reference implementation by the benchmark result. This normalization produces higher numbers for better results, which better aligns with human intuition. === Scoring An MLPerf submission score is intended to represent the median expected result across a large number of runs. To reduce statistical variance and the potential to cherry pick results, each benchmark submission is composed of a set of N independent runs, with N chosen based on the observed variation of the benchmark, as described in the table above. Running multiple iterations of N independent runs with the goal of validating that the submission is close to a median result is encouraged but not required. Running multiple iterations of N runs to try find the lowest one is against the spirit of MLPerf and is prohibited – see Section 2.1, “Strive to be fair”. Results that appear to be too far away from a median result may be rejected. As a more computationally efficient method of validating that a submission is close to the median result, it is also allowed to run M>N independent runs as a group and to designate N consecutive runs from the group as the runs to be used for scoring, provided that the submitter chooses the N consecutive runs that are closest to the median result. For the purposes of calculating the median, sets of N consecutive runs that would create an invalid benchmark result should be included in the median calculation as ""infinite"" scores. If the median set would be an invalid benchmark result, the entire result is invalid. Submitting the full run set (vs just the N runs used for scoring) as a reference is optional, but may be required in the future. For purposes of this scoring, ""consecutive"" is defined as an objective and deterministic method, such as submission timestamps. Submitters are not allowed to pick different orderings to improve their score. Runs may go in parallel on the submitter's compute resources, as long as there is a way to objectively and deterministically sort the runs, for example by timestamp. An example could be for a benchmark with N=5 runs, a submitter could ahead of time pick M=10, launch 10 runs on their compute resources, sort the 10 runs by their launch time stamp, then take a sliding window of 5 consecutive runs over those 10 runs. That sliding window would create 6 possible sets of 5 runs. Each of those 6 sets would be olympically scored, and the set with the median runtime would be submitted as that submitter's score. Any failed runs within those 10 runs would count as infinity time and need to be included in the olympic scoring (could be thrown away as the slowest score). It is recommended that a submitter keep the logs for all M runs, because the review committee may ask for the submitter to share the M logs during the review period. == Reference Convergence Points (RCPs) Reference Convergence Points are used to ensure that the convergence of the submission does not deviate from the convergence of the reference. We are interested in avoiding cases where the submission convergence is faster than the reference. Reference implementation convergence sets a lower bound on epoch convergence that a valid submission should not beat. From a statistical standpoint if the submission mean epochs to converge is significantly lower than the reference mean epochs to converge, then submission convergence points belong to a different population than the reference convergence points, and thus the submission should not be accepted. Compliance to reference convergence points is validated as follows * Reference implementations provide at least 2N epoch convergence numbers, where N is the number of submission runs needed for each benchmark. Since convergence is affected by batch size (larger batch size means slower convergence), reference implementations provide convergence data for a few different batch sizes. * Using the mean and standard deviation of the reference convergence we apply a 1-sided independent two-sample Student's t-test with unequal sample sizes, similar variances with p-value=0.05 (explained link:https://en.wikipedia.org/wiki/Student%27s_t-test#Equal_or_unequal_sample_sizes,_similar_variances_(1/2_%3C_sX1/sX2_%3C_2)[here]) to find the maximum acceptable speedup for submission convergence. * At submission time, the submission is matched to an RCP based on the submission batch size. ** If there is an RCP for that batch size then mean epochs to converge of the submission is extracted from submission logs. If this does not violate the maximum acceptable speedup condition when compared to the reference then the submission is accepted, otherwise it may be rejected. ** If there is no RCP for that batch size but there are RCPs for smaller and larger batch sizes an interpolated RCP is created, and the mean epochs to converge is compared against the interpolated RCP just like in the previous case ** If the submission batch size is larger than the batch size of any RCP the submitter must provide the missing RCPs by running the reference implementation with their batch size. ** If the submission batch size is smaller that the batch size of any RCP AND the convergence test against the RCP with the minimum batch size fails, then again the submitter must provide the missing RCPs by running the reference implementation with their batch size. Please refer to the related Appendix for examples that shed light to the RCP process. === RCP Rules and Guidelines Submitters are encouraged to run the RCP checker script prior to their submission to make sure they do not violate RCP limits. If a submission fails the RCP test, such as S2 in the Appendix, they have the option to submit with the --rcp_bypass parameter. This will allow the submission to upload, but the submitter must notify the results chair, and prepare for the audit process described in the link:https://github.com/mlcommons/policies/blob/master/submission_rules.adoc#auditing[policies document] but at review time the submitter should be able to justify why their submission is valid while it failed the RCP test. If a submission is missing the RCP for the batch size they are submitting, such as S4 and S6 in the Appendix they must provide the missing convergence points by making a PR in the logger. If not, the submission will not be accepted. All missing RCPs are due at submission time. RCPs are added by making a pull request into the RCP library in the logging repository. During hyperparameter borrowing, borrowers can use hyperparameters from submissions that passed or failed the RCP test. If their submission fails to pass the RCP test they can have it upload by using --rcp-bypass and then prepare for the audit decribed in the link:https://github.com/mlcommons/policies/blob/master/submission_rules.adoc#auditing[policies document] To extract submission convergence points, logs should report epochs as follows. For this round no RCP checks will be made for Minigo. |=== | Benchmark | Epoch reporting | RN50 | Epoch | BERT | Eval sample (integer) | DLRM | Epoch / 20.0 | SSD | Epoch | Mask-RCNN | Epoch | RNN-T | Epoch | UNET3D | Epoch | Minigo | N/A |=== == Appendix: Benchmark Specific Rules * Image Classification ** The model may have 1000 or 1001 classes, where the 1001st is ""I don't know"" == Appendix: Allowed Closed Division Optimizers Analysis to support this can be found in the document ""MLPerf Optimizer Review"" in the MLPerf Training document area. TODO: locate the document and provide working link |=== | Benchmark | Algorithm | Framework | Allowed Optimizer | Image classification | LARS | PyTorch | [No compliant implementation] | | | TensorFlow | MLPERF_LARSOptimizer | | | MxNet | SGDwFASTLARS | Image classification | SGD with Momentum | PyTorch | apex.optimizers.FusedSGD | | | PyTorch | torch.optim.SGD | | | TensorFlow | tf.train.MomentumOptimizer | | | MxNet | [No compliant implementation] | Reinforcement learning| SGD with Momentum | PyTorch | apex.optimizers.FusedSGD | | | PyTorch | torch.optim.SGD | | | TensorFlow | tf.train.MomentumOptimizer | Object detection (heavy weight) | SGD with Momentum | PyTorch | apex.optimizers.FusedSGD | | | PyTorch | torch.optim.SGD | | | TensorFlow | tf.train.MomentumOptimizer | Object detection (light weight) | SGD with Momentum | PyTorch | apex.optimizers.FusedSGD | | | PyTorch | torch.optim.SGD | | | TensorFlow | tf.train.MomentumOptimizer | NLP | LAMB | PyTorch | apex.optimizers.FusedLAMB | | | TensorFlow | tf.optimizers.LAMB | Speech recognition | LAMB | PyTorch | apex.optimizers.FusedLAMB | | | TensorFlow | tf.optimizers.LAMB | Recommendation | SGD | PyTorch | torch.optim.SGD | | | TensorFlow | tf.train.MomentumOptimizer | Image segmentation (medical) | SGD with Momentum | PyTorch | torch.optim.SGD | | | TensorFlow | tf.train.MomentumOptimizer | | | MXNet | mx.optimizer.NAG |=== == Appendix: v1.0 Specific Rules This section contains rules specific to the v1.0 round of MLPerf Training. These do not apply to future rounds, unless explicitly ratified as rules for those rounds, or unless these rules are promoted to official rules in previous sections of this document. === MaskRCNN backbone For v1.0 only, Mask-RCNN submitters may use the non-reference backbone located https://drive.google.com/drive/folders/1lGU_pP2Pr2k578DslciwE4AlOKm6dKCK?usp=sharing[here] with the understanding that it converges similarly to the reference backbone. If the non-reference backbone is shown to converge faster than the reference backbone at any scale on any submitted hyperparameter set, all uses of that backbone for any submitter are to be re-run with the reference backbone to have their submission published. For future rounds, the expectation is that all submitters will use the reference backbone, which will fixed at reference code freeze time. === BERT clip-normalization order For v1.0 only, BERT submissions may implement clip-norm either before or after inter-accelerator all-reduce. For future rounds, the expectation is that submissions must use clip-norm-after-reduce, to be consistent with most commonly used public BERT model repos. For performance consistency of at scale BERT submissions for v1.0, submitters are disallowed from using clip-norm-after-reduce to enable additional overlap of communication and math. If a submitter plans to use clip-norm-after-reduce for v1.0, they must notify the committee before the submission deadline, and be prepared to show code in their submission proving that they do not do overlap as a result of clip-norm-after-reduce. Furthermore, for simplicity, the RCPs for this round will use clip-norm-before-reduce. In theory, this could allow clip-norm-after-reduce submissions that converge faster than they should, but still not faster than clip-norm-before-reduce, but the Training Working Group feels that this is ok risk for v1.0, in interest of simplifying the RCPs for v1.0. === Compile time For v1.0 only, the allowed untimed compile time is increased from 20 minutes to 30 minutes. This is to enable new submitters to submit who were close to the 20 minute limit. The 20 minute number was chosen empirically for rounds prior to v1.0. For v1.1 and beyond, the training working group should make a data driven decision on what compile time is reasonable for real user applications. == Appendix: v1.1 Specific Rules This section contains rules specific to the v1.1 round of MLPerf Training. These do not apply to future rounds, unless explicitly ratified as rules for those rounds, or unless these rules are promoted to official rules in previous sections of this document. === BERT clip-normalization order For v1.0 only, BERT submissions may implement clip-norm either before or after inter-accelerator all-reduce. For future rounds, the expectation is that submissions must use clip-norm-after-reduce, to be consistent with most commonly used public BERT model repos. This exception from v1.0 was extended to v1.1 because of the tight schedule between rounds. === Preview Category For v1.1, we changed the policy documentation to say that a Preview submission needs to be available at the next submission after 140 days, not 180 days like it was before. However, this does not apply to Preview submissions from v1.0, which will still follow the 180 day policy. For v1.1 Preview submissions and beyond, the 140 day rule will apply. This is not necessarily an ""exception,"" but we are listing it here as a special case for the record. == Appendix: RCP Examples The RCP checking process is best illustrated with the following examples: Benchmark A requires 5 submission runs. The reference implementation provides (at least) 10 convergence points, let's say [16, 14, 16, 17, 16, 16, 15, 16, 15, 16] for batch size 128. The top and bottom run are excluded from the mean and standard deviation computation. So in this case the Mean = 15.75 epochs and Stdev = 0.43. Based on the t-test the maximum allowed speedup for p-value=0.05 is 3.53%. In other words the minimum mean epochs to converge for each submission with batch size 128 is 15.21. The reference also provides convergence points for batch size 256: [20, 21, 21, 20, 22, 22, 21, 21, 20, 20]. In this case Mean = 20.75, Stdev = 0.66 and based on the t-test the maximum allowed speedup for p-value=0.05 is 4.12%. In other words the minimum mean epochs to converge for batch-256 is 19.93. Let's consider now the following submission scenarios: * Submitter S1 makes a submission for A with batch size 128, and from the logs the epochs to converge are [15, 15, 15, 16, 16]. Excluding the top and bottom runs the mean epochs to converge is 15.33 (> 15.21), so S1 passes the RCP test for benchmark A, batch size 128. * Submitter S2 makes a submission for A with batch size 256, and from the logs the epochs to converge are [19, 19, 19, 20, 21]. Excluding the top and bottom runs the mean epochs to converge is 19.33 (< 19.93), so S2 fails the RCP test for benchmark A, batch size 256. * Submitter S3 makes a submission for A with batch size 192, and from the logs the epochs to converge are [17, 18, 18, 18, 20]. There are no RCPs for 192, but there are for larger and lower batch sizes. In this situation we find an interpolation of the mean and standard deviations for the RCPs at batch size 192. Mean = 18.25 and Stdev=0.547. Based on the t-test with p-value=0.05 the maximum allowed speedup is 3.68%. Exclusing the top and botton submission runs, the submission mean epochs to converge is 18, which is more than 18.25 / 1.0368, so the submission is accepted for batch size 192. * Submitter S4 makes a submission for A with batch size 512. Since there is neither RCP for that batch size, nor RCPs for larger batch sizes, S2 needs to provide convergence points by running the reference with that batch size. * Submitter S5 makes a submission for A with batch size 64 that meets the (stricter) convergence criteria for the RCP with the smallest batch size (128). In this case the submission is accepted. * Submitter S6 makes a submission for A with batch size 64 that does not meet the convergence criteria for the RCP with the smallest batch size (128). In this case S1 needs to provide convergence points by running the reference with batch size = 64. ",16251,True,2867.1098719704573,median "[[production-ready]] = Spring Boot Actuator: Production-ready features [partintro] -- Spring Boot includes a number of additional features to help you monitor and manage your application when you push it to production. You can choose to manage and monitor your application by using HTTP endpoints or with JMX. Auditing, health, and metrics gathering can also be automatically applied to your application. -- [[production-ready-enabling]] == Enabling Production-ready Features The {github-code}/spring-boot-project/spring-boot-actuator[`spring-boot-actuator`] module provides all of Spring Boot's production-ready features. The simplest way to enable the features is to add a dependency to the `spring-boot-starter-actuator` '`Starter`'. .Definition of Actuator **** An actuator is a manufacturing term that refers to a mechanical device for moving or controlling something. Actuators can generate a large amount of motion from a small change. **** To add the actuator to a Maven based project, add the following '`Starter`' dependency: [source,xml,indent=0] ---- org.springframework.boot spring-boot-starter-actuator ---- For Gradle, use the following declaration: [source,groovy,indent=0] ---- dependencies { compile(""org.springframework.boot:spring-boot-starter-actuator"") } ---- [[production-ready-endpoints]] == Endpoints Actuator endpoints let you monitor and interact with your application. Spring Boot includes a number of built-in endpoints and lets you add your own. For example, the `health` endpoint provides basic application health information. Each individual endpoint can be <>. This controls whether or not the endpoint is created and its bean exists in the application context. To be remotely accessible an endpoint also has to be <>. Most applications choose HTTP, where the ID of the endpoint along with a prefix of `/actuator` is mapped to a URL. For example, by default, the `health` endpoint is mapped to `/actuator/health`. The following technology-agnostic endpoints are available: [cols=""2,5,2""] |=== | ID | Description | Enabled by default |`auditevents` |Exposes audit events information for the current application. |Yes |`beans` |Displays a complete list of all the Spring beans in your application. |Yes |`caches` |Exposes available caches. |Yes |`conditions` |Shows the conditions that were evaluated on configuration and auto-configuration classes and the reasons why they did or did not match. |Yes |`configprops` |Displays a collated list of all `@ConfigurationProperties`. |Yes |`env` |Exposes properties from Spring's `ConfigurableEnvironment`. |Yes |`flyway` |Shows any Flyway database migrations that have been applied. |Yes |`health` |Shows application health information. |Yes |`httptrace` |Displays HTTP trace information (by default, the last 100 HTTP request-response exchanges). |Yes |`info` |Displays arbitrary application info. |Yes |`integrationgraph` |Shows the Spring Integration graph. |Yes |`loggers` |Shows and modifies the configuration of loggers in the application. |Yes |`liquibase` |Shows any Liquibase database migrations that have been applied. |Yes |`metrics` |Shows '`metrics`' information for the current application. |Yes |`mappings` |Displays a collated list of all `@RequestMapping` paths. |Yes |`scheduledtasks` |Displays the scheduled tasks in your application. |Yes |`sessions` |Allows retrieval and deletion of user sessions from a Spring Session-backed session store. Not available when using Spring Session's support for reactive web applications. |Yes |`shutdown` |Lets the application be gracefully shutdown. |No |`threaddump` |Performs a thread dump. |Yes |=== If your application is a web application (Spring MVC, Spring WebFlux, or Jersey), you can use the following additional endpoints: [cols=""2,5,2""] |=== | ID | Description | Enabled by default |`heapdump` |Returns a GZip compressed `hprof` heap dump file. |Yes |`jolokia` |Exposes JMX beans over HTTP (when Jolokia is on the classpath, not available for WebFlux). |Yes |`logfile` |Returns the contents of the logfile (if `logging.file` or `logging.path` properties have been set). Supports the use of the HTTP `Range` header to retrieve part of the log file's content. |Yes |`prometheus` |Exposes metrics in a format that can be scraped by a Prometheus server. |Yes |=== To learn more about the Actuator's endpoints and their request and response formats, please refer to the separate API documentation ({spring-boot-actuator-api}/html[HTML] or {spring-boot-actuator-api}/pdf/spring-boot-actuator-web-api.pdf[PDF]). [[production-ready-endpoints-enabling-endpoints]] === Enabling Endpoints By default, all endpoints except for `shutdown` are enabled. To configure the enablement of an endpoint, use its `management.endpoint..enabled` property. The following example enables the `shutdown` endpoint: [source,properties,indent=0] ---- management.endpoint.shutdown.enabled=true ---- If you prefer endpoint enablement to be opt-in rather than opt-out, set the `management.endpoints.enabled-by-default` property to `false` and use individual endpoint `enabled` properties to opt back in. The following example enables the `info` endpoint and disables all other endpoints: [source,properties,indent=0] ---- management.endpoints.enabled-by-default=false management.endpoint.info.enabled=true ---- NOTE: Disabled endpoints are removed entirely from the application context. If you want to change only the technologies over which an endpoint is exposed, use the <> instead. [[production-ready-endpoints-exposing-endpoints]] === Exposing Endpoints Since Endpoints may contain sensitive information, careful consideration should be given about when to expose them. The following table shows the default exposure for the built-in endpoints: [cols=""1,1,1""] |=== | ID | JMX | Web |`auditevents` |Yes |No |`beans` |Yes |No |`conditions` |Yes |No |`configprops` |Yes |No |`env` |Yes |No |`flyway` |Yes |No |`health` |Yes |Yes |`heapdump` |N/A |No |`httptrace` |Yes |No |`info` |Yes |Yes |`integrationgraph` |Yes |Yes |`jolokia` |N/A |No |`logfile` |N/A |No |`loggers` |Yes |No |`liquibase` |Yes |No |`metrics` |Yes |No |`mappings` |Yes |No |`prometheus` |N/A |No |`scheduledtasks` |Yes |No |`sessions` |Yes |No |`shutdown` |Yes |No |`threaddump` |Yes |No |=== To change which endpoints are exposed, use the following technology-specific `include` and `exclude` properties: [cols=""3,1""] |=== |Property | Default |`management.endpoints.jmx.exposure.exclude` | |`management.endpoints.jmx.exposure.include` | `*` |`management.endpoints.web.exposure.exclude` | |`management.endpoints.web.exposure.include` | `info, health` |=== The `include` property lists the IDs of the endpoints that are exposed. The `exclude` property lists the IDs of the endpoints that should not be exposed. The `exclude` property takes precedence over the `include` property. Both `include` and `exclude` properties can be configured with a list of endpoint IDs. For example, to stop exposing all endpoints over JMX and only expose the `health` and `info` endpoints, use the following property: [source,properties,indent=0] ---- management.endpoints.jmx.exposure.include=health,info ---- `*` can be used to select all endpoints. For example, to expose everything over HTTP except the `env` and `beans` endpoints, use the following properties: [source,properties,indent=0] ---- management.endpoints.web.exposure.include=* management.endpoints.web.exposure.exclude=env,beans ---- [NOTE] ==== `*` has a special meaning in YAML, so be sure to add quotes if you want to include (or exclude) all endpoints, as shown in the following example: [source,yaml,indent=0] ---- management: endpoints: web: exposure: include: ""*"" ---- ==== NOTE: If your application is exposed publicly, we strongly recommend that you also <>. TIP: If you want to implement your own strategy for when endpoints are exposed, you can register an `EndpointFilter` bean. [[production-ready-endpoints-security]] === Securing HTTP Endpoints You should take care to secure HTTP endpoints in the same way that you would any other sensitive URL. If Spring Security is present, endpoints are secured by default using Spring Security’s content-negotiation strategy. If you wish to configure custom security for HTTP endpoints, for example, only allow users with a certain role to access them, Spring Boot provides some convenient `RequestMatcher` objects that can be used in combination with Spring Security. A typical Spring Security configuration might look something like the following example: [source,java,indent=0] ---- @Configuration public class ActuatorSecurity extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.requestMatcher(EndpointRequest.toAnyEndpoint()).authorizeRequests() .anyRequest().hasRole(""ENDPOINT_ADMIN"") .and() .httpBasic(); } } ---- The preceding example uses `EndpointRequest.toAnyEndpoint()` to match a request to any endpoint and then ensures that all have the `ENDPOINT_ADMIN` role. Several other matcher methods are also available on `EndpointRequest`. See the API documentation ({spring-boot-actuator-api}/html[HTML] or {spring-boot-actuator-api}/pdf/spring-boot-actuator-web-api.pdf[PDF]) for details. If you deploy applications behind a firewall, you may prefer that all your actuator endpoints can be accessed without requiring authentication. You can do so by changing the `management.endpoints.web.exposure.include` property, as follows: .application.properties [source,properties,indent=0] ---- management.endpoints.web.exposure.include=* ---- Additionally, if Spring Security is present, you would need to add custom security configuration that allows unauthenticated access to the endpoints as shown in the following example: [source,java,indent=0] ---- @Configuration public class ActuatorSecurity extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.requestMatcher(EndpointRequest.toAnyEndpoint()).authorizeRequests() .anyRequest().permitAll(); } } ---- [[production-ready-endpoints-caching]] === Configuring Endpoints Endpoints automatically cache responses to read operations that do not take any parameters. To configure the amount of time for which an endpoint will cache a response, use its `cache.time-to-live` property. The following example sets the time-to-live of the `beans` endpoint's cache to 10 seconds: .application.properties [source,properties,indent=0] ---- management.endpoint.beans.cache.time-to-live=10s ---- NOTE: The prefix `management.endpoint.` is used to uniquely identify the endpoint that is being configured. NOTE: When making an authenticated HTTP request, the `Principal` is considered as input to the endpoint and, therefore, the response will not be cached. [[production-ready-endpoints-hypermedia]] === Hypermedia for Actuator Web Endpoints A ""`discovery page`"" is added with links to all the endpoints. The ""`discovery page`"" is available on `/actuator` by default. When a custom management context path is configured, the ""`discovery page`"" automatically moves from `/actuator` to the root of the management context. For example, if the management context path is `/management`, then the discovery page is available from `/management`. When the management context path is set to `/`, the discovery page is disabled to prevent the possibility of a clash with other mappings. [[production-ready-endpoints-custom-mapping]] === Actuator Web Endpoint Paths By default, endpoints are exposed over HTTP under the `/actuator` path by using the ID of the endpoint. For example, the `beans` endpoint is exposed under `/actuator/beans`. If you want to map endpoints to a different path, you can use the `management.endpoints.web.path-mapping` property. Also, if you want change the base path, you can use `management.endpoints.web.base-path`. The following example remaps `/actuator/health` to `/healthcheck`: .application.properties [source,properties,indent=0] ---- management.endpoints.web.base-path=/ management.endpoints.web.path-mapping.health=healthcheck ---- [[production-ready-endpoints-cors]] === CORS Support https://en.wikipedia.org/wiki/Cross-origin_resource_sharing[Cross-origin resource sharing] (CORS) is a https://www.w3.org/TR/cors/[W3C specification] that lets you specify in a flexible way what kind of cross-domain requests are authorized. If you use Spring MVC or Spring WebFlux, Actuator's web endpoints can be configured to support such scenarios. CORS support is disabled by default and is only enabled once the `management.endpoints.web.cors.allowed-origins` property has been set. The following configuration permits `GET` and `POST` calls from the `example.com` domain: [source,properties,indent=0] ---- management.endpoints.web.cors.allowed-origins=http://example.com management.endpoints.web.cors.allowed-methods=GET,POST ---- TIP: See {sc-spring-boot-actuator-autoconfigure}/endpoint/web/CorsEndpointProperties.{sc-ext}[CorsEndpointProperties] for a complete list of options. [[production-ready-endpoints-custom]] === Implementing Custom Endpoints If you add a `@Bean` annotated with `@Endpoint`, any methods annotated with `@ReadOperation`, `@WriteOperation`, or `@DeleteOperation` are automatically exposed over JMX and, in a web application, over HTTP as well. Endpoints can be exposed over HTTP using Jersey, Spring MVC, or Spring WebFlux. You can also write technology-specific endpoints by using `@JmxEndpoint` or `@WebEndpoint`. These endpoints are restricted to their respective technologies. For example, `@WebEndpoint` is exposed only over HTTP and not over JMX. You can write technology-specific extensions by using `@EndpointWebExtension` and `@EndpointJmxExtension`. These annotations let you provide technology-specific operations to augment an existing endpoint. Finally, if you need access to web-framework-specific functionality, you can implement Servlet or Spring `@Controller` and `@RestController` endpoints at the cost of them not being available over JMX or when using a different web framework. [[production-ready-endpoints-custom-input]] ==== Receiving Input Operations on an endpoint receive input via their parameters. When exposed via the web, the values for these parameters are taken from the URL's query parameters and from the JSON request body. When exposed via JMX, the parameters are mapped to the parameters of the MBean's operations. Parameters are required by default. They can be made optional by annotating them with `@org.springframework.lang.Nullable`. Each root property in the JSON request body can be mapped to a parameter of the endpoint. Consider the following JSON request body: [source,json,indent=0] ---- { ""name"": ""test"", ""counter"": 42 } ---- This can be used to invoke a write operation that takes a `String test` and `int counter` parameters. TIP: Because endpoints are technology agnostic, only simple types can be specified in the method signature. In particular declaring a single parameter with a custom type defining a `name` and `counter` properties is not supported. NOTE: To allow the input to be mapped to the operation method's parameters, Java code implementing an endpoint should be compiled with `-parameters`, and Kotlin code implementing an endpoint should be compiled with `-java-parameters`. This will happen automatically if you are using Spring Boot's Gradle plugin or if you are using Maven and `spring-boot-starter-parent`. [[production-ready-endpoints-custom-input-conversion]] ===== Input type conversion The parameters passed to endpoint operation methods are, if necessary, automatically converted to the required type. Before calling an operation method, the input received via JMX or an HTTP request is converted to the required types using an instance of `ApplicationConversionService`. [[production-ready-endpoints-custom-web]] ==== Custom Web Endpoints Operations on an `@Endpoint`, `@WebEndpoint`, or `@EndpointWebExtension` are automatically exposed over HTTP using Jersey, Spring MVC, or Spring WebFlux. [[production-ready-endpoints-custom-web-predicate]] ===== Web Endpoint Request Predicates A request predicate is automatically generated for each operation on a web-exposed endpoint. [[production-ready-endpoints-custom-web-predicate-path]] ===== Path The path of the predicate is determined by the ID of the endpoint and the base path of web-exposed endpoints. The default base path is `/actuator`. For example, an endpoint with the ID `sessions` will use `/actuator/sessions` as its path in the predicate. The path can be further customized by annotating one or more parameters of the operation method with `@Selector`. Such a parameter is added to the path predicate as a path variable. The variable's value is passed into the operation method when the endpoint operation is invoked. [[production-ready-endpoints-custom-web-predicate-http-method]] ===== HTTP method The HTTP method of the predicate is determined by the operation type, as shown in the following table: [cols=""3, 1""] |=== |Operation |HTTP method |`@ReadOperation` |`GET` |`@WriteOperation` |`POST` |`@DeleteOperation` |`DELETE` |=== [[production-ready-endpoints-custom-web-predicate-consumes]] ===== Consumes For a `@WriteOperation` (HTTP `POST`) that uses the request body, the consumes clause of the predicate is `application/vnd.spring-boot.actuator.v2+json, application/json`. For all other operations the consumes clause is empty. [[production-ready-endpoints-custom-web-predicate-produces]] ===== Produces The produces clause of the predicate can be determined by the `produces` attribute of the `@DeleteOperation`, `@ReadOperation`, and `@WriteOperation` annotations. The attribute is optional. If it is not used, the produces clause is determined automatically. If the operation method returns `void` or `Void` the produces clause is empty. If the operation method returns a `org.springframework.core.io.Resource`, the produces clause is `application/octet-stream`. For all other operations the produces clause is `application/vnd.spring-boot.actuator.v2+json, application/json`. [[production-ready-endpoints-custom-web-response-status]] ===== Web Endpoint Response Status The default response status for an endpoint operation depends on the operation type (read, write, or delete) and what, if anything, the operation returns. A `@ReadOperation` returns a value, the response status will be 200 (OK). If it does not return a value, the response status will be 404 (Not Found). If a `@WriteOperation` or `@DeleteOperation` returns a value, the response status will be 200 (OK). If it does not return a value the response status will be 204 (No Content). If an operation is invoked without a required parameter, or with a parameter that cannot be converted to the required type, the operation method will not be called and the response status will be 400 (Bad Request). [[production-ready-endpoints-custom-web-range-requests]] ===== Web Endpoint Range Requests An HTTP range request can be used to request part of an HTTP resource. When using Spring MVC or Spring Web Flux, operations that return a `org.springframework.core.io.Resource` automatically support range requests. NOTE: Range requests are not supported when using Jersey. [[production-ready-endpoints-custom-web-security]] ===== Web Endpoint Security An operation on a web endpoint or a web-specific endpoint extension can receive the current `java.security.Principal` or `org.springframework.boot.actuate.endpoint.SecurityContext` as a method parameter. The former is typically used in conjunction with `@Nullable` to provide different behaviour for authenticated and unauthenticated users. The latter is typically used to perform authorization checks using its `isUserInRole(String)` method. [[production-ready-endpoints-custom-servlet]] ==== Servlet endpoints A `Servlet` can be exposed as an endpoint by implementing a class annotated with `@ServletEndpoint` that also implements `Supplier`. Servlet endpoints provide deeper integration with the Servlet container but at the expense of portability. They are intended to be used to expose an existing `Servlet` as an endpoint. For new endpoints, the `@Endpoint` and `@WebEndpoint` annotations should be preferred whenever possible. [[production-ready-endpoints-custom-controller]] ==== Controller endpoints `@ControllerEndpoint` and `@RestControllerEndpoint` can be used to implement an endpoint that is only exposed by Spring MVC or Spring WebFlux. Methods are mapped using the standard annotations for Spring MVC and Spring WebFlux such as `@RequestMapping` and `@GetMapping`, with the endpoint's ID being used as a prefix for the path. Controller endpoints provide deeper integration with Spring's web frameworks but at the expense of portability. The `@Endpoint` and `@WebEndpoint` annotations should be preferred whenever possible. [[production-ready-health]] === Health Information You can use health information to check the status of your running application. It is often used by monitoring software to alert someone when a production system goes down. The information exposed by the `health` endpoint depends on the `management.endpoint.health.show-details` property which can be configured with one of the following values: [cols=""1, 3""] |=== |Name |Description |`never` |Details are never shown. |`when-authorized` |Details are only shown to authorized users. Authorized roles can be configured using `management.endpoint.health.roles`. |`always` |Details are shown to all users. |=== The default value is `never`. A user is considered to be authorized when they are in one or more of the endpoint's roles. If the endpoint has no configured roles (the default) all authenticated users are considered to be authorized. The roles can be configured using the `management.endpoint.health.roles` property. NOTE: If you have secured your application and wish to use `always`, your security configuration must permit access to the health endpoint for both authenticated and unauthenticated users. Health information is collected from the content of a {sc-spring-boot-actuator}/health/HealthIndicatorRegistry.{sc-ext}[ `HealthIndicatorRegistry`] (by default all {sc-spring-boot-actuator}/health/HealthIndicator.{sc-ext}[`HealthIndicator`] instances defined in your `ApplicationContext`. Spring Boot includes a number of auto-configured `HealthIndicators` and you can also write your own. By default, the final system state is derived by the `HealthAggregator` which sorts the statuses from each `HealthIndicator` based on an ordered list of statuses. The first status in the sorted list is used as the overall health status. If no `HealthIndicator` returns a status that is known to the `HealthAggregator`, an `UNKNOWN` status is used. TIP: The `HealthIndicatorRegistry` can be used to register and unregister health indicators at runtime. ==== Auto-configured HealthIndicators The following `HealthIndicators` are auto-configured by Spring Boot when appropriate: [cols=""4,6""] |=== |Name |Description |{sc-spring-boot-actuator}/cassandra/CassandraHealthIndicator.{sc-ext}[`CassandraHealthIndicator`] |Checks that a Cassandra database is up. |{sc-spring-boot-actuator}/system/DiskSpaceHealthIndicator.{sc-ext}[`DiskSpaceHealthIndicator`] |Checks for low disk space. |{sc-spring-boot-actuator}/jdbc/DataSourceHealthIndicator.{sc-ext}[`DataSourceHealthIndicator`] |Checks that a connection to `DataSource` can be obtained. |{sc-spring-boot-actuator}/elasticsearch/ElasticsearchHealthIndicator.{sc-ext}[`ElasticsearchHealthIndicator`] |Checks that an Elasticsearch cluster is up. |{sc-spring-boot-actuator}/influx/InfluxDbHealthIndicator.{sc-ext}[`InfluxDbHealthIndicator`] |Checks that an InfluxDB server is up. |{sc-spring-boot-actuator}/jms/JmsHealthIndicator.{sc-ext}[`JmsHealthIndicator`] |Checks that a JMS broker is up. |{sc-spring-boot-actuator}/mail/MailHealthIndicator.{sc-ext}[`MailHealthIndicator`] |Checks that a mail server is up. |{sc-spring-boot-actuator}/mongo/MongoHealthIndicator.{sc-ext}[`MongoHealthIndicator`] |Checks that a Mongo database is up. |{sc-spring-boot-actuator}/neo4j/Neo4jHealthIndicator.{sc-ext}[`Neo4jHealthIndicator`] |Checks that a Neo4j server is up. |{sc-spring-boot-actuator}/amqp/RabbitHealthIndicator.{sc-ext}[`RabbitHealthIndicator`] |Checks that a Rabbit server is up. |{sc-spring-boot-actuator}/redis/RedisHealthIndicator.{sc-ext}[`RedisHealthIndicator`] |Checks that a Redis server is up. |{sc-spring-boot-actuator}/solr/SolrHealthIndicator.{sc-ext}[`SolrHealthIndicator`] |Checks that a Solr server is up. |=== TIP: You can disable them all by setting the `management.health.defaults.enabled` property. ==== Writing Custom HealthIndicators To provide custom health information, you can register Spring beans that implement the {sc-spring-boot-actuator}/health/HealthIndicator.{sc-ext}[`HealthIndicator`] interface. You need to provide an implementation of the `health()` method and return a `Health` response. The `Health` response should include a status and can optionally include additional details to be displayed. The following code shows a sample `HealthIndicator` implementation: [source,java,indent=0] ---- import org.springframework.boot.actuate.health.Health; import org.springframework.boot.actuate.health.HealthIndicator; import org.springframework.stereotype.Component; @Component public class MyHealthIndicator implements HealthIndicator { @Override public Health health() { int errorCode = check(); // perform some specific health check if (errorCode != 0) { return Health.down().withDetail(""Error Code"", errorCode).build(); } return Health.up().build(); } } ---- NOTE: The identifier for a given `HealthIndicator` is the name of the bean without the `HealthIndicator` suffix, if it exists. In the preceding example, the health information is available in an entry named `my`. In addition to Spring Boot's predefined {sc-spring-boot-actuator}/health/Status.{sc-ext}[`Status`] types, it is also possible for `Health` to return a custom `Status` that represents a new system state. In such cases, a custom implementation of the {sc-spring-boot-actuator}/health/HealthAggregator.{sc-ext}[`HealthAggregator`] interface also needs to be provided, or the default implementation has to be configured by using the `management.health.status.order` configuration property. For example, assume a new `Status` with code `FATAL` is being used in one of your `HealthIndicator` implementations. To configure the severity order, add the following property to your application properties: [source,properties,indent=0] ---- management.health.status.order=FATAL, DOWN, OUT_OF_SERVICE, UNKNOWN, UP ---- The HTTP status code in the response reflects the overall health status (for example, `UP` maps to 200, while `OUT_OF_SERVICE` and `DOWN` map to 503). You might also want to register custom status mappings if you access the health endpoint over HTTP. For example, the following property maps `FATAL` to 503 (service unavailable): [source,properties,indent=0] ---- management.health.status.http-mapping.FATAL=503 ---- TIP: If you need more control, you can define your own `HealthStatusHttpMapper` bean. The following table shows the default status mappings for the built-in statuses: [cols=""1,3""] |=== |Status |Mapping |DOWN |SERVICE_UNAVAILABLE (503) |OUT_OF_SERVICE |SERVICE_UNAVAILABLE (503) |UP |No mapping by default, so http status is 200 |UNKNOWN |No mapping by default, so http status is 200 |=== [[reactive-health-indicators]] ==== Reactive Health Indicators For reactive applications, such as those using Spring WebFlux, `ReactiveHealthIndicator` provides a non-blocking contract for getting application health. Similar to a traditional `HealthIndicator`, health information is collected from the content of a {sc-spring-boot-actuator}/health/ReactiveHealthIndicatorRegistry.{sc-ext}[ `ReactiveHealthIndicatorRegistry`] (by default all {sc-spring-boot-actuator}/health/HealthIndicator.{sc-ext}[`HealthIndicator`] and {sc-spring-boot-actuator}/health/ReactiveHealthIndicator.{sc-ext}[ `ReactiveHealthIndicator`] instances defined in your `ApplicationContext`. Regular `HealthIndicator` that do not check against a reactive API are executed on the elastic scheduler. TIP: In a reactive application, The `ReactiveHealthIndicatorRegistry` can be used to register and unregister health indicators at runtime. To provide custom health information from a reactive API, you can register Spring beans that implement the {sc-spring-boot-actuator}/health/ReactiveHealthIndicator.{sc-ext}[`ReactiveHealthIndicator`] interface. The following code shows a sample `ReactiveHealthIndicator` implementation: [source,java,indent=0] ---- @Component public class MyReactiveHealthIndicator implements ReactiveHealthIndicator { @Override public Mono health() { return doHealthCheck() //perform some specific health check that returns a Mono .onErrorResume(ex -> Mono.just(new Health.Builder().down(ex).build()))); } } ---- TIP: To handle the error automatically, consider extending from `AbstractReactiveHealthIndicator`. ==== Auto-configured ReactiveHealthIndicators The following `ReactiveHealthIndicators` are auto-configured by Spring Boot when appropriate: [cols=""1,4""] |=== |Name |Description |{sc-spring-boot-actuator}/cassandra/CassandraReactiveHealthIndicator.{sc-ext}[`CassandraReactiveHealthIndicator`] |Checks that a Cassandra database is up. |{sc-spring-boot-actuator}/mongo/MongoReactiveHealthIndicator.{sc-ext}[`MongoReactiveHealthIndicator`] |Checks that a Mongo database is up. |{sc-spring-boot-actuator}/redis/RedisReactiveHealthIndicator.{sc-ext}[`RedisReactiveHealthIndicator`] |Checks that a Redis server is up. |=== TIP: If necessary, reactive indicators replace the regular ones. Also, any `HealthIndicator` that is not handled explicitly is wrapped automatically. [[production-ready-application-info]] === Application Information Application information exposes various information collected from all {sc-spring-boot-actuator}/info/InfoContributor.{sc-ext}[`InfoContributor`] beans defined in your `ApplicationContext`. Spring Boot includes a number of auto-configured `InfoContributor` beans, and you can write your own. [[production-ready-application-info-autoconfigure]] ==== Auto-configured InfoContributors The following `InfoContributor` beans are auto-configured by Spring Boot, when appropriate: [cols=""1,4""] |=== |Name |Description |{sc-spring-boot-actuator}/info/EnvironmentInfoContributor.{sc-ext}[`EnvironmentInfoContributor`] |Exposes any key from the `Environment` under the `info` key. |{sc-spring-boot-actuator}/info/GitInfoContributor.{sc-ext}[`GitInfoContributor`] |Exposes git information if a `git.properties` file is available. |{sc-spring-boot-actuator}/info/BuildInfoContributor.{sc-ext}[`BuildInfoContributor`] |Exposes build information if a `META-INF/build-info.properties` file is available. |=== TIP: It is possible to disable them all by setting the `management.info.defaults.enabled` property. [[production-ready-application-info-env]] ==== Custom Application Information You can customize the data exposed by the `info` endpoint by setting `+info.*+` Spring properties. All `Environment` properties under the `info` key are automatically exposed. For example, you could add the following settings to your `application.properties` file: [source,properties,indent=0] ---- info.app.encoding=UTF-8 info.app.java.source=1.8 info.app.java.target=1.8 ---- [TIP] ==== Rather than hardcoding those values, you could also <>. Assuming you use Maven, you could rewrite the preceding example as follows: [source,properties,indent=0] ---- info.app.encoding=@project.build.sourceEncoding@ info.app.java.source=@java.version@ info.app.java.target=@java.version@ ---- ==== [[production-ready-application-info-git]] ==== Git Commit Information Another useful feature of the `info` endpoint is its ability to publish information about the state of your `git` source code repository when the project was built. If a `GitProperties` bean is available, the `git.branch`, `git.commit.id`, and `git.commit.time` properties are exposed. TIP: A `GitProperties` bean is auto-configured if a `git.properties` file is available at the root of the classpath. See ""<>"" for more details. If you want to display the full git information (that is, the full content of `git.properties`), use the `management.info.git.mode` property, as follows: [source,properties,indent=0] ---- management.info.git.mode=full ---- [[production-ready-application-info-build]] ==== Build Information If a `BuildProperties` bean is available, the `info` endpoint can also publish information about your build. This happens if a `META-INF/build-info.properties` file is available in the classpath. TIP: The Maven and Gradle plugins can both generate that file. See ""<>"" for more details. [[production-ready-application-info-custom]] ==== Writing Custom InfoContributors To provide custom application information, you can register Spring beans that implement the {sc-spring-boot-actuator}/info/InfoContributor.{sc-ext}[`InfoContributor`] interface. The following example contributes an `example` entry with a single value: [source,java,indent=0] ---- import java.util.Collections; import org.springframework.boot.actuate.info.Info; import org.springframework.boot.actuate.info.InfoContributor; import org.springframework.stereotype.Component; @Component public class ExampleInfoContributor implements InfoContributor { @Override public void contribute(Info.Builder builder) { builder.withDetail(""example"", Collections.singletonMap(""key"", ""value"")); } } ---- If you reach the `info` endpoint, you should see a response that contains the following additional entry: [source,json,indent=0] ---- { ""example"": { ""key"" : ""value"" } } ---- [[production-ready-monitoring]] == Monitoring and Management over HTTP If you are developing a web application, Spring Boot Actuator auto-configures all enabled endpoints to be exposed over HTTP. The default convention is to use the `id` of the endpoint with a prefix of `/actuator` as the URL path. For example, `health` is exposed as `/actuator/health`. TIP: Actuator is supported natively with Spring MVC, Spring WebFlux, and Jersey. [[production-ready-customizing-management-server-context-path]] === Customizing the Management Endpoint Paths Sometimes, it is useful to customize the prefix for the management endpoints. For example, your application might already use `/actuator` for another purpose. You can use the `management.endpoints.web.base-path` property to change the prefix for your management endpoint, as shown in the following example: [source,properties,indent=0] ---- management.endpoints.web.base-path=/manage ---- The preceding `application.properties` example changes the endpoint from `/actuator/{id}` to `/manage/{id}` (for example, `/manage/info`). NOTE: Unless the management port has been configured to <>, `management.endpoints.web.base-path` is relative to `server.servlet.context-path`. If `management.server.port` is configured, `management.endpoints.web.base-path` is relative to `management.server.servlet.context-path`. [[production-ready-customizing-management-server-port]] === Customizing the Management Server Port Exposing management endpoints by using the default HTTP port is a sensible choice for cloud-based deployments. If, however, your application runs inside your own data center, you may prefer to expose endpoints by using a different HTTP port. You can set the `management.server.port` property to change the HTTP port, as shown in the following example: [source,properties,indent=0] ---- management.server.port=8081 ---- [[production-ready-management-specific-ssl]] === Configuring Management-specific SSL When configured to use a custom port, the management server can also be configured with its own SSL by using the various `management.server.ssl.*` properties. For example, doing so lets a management server be available over HTTP while the main application uses HTTPS, as shown in the following property settings: [source,properties,indent=0] ---- server.port=8443 server.ssl.enabled=true server.ssl.key-store=classpath:store.jks server.ssl.key-password=secret management.server.port=8080 management.server.ssl.enabled=false ---- Alternatively, both the main server and the management server can use SSL but with different key stores, as follows: [source,properties,indent=0] ---- server.port=8443 server.ssl.enabled=true server.ssl.key-store=classpath:main.jks server.ssl.key-password=secret management.server.port=8080 management.server.ssl.enabled=true management.server.ssl.key-store=classpath:management.jks management.server.ssl.key-password=secret ---- [[production-ready-customizing-management-server-address]] === Customizing the Management Server Address You can customize the address that the management endpoints are available on by setting the `management.server.address` property. Doing so can be useful if you want to listen only on an internal or ops-facing network or to listen only for connections from `localhost`. NOTE: You can listen on a different address only when the port differs from the main server port. The following example `application.properties` does not allow remote management connections: [source,properties,indent=0] ---- management.server.port=8081 management.server.address=127.0.0.1 ---- [[production-ready-disabling-http-endpoints]] === Disabling HTTP Endpoints If you do not want to expose endpoints over HTTP, you can set the management port to `-1`, as shown in the following example: [source,properties,indent=0] ---- management.server.port=-1 ---- [[production-ready-jmx]] == Monitoring and Management over JMX Java Management Extensions (JMX) provide a standard mechanism to monitor and manage applications. By default, Spring Boot exposes management endpoints as JMX MBeans under the `org.springframework.boot` domain. [[production-ready-custom-mbean-names]] === Customizing MBean Names The name of the MBean is usually generated from the `id` of the endpoint. For example, the `health` endpoint is exposed as `org.springframework.boot:type=Endpoint,name=Health`. If your application contains more than one Spring `ApplicationContext`, you may find that names clash. To solve this problem, you can set the `spring.jmx.unique-names` property to `true` so that MBean names are always unique. You can also customize the JMX domain under which endpoints are exposed. The following settings show an example of doing so in `application.properties`: [source,properties,indent=0] ---- spring.jmx.unique-names=true management.endpoints.jmx.domain=com.example.myapp ---- [[production-ready-disable-jmx-endpoints]] === Disabling JMX Endpoints If you do not want to expose endpoints over JMX, you can set the `management.endpoints.jmx.exposure.exclude` property to `*`, as shown in the following example: [source,properties,indent=0] ---- management.endpoints.jmx.exposure.exclude=* ---- [[production-ready-jolokia]] === Using Jolokia for JMX over HTTP Jolokia is a JMX-HTTP bridge that provides an alternative method of accessing JMX beans. To use Jolokia, include a dependency to `org.jolokia:jolokia-core`. For example, with Maven, you would add the following dependency: [source,xml,indent=0] ---- org.jolokia jolokia-core ---- The Jolokia endpoint can then be exposed by adding `jolokia` or `*` to the `management.endpoints.web.exposure.include` property. You can then access it by using `/actuator/jolokia` on your management HTTP server. [[production-ready-customizing-jolokia]] ==== Customizing Jolokia Jolokia has a number of settings that you would traditionally configure by setting servlet parameters. With Spring Boot, you can use your `application.properties` file. To do so, prefix the parameter with `management.endpoint.jolokia.config.`, as shown in the following example: [source,properties,indent=0] ---- management.endpoint.jolokia.config.debug=true ---- [[production-ready-disabling-jolokia]] ==== Disabling Jolokia If you use Jolokia but do not want Spring Boot to configure it, set the `management.endpoint.jolokia.enabled` property to `false`, as follows: [source,properties,indent=0] ---- management.endpoint.jolokia.enabled=false ---- [[production-ready-loggers]] == Loggers Spring Boot Actuator includes the ability to view and configure the log levels of your application at runtime. You can view either the entire list or an individual logger's configuration, which is made up of both the explicitly configured logging level as well as the effective logging level given to it by the logging framework. These levels can be one of: * `TRACE` * `DEBUG` * `INFO` * `WARN` * `ERROR` * `FATAL` * `OFF` * `null` `null` indicates that there is no explicit configuration. [[production-ready-logger-configuration]] === Configure a Logger To configure a given logger, `POST` a partial entity to the resource's URI, as shown in the following example: [source,json,indent=0] ---- { ""configuredLevel"": ""DEBUG"" } ---- TIP: To ""`reset`"" the specific level of the logger (and use the default configuration instead), you can pass a value of `null` as the `configuredLevel`. [[production-ready-metrics]] == Metrics Spring Boot Actuator provides dependency management and auto-configuration for https://micrometer.io[Micrometer], an application metrics facade that supports numerous monitoring systems, including: - <> - <> - <> - <> - <> - <> - <> - <> - <> - <> - <> - <> TIP: To learn more about Micrometer's capabilities, please refer to its https://micrometer.io/docs[reference documentation], in particular the {micrometer-concepts-documentation}[concepts section]. [[production-ready-metrics-getting-started]] === Getting started Spring Boot auto-configures a composite `MeterRegistry` and adds a registry to the composite for each of the supported implementations that it finds on the classpath. Having a dependency on `micrometer-registry-{system}` in your runtime classpath is enough for Spring Boot to configure the registry. Most registries share common features. For instance, you can disable a particular registry even if the Micrometer registry implementation is on the classpath. For instance, to disable Datadog: [source,properties,indent=0] ---- management.metrics.export.datadog.enabled=false ---- Spring Boot will also add any auto-configured registries to the global static composite registry on the `Metrics` class unless you explicitly tell it not to: [source,properties,indent=0] ---- management.metrics.use-global-registry=false ---- You can register any number of `MeterRegistryCustomizer` beans to further configure the registry, such as applying common tags, before any meters are registered with the registry: [source,java,indent=0] ---- @Bean MeterRegistryCustomizer metricsCommonTags() { return registry -> registry.config().commonTags(""region"", ""us-east-1""); } ---- You can apply customizations to particular registry implementations by being more specific about the generic type: [source,java,indent=0] ---- @Bean MeterRegistryCustomizer graphiteMetricsNamingConvention() { return registry -> registry.config().namingConvention(MY_CUSTOM_CONVENTION); } ---- With that setup in place you can inject `MeterRegistry` in your components and register metrics: [source,java,indent=0] ---- include::{code-examples}/actuate/metrics/SampleBean.java[tag=example] ---- Spring Boot also <> (i.e. `MeterBinder` implementations) that you can control via configuration or dedicated annotation markers. [[production-ready-metrics-export]] === Supported monitoring systems [[production-ready-metrics-export-atlas]] ==== Atlas By default, metrics are exported to {micrometer-registry-documentation}/atlas[Atlas] running on your local machine. The location of the https://github.com/Netflix/atlas[Atlas server] to use can be provided using: [source,properties,indent=0] ---- management.metrics.export.atlas.uri=http://atlas.example.com:7101/api/v1/publish ---- [[production-ready-metrics-export-datadog]] ==== Datadog Datadog registry pushes metrics to https://www.datadoghq.com[datadoghq] periodically. To export metrics to {micrometer-registry-documentation}/datadog[Datadog], your API key must be provided: [source,properties,indent=0] ---- management.metrics.export.datadog.api-key=YOUR_KEY ---- You can also change the interval at which metrics are sent to Datadog: [source,properties,indent=0] ---- management.metrics.export.datadog.step=30s ---- [[production-ready-metrics-export-ganglia]] ==== Ganglia By default, metrics are exported to {micrometer-registry-documentation}/ganglia[Ganglia] running on your local machine. The http://ganglia.sourceforge.net[Ganglia server] host and port to use can be provided using: [source,properties,indent=0] ---- management.metrics.export.ganglia.host=ganglia.example.com management.metrics.export.ganglia.port=9649 ---- [[production-ready-metrics-export-graphite]] ==== Graphite By default, metrics are exported to {micrometer-registry-documentation}/graphite[Graphite] running on your local machine. The https://graphiteapp.org[Graphite server] host and port to use can be provided using: [source,properties,indent=0] ---- management.metrics.export.graphite.host=graphite.example.com management.metrics.export.graphite.port=9004 ---- Micrometer provides a default `HierarchicalNameMapper` that governs how a dimensional meter id is {micrometer-registry-documentation}/graphite#_hierarchical_name_mapping[mapped to flat hierarchical names]. TIP: To take control over this behaviour, define your `GraphiteMeterRegistry` and supply your own `HierarchicalNameMapper`. An auto-configured `GraphiteConfig` and `Clock` beans are provided unless you define your own: [source,java] ---- @Bean public GraphiteMeterRegistry graphiteMeterRegistry(GraphiteConfig config, Clock clock) { return new GraphiteMeterRegistry(config, clock, MY_HIERARCHICAL_MAPPER); } ---- [[production-ready-metrics-export-influx]] ==== Influx By default, metrics are exported to {micrometer-registry-documentation}/influx[Influx] running on your local machine. The location of the https://www.influxdata.com[Influx server] to use can be provided using: [source,properties,indent=0] ---- management.metrics.export.influx.uri=http://influx.example.com:8086 ---- [[production-ready-metrics-export-jmx]] ==== JMX Micrometer provides a hierarchical mapping to {micrometer-registry-documentation}/jmx[JMX], primarily as a cheap and portable way to view metrics locally. By default, metrics are exported to the `metrics` JMX domain. The domain to use can be provided using: [source,properties,indent=0] ---- management.metrics.export.jmx.domain=com.example.app.metrics ---- Micrometer provides a default `HierarchicalNameMapper` that governs how a dimensional meter id is {micrometer-registry-documentation}/jmx#_hierarchical_name_mapping[mapped to flat hierarchical names]. TIP: To take control over this behaviour, define your `JmxMeterRegistry` and supply your own `HierarchicalNameMapper`. An auto-configured `JmxConfig` and `Clock` beans are provided unless you define your own: [source,java] ---- @Bean public JmxMeterRegistry jmxMeterRegistry(JmxConfig config, Clock clock) { return new JmxMeterRegistry(config, clock, MY_HIERARCHICAL_MAPPER); } ---- [[production-ready-metrics-export-newrelic]] ==== New Relic New Relic registry pushes metrics to {micrometer-registry-documentation}/new-relic[New Relic] periodically. To export metrics to https://newrelic.com[New Relic], your API key and account id must be provided: [source,properties,indent=0] ---- management.metrics.export.newrelic.api-key=YOUR_KEY management.metrics.export.newrelic.account-id=YOUR_ACCOUNT_ID ---- You can also change the interval at which metrics are sent to New Relic: [source,properties,indent=0] ---- management.metrics.export.newrelic.step=30s ---- [[production-ready-metrics-export-prometheus]] ==== Prometheus {micrometer-registry-documentation}/prometheus[Prometheus] expects to scrape or poll individual app instances for metrics. Spring Boot provides an actuator endpoint available at `/actuator/prometheus` to present a https://prometheus.io[Prometheus scrape] with the appropriate format. TIP: The endpoint is not available by default and must be exposed, see <> for more details. Here is an example `scrape_config` to add to `prometheus.yml`: [source,yaml,indent=0] ---- scrape_configs: - job_name: 'spring' metrics_path: '/actuator/prometheus' static_configs: - targets: ['HOST:PORT'] ---- [[production-ready-metrics-export-signalfx]] ==== SignalFx SignalFx registry pushes metrics to {micrometer-registry-documentation}/signalfx[SignalFx] periodically. To export metrics to https://signalfx.com[SignalFx], your access token must be provided: [source,properties,indent=0] ---- management.metrics.export.signalfx.access-token=YOUR_ACCESS_TOKEN ---- You can also change the interval at which metrics are sent to SignalFx: [source,properties,indent=0] ---- management.metrics.export.signalfx.step=30s ---- [[production-ready-metrics-export-simple]] ==== Simple Micrometer ships with a simple, in-memory backend that is automatically used as a fallback if no other registry is configured. This allows you to see what metrics are collected in the <>. The in-memory backend disables itself as soon as you're using any of the other available backend. You can also disable it explicitly: [source,properties,indent=0] ---- management.metrics.export.simple.enabled=false ---- [[production-ready-metrics-export-statsd]] ==== StatsD The StatsD registry pushes metrics over UDP to a StatsD agent eagerly. By default, metrics are exported to a {micrometer-registry-documentation}/statsd[StatsD] agent running on your local machine. The StatsD agent host and port to use can be provided using: [source,properties,indent=0] ---- management.metrics.export.statsd.host=statsd.example.com management.metrics.export.statsd.port=9125 ---- You can also change the StatsD line protocol to use (default to Datadog): [source,properties,indent=0] ---- management.metrics.export.statsd.flavor=etsy ---- [[production-ready-metrics-export-wavefront]] ==== Wavefront Wavefront registry pushes metrics to {micrometer-registry-documentation}/wavefront[Wavefront] periodically. If you are exporting metrics to https://www.wavefront.com/[Wavefront] directly, your API token must be provided: [source,properties,indent=0] ---- management.metrics.export.wavefront.api-token=YOUR_API_TOKEN ---- Alternatively, you may use a Wavefront sidecar or an internal proxy set up in your environment that forwards metrics data to the Wavefront API host: [source,properties,indent=0] ---- management.metrics.export.wavefront.uri=proxy://localhost:2878 ---- TIP: If publishing metrics to a Wavefront proxy (as described in https://docs.wavefront.com/proxies_installing.html[the documentation]), the host must be in the `proxy://HOST:PORT` format. You can also change the interval at which metrics are sent to Wavefront: [source,properties,indent=0] ---- management.metrics.export.wavefront.step=30s ---- [[production-ready-metrics-meter]] === Supported Metrics Spring Boot registers the following core metrics when applicable: * JVM metrics, report utilization of: ** Various memory and buffer pools ** Statistics related to garbage collection ** Threads utilization ** Number of classes loaded/unloaded * CPU metrics * File descriptor metrics * Logback metrics: record the number of events logged to Logback at each level * Uptime metrics: report a gauge for uptime and a fixed gauge representing the application's absolute start time * Tomcat metrics * https://docs.spring.io/spring-integration/docs/current/reference/html/system-management-chapter.html#micrometer-integration[Spring Integration] metrics [[production-ready-metrics-spring-mvc]] ==== Spring MVC Metrics Auto-configuration enables the instrumentation of requests handled by Spring MVC. When `management.metrics.web.server.auto-time-requests` is `true`, this instrumentation occurs for all requests. Alternatively, when set to `false`, you can enable instrumentation by adding `@Timed` to a request-handling method: [source,java,indent=0] ---- @RestController @Timed <1> public class MyController { @GetMapping(""/api/people"") @Timed(extraTags = { ""region"", ""us-east-1"" }) <2> @Timed(value = ""all.people"", longTask = true) <3> public List listPeople() { ... } } ---- <1> A controller class to enable timings on every request handler in the controller. <2> A method to enable for an individual endpoint. This is not necessary if you have it on the class, but can be used to further customize the timer for this particular endpoint. <3> A method with `longTask = true` to enable a long task timer for the method. Long task timers require a separate metric name, and can be stacked with a short task timer. By default, metrics are generated with the name, `http.server.requests`. The name can be customized by setting the `management.metrics.web.server.requests-metric-name` property. By default, Spring MVC-related metrics are tagged with the following information: * `method`, the request's method (for example, `GET` or `POST`). * `uri`, the request's URI template prior to variable substitution, if possible (for example, `/api/person/{id}`). * `status`, the response's HTTP status code (for example, `200` or `500`). * `exception`, the simple class name of any exception that was thrown while handling the request. To customize the tags, provide a `@Bean` that implements `WebMvcTagsProvider`. [[production-ready-metrics-web-flux]] ==== Spring WebFlux Metrics Auto-configuration enables the instrumentation of all requests handled by WebFlux controllers and functional handlers. By default, metrics are generated with the name `http.server.requests`. You can customize the name by setting the `management.metrics.web.server.requests-metric-name` property. By default, WebFlux-related metrics are tagged with the following information: * `method`, the request's method (for example, `GET` or `POST`). * `uri`, the request's URI template prior to variable substitution, if possible (for example, `/api/person/{id}`). * `status`, the response's HTTP status code (for example, `200` or `500`). * `exception`, the simple class name of any exception that was thrown while handling the request. To customize the tags, provide a `@Bean` that implements `WebFluxTagsProvider`. [[production-ready-metrics-http-clients]] ==== HTTP Client Metrics Spring Boot Actuator manages the instrumentation of both `RestTemplate` and `WebClient`. For that, you have to get injected with an auto-configured builder and use it to create instances: * `RestTemplateBuilder` for `RestTemplate` * `WebClient.Builder` for `WebClient` It is also possible to apply manually the customizers responsible for this instrumentation, namely `MetricsRestTemplateCustomizer` and `MetricsWebClientCustomizer`. By default, metrics are generated with the name, `http.client.requests`. The name can be customized by setting the `management.metrics.web.client.requests-metric-name` property. By default, metrics generated by an instrumented client are tagged with the following information: * `method`, the request's method (for example, `GET` or `POST`). * `uri`, the request's URI template prior to variable substitution, if possible (for example, `/api/person/{id}`). * `status`, the response's HTTP status code (for example, `200` or `500`). * `clientName`, the host portion of the URI. To customize the tags, and depending on your choice of client, you can provide a `@Bean` that implements `RestTemplateExchangeTagsProvider` or `WebClientExchangeTagsProvider`. There are convenience static functions in `RestTemplateExchangeTags` and `WebClientExchangeTags`. [[production-ready-metrics-cache]] ==== Cache Metrics Auto-configuration enables the instrumentation of all available ``Cache``s on startup with metrics prefixed with `cache`. Cache instrumentation is standardized for a basic set of metrics. Additional, cache-specific metrics are also available. The following cache libraries are supported: * Caffeine * EhCache 2 * Hazelcast * Any compliant JCache (JSR-107) implementation Metrics are tagged by the name of the cache and by the name of the `CacheManager` that is derived from the bean name. NOTE: Only caches that are available on startup are bound to the registry. For caches created on-the-fly or programmatically after the startup phase, an explicit registration is required. A `CacheMetricsRegistrar` bean is made available to make that process easier. [[production-ready-metrics-jdbc]] ==== DataSource Metrics Auto-configuration enables the instrumentation of all available `DataSource` objects with a metric named `jdbc`. Data source instrumentation results in gauges representing the currently active, maximum allowed, and minimum allowed connections in the pool. Each of these gauges has a name that is prefixed by `jdbc`. Metrics are also tagged by the name of the `DataSource` computed based on the bean name. TIP: By default, Spring Boot provides metadata for all supported data sources; you can add additional `DataSourcePoolMetadataProvider` beans if your favorite data source isn't supported out of the box. See `DataSourcePoolMetadataProvidersConfiguration` for examples. Also, Hikari-specific metrics are exposed with a `hikaricp` prefix. Each metric is tagged by the name of the Pool (can be controlled with `spring.datasource.name`). [[production-ready-metrics-hibernate]] ==== Hibernate Metrics Auto-configuration enables the instrumentation of all available Hibernate `EntityManagerFactory` instances that have statistics enabled with a metric named `hibernate`. Metrics are also tagged by the name of the `EntityManagerFactory` that is derived from the bean name. To enable statistics, the standard JPA property `hibernate.generate_statistics` must be set to `true`. You can enable that on the auto-configured `EntityManagerFactory` as shown in the following example: [source,properties,indent=0] ---- spring.jpa.properties.hibernate.generate_statistics=true ---- [[production-ready-metrics-rabbitmq]] ==== RabbitMQ Metrics Auto-configuration will enable the instrumentation of all available RabbitMQ connection factories with a metric named `rabbitmq`. [[production-ready-metrics-custom]] === Registering custom metrics To register custom metrics, inject `MeterRegistry` into your component, as shown in the following example: [source,java,indent=0] ---- include::{code-examples}/actuate/metrics/MetricsMeterRegistryInjectionExample.java[tag=component] ---- If you find that you repeatedly instrument a suite of metrics across components or applications, you may encapsulate this suite in a `MeterBinder` implementation. By default, metrics from all `MeterBinder` beans will be automatically bound to the Spring-managed `MeterRegistry`. [[production-ready-metrics-per-meter-properties]] === Customizing individual metrics If you need to apply customizations to specific `Meter` instances you can use the `io.micrometer.core.instrument.config.MeterFilter` interface. By default, all `MeterFilter` beans will be automatically applied to the micrometer `MeterRegistry.Config`. For example, if you want to rename the `mytag.region` tag to `mytag.area` for all meter IDs beginning with `com.example`, you can do the following: [source,java,indent=0] ---- include::{code-examples}/actuate/metrics/MetricsFilterBeanExample.java[tag=configuration] ---- [[production-ready-metrics-common-tags]] ==== Common tags Common tags are generally used for dimensional drill-down on the operating environment like host, instance, region, stack, etc. Commons tags are applied to all meters and can be configured as shown in the following example: [source,properties,indent=0] ---- management.metrics.tags.region=us-east-1 management.metrics.tags.stack=prod ---- The example above adds `region` and `stack` tags to all meters with a value of `us-east-1` and `prod` respectively. NOTE: The order of common tags is important if you are using Graphite. As the order of common tags cannot be guaranteed using this approach, Graphite users are advised to define a custom `MeterFilter` instead. ==== Per-meter properties In addition to `MeterFilter` beans, it's also possible to apply a limited set of customization on a per-meter basis using properties. Per-meter customizations apply to any all meter IDs that start with the given name. For example, the following will disable any meters that have an ID starting with `example.remote` [source,properties,indent=0] ---- management.metrics.enable.example.remote=false ---- The following properties allow per-meter customization: .Per-meter customizations |=== | Property | Description | `management.metrics.enable` | Whether to deny meters from emitting any metrics. | `management.metrics.distribution.percentiles-histogram` | Whether to publish a histogram suitable for computing aggregable (across dimension) percentile approximations. | `management.metrics.distribution.percentiles` | Publish percentile values computed in your application | `management.metrics.distribution.sla` | Publish a cumulative histogram with buckets defined by your SLAs. |=== For more details on concepts behind `percentiles-histogram`, `percentiles` and `sla` refer to the {micrometer-concepts-documentation}#_histograms_and_percentiles[""Histograms and percentiles"" section] of the micrometer documentation. [[production-ready-metrics-endpoint]] === Metrics endpoint Spring Boot provides a `metrics` endpoint that can be used diagnostically to examine the metrics collected by an application. The endpoint is not available by default and must be exposed, see <> for more details. Navigating to `/actuator/metrics` displays a list of available meter names. You can drill down to view information about a particular meter by providing its name as a selector, e.g. `/actuator/metrics/jvm.memory.max`. [TIP] ==== The name you use here should match the name used in the code, not the name after it has been naming-convention normalized for a monitoring system it is shipped to. In other words, if `jvm.memory.max` appears as `jvm_memory_max` in Prometheus because of its snake case naming convention, you should still use `jvm.memory.max` as the selector when inspecting the meter in the `metrics` endpoint. ==== You can also add any number of `tag=KEY:VALUE` query parameters to the end of the URL to dimensionally drill down on a meter, e.g. `/actuator/metrics/jvm.memory.max?tag=area:nonheap`. [TIP] ==== The reported measurements are the _sum_ of the statistics of all meters matching the meter name and any tags that have been applied. So in the example above, the returned ""Value"" statistic is the sum of the maximum memory footprints of ""Code Cache"", ""Compressed Class Space"", and ""Metaspace"" areas of the heap. If you just wanted to see the maximum size for the ""Metaspace"", you could add an additional `tag=id:Metaspace`, i.e. `/actuator/metrics/jvm.memory.max?tag=area:nonheap&tag=id:Metaspace`. ==== [[production-ready-auditing]] == Auditing Once Spring Security is in play, Spring Boot Actuator has a flexible audit framework that publishes events (by default, ""`authentication success`"", ""`failure`"" and ""`access denied`"" exceptions). This feature can be very useful for reporting and for implementing a lock-out policy based on authentication failures. To customize published security events, you can provide your own implementations of `AbstractAuthenticationAuditListener` and `AbstractAuthorizationAuditListener`. You can also use the audit services for your own business events. To do so, either inject the existing `AuditEventRepository` into your own components and use that directly or publish an `AuditApplicationEvent` with the Spring `ApplicationEventPublisher` (by implementing `ApplicationEventPublisherAware`). [[production-ready-http-tracing]] == HTTP Tracing Tracing is automatically enabled for all HTTP requests. You can view the `httptrace` endpoint and obtain basic information about the last 100 request-response exchanges. [[production-ready-http-tracing-custom]] === Custom HTTP tracing To customize the items that are included in each trace, use the `management.trace.http.include` configuration property. For advanced customization, consider registering your own `HttpExchangeTracer` implementation. By default, an `InMemoryHttpTraceRepository` that stores traces for the last 100 request-response exchanges is used. If you need to expand the capacity, you can define your own instance of the `InMemoryHttpTraceRepository` bean. You can also create your own alternative `HttpTraceRepository` implementation. [[production-ready-process-monitoring]] == Process Monitoring In the `spring-boot` module, you can find two classes to create files that are often useful for process monitoring: * `ApplicationPidFileWriter` creates a file containing the application PID (by default, in the application directory with a file name of `application.pid`). * `WebServerPortFileWriter` creates a file (or files) containing the ports of the running web server (by default, in the application directory with a file name of `application.port`). By default, these writers are not activated, but you can enable: * <> * <> [[production-ready-process-monitoring-configuration]] === Extending Configuration In the `META-INF/spring.factories` file, you can activate the listener(s) that writes a PID file, as shown in the following example: [indent=0] ---- org.springframework.context.ApplicationListener=\\ org.springframework.boot.context.ApplicationPidFileWriter,\\ org.springframework.boot.web.context.WebServerPortFileWriter ---- [[production-ready-process-monitoring-programmatically]] === Programmatically You can also activate a listener by invoking the `SpringApplication.addListeners(...)` method and passing the appropriate `Writer` object. This method also lets you customize the file name and path in the `Writer` constructor. [[production-ready-cloudfoundry]] == Cloud Foundry Support Spring Boot's actuator module includes additional support that is activated when you deploy to a compatible Cloud Foundry instance. The `/cloudfoundryapplication` path provides an alternative secured route to all `@Endpoint` beans. The extended support lets Cloud Foundry management UIs (such as the web application that you can use to view deployed applications) be augmented with Spring Boot actuator information. For example, an application status page may include full health information instead of the typical ""`running`"" or ""`stopped`"" status. NOTE: The `/cloudfoundryapplication` path is not directly accessible to regular users. In order to use the endpoint, a valid UAA token must be passed with the request. [[production-ready-cloudfoundry-disable]] === Disabling Extended Cloud Foundry Actuator Support If you want to fully disable the `/cloudfoundryapplication` endpoints, you can add the following setting to your `application.properties` file: .application.properties [source,properties,indent=0] ---- management.cloudfoundry.enabled=false ---- [[production-ready-cloudfoundry-ssl]] === Cloud Foundry Self-signed Certificates By default, the security verification for `/cloudfoundryapplication` endpoints makes SSL calls to various Cloud Foundry services. If your Cloud Foundry UAA or Cloud Controller services use self-signed certificates, you need to set the following property: .application.properties [source,properties,indent=0] ---- management.cloudfoundry.skip-ssl-validation=true ---- === Custom context path If the server's context-path has been configured to anything other than `/`, the Cloud Foundry endpoints will not be available at the root of the application. For example, if `server.servlet.context-path=/app`, Cloud Foundry endpoints will be available at `/app/cloudfoundryapplication/*`. If you expect the Cloud Foundry endpoints to always be available at `/cloudfoundryapplication/*`, regardless of the server's context-path, you will need to explicitly configure that in your application. The configuration will differ depending on the web server in use. For Tomcat, the following configuration can be added: [source,java,indent=0] ---- include::{code-examples}/cloudfoundry/CloudFoundryCustomContextPathExample.java[tag=configuration] ---- [[production-ready-whats-next]] == What to Read Next If you want to explore some of the concepts discussed in this chapter, you can take a look at the actuator {github-code}/spring-boot-samples[sample applications]. You also might want to read about graphing tools such as http://graphite.wikidot.com/[Graphite]. Otherwise, you can continue on, to read about <> or jump ahead for some in-depth information about Spring Boot's _<>_. ",16266,True,2884.1621159284923,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. //// anchor:gremlin-variants[] [[gremlin-drivers-variants]] = Gremlin Drivers and Variants image::gremlin-house-of-mirrors.png[width=1024] At this point, readers should be well familiar with the <> to this Reference Documentation and will likely be thinking about implementation details specific to the graph provider they have selected as well as the programming language they intend to use. The choice of programming language could have implications to the architecture and design of the application and the choice itself may have limits imposed upon it by the chosen graph provider. For example, a <> will require the selection of a driver to interact with it. On the other hand, a graph system that is designed for embedded use, like TinkerGraph, needs the Java Virtual Machine (JVM) environment so will require <>, if using a programming language that is not on the JVM and will further require driver selection. TinkerPop provides an array of drivers in different programming languages as a way to connect to a remote Gremlin Server or Remote Gremlin Provider. Drivers allow the developer to make requests to that remote system and get back results from the TinkerPop-enabled graphs hosted within. A driver can submit Gremlin strings and Gremlin bytecode over this sub-protocol. Gremlin strings are written in the scripting language made available by the remote system that the driver is connecting to (typically, Groovy-based). This connection approach is quite similar to what developers are likely familiar with when using JDBC and SQL. While it is familiar, it is not recommended and for TinkerPop it is considered an out-dated concept and is largely still present for the purpose of supporting applications that might still be using that method of interaction. The preferred approach is to use bytecode-based requests, which essentially allows the ability to craft Gremlin directly in the programming language of choice. As Gremlin makes use of two fundamental programming constructs: link:https://en.wikipedia.org/wiki/Function_composition[function composition] and link:https://en.wikipedia.org/wiki/Nested_function[function nesting]. it is possible to embed the Gremlin language in any modern programming language. It is a far more natural way to program, because it enables IDE interaction, compile time checks, and language level checks that can help prevent errors prior to execution. The differences between these two approaches were outlined in the <> Section, which applies to Gremlin Server, but also to Remote Gremlin Providers. In addition to the languages and drivers that TinkerPop supports, there are also third-party implementations, as well as extensions to the Gremlin language that might be specific to a particular graph provider. That listing can be found on the TinkerPop link:https://tinkerpop.apache.org/#graph-systems[home page]. Their description is beyond the scope of this documentation. TIP: When possible, it is typically best to align the version of TinkerPop used on the client with the version supported on the server. While it is not impossible to have a different version between client and server, it may require additional configuration and/or a deeper knowledge of that changes introduced between versions. It's simply safer to avoid the conflict, when allowed to do so. IMPORTANT: Gremlin-Java is the canonical representation of Gremlin and any (proper) Gremlin language variant will emulate its structure as best as possible given the constructs of the host language. A strong correspondence between variants ensures that the general Gremlin reference documentation is applicable to all variants and that users moving between development languages can easily adopt the Gremlin variant for that language. image::gremlin-variant-architecture.png[width=650,float=left] NOTE: The information herein describes how to use the Gremlin language variants distributed with Apache TinkerPop. For information on how to build a Gremlin language variant, please review the link:https://tinkerpop.apache.org/docs/x.y.z/tutorials/gremlin-language-variants/[Gremlin Language Variants] tutorial. The following sections describe each language variant and driver that is officially TinkerPop a part of the project, provided more detailed information about usage, configuration and known limitations. anchor:connecting-via-remotegraph[] anchor:connecting-via-java[] [[gremlin-java]] == Gremlin-Java image:gremlin-java-drawing.png[width=130,float=right] Apache TinkerPop's Gremlin-Java implements Gremlin within the Java language and can be used by any Java Virtual Machine. Gremlin-Java is considered the canonical, reference implementation of Gremlin and serves as the foundation by which all other Gremlin language variants should emulate. As the Gremlin Traversal Machine that processes Gremlin queries is also written in Java, it can be used in all three connection methods described in the <> Section. [source,xml] ---- org.apache.tinkerpop gremlin-core x.y.z org.apache.tinkerpop gremlin-driver x.y.z ---- === Connecting The pattern for connecting is described in <> and it basically distills down to creating a `GraphTraversalSource`. For <> mode, this involves first creating a `Graph` and then spawning the `GraphTraversalSource`: [source,java] ---- Graph graph = ...; GraphTraversalSource g = graph.traversal(); ---- Using ""g"" it is then possible to start writing Gremlin. The ""g"" allows for the setting of many configuration options which affect traversal execution. The <> Section describes some of these options and some are only suitable with <> style usage. For remote options however there are some added configurations to consider and this section looks to address those. When connecting to <> or <> it is possible to configure the `DriverRemoteConnection` manually as shown in earlier examples where the host and port are provided as follows: [source,java] ---- GraphTraversalSource g = traversal().withRemote(DriverRemoteConnection.using(""localhost"",8182,""g"")); ---- It is also possible to create it from a configuration. The most basic way to do so involves the following line of code: [source,java] ---- GraphTraversalSource g = traversal().withRemote('conf/remote-graph.properties'); ---- The `remote-graph.properties` file simply provides connection information to the `GraphTraversalSource` which is used to configure a `RemoteConnection`. That file looks like this: [source,text] ---- gremlin.remote.remoteConnectionClass=org.apache.tinkerpop.gremlin.driver.remote.DriverRemoteConnection gremlin.remote.driver.clusterFile=conf/remote-objects.yaml gremlin.remote.driver.sourceName=g ---- The `RemoteConnection` is an interface that provides the transport mechanism for ""g"" and makes it possible to for that mechanism to be altered (typically by graph providers who have their own protocols). TinkerPop provides one such implementation called the `DriverRemoteConnection` which enables transport over Gremlin Server protocols using the TinkerPop driver. The driver is configured by the specified `gremlin.remote.driver.clusterFile` and the local ""g"" is bound to the `GraphTraversalSource` on the remote end with `gremlin.remote.driver.sourceName` which in this case is also ""g"". There are other ways to configure the traversal using `withRemote()` as it has other overloads. It can take an Apache Commons `Configuration` object which would have keys similar to those shown in the properties file and it can also take a `RemoteConnection` instance directly. The latter is interesting in that it means it is possible to programmatically construct all aspects of the `RemoteConnection`. For TinkerPop usage, that might mean directly constructing the `DriverRemoteConnection` and the driver instance that supplies the transport mechanism. For example, the command shown above could be re-written using programmatic construction as follows: [source,java] ---- Cluster cluster = Cluster.open(); GraphTraversalSource g = traversal().withRemote(DriverRemoteConnection.using(cluster, ""g"")); ---- Please consider the following example: [gremlin-groovy] ---- g = traversal().withRemote('conf/remote-graph.properties') g.V().elementMap() g.close() ---- [source,java] ---- GraphTraversalSource g = traversal().withRemote(""conf/remote-graph.properties""); List list = g.V().elementMap(); g.close(); ---- Note the call to `close()` above. The call to `withRemote()` internally instantiates a connection via the driver that can only be released by ""closing"" the `GraphTraversalSource`. It is important to take that step to release resources created in that step. If working with multiple remote `TraversalSource` instances it is more efficient to construct `Cluster` and `Client objects and then re-use them. [gremlin-groovy] ---- cluster = Cluster.open('conf/remote-objects.yaml') client = cluster.connect() g = traversal().withRemote(DriverRemoteConnection.using(client, ""g"")) g.V().elementMap() g.close() client.close() cluster.close() ---- If the `Client` instance is supplied externally, as is shown above, then it is not closed implicitly by the close of ""g"". Closing ""g"" will have no effect on ""client"" or ""cluster"". When supplying them externally, the `Client` and `Cluster` objects must also be closed explicitly. It's worth noting that the close of a `Cluster` will close all `Client` instances spawned by the `Cluster`. IMPORTANT: Bytecode-based traversals use the `TraversalOpProcessor` in Gremlin Server which requires a cache to enable the retrieval of side-effects (if the `Traversal` produces any). That cache can be configured (e.g. controlling eviction times and sizing) in the Gremlin Server configuration file as described <>. Some connection options can also be set on individual requests made through the Java driver using `with()` step on the `TraversalSource`. For instance to set request timeout to 500 milliseconds: [source,java] ---- GraphTraversalSource g = traversal().withRemote(conf); List vertices = g.with(Tokens.ARGS_EVAL_TIMEOUT, 500L).V().out(""knows"").toList() ---- [[java-imports]] === Common Imports There are a number of classes, functions and tokens that are typically used with Gremlin. The following imports provide most of the common functionality required to use Gremlin: [source,java] ---- import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; import org.apache.tinkerpop.gremlin.process.traversal.IO; import static org.apache.tinkerpop.gremlin.process.traversal.AnonymousTraversalSource.traversal; import static org.apache.tinkerpop.gremlin.process.traversal.Operator.*; import static org.apache.tinkerpop.gremlin.process.traversal.Order.*; import static org.apache.tinkerpop.gremlin.process.traversal.P.*; import static org.apache.tinkerpop.gremlin.process.traversal.Pop.*; import static org.apache.tinkerpop.gremlin.process.traversal.SackFunctions.*; import static org.apache.tinkerpop.gremlin.process.traversal.Scope.*; import static org.apache.tinkerpop.gremlin.process.traversal.TextP.*; import static org.apache.tinkerpop.gremlin.structure.Column.*; import static org.apache.tinkerpop.gremlin.structure.Direction.*; import static org.apache.tinkerpop.gremlin.structure.T.*; import static org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__.*; ---- === Configuration The following table describes the various configuration options for the Gremlin Driver: [width=""100%"",cols=""3,10,^2"",options=""header""] |========================================================= |Key |Description |Default |connectionPool.channelizer |The fully qualified classname of the client `Channelizer` that defines how to connect to the server. |`Channelizer.WebSocketChannelizer` |connectionPool.enableSsl |Determines if SSL should be enabled or not. If enabled on the server then it must be enabled on the client. |false |connectionPool.keepAliveInterval |Length of time in milliseconds to wait on an idle connection before sending a keep-alive request. Set to zero to disable this feature. |180000 |connectionPool.keyStore |The private key in JKS or PKCS#12 format. |_none_ |connectionPool.keyStorePassword |The password of the `keyStore` if it is password-protected. |_none_ |connectionPool.keyStoreType |`JKS` (Java 8 default) or `PKCS12` (Java 9+ default)|_none_ |connectionPool.maxContentLength |The maximum length in bytes that a message can be sent to the server. This number can be no greater than the setting of the same name in the server configuration. |65536 |connectionPool.maxInProcessPerConnection |The maximum number of in-flight requests that can occur on a connection. |4 |connectionPool.maxSimultaneousUsagePerConnection |The maximum number of times that a connection can be borrowed from the pool simultaneously. |16 |connectionPool.maxSize |The maximum size of a connection pool for a host. |8 |connectionPool.maxWaitForConnection |The amount of time in milliseconds to wait for a new connection before timing out. |3000 |connectionPool.maxWaitForClose |The amount of time in milliseconds to wait for pending messages to be returned from the server before closing the connection. |3000 |connectionPool.minInProcessPerConnection |The minimum number of in-flight requests that can occur on a connection. |1 |connectionPool.minSimultaneousUsagePerConnection |The maximum number of times that a connection can be borrowed from the pool simultaneously. |8 |connectionPool.minSize |The minimum size of a connection pool for a host. |2 |connectionPool.reconnectInterval |The amount of time in milliseconds to wait before trying to reconnect to a dead host. |1000 |connectionPool.resultIterationBatchSize |The override value for the size of the result batches to be returned from the server. |64 |connectionPool.sslCipherSuites |The list of JSSE ciphers to support for SSL connections. If specified, only the ciphers that are listed and supported will be enabled. If not specified, the JVM default is used. |_none_ |connectionPool.sslEnabledProtocols |The list of SSL protocols to support for SSL connections. If specified, only the protocols that are listed and supported will be enabled. If not specified, the JVM default is used. |_none_ |connectionPool.sslSkipCertValidation |Configures the `TrustManager` to trust all certs without any validation. Should not be used in production.|false |connectionPool.trustStore |File location for a SSL Certificate Chain to use when SSL is enabled. If this value is not provided and SSL is enabled, the default `TrustManager` will be used. |_none_ |connectionPool.trustStorePassword |The password of the `trustStore` if it is password-protected |_none_ |connectionPool.validationRequest |A script that is used to test server connectivity. A good script to use is one that evaluates quickly and returns no data. The default simply returns an empty string, but if a graph is required by a particular provider, a good traversal might be `g.inject()`. |_''_ |hosts |The list of hosts that the driver will connect to. |localhost |jaasEntry |Sets the `AuthProperties.Property.JAAS_ENTRY` properties for authentication to Gremlin Server. |_none_ |nioPoolSize |Size of the pool for handling request/response operations. |available processors |password |The password to submit on requests that require authentication. |_none_ |path |The URL path to the Gremlin Server. |_/gremlin_ |port |The port of the Gremlin Server to connect to. The same port will be applied for all hosts. |8192 |protocol |Sets the `AuthProperties.Property.PROTOCOL` properties for authentication to Gremlin Server. |_none_ |serializer.className |The fully qualified class name of the `MessageSerializer` that will be used to communicate with the server. Note that the serializer configured on the client should be supported by the server configuration. |_none_ |serializer.config |A `Map` of configuration settings for the serializer. |_none_ |username |The username to submit on requests that require authentication. |_none_ |workerPoolSize |Size of the pool for handling background work. |available processors * 2 |========================================================= Please see the link:https://tinkerpop.apache.org/javadocs/x.y.z/core/org/apache/tinkerpop/gremlin/driver/Cluster.Builder.html[Cluster.Builder javadoc] to get more information on these settings. === Serialization Remote systems like Gremlin Server and Remote Gremlin Providers respond to requests made in a particular serialization format and respond by serializing results to some format to be interpreted by the client. For JVM-based languages, there are three options for serialization: Gryo, GraphSON and GraphBinary. It is important that the client and server have the same serializers configured in the same way or else one or the other will experience serialization exceptions and fail to always communicate. Discrepancy in serializer registration between client and server can happen fairly easily as different graph systems may automatically include serializers on the server-side, thus leaving the client to be configured manually. As an example: [source,java] ---- IoRegistry registry = ...; // an IoRegistry instance exposed by a specific graph provider TypeSerializerRegistry typeSerializerRegistry = TypeSerializerRegistry.build().addRegistry(registry).create(); MessageSerializer serializer = new GraphBinaryMessageSerializerV1(typeSerializerRegistry); Cluster cluster = Cluster.build(). serializer(serializer). create(); Client client = cluster.connect(); GraphTraversalSource g = traversal().withRemote(DriverRemoteConnection.using(client, ""g"")); ---- The `IoRegistry` tells the serializer what classes from the graph provider to auto-register during serialization. Gremlin Server roughly uses this same approach when it configures its serializers, so using this same model will ensure compatibility when making requests. Obviously, it is possible to switch to GraphSON or Gryo by using the appropriate `MessageSerializer` (e.g. `GraphSONMessageSerializerV3d0` or `GryoMessageSerializerV3d0` respectively) in the same way and building that into the `Cluster` object. NOTE: Gryo is no longer the preferred binary serialization format for Gremlin Server - please prefer GraphBinary. === The Lambda Solution Supporting link:https://en.wikipedia.org/wiki/Anonymous_function[anonymous functions] across languages is difficult as most languages do not support lambda introspection and thus, code analysis. In Gremlin-Java and with <> usage, lambdas can be leveraged directly: [source,java] ---- g.V().out(""knows"").map(t -> t.get().value(""name"") + "" is the friend name"") <1> g.V().out(""knows"").sideEffect(System.out::println) <2> g.V().as(""a"").out(""knows"").as(""b"").select(""b"").by((Function) v -> v.value(""name"").length()) <3> ---- <1> A Java `Function` is used to map a `Traverser` to an object `E`. <2> Gremlin steps that take consumer arguments can be passed Java method references. <3> Gremlin-Java may sometimes require explicit lambda typing when types can not be automatically inferred. When sending traversals remotely to <> or <>, the static methods of `Lambda` should be used and should denote a particular JSR-223 `ScriptEngine` that is available on the remote end (typically, this is Groovy). `Lambda` creates a string-based lambda that is then converted into a lambda/closure/anonymous-function/etc. by the respective lambda language's JSR-223 `ScriptEngine` implementation. [source,java] ---- g.V().out(""knows"").map(Lambda.function(""it.get().value('name') + ' is the friend name'"")) g.V().out(""knows"").sideEffect(Lambda.consumer(""println it"")) g.V().as(""a"").out(""knows"").as(""b"").select(""b"").by(Lambda.function(""it.value('name').length()"")) ---- Finally, Gremlin `Bytecode` that includes lambdas requires that the traversal be processed by the `ScriptEngine`. To avoid continued recompilation costs, it supports the encoding of bindings, which allow Gremlin Server to cache traversals that will be reused over and over again save that some parameterization may change. Thus, instead of translating, compiling, and then executing each submitted bytecode request, it is possible to simply execute. To express bindings in Java, use `Bindings`. [source,java] ---- b = Bindings.instance() g.V(b.of('id',1)).out('created').values('name').map{t -> ""name: "" + t.get() } g.V(b.of('id',4)).out('created').values('name').map{t -> ""name: "" + t.get() } g.V(b.of('id',4)).out('created').values('name').getBytecode() g.V(b.of('id',4)).out('created').values('name').getBytecode().getBindings() cluster.close() ---- Both traversals are abstractly defined as `g.V(id).out('created').values('name').map{t -> ""name: "" + t.get() }` and thus, the first submission can be cached for faster evaluation on the next submission. WARNING: It is generally advised to avoid lambda usage. Please consider <> for more information. === Submitting Scripts WARNING: TinkerPop does not recommend submitting script-based requests and generally continues to support this feature for legacy reasons and corner use cases which are still not completely addressed by the Gremlin language. Please consider using bytecode-based requests instead when possible. image:gremlin-java.png[width=175,float=left] TinkerPop comes equipped with a reference client for Java-based applications. It is referred to as `gremlin-driver`, which enables applications to send requests to Gremlin Server and get back results. Gremlin scripts are sent to the server from a `Client` instance. A `Client` is created as follows: [source,java] ---- Cluster cluster = Cluster.open(); <1> Client client = cluster.connect(); <2> ---- <1> Opens a reference to `localhost` - note that there are many configuration options available in defining a `Cluster` object. <2> Creates a `Client` given the configuration options of the `Cluster`. Once a `Client` instance is ready, it is possible to issue some Gremlin Groovy scripts: [source,java] ---- ResultSet results = client.submit(""[1,2,3,4]""); <1> results.stream().map(i -> i.get(Integer.class) * 2); <2> CompletableFuture> results = client.submit(""[1,2,3,4]"").all(); <3> CompletableFuture future = client.submitAsync(""[1,2,3,4]""); <4> Map params = new HashMap<>(); params.put(""x"",4); client.submit(""[1,2,3,x]"", params); <5> ---- <1> Submits a script that simply returns a `List` of integers. This method blocks until the request is written to the server and a `ResultSet` is constructed. <2> Even though the `ResultSet` is constructed, it does not mean that the server has sent back the results (or even evaluated the script potentially). The `ResultSet` is just a holder that is awaiting the results from the server. In this case, they are streamed from the server as they arrive. <3> Submit a script, get a `ResultSet`, then return a `CompletableFuture` that will be called when all results have been returned. <4> Submit a script asynchronously without waiting for the request to be written to the server. <5> Parameterized request are considered the most efficient way to send Gremlin to the server as they can be cached, which will boost performance and reduce resources required on the server. ==== Per Request Settings There are a number of overloads to `Client.submit()` that accept a `RequestOptions` object. The `RequestOptions` provide a way to include options that are specific to the request made with the call to `submit()`. A good use-case for this feature is to set a per-request override to the `evaluationTimeout` so that it only applies to the current request. [source,java] ---- Cluster cluster = Cluster.open(); Client client = cluster.connect(); RequestOptions options = RequestOptions.build().timeout(500).create(); List result = client.submit(""g.V()"", options).all().get(); ---- ==== Aliases Scripts submitted to Gremlin Server automatically have the globally configured `Graph` and `TraversalSource` instances made available to them. Therefore, if Gremlin Server configures two `TraversalSource` instances called ""g1"" and ""g2"" a script can simply reference them directly as: [source,java] ---- client.submit(""g1.V()"") client.submit(""g2.V()"") ---- While this is an acceptable way to submit scripts, it has the downside of forcing the client to encode the server-side variable name directly into the script being sent. If the server configuration ever changed such that ""g1"" became ""g100"", the client-side code might have to see a significant amount of change. Decoupling the script code from the server configuration can be managed by the `alias` method on `Client` as follows: [source,java] ---- Client g1Client = client.alias(""g1"") Client g2Client = client.alias(""g2"") g1Client.submit(""g.V()"") g2Client.submit(""g.V()"") ---- The above code demonstrates how the `alias` method can be used such that the script need only contain a reference to ""g"" and ""g1"" and ""g2"" are automatically rebound into ""g"" on the server-side. [[gremlin-java-dsl]] === Domain Specific Languages Creating a <> (DSL) in Java requires the `@GremlinDsl` Java annotation in `gremlin-core`. This annotation should be applied to a ""DSL interface"" that extends `GraphTraversal.Admin`: [source,java] ---- @GremlinDsl public interface SocialTraversalDsl extends GraphTraversal.Admin { } ---- IMPORTANT: The name of the DSL interface should be suffixed with ""TraversalDSL"". All characters in the interface name before that become the ""name"" of the DSL. In this interface, define the methods that the DSL will be composed of: [source,java] ---- @GremlinDsl public interface SocialTraversalDsl extends GraphTraversal.Admin { public default GraphTraversal knows(String personName) { return out(""knows"").hasLabel(""person"").has(""name"", personName); } public default GraphTraversal youngestFriendsAge() { return out(""knows"").hasLabel(""person"").values(""age"").min(); } public default GraphTraversal createdAtLeast(int number) { return outE(""created"").count().is(P.gte(number)); } } ---- IMPORTANT: Follow the TinkerPop convention of using `` in naming generics as those conventions are taken into account when generating the anonymous traversal class. The processor attempts to infer the appropriate type parameters when generating the anonymous traversal class. If it cannot do it correctly, it is possible to avoid the inference by using the `GremlinDsl.AnonymousMethod` annotation on the DSL method. It allows explicit specification of the types to use. The `@GremlinDsl` annotation is used by the link:https://docs.oracle.com/javase/8/docs/api/index.html?javax/annotation/processing/Processor.html[Java Annotation Processor] to generate the boilerplate class structure required to properly use the DSL within the TinkerPop framework. These classes can be generated and maintained by hand, but it would be time consuming, monotonous and error-prone to do so. Typically, the Java compilation process is automatically configured to detect annotation processors on the classpath and will automatically use them when found. If that does not happen, it may be necessary to make configuration changes to the build to allow for the compilation process to be aware of the following `javax.annotation.processing.Processor` implementation: [source,java] ---- org.apache.tinkerpop.gremlin.process.traversal.dsl.GremlinDslProcessor ---- The annotation processor will generate several classes for the DSL: * `SocialTraversal` - A `Traversal` interface that extends the `SocialTraversalDsl` proxying methods to its underlying interfaces (such as `GraphTraversal`) to instead return a `SocialTraversal` * `DefaultSocialTraversal` - A default implementation of `SocialTraversal` (typically not used directly by the user) * `SocialTraversalSource` - Spawns `DefaultSocialTraversal` instances. * `__` - Spawns anonymous `DefaultSocialTraversal` instances. Using the DSL then just involves telling the `Graph` to use it: [source,java] ---- SocialTraversalSource social = graph.traversal(SocialTraversalSource.class); social.V().has(""name"",""marko"").knows(""josh""); ---- The `SocialTraversalSource` can also be customized with DSL functions. As an additional step, include a class that extends from `GraphTraversalSource` and with a name that is suffixed with ""TraversalSourceDsl"". Include in this class, any custom methods required by the DSL: [source,java] ---- public class SocialTraversalSourceDsl extends GraphTraversalSource { public SocialTraversalSourceDsl(Graph graph, TraversalStrategies traversalStrategies) { super(graph, traversalStrategies); } public SocialTraversalSourceDsl(Graph graph) { super(graph); } public GraphTraversal persons(String... names) { GraphTraversalSource clone = this.clone(); // Manually add a ""start"" step for the traversal in this case the equivalent of V(). GraphStep is marked // as a ""start"" step by passing ""true"" in the constructor. clone.getBytecode().addStep(GraphTraversal.Symbols.V); GraphTraversal traversal = new DefaultGraphTraversal<>(clone); traversal.asAdmin().addStep(new GraphStep<>(traversal.asAdmin(), Vertex.class, true)); traversal = traversal.hasLabel(""person""); if (names.length > 0) traversal = traversal.has(""name"", P.within(names)); return traversal; } } ---- Then, back in the `SocialTraversal` interface, update the `GremlinDsl` annotation with the `traversalSource` argument to point to the fully qualified class name of the `SocialTraversalSourceDsl`: [source,java] ---- @GremlinDsl(traversalSource = ""com.company.SocialTraversalSourceDsl"") public interface SocialTraversalDsl extends GraphTraversal.Admin { ... } ---- It is then possible to use the `persons()` method to start traversals: [source,java] ---- SocialTraversalSource social = graph.traversal(SocialTraversalSource.class); social.persons(""marko"").knows(""josh""); ---- NOTE: Using Maven, as shown in the `gremlin-archetype-dsl` module, makes developing DSLs with the annotation processor straightforward in that it sets up appropriate paths to the generated code automatically. anchor:java-application-examples[] [[gremlin-archetypes]] === Application Examples The available link:https://maven.apache.org/guides/introduction/introduction-to-archetypes.html[Maven archetypes] are as follows: * `gremlin-archetype-dsl` - An example project that demonstrates how to build Domain Specific Languages with Gremlin in Java. * `gremlin-archetype-server` - An example project that demonstrates the basic structure of a <> project, how to connect with the Gremlin Driver, and how to embed Gremlin Server in a testing framework. * `gremlin-archetype-tinkergraph` - A basic example of how to structure a TinkerPop project with Maven. Use Maven to generate these example projects with a command like: [source,shell] $ mvn archetype:generate -DarchetypeGroupId=org.apache.tinkerpop -DarchetypeArtifactId=gremlin-archetype-server \\ -DarchetypeVersion=x.y.z -DgroupId=com.my -DartifactId=app -Dversion=0.1 -DinteractiveMode=false This command will generate a new Maven project in a directory called ""app"" with a `pom.xml` specifying a `groupId` of `com.my`. Please see the `README.asciidoc` in the root of each generated project for information on how to build and execute it. [[gremlin-groovy]] == Gremlin-Groovy image:gremlin-groovy-drawing.png[width=130,float=right] Apache TinkerPop's Gremlin-Groovy implements Gremlin within the link:http://groovy.apache.org[Apache Groovy] language. As a JVM-based language variant, Gremlin-Groovy is backed by Gremlin-Java constructs. Moreover, given its scripting nature, Gremlin-Groovy serves as the language of <> and <>. [source,groovy] ---- compile group: 'org.apache.tinkerpop', name: 'gremlin-core', version: '3.3.4' compile group: 'org.apache.tinkerpop', name: 'gremlin-driver', version: '3.3.4' ---- [[gremlin-groovy-differences]] === Differences In Groovy, `as`, `in`, and `not` are reserved words. Gremlin-Groovy does not allow these steps to be called statically from the anonymous traversal `+__+` and therefore, must always be prefixed with `+__.+` For instance: `+g.V().as('a').in().as('b').where(__.not(__.as('a').out().as('b')))+` [[gremlin-python]] == Gremlin-Python image:gremlin-python-drawing.png[width=130,float=right] Apache TinkerPop's Gremlin-Python implements Gremlin within the link:https://www.python.org/[Python] language and can be used on any Python virtual machine including the popular link:https://en.wikipedia.org/wiki/CPython[CPython] machine. Python's syntax has the same constructs as Java including ""dot notation"" for function chaining (`a.b.c`), round bracket function arguments (`a(b,c)`), and support for global namespaces (`a(b())` vs `a(__.b())`). As such, anyone familiar with Gremlin-Java will immediately be able to work with Gremlin-Python. Moreover, there are a few added constructs to Gremlin-Python that make traversals a bit more succinct. To install Gremlin-Python, use Python's link:https://en.wikipedia.org/wiki/Pip_(package_manager)[pip] package manager. [source,bash] ---- pip install gremlinpython pip install gremlinpython[kerberos] # Optional, not available on Microsoft Windows ---- === Connecting The pattern for connecting is described in <> and it basically distills down to creating a `GraphTraversalSource`. A `GraphTraversalSource` is created from the anonymous `traversal()` method where the ""g"" provided to the `DriverRemoteConnection` corresponds to the name of a `GraphTraversalSource` on the remote end. [source,python] ---- g = traversal().withRemote(DriverRemoteConnection('ws://localhost:8182/gremlin','g')) ---- If you need to send additional headers in the websockets connection, you can pass an optional `headers` parameter to the `DriverRemoteConnection` constructor. [source,python] ---- g = traversal().withRemote(DriverRemoteConnection( 'ws://localhost:8182/gremlin', 'g', headers={'Header':'Value'})) ---- Gremlin-Python supports plain text and Kerberos SASL authentication, you can set it on the connection options. [source,python] ---- # Plain text authentication g = traversal().withRemote(DriverRemoteConnection( 'ws://localhost:8182/gremlin', 'g', username='stephen', password='password')) # Kerberos authentication g = traversal().withRemote(DriverRemoteConnection( 'ws://localhost:8182/gremlin', 'g', kerberized_service='gremlin@hostname.your.org')) ---- The value specified for the kerberized_service should correspond to the first part of the principal name configured for the gremlin service, but with the slash replaced by an _at_ sign. The Gremlin-Python client reads the kerberos configurations from your system. It finds the KDC's hostname and port from the krb5.conf file at the https://web.mit.edu/kerberos/krb5-devel/doc/mitK5defaults.html[default location] or as indicated in the KRB5_CONFIG environment variable. It finds credentials from the credential cache or a keytab file at the https://web.mit.edu/kerberos/krb5-devel/doc/mitK5defaults.html[default locations] or as indicated in the KRB5CCNAME or KRB5_KTNAME environment variables. If you authenticate to a remote <> or <>, this server normally has SSL activated and the websockets url will start with 'wss://'. If Gremlin-Server uses a self-signed certificate for SSL, Gremlin-Python needs access to a local copy of the CA certificate file (in openssl .pem format), to be specified in the SSL_CERT_FILE environment variable. [[python-imports]] === Common Imports There are a number of classes, functions and tokens that are typically used with Gremlin. The following imports provide most of the typical functionality required to use Gremlin: [source,python] ---- from gremlin_python import statics from gremlin_python.process.anonymous_traversal import traversal from gremlin_python.process.graph_traversal import __ from gremlin_python.process.strategies import * from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection from gremlin_python.process.traversal import T from gremlin_python.process.traversal import Order from gremlin_python.process.traversal import Cardinality from gremlin_python.process.traversal import Column from gremlin_python.process.traversal import Direction from gremlin_python.process.traversal import Operator from gremlin_python.process.traversal import P from gremlin_python.process.traversal import Pop from gremlin_python.process.traversal import Scope from gremlin_python.process.traversal import Barrier from gremlin_python.process.traversal import Bindings from gremlin_python.process.traversal import WithOptions ---- These can be used analogously to how they are used in Gremlin-Java. [source,python] ---- >>> g.V().hasLabel('person').has('age',P.gt(30)).order().by('age',Order.desc).toList() [v[6], v[4]] ---- Moreover, by importing the `statics` of Gremlin-Python, the class prefixes can be omitted. [source,python] ---- >>> statics.load_statics(globals()) ---- With statics loaded its possible to represent the above traversal as below. [source,python] ---- >>> g.V().hasLabel('person').has('age',gt(30)).order().by('age',desc).toList() [v[6], v[4]] ---- Finally, statics includes all the `+__+`-methods and thus, anonymous traversals like `+__.out()+` can be expressed as below. That is, without the `+__+`-prefix. [source,python] ---- >>> g.V().repeat(out()).times(2).name.fold().toList() [['ripple', 'lop']] ---- === Configuration The following table describes the various configuration options for the Gremlin-Python Driver. They can be passed to the `Client` or `DriverRemoteConnection` instance as keyword arguments: [width=""100%"",cols=""3,10,^2"",options=""header""] |========================================================= |Key |Description |Default |protocol_factory |A callable that returns an instance of `AbstractBaseProtocol`. |`gremlin_python.driver.protocol.GremlinServerWSProtocol` |transport_factory |A callable that returns an instance of `AbstractBaseTransport`. |`gremlin_python.driver.tornado.transport.TornadoTransport` |pool_size |The number of connections used by the pool. |4 |max_workers |Maximum number of worker threads. |Number of CPUs * 5 |message_serializer |The message serializer implementation.|`gremlin_python.driver.serializer.GraphSONMessageSerializer` |password |The password to submit on requests that require authentication. |"""" |username |The username to submit on requests that require authentication. |"""" |kerberized_service |the first part of the principal name configured for the gremlin service|"""""" |session | A unique string-based identifier (typically a UUID) to enable a <>. This is not a valid configuration for `DriverRemoteConnection`. |None |========================================================= === Traversal Strategies In order to add and remove <> from a traversal source, Gremlin-Python has a `TraversalStrategy` class along with a collection of subclasses that mirror the standard Gremlin-Java strategies. [source,python] ---- >>> g = g.withStrategies(SubgraphStrategy(vertices=hasLabel('person'),edges=has('weight',gt(0.5)))) >>> g.V().name.toList() ['marko', 'vadas', 'josh', 'peter'] >>> g.V().outE().elementMap().toList() [{: 8, : 'knows', : {: 4, : 'person'}, : {: 1, : 'person'}, 'weight': 1.0}] >>> g = g.withoutStrategies(SubgraphStrategy) >>> g.V().name.toList() ['marko', 'vadas', 'lop', 'josh', 'ripple', 'peter'] >>> g.V().outE().elementMap().toList() [{: 9, : 'created', : {: 3, : 'software'}, : {: 1, : 'person'}, 'weight': 0.4}, {: 7, : 'knows', : {: 2, : 'person'}, : {: 1, : 'person'}, 'weight': 0.5}, {: 8, : 'knows', : {: 4, : 'person'}, : {: 1, : 'person'}, 'weight': 1.0}, {: 10, : 'created', : {: 5, : 'software'}, : {: 4, : 'person'}, 'weight': 1.0}, {: 11, : 'created', : {: 3, : 'software'}, : {: 4, : 'person'}, 'weight': 0.4}, {: 12, : 'created', : {: 3, : 'software'}, : {: 6, : 'person'}, 'weight': 0.2}] >>> g = g.withComputer(workers=2,vertices=has('name','marko')) >>> g.V().name.toList() ['marko'] >>> g.V().outE().valueMap().with_(WithOptions.tokens).toList() [{: 9, : 'created', 'weight': 0.4}, {: 7, : 'knows', 'weight': 0.5}, {: 8, : 'knows', 'weight': 1.0}] ---- NOTE: Many of the `TraversalStrategy` classes in Gremlin-Python are proxies to the respective strategy on Apache TinkerPop's JVM-based Gremlin traversal machine. As such, their `apply(Traversal)` method does nothing. However, the strategy is encoded in the Gremlin-Python bytecode and transmitted to the Gremlin traversal machine for re-construction machine-side. === The Lambda Solution Supporting link:https://en.wikipedia.org/wiki/Anonymous_function[anonymous functions] across languages is difficult as most languages do not support lambda introspection and thus, code analysis. In Gremlin-Python, a link:https://docs.python.org/2/reference/expressions.html#lambda[Python lambda] should be represented as a zero-arg callable that returns a string representation of a lambda. The lambda should be written as a `Gremlin-Groovy`string. When the lambda is represented in `Bytecode` its language is encoded such that the remote connection host can infer which translator and ultimate execution engine to use. [source,python] ---- >>> g.V().out().map(lambda: ""it.get().value('name').length()"").sum().toList() [24] ---- TIP: When running into situations where Groovy cannot properly discern a method signature based on the `Lambda` instance created, it will help to fully define the closure in the lambda expression - so rather than `lambda: (""it.get().value(""name')"",""gremlin-groovy"")`, prefer `lambda: (""x -> x.get().value(""name""),""gremlin-groovy"")`. Finally, Gremlin `Bytecode` that includes lambdas requires that the traversal be processed by the `ScriptEngine`. To avoid continued recompilation costs, it supports the encoding of bindings, which allow a remote engine to to cache traversals that will be reused over and over again save that some parameterization may change. Thus, instead of translating, compiling, and then executing each submitted bytecode, it is possible to simply execute. [source,python] ---- >>> g.V(Bindings.of('x',1)).out('created').map(lambda: ""it.get().value('name').length()"").sum().toList() [3] >>> g.V(Bindings.of('x',4)).out('created').map(lambda: ""it.get().value('name').length()"").sum().toList() [9] ---- WARNING: As explained throughout the documentation, when possible <> lambdas. === Submitting Scripts WARNING: TinkerPop does not recommend submitting script-based requests and generally continues to support this feature for legacy reasons and corner use cases which are still not completely addressed by the Gremlin language. Please consider using bytecode-based requests instead when possible. The `Client` class implementation/interface is based on the Java Driver, with some restrictions. Most notably, Gremlin-Python does not yet implement the `Cluster` class. Instead, `Client` is instantiated directly. Usage is as follows: [source,python] ---- from gremlin_python.driver import client <1> client = client.Client('ws://localhost:8182/gremlin', 'g') <2> ---- <1> Import the Gremlin-Python `client` module. <2> Opens a reference to `localhost` - note that there are various configuration options that can be passed to the `Client` object upon instantiation as keyword arguments. Once a `Client` instance is ready, it is possible to issue some Gremlin: [source,python] ---- result_set = client.submit(""[1,2,3,4]"") <1> future_results = result_set.all() <2> results = future_results.result() <3> assert results == [1, 2, 3, 4] <4> future_result_set = client.submitAsync(""[1,2,3,4]"") <5> result_set = future_result_set.result() <6> result = result_set.one() <7> assert results == [1, 2, 3, 4] <8> assert result_set.done.done() <9> client.close() <10> ---- <1> Submit a script that simply returns a `List` of integers. This method blocks until the request is written to the server and a `ResultSet` is constructed. <2> Even though the `ResultSet` is constructed, it does not mean that the server has sent back the results (or even evaluated the script potentially). The `ResultSet` is just a holder that is awaiting the results from the server. The `all` method returns a `concurrent.futures.Future` that resolves to a list when it is complete. <3> Block until the the script is evaluated and results are sent back by the server. <4> Verify the result. <5> Submit the same script to the server but don't block. <6> Wait until request is written to the server and `ResultSet` is constructed. <7> Read a single result off the result stream. <8> Again, verify the result. <9> Verify that the all results have been read and stream is closed. <10> Close client and underlying pool connections. [[gremlin-python-dsl]] === Domain Specific Languages Writing a Gremlin <> (DSL) in Python simply requires direct extension of several classes: * `GraphTraversal` - which exposes the various steps used in traversal writing * `__` - which spawns anonymous traversals from steps * `GraphTraversalSource` - which spawns `GraphTraversal` instances The Social DSL based on the link:https://tinkerpop.apache.org/docs/current/images/tinkerpop-modern.png[""modern"" toy graph] might look like this: [source,python] ---- class SocialTraversal(GraphTraversal): def knows(self, person_name): return self.out(""knows"").hasLabel(""person"").has(""name"", person_name) def youngestFriendsAge(self): return self.out(""knows"").hasLabel(""person"").values(""age"").min() def createdAtLeast(self, number): return self.outE(""created"").count().is_(P.gte(number)) class __(AnonymousTraversal): graph_traversal = SocialTraversal @classmethod def knows(cls, *args): return cls.graph_traversal(None, None, Bytecode()).knows(*args) @classmethod def youngestFriendsAge(cls, *args): return cls.graph_traversal(None, None, Bytecode()).youngestFriendsAge(*args) @classmethod def createdAtLeast(cls, *args): return cls.graph_traversal(None, None, Bytecode()).createdAtLeast(*args) class SocialTraversalSource(GraphTraversalSource): def __init__(self, *args, **kwargs): super(SocialTraversalSource, self).__init__(*args, **kwargs) self.graph_traversal = SocialTraversal def persons(self, *args): traversal = self.get_graph_traversal() traversal.bytecode.add_step(""V"") traversal.bytecode.add_step(""hasLabel"", ""person"") if len(args) > 0: traversal.bytecode.add_step(""has"", ""name"", P.within(args)) return traversal ---- NOTE: The `AnonymousTraversal` class above is just an alias for `+__+` as in `+from gremlin_python.process.graph_traversal import __ as AnonymousTraversal+` Using the DSL is straightforward and just requires that the graph instance know the `SocialTraversalSource` should be used: [source,python] ---- social = Graph().traversal(SocialTraversalSource).withRemote(DriverRemoteConnection('ws://localhost:8182/gremlin','g')) social.persons(""marko"").knows(""josh"") social.persons(""marko"").youngestFriendsAge() social.persons().filter(__.createdAtLeast(2)).count() ---- === Syntactic Sugar Python supports meta-programming and operator overloading. There are three uses of these techniques in Gremlin-Python that makes traversals a bit more concise. [source,python] ---- >>> g.V().both()[1:3].toList() [v[2], v[4]] >>> g.V().both()[1].toList() [v[2]] >>> g.V().both().name.toList() ['lop', 'lop', 'lop', 'vadas', 'josh', 'josh', 'josh', 'marko', 'marko', 'marko', 'peter', 'ripple'] ---- [[gremlin-python-differences]] === Differences In situations where Python reserved words and global functions overlap with standard Gremlin steps and tokens, those bits of conflicting Gremlin get an underscore appended as a suffix: *Steps* - <>, <>, <>, <>, <>, <>, <>, <> *Tokens* - <> === Limitations * Traversals that return a `Set` *might* be coerced to a `List` in Python. In the case of Python, number equality is different from JVM languages which produces different `Set` results when those types are in use. When this case is detected during deserialization, the `Set` is coerced to a `List` so that traversals return consistent results within a collection across different languages. If a `Set` is needed then convert `List` results to `Set` manually. * Gremlin is capable of returning `Dictionary` results that use non-hashable keys (e.g. Dictionary as a key) and Python does not support that at a language level. Gremlin that returns such results will need to be re-written to avoid that. === Application Examples The TinkerPop source code contains a simple Python script that shows a basic example of how gremlinpython works. It can be found in GitHub link:https://github.com/apache/tinkerpop/tree/xx.yy.zz/gremlin-python/src/main/python/example.py[here] and is designed to work best with a running <> configured with the default `conf/gremlin-server.yaml` file as included with the standard release packaging. [source,shell] ---- pip install gremlinpython pip install tornado python example.py ---- anchor:gremlin-DotNet[] [[gremlin-dotnet]] == Gremlin.Net image:gremlin-dotnet-logo.png[width=371,float=right] Apache TinkerPop's Gremlin.Net implements Gremlin within the C# language. It targets .NET Standard and can therefore be used on different operating systems and with different .NET frameworks, such as .NET Framework and link:https://www.microsoft.com/net/core[.NET Core]. Since the C# syntax is very similar to that of Java, it should be very easy to switch between Gremlin-Java and Gremlin.Net. The only major syntactical difference is that all method names in Gremlin.Net use PascalCase as opposed to camelCase in Gremlin-Java in order to comply with .NET conventions. [source,powershell] nuget install Gremlin.Net === Connecting The pattern for connecting is described in <> and it basically distills down to creating a `GraphTraversalSource`. A `GraphTraversalSource` is created from the `AnonymousTraversalSource.traversal()` method where the ""g"" provided to the `DriverRemoteConnection` corresponds to the name of a `GraphTraversalSource` on the remote end. [source,csharp] ---- include::../../../gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Docs/Reference/GremlinVariantsTests.cs[tags=connecting] ---- === Common Imports There are a number of classes, functions and tokens that are typically used with Gremlin. The following imports provide most of the typical functionality required to use Gremlin: [source,csharp] ---- include::../../../gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Docs/Reference/GremlinVariantsTests.cs[tags=commonImports] ---- === Configuration The connection properties for the Gremlin.Net driver can be passed to the `GremlinServer` instance as keyword arguments: [width=""100%"",cols=""3,10,^2"",options=""header""] |========================================================= |Key |Description |Default |hostname |The hostname that the driver will connect to. |localhost |port |The port on which Gremlin Server can be reached. |8182 |enableSsl |Determines if SSL should be enabled or not. If enabled on the server then it must be enabled on the client. |false |username |The username to submit on requests that require authentication. |_none_ |password |The password to submit on requests that require authentication. |_none_ |========================================================= ==== Connection Pool It is also possible to configure the `ConnectionPool` of the Gremlin.Net driver. These configuration options can be set as properties on the `ConnectionPoolSettings` instance that can be passed to the `GremlinClient`: [width=""100%"",cols=""3,10,^2"",options=""header""] |========================================================= |Key |Description |Default |PoolSize |The size of the connection pool. |4 |MaxInProcessPerConnection |The maximum number of in-flight requests that can occur on a connection. |32 |========================================================= A `NoConnectionAvailableException` is thrown if all connections have reached the `MaxInProcessPerConnection` limit when a new request comes in. ==== Serialization The Gremlin.Net driver uses by default GraphSON 3.0 but it is also possible to use GraphSON 2.0 which can be necessary when the server does not support GraphSON 3.0 yet: [source,csharp] ---- include::../../../gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Docs/Reference/GremlinVariantsTests.cs[tags=serialization] ---- === Traversal Strategies In order to add and remove traversal strategies from a traversal source, Gremlin.Net has an `AbstractTraversalStrategy` class along with a collection of subclasses that mirror the standard Gremlin-Java strategies. [source,csharp] ---- include::../../../gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Docs/Reference/GremlinVariantsTests.cs[tags=traversalStrategies] ---- NOTE: Many of the TraversalStrategy classes in Gremlin.Net are proxies to the respective strategy on Apache TinkerPop’s JVM-based Gremlin traversal machine. As such, their `Apply(ITraversal)` method does nothing. However, the strategy is encoded in the Gremlin.Net bytecode and transmitted to the Gremlin traversal machine for re-construction machine-side. === The Lambda Solution Supporting link:https://en.wikipedia.org/wiki/Anonymous_function[anonymous functions] across languages is difficult as most languages do not support lambda introspection and thus, code analysis. While Gremlin.Net doesn't support C# lambdas, it is still able to represent lambdas in other languages. When the lambda is represented in `Bytecode` its language is encoded such that the remote connection host can infer which translator and ultimate execution engine to use. [source,csharp] ---- g.V().Out().Map(Lambda.Groovy(""it.get().value('name').length()"")).Sum().ToList(); <1> g.V().Out().Map(Lambda.Python(""lambda x: len(x.get().value('name'))"")).Sum().ToList(); <2> ---- <1> `Lambda.Groovy()` can be used to create a Groovy lambda. <2> `Lambda.Python()` can be used to create a Python lambda. The `ILambda` interface returned by these two methods inherits interfaces like `IFunction` and `IPredicate` that mirror their Java counterparts which makes it possible to use lambdas with Gremlin.Net for the same steps as in Gremlin-Java. TIP: When running into situations where Groovy cannot properly discern a method signature based on the `Lambda` instance created, it will help to fully define the closure in the lambda expression - so rather than `Lambda.Groovy(""it.get().value('name'))`, prefer `Lambda.Groovy(""x -> x.get().value('name'))`. === Submitting Scripts WARNING: TinkerPop does not recommend submitting script-based requests and generally continues to support this feature for legacy reasons and corner use cases which are still not completely addressed by the Gremlin language. Please consider using bytecode-based requests instead when possible. Gremlin scripts are sent to the server from a `IGremlinClient` instance. A `IGremlinClient` is created as follows: [source,csharp] ---- include::../../../gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Docs/Reference/GremlinVariantsTests.cs[tags=submittingScripts] ---- If the remote system has authentication and SSL enabled, then the `GremlinServer` object can be configured as follows: [source,csharp] ---- include::../../../gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Docs/Reference/GremlinVariantsTests.cs[tags=submittingScriptsWithAuthentication] ---- It is also possible to initialize the `Client` to use <>: [source,csharp] ---- var gremlinServer = new GremlinServer(""localhost"", 8182); var client = new GremlinClient(gremlinServer, sessionId: Guid.NewGuid().ToString())) ---- [[gremlin-net-dsl]] === Domain Specific Languages Developing a <> (DSL) for .Net is most easily implemented using link:https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods[Extension Methods] as they don't require direct extension of classes in the TinkerPop hierarchy. Extension Method classes simply need to be constructed for the `GraphTraversal` and the `GraphTraversalSource`. Unfortunately, anonymous traversals (spawned from `+__+`) can't use the Extension Method approach as they do not work for static classes and static classes can't be extended. The only option is to re-implement the methods of `+__+` as a wrapper in the anonymous traversal for the DSL or to simply create a static class for the DSL and use the two anonymous traversals creators independently. The following example uses the latter approach as it saves a lot of boilerplate code with the minor annoyance of having a second static class to deal with when writing traversals rather than just calling `+__+` for everything. [source,csharp] ---- include::../../../gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Docs/Reference/GremlinVariantsDsl.cs[tags=dsl] ---- Note the creation of `__Social` as the Social DSL's ""extension"" to the available ways in which to spawn anonymous traversals. The use of the double underscore prefix in the name is just a convention to consider using and is not a requirement. To use the DSL, bring it into scope with the `using` directive: [source,csharp] ---- include::../../../gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Docs/Reference/GremlinVariantsDslTests.cs[tags=dslUsing] ---- and then it can be called from the application as follows: [source,csharp] ---- include::../../../gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Docs/Reference/GremlinVariantsDslTests.cs[tags=dslExamples] ---- [[gremlin-dotnet-differences]] === Differences Gremlin allows for `Map` instances to include `null` keys, but `null` keys in C# `Dictionary` instances are not allowed. It is therefore necessary to rewrite a traversal such as: [source,javascript] ---- g.V().groupCount().by('age') ---- where ""age"" is not a valid key for all vertices in a way that will remove the need for a `null` to be returned. [source,javascript] ---- g.V().has('age').groupCount().by('age') g.V().hasLabel('person').groupCount().by('age') ---- Either of the above two options accomplishes the desired goal as both prevent `groupCount()` from having to process the possibility of `null`. anchor:gremlin-dotnet-template[] [[dotnet-application-examples]] === Application Examples This link:https://docs.microsoft.com/dotnet/core/tools/custom-templates[dotnet template] helps getting started with <>. It creates a new C# console project that shows how to connect to a <> with Gremlin.Net. You can install the template with the dotnet CLI tool: [source,shell] dotnet new -i Gremlin.Net.Template After the template is installed, a new project based on this template can be installed: [source,shell] dotnet new gremlin Specify the output directory for the new project which will then also be used as the name of the created project: [source,shell] dotnet new gremlin -o MyFirstGremlinProject [[gremlin-javascript]] == Gremlin-JavaScript image:gremlin-js.png[width=130,float=right] Apache TinkerPop's Gremlin-JavaScript implements Gremlin within the JavaScript language. It targets Node.js runtime and can be used on different operating systems on any Node.js 6 or above. Since the JavaScript naming conventions are very similar to that of Java, it should be very easy to switch between Gremlin-Java and Gremlin-JavaScript. [source,bash] npm install gremlin === Connecting The pattern for connecting is described in <> and it basically distills down to creating a `GraphTraversalSource`. A `GraphTraversalSource` is created from the `AnonymousTraversalSource.traversal()` method where the ""g"" provided to the `DriverRemoteConnection` corresponds to the name of a `GraphTraversalSource` on the remote end. [source,javascript] ---- const g = traversal().withRemote(new DriverRemoteConnection('ws://localhost:8182/gremlin')); ---- Gremlin-JavaScript supports plain text SASL authentication, you can set it on the connection options. [source,javascript] ---- const authenticator = new gremlin.driver.auth.PlainTextSaslAuthenticator('myuser', 'mypassword'); const g = traversal().withRemote(new DriverRemoteConnection('ws://localhost:8182/gremlin', { authenticator }); ---- Given that I/O operations in Node.js are asynchronous by default, <> return a `Promise`: * `Traversal.toList()`: Returns a `Promise` with an `Array` as result value. * `Traversal.next()`: Returns a `Promise` with a `{ value, done }` tuple as result value, according to the link:https://github.com/tc39/proposal-async-iteration[async iterator proposal]. * `Traversal.iterate()`: Returns a `Promise` without a value. For example: [source,javascript] ---- g.V().hasLabel('person').values('name').toList() .then(names => console.log(names)); ---- When using `async` functions it is possible to `await` the promises: [source,javascript] ---- const names = await g.V().hasLabel('person').values('name').toList(); console.log(names); ---- === Common Imports There are a number of classes, functions and tokens that are typically used with Gremlin. The following imports provide most of the typical functionality required to use Gremlin: [source,javascript] ---- const gremlin = require('gremlin'); const traversal = gremlin.process.AnonymousTraversalSource.traversal; const __ = gremlin.process.statics; const DriverRemoteConnection = gremlin.driver.DriverRemoteConnection; const column = gremlin.process.traversal.column const direction = gremlin.process.traversal.direction const p = gremlin.process.traversal.P const pick = gremlin.process.traversal.pick const pop = gremlin.process.traversal.pop const order = gremlin.process.traversal.order const scope = gremlin.process.traversal.scope const t = gremlin.process.traversal.t ---- === Submitting Scripts WARNING: TinkerPop does not recommend submitting script-based requests and generally continues to support this feature for legacy reasons and corner use cases which are still not completely addressed by the Gremlin language. Please consider using bytecode-based requests instead when possible. It is possible to submit parametrized Gremlin scripts to the server as strings, using the `Client` class: [source,javascript] ---- const gremlin = require('gremlin'); const client = new gremlin.driver.Client('ws://localhost:8182/gremlin', { traversalSource: 'g' }); const result1 = await client.submit('g.V(vid)', { vid: 1 }); const vertex = result1.first(); const result2 = await client.submit('g.V().hasLabel(label).tail(n)', { label: 'person', n: 3 }); // ResultSet is an iterable for (const vertex of result2) { console.log(vertex.id); } ---- It is also possible to initialize the `Client` to use <>: [source,javascript] ---- const client = new gremlin.driver.Client('ws://localhost:8182/gremlin', { traversalSource: 'g', 'session': 'unique-string-id' }); ---- With this configuration, the state of variables within scripts are preserved between requests. [[gremlin-javascript-dsl]] === Domain Specific Languages Developing Gremlin DSLs in JavaScript largely requires extension of existing core classes with use of standalone functions for anonymous traversal spawning. The pattern is demonstrated in the following example: [source,javascript] ---- class SocialTraversal extends GraphTraversal { constructor(graph, traversalStrategies, bytecode) { super(graph, traversalStrategies, bytecode); } aged(age) { return this.has('person', 'age', age); } } class SocialTraversalSource extends GraphTraversalSource { constructor(graph, traversalStrategies, bytecode) { super(graph, traversalStrategies, bytecode, SocialTraversalSource, SocialTraversal); } person(name) { return this.V().has('person', 'name', name); } } function anonymous() { return new SocialTraversal(null, null, new Bytecode()); } function aged(age) { return anonymous().aged(age); } ---- `SocialTraversal` extends the core `GraphTraversal` class and has a three argument constructor which is immediately proxied to the `GraphTraversal` constructor. New DSL steps are then added to this class using available steps to construct the underlying traversal to execute as demonstrated in the `aged()` step. The `SocialTraversal` is spawned from a `SocialTraversalSource` which is extended from `GraphTraversalSource`. Steps added here are meant to be start steps. In the above case, the `person()` start step find a ""person"" vertex to begin the traversal from. Typically, steps that are made available on a `GraphTraversal` (i.e. SocialTraversal in this example) should also be made available as spawns for anonymous traversals. The recommendation is that these steps be exposed in the module as standalone functions. In the example above, the standalone `aged()` step creates an anonymous traversal through an `anonymous()` utility function. The method for creating these standalone functions can be handled in other ways if desired. To use the DSL, simply initialize the `g` as follows: [source,javascript] ---- const g = traversal(SocialTraversalSource).withRemote(connection); g.person('marko').aged(29).values('name').toList(). then(names => console.log(names)); ---- [[gremlin-javascript-differences]] === Differences In situations where Javascript reserved words and global functions overlap with standard Gremlin steps and tokens, those bits of conflicting Gremlin get an underscore appended as a suffix: *Steps* - <>, <>, <> Gremlin allows for `Map` instances to include `null` keys, but `null` keys in Javascript have some interesting behavior as in: [source,text] ---- > var a = { null: 'something', 'b': 'else' }; > JSON.stringify(a) '{""null"":""something"",""b"":""else""}' > JSON.parse(JSON.stringify(a)) { null: 'something', b: 'else' } > a[null] 'something' > a['null'] 'something' ---- This behavior needs to be considered when using Gremlin to return such results. A typical situation where this might happen is with `group()` or `groupCount()` as in: [source,javascript] ---- g.V().groupCount().by('age') ---- where ""age"" is not a valid key for all vertices. In these cases, it will return `null` for that key and group on that. It may bet better in Javascript to filter away those vertices to avoid the return of `null` in the returned `Map`: [source,javascript] ---- g.V().has('age').groupCount().by('age') g.V().hasLabel('person').groupCount().by('age') ---- Either of the above two options accomplishes the desired goal as both prevent `groupCount()` from having to process the possibility of `null`.",16373,True,2786.8936379808747,median "------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- G N A T . C O M M A N D _ L I N E -- -- -- -- S p e c -- -- -- -- Copyright (C) 1999-2016, AdaCore -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- As a special exception under Section 7 of GPL version 3, you are granted -- -- additional permissions described in the GCC Runtime Library Exception, -- -- version 3.1, as published by the Free Software Foundation. -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- . -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ -- High level package for command line parsing and manipulation ---------------------------------------- -- Simple Parsing of the Command Line -- ---------------------------------------- -- This package provides an interface for parsing command line arguments, -- when they are either read from Ada.Command_Line or read from a string list. -- As shown in the example below, one should first retrieve the switches -- (special command line arguments starting with '-' by default) and their -- parameters, and then the rest of the command line arguments. -- -- While it may appear easy to parse the command line arguments with -- Ada.Command_Line, there are in fact lots of special cases to handle in some -- applications. Those are fully managed by GNAT.Command_Line. Among these are -- switches with optional parameters, grouping switches (for instance ""-ab"" -- might mean the same as ""-a -b""), various characters to separate a switch -- and its parameter (or none: ""-a 1"" and ""-a1"" are generally the same, which -- can introduce confusion with grouped switches),... -- -- begin -- loop -- case Getopt (""a b: ad"") is -- Accepts '-a', '-ad', or '-b argument' -- when ASCII.NUL => exit; -- when 'a' => -- if Full_Switch = ""a"" then -- Put_Line (""Got a""); -- else -- Put_Line (""Got ad""); -- end if; -- when 'b' => Put_Line (""Got b + "" & Parameter); -- when others => -- raise Program_Error; -- cannot occur -- end case; -- end loop; -- loop -- declare -- S : constant String := Get_Argument (Do_Expansion => True); -- begin -- exit when S'Length = 0; -- Put_Line (""Got "" & S); -- end; -- end loop; -- exception -- when Invalid_Switch => Put_Line (""Invalid Switch "" & Full_Switch); -- when Invalid_Parameter => Put_Line (""No parameter for "" & Full_Switch); -- end; -------------- -- Sections -- -------------- -- A more complicated example would involve the use of sections for the -- switches, as for instance in gnatmake. The same command line is used to -- provide switches for several tools. Each tool recognizes its switches by -- separating them with special switches that act as section separators. -- Each section acts as a command line of its own. -- begin -- Initialize_Option_Scan ('-', False, ""largs bargs cargs""); -- loop -- -- Same loop as above to get switches and arguments -- end loop; -- Goto_Section (""bargs""); -- loop -- -- Same loop as above to get switches and arguments -- -- The supported switches in Getopt might be different -- end loop; -- Goto_Section (""cargs""); -- loop -- -- Same loop as above to get switches and arguments -- -- The supported switches in Getopt might be different -- end loop; -- end; ------------------------------- -- Parsing a List of Strings -- ------------------------------- -- The examples above show how to parse the command line when the arguments -- are read directly from Ada.Command_Line. However, these arguments can also -- be read from a list of strings. This can be useful in several contexts, -- either because your system does not support Ada.Command_Line, or because -- you are manipulating other tools and creating their command lines by hand, -- or for any other reason. -- To create the list of strings, it is recommended to use -- GNAT.OS_Lib.Argument_String_To_List. -- The example below shows how to get the parameters from such a list. Note -- also the use of '*' to get all the switches, and not report errors when an -- unexpected switch was used by the user -- declare -- Parser : Opt_Parser; -- Args : constant Argument_List_Access := -- GNAT.OS_Lib.Argument_String_To_List (""-g -O1 -Ipath""); -- begin -- Initialize_Option_Scan (Parser, Args); -- while Getopt (""* g O! I="", Parser) /= ASCII.NUL loop -- Put_Line (""Switch "" & Full_Switch (Parser) -- & "" param="" & Parameter (Parser)); -- end loop; -- Free (Parser); -- end; ------------------------------------------- -- High-Level Command Line Configuration -- ------------------------------------------- -- As shown above, the code is still relatively low-level. For instance, there -- is no way to indicate which switches are related (thus if ""-l"" and ""--long"" -- should have the same effect, your code will need to test for both cases). -- Likewise, it is difficult to handle more advanced constructs, like: -- * Specifying -gnatwa is the same as specifying -gnatwu -gnatwv, but -- shorter and more readable -- * All switches starting with -gnatw can be grouped, for instance one -- can write -gnatwcd instead of -gnatwc -gnatwd. -- Of course, this can be combined with the above and -gnatwacd is the -- same as -gnatwc -gnatwd -gnatwu -gnatwv -- * The switch -T is the same as -gnatwAB (same as -gnatwA -gnatwB) -- With the above form of Getopt, you would receive ""-gnatwa"", ""-T"" or -- ""-gnatwcd"" in the examples above, and thus you require additional manual -- parsing of the switch. -- Instead, this package provides the type Command_Line_Configuration, which -- stores all the knowledge above. For instance: -- Config : Command_Line_Configuration; -- Define_Alias (Config, ""-gnatwa"", ""-gnatwu -gnatwv""); -- Define_Prefix (Config, ""-gnatw""); -- Define_Alias (Config, ""-T"", ""-gnatwAB""); -- You then need to specify all possible switches in your application by -- calling Define_Switch, for instance: -- Define_Switch (Config, ""-gnatwu"", Help => ""warn on unused entities""); -- Define_Switch (Config, ""-gnatwv"", Help => ""warn on unassigned var""); -- ... -- Specifying the help message is optional, but makes it easy to then call -- the function: -- Display_Help (Config); -- that will display a properly formatted help message for your application, -- listing all possible switches. That way you have a single place in which -- to maintain the list of switches and their meaning, rather than maintaining -- both the string to pass to Getopt and a subprogram to display the help. -- Both will properly stay synchronized. -- Once you have this Config, you just have to call: -- Getopt (Config, Callback'Access); -- to parse the command line. The Callback will be called for each switch -- found on the command line (in the case of our example, that is ""-gnatwu"" -- and then ""-gnatwv"", not ""-gnatwa"" itself). This simplifies command line -- parsing a lot. -- In fact, this can be further automated for the most command case where the -- parameter passed to a switch is stored in a variable in the application. -- When a switch is defined, you only have to indicate where to store the -- value, and let Getopt do the rest. For instance: -- Optimization : aliased Integer; -- Verbose : aliased Boolean; -- Define_Switch (Config, Verbose'Access, -- ""-v"", Long_Switch => ""--verbose"", -- Help => ""Output extra verbose information""); -- Define_Switch (Config, Optimization'Access, -- ""-O?"", Help => ""Optimization level""); -- Getopt (Config); -- No callback -- Since all switches are handled automatically, we don't even need to pass -- a callback to Getopt. Once getopt has been called, the two variables -- Optimization and Verbose have been properly initialized, either to the -- default value or to the value found on the command line. ------------------------------------------------ -- Creating and Manipulating the Command Line -- ------------------------------------------------ -- This package provides mechanisms to create and modify command lines by -- adding or removing arguments from them. The resulting command line is kept -- as short as possible by coalescing arguments whenever possible. -- Complex command lines can thus be constructed, for example from a GUI -- (although this package does not by itself depend upon any specific GUI -- toolkit). -- Using the configuration defined earlier, one can then construct a command -- line for the tool with: -- Cmd : Command_Line; -- Set_Configuration (Cmd, Config); -- Config created earlier -- Add_Switch (Cmd, ""-bar""); -- Add_Switch (Cmd, ""-gnatwu""); -- Add_Switch (Cmd, ""-gnatwv""); -- will be grouped with the above -- Add_Switch (Cmd, ""-T""); -- The resulting command line can be iterated over to get all its switches, -- There are two modes for this iteration: either you want to get the -- shortest possible command line, which would be: -- -bar -gnatwaAB -- or on the other hand you want each individual switch (so that your own -- tool does not have to do further complex processing), which would be: -- -bar -gnatwu -gnatwv -gnatwA -gnatwB -- Of course, we can assume that the tool you want to spawn would understand -- both of these, since they are both compatible with the description we gave -- above. However, the first result is useful if you want to show the user -- what you are spawning (since that keeps the output shorter), and the second -- output is more useful for a tool that would check whether -gnatwu was -- passed (which isn't obvious in the first output). Likewise, the second -- output is more useful if you have a graphical interface since each switch -- can be associated with a widget, and you immediately know whether -gnatwu -- was selected. -- -- Some command line arguments can have parameters, which on a command line -- appear as a separate argument that must immediately follow the switch. -- Since the subprograms in this package will reorganize the switches to group -- them, you need to indicate what is a command line parameter, and what is a -- switch argument. -- This is done by passing an extra argument to Add_Switch, as in: -- Add_Switch (Cmd, ""-foo"", Parameter => ""arg1""); -- This ensures that ""arg1"" will always be treated as the argument to -foo, -- and will not be grouped with other parts of the command line. with Ada.Command_Line; with GNAT.Directory_Operations; with GNAT.OS_Lib; with GNAT.Regexp; with GNAT.Strings; package GNAT.Command_Line is ------------- -- Parsing -- ------------- type Opt_Parser is private; Command_Line_Parser : constant Opt_Parser; -- This object is responsible for parsing a list of arguments, which by -- default are the standard command line arguments from Ada.Command_Line. -- This is really a pointer to actual data, which must therefore be -- initialized through a call to Initialize_Option_Scan, and must be freed -- with a call to Free. -- -- As a special case, Command_Line_Parser does not need to be either -- initialized or free-ed. procedure Initialize_Option_Scan (Switch_Char : Character := '-'; Stop_At_First_Non_Switch : Boolean := False; Section_Delimiters : String := """"); procedure Initialize_Option_Scan (Parser : out Opt_Parser; Command_Line : GNAT.OS_Lib.Argument_List_Access; Switch_Char : Character := '-'; Stop_At_First_Non_Switch : Boolean := False; Section_Delimiters : String := """"); -- The first procedure resets the internal state of the package to prepare -- to rescan the parameters. It does not need to be called before the -- first use of Getopt (but it could be), but it must be called if you -- want to start rescanning the command line parameters from the start. -- The optional parameter Switch_Char can be used to reset the switch -- character, e.g. to '/' for use in DOS-like systems. -- -- The second subprogram initializes a parser that takes its arguments -- from an array of strings rather than directly from the command line. In -- this case, the parser is responsible for freeing the strings stored in -- Command_Line. If you pass null to Command_Line, this will in fact create -- a second parser for Ada.Command_Line, which doesn't share any data with -- the default parser. This parser must be free'ed. -- -- The optional parameter Stop_At_First_Non_Switch indicates if Getopt is -- to look for switches on the whole command line, or if it has to stop as -- soon as a non-switch argument is found. -- -- Example: -- -- Arguments: my_application file1 -c -- -- If Stop_At_First_Non_Switch is False, then -c will be considered -- as a switch (returned by getopt), otherwise it will be considered -- as a normal argument (returned by Get_Argument). -- -- If Section_Delimiters is set, then every following subprogram -- (Getopt and Get_Argument) will only operate within a section, which -- is delimited by any of these delimiters or the end of the command line. -- -- Example: -- Initialize_Option_Scan (Section_Delimiters => ""largs bargs cargs""); -- -- Arguments on command line : my_application -c -bargs -d -e -largs -f -- This line contains three sections, the first one is the default one -- and includes only the '-c' switch, the second one is between -bargs -- and -largs and includes '-d -e' and the last one includes '-f'. procedure Free (Parser : in out Opt_Parser); -- Free the memory used by the parser. Calling this is not mandatory for -- the Command_Line_Parser procedure Goto_Section (Name : String := """"; Parser : Opt_Parser := Command_Line_Parser); -- Change the current section. The next Getopt or Get_Argument will start -- looking at the beginning of the section. An empty name ("""") refers to -- the first section between the program name and the first section -- delimiter. If the section does not exist in Section_Delimiters, then -- Invalid_Section is raised. If the section does not appear on the command -- line, then it is treated as an empty section. function Full_Switch (Parser : Opt_Parser := Command_Line_Parser) return String; -- Returns the full name of the last switch found (Getopt only returns the -- first character). Does not include the Switch_Char ('-' by default), -- unless the ""*"" option of Getopt is used (see below). function Current_Section (Parser : Opt_Parser := Command_Line_Parser) return String; -- Return the name of the current section. -- The list of valid sections is defined through Initialize_Option_Scan function Getopt (Switches : String; Concatenate : Boolean := True; Parser : Opt_Parser := Command_Line_Parser) return Character; -- This function moves to the next switch on the command line (defined as -- switch character followed by a character within Switches, casing being -- significant). The result returned is the first character of the switch -- that is located. If there are no more switches in the current section, -- returns ASCII.NUL. If Concatenate is True (the default), the switches do -- not need to be separated by spaces (they can be concatenated if they do -- not require an argument, e.g. -ab is the same as two separate arguments -- -a -b). -- -- Switches is a string of all the possible switches, separated by -- spaces. A switch can be followed by one of the following characters: -- -- ':' The switch requires a parameter. There can optionally be a space -- on the command line between the switch and its parameter. -- -- '=' The switch requires a parameter. There can either be a '=' or a -- space on the command line between the switch and its parameter. -- -- '!' The switch requires a parameter, but there can be no space on the -- command line between the switch and its parameter. -- -- '?' The switch may have an optional parameter. There can be no space -- between the switch and its argument. -- -- e.g. if Switches has the following value : ""a? b"", -- The command line can be: -- -- -afoo : -a switch with 'foo' parameter -- -a foo : -a switch and another element on the -- command line 'foo', returned by Get_Argument -- -- Example: if Switches is ""-a: -aO:"", you can have the following -- command lines: -- -- -aarg : 'a' switch with 'arg' parameter -- -a arg : 'a' switch with 'arg' parameter -- -aOarg : 'aO' switch with 'arg' parameter -- -aO arg : 'aO' switch with 'arg' parameter -- -- Example: -- -- Getopt (""a b: ac ad?"") -- -- accept either 'a' or 'ac' with no argument, -- accept 'b' with a required argument -- accept 'ad' with an optional argument -- -- If the first item in switches is '*', then Getopt will catch -- every element on the command line that was not caught by any other -- switch. The character returned by GetOpt is '*', but Full_Switch -- contains the full command line argument, including leading '-' if there -- is one. If this character was not returned, there would be no way of -- knowing whether it is there or not. -- -- Example -- Getopt (""* a b"") -- If the command line is '-a -c toto.o -b', Getopt will return -- successively 'a', '*', '*' and 'b', with Full_Switch returning -- ""a"", ""-c"", ""toto.o"", and ""b"". -- -- When Getopt encounters an invalid switch, it raises the exception -- Invalid_Switch and sets Full_Switch to return the invalid switch. -- When Getopt cannot find the parameter associated with a switch, it -- raises Invalid_Parameter, and sets Full_Switch to return the invalid -- switch. -- -- Note: in case of ambiguity, e.g. switches a ab abc, then the longest -- matching switch is returned. -- -- Arbitrary characters are allowed for switches, although it is -- strongly recommended to use only letters and digits for portability -- reasons. -- -- When Concatenate is False, individual switches need to be separated by -- spaces. -- -- Example -- Getopt (""a b"", Concatenate => False) -- If the command line is '-ab', exception Invalid_Switch will be -- raised and Full_Switch will return ""ab"". function Get_Argument (Do_Expansion : Boolean := False; Parser : Opt_Parser := Command_Line_Parser) return String; -- Returns the next element on the command line that is not a switch. This -- function should not be called before Getopt has returned ASCII.NUL. -- -- If Do_Expansion is True, then the parameter on the command line will -- be considered as a filename with wild cards, and will be expanded. The -- matching file names will be returned one at a time. This is useful in -- non-Unix systems for obtaining normal expansion of wild card references. -- When there are no more arguments on the command line, this function -- returns an empty string. function Parameter (Parser : Opt_Parser := Command_Line_Parser) return String; -- Returns parameter associated with the last switch returned by Getopt. -- If no parameter was associated with the last switch, or no previous call -- has been made to Get_Argument, raises Invalid_Parameter. If the last -- switch was associated with an optional argument and this argument was -- not found on the command line, Parameter returns an empty string. function Separator (Parser : Opt_Parser := Command_Line_Parser) return Character; -- The separator that was between the switch and its parameter. This is -- useful if you want to know exactly what was on the command line. This -- is in general a single character, set to ASCII.NUL if the switch and -- the parameter were concatenated. A space is returned if the switch and -- its argument were in two separate arguments. Invalid_Section : exception; -- Raised when an invalid section is selected by Goto_Section Invalid_Switch : exception; -- Raised when an invalid switch is detected in the command line Invalid_Parameter : exception; -- Raised when a parameter is missing, or an attempt is made to obtain a -- parameter for a switch that does not allow a parameter. ----------------------------------------- -- Expansion of command line arguments -- ----------------------------------------- -- These subprograms take care of expanding globbing patterns on the -- command line. On Unix, such expansion is done by the shell before your -- application is called. But on Windows you must do this expansion -- yourself. type Expansion_Iterator is limited private; -- Type used during expansion of file names procedure Start_Expansion (Iterator : out Expansion_Iterator; Pattern : String; Directory : String := """"; Basic_Regexp : Boolean := True); -- Initialize a wild card expansion. The next calls to Expansion will -- return the next file name in Directory which match Pattern (Pattern -- is a regular expression, using only the Unix shell and DOS syntax if -- Basic_Regexp is True). When Directory is an empty string, the current -- directory is searched. -- -- Pattern may contain directory separators (as in ""src/*/*.ada""). -- Subdirectories of Directory will also be searched, up to one -- hundred levels deep. -- -- When Start_Expansion has been called, function Expansion should -- be called repeatedly until it returns an empty string, before -- Start_Expansion can be called again with the same Expansion_Iterator -- variable. function Expansion (Iterator : Expansion_Iterator) return String; -- Returns the next file in the directory matching the parameters given -- to Start_Expansion and updates Iterator to point to the next entry. -- Returns an empty string when there are no more files. -- -- If Expansion is called again after an empty string has been returned, -- then the exception GNAT.Directory_Operations.Directory_Error is raised. ----------------- -- Configuring -- ----------------- -- The following subprograms are used to manipulate a command line -- represented as a string (for instance ""-g -O2""), as well as parsing -- the switches from such a string. They provide high-level configurations -- to define aliases (a switch is equivalent to one or more other switches) -- or grouping of switches (""-gnatyac"" is equivalent to ""-gnatya"" and -- ""-gnatyc""). -- See the top of this file for examples on how to use these subprograms type Command_Line_Configuration is private; procedure Define_Section (Config : in out Command_Line_Configuration; Section : String); -- Indicates a new switch section. All switches belonging to the same -- section are ordered together, preceded by the section. They are placed -- at the end of the command line (as in ""gnatmake somefile.adb -cargs -g"") -- -- The section name should not include the leading '-'. So for instance in -- the case of gnatmake we would use: -- -- Define_Section (Config, ""cargs""); -- Define_Section (Config, ""bargs""); procedure Define_Alias (Config : in out Command_Line_Configuration; Switch : String; Expanded : String; Section : String := """"); -- Indicates that whenever Switch appears on the command line, it should -- be expanded as Expanded. For instance, for the GNAT compiler switches, -- we would define ""-gnatwa"" as an alias for ""-gnatwcfijkmopruvz"", ie some -- default warnings to be activated. -- -- This expansion is only done within the specified section, which must -- have been defined first through a call to [Define_Section]. procedure Define_Prefix (Config : in out Command_Line_Configuration; Prefix : String); -- Indicates that all switches starting with the given prefix should be -- grouped. For instance, for the GNAT compiler we would define ""-gnatw"" as -- a prefix, so that ""-gnatwu -gnatwv"" can be grouped into ""-gnatwuv"" It is -- assumed that the remainder of the switch (""uv"") is a set of characters -- whose order is irrelevant. In fact, this package will sort them -- alphabetically. -- -- When grouping switches that accept arguments (for instance ""-gnatyL!"" -- as the definition, and ""-gnatyaL12b"" as the command line), only -- numerical arguments are accepted. The above is equivalent to -- ""-gnatya -gnatyL12 -gnatyb"". procedure Define_Switch (Config : in out Command_Line_Configuration; Switch : String := """"; Long_Switch : String := """"; Help : String := """"; Section : String := """"; Argument : String := ""ARG""); -- Indicates a new switch. The format of this switch follows the getopt -- format (trailing ':', '?', etc for defining a switch with parameters). -- -- Switch should also start with the leading '-' (or any other characters). -- If this character is not '-', you need to call Initialize_Option_Scan to -- set the proper character for the parser. -- -- The switches defined in the command_line_configuration object are used -- when ungrouping switches with more that one character after the prefix. -- -- Switch and Long_Switch (when specified) are aliases and can be used -- interchangeably. There is no check that they both take an argument or -- both take no argument. Switch can be set to ""*"" to indicate that any -- switch is supported (in which case Getopt will return '*', see its -- documentation). -- -- Help is used by the Display_Help procedure to describe the supported -- switches. -- -- In_Section indicates in which section the switch is valid (you need to -- first define the section through a call to Define_Section). -- -- Argument is the name of the argument, as displayed in the automatic -- help message. It is always capitalized for consistency. procedure Define_Switch (Config : in out Command_Line_Configuration; Output : access Boolean; Switch : String := """"; Long_Switch : String := """"; Help : String := """"; Section : String := """"; Value : Boolean := True); -- See Define_Switch for a description of the parameters. -- When the switch is found on the command line, Getopt will set -- Output.all to Value. -- -- Output is always initially set to ""not Value"", so that if the switch is -- not found on the command line, Output still has a valid value. -- The switch must not take any parameter. -- -- Output must exist at least as long as Config, otherwise an erroneous -- memory access may occur. procedure Define_Switch (Config : in out Command_Line_Configuration; Output : access Integer; Switch : String := """"; Long_Switch : String := """"; Help : String := """"; Section : String := """"; Initial : Integer := 0; Default : Integer := 1; Argument : String := ""ARG""); -- See Define_Switch for a description of the parameters. When the -- switch is found on the command line, Getopt will set Output.all to the -- value of the switch's parameter. If the parameter is not an integer, -- Invalid_Parameter is raised. -- Output is always initialized to Initial. If the switch has an optional -- argument which isn't specified by the user, then Output will be set to -- Default. The switch must accept an argument. procedure Define_Switch (Config : in out Command_Line_Configuration; Output : access GNAT.Strings.String_Access; Switch : String := """"; Long_Switch : String := """"; Help : String := """"; Section : String := """"; Argument : String := ""ARG""); -- Set Output to the value of the switch's parameter when the switch is -- found on the command line. Output is always initialized to the empty -- string if it does not have a value already (otherwise it is left as is -- so that you can specify the default value directly in the declaration -- of the variable). The switch must accept an argument. procedure Set_Usage (Config : in out Command_Line_Configuration; Usage : String := ""[switches] [arguments]""; Help : String := """"; Help_Msg : String := """"); -- Defines the general format of the call to the application, and a short -- help text. These are both displayed by Display_Help. When a non-empty -- Help_Msg is given, it is used by Display_Help instead of the -- automatically generated list of supported switches. procedure Display_Help (Config : Command_Line_Configuration); -- Display the help for the tool (ie its usage, and its supported switches) function Get_Switches (Config : Command_Line_Configuration; Switch_Char : Character := '-'; Section : String := """") return String; -- Get the switches list as expected by Getopt, for a specific section of -- the command line. This list is built using all switches defined -- previously via Define_Switch above. function Section_Delimiters (Config : Command_Line_Configuration) return String; -- Return a string suitable for use in Initialize_Option_Scan procedure Free (Config : in out Command_Line_Configuration); -- Free the memory used by Config type Switch_Handler is access procedure (Switch : String; Parameter : String; Section : String); -- Called when a switch is found on the command line. Switch includes -- any leading '-' that was specified in Define_Switch. This is slightly -- different from the functional version of Getopt above, for which -- Full_Switch omits the first leading '-'. Exit_From_Command_Line : exception; -- Emitted when the program should exit. This is called when Getopt below -- has seen -h, --help or an invalid switch. procedure Getopt (Config : Command_Line_Configuration; Callback : Switch_Handler := null; Parser : Opt_Parser := Command_Line_Parser; Concatenate : Boolean := True); -- Similar to the standard Getopt function. For each switch found on the -- command line, this calls Callback, if the switch is not handled -- automatically. -- -- The list of valid switches are the ones from the configuration. The -- switches that were declared through Define_Switch with an Output -- parameter are never returned (and result in a modification of the Output -- variable). This function will in fact never call [Callback] if all -- switches were handled automatically and there is nothing left to do. -- -- The option Concatenate is identical to the one of the standard Getopt -- function. -- -- This procedure automatically adds -h and --help to the valid switches, -- to display the help message and raises Exit_From_Command_Line. -- If an invalid switch is specified on the command line, this procedure -- will display an error message and raises Invalid_Switch again. -- -- This function automatically expands switches: -- -- If Define_Prefix was called (for instance ""-gnaty"") and the user -- specifies ""-gnatycb"" on the command line, then Getopt returns -- ""-gnatyc"" and ""-gnatyb"" separately. -- -- If Define_Alias was called (for instance ""-gnatya = -gnatycb"") then -- the latter is returned (in this case it also expands -gnaty as per -- the above. -- -- The goal is to make handling as easy as possible by leaving as much -- work as possible to this package. -- -- As opposed to the standard Getopt, this one will analyze all sections -- as defined by Define_Section, and automatically jump from one section to -- the next. ------------------------------ -- Generating command lines -- ------------------------------ -- Once the command line configuration has been created, you can build your -- own command line. This will be done in general because you need to spawn -- external tools from your application. -- Although it could be done by concatenating strings, the following -- subprograms will properly take care of grouping switches when possible, -- so as to keep the command line as short as possible. They also provide a -- way to remove a switch from an existing command line. -- For instance: -- declare -- Config : Command_Line_Configuration; -- Line : Command_Line; -- Args : Argument_List_Access; -- begin -- Define_Switch (Config, ""-gnatyc""); -- Define_Switch (Config, ...); -- for all valid switches -- Define_Prefix (Config, ""-gnaty""); -- Set_Configuration (Line, Config); -- Add_Switch (Line, ""-O2""); -- Add_Switch (Line, ""-gnatyc""); -- Add_Switch (Line, ""-gnatyd""); -- -- Build (Line, Args); -- -- Args is now [""-O2"", ""-gnatycd""] -- end; type Command_Line is private; procedure Set_Configuration (Cmd : in out Command_Line; Config : Command_Line_Configuration); function Get_Configuration (Cmd : Command_Line) return Command_Line_Configuration; -- Set or retrieve the configuration used for that command line. The Config -- must have been initialized first, by calling one of the Define_Switches -- subprograms. procedure Set_Command_Line (Cmd : in out Command_Line; Switches : String; Getopt_Description : String := """"; Switch_Char : Character := '-'); -- Set the new content of the command line, by replacing the current -- version with Switches. -- -- The parsing of Switches is done through calls to Getopt, by passing -- Getopt_Description as an argument. (A ""*"" is automatically prepended so -- that all switches and command line arguments are accepted). If a config -- was defined via Set_Configuration, the Getopt_Description parameter will -- be ignored. -- -- To properly handle switches that take parameters, you should document -- them in Getopt_Description. Otherwise, the switch and its parameter will -- be recorded as two separate command line arguments as returned by a -- Command_Line_Iterator (which might be fine depending on your -- application). -- -- If the command line has sections (such as -bargs -cargs), then they -- should be listed in the Sections parameter (as ""-bargs -cargs""). -- -- This function can be used to reset Cmd by passing an empty string -- -- If an invalid switch is found on the command line (ie wasn't defined in -- the configuration via Define_Switch), and the configuration wasn't set -- to accept all switches (by defining ""*"" as a valid switch), then an -- exception Invalid_Switch is raised. The exception message indicates the -- invalid switch. procedure Add_Switch (Cmd : in out Command_Line; Switch : String; Parameter : String := """"; Separator : Character := ASCII.NUL; Section : String := """"; Add_Before : Boolean := False); -- Add a new switch to the command line, and combine/group it with existing -- switches if possible. Nothing is done if the switch already exists with -- the same parameter. -- -- If the Switch takes a parameter, the latter should be specified -- separately, so that the association between the two is always correctly -- recognized even if the order of switches on the command line changes. -- For instance, you should pass ""--check=full"" as (""--check"", ""full"") so -- that Remove_Switch below can simply take ""--check"" in parameter. That -- will automatically remove ""full"" as well. The value of the parameter is -- never modified by this package. -- -- On the other hand, you could decide to simply pass ""--check=full"" as -- the Switch above, and then pass no parameter. This means that you need -- to pass ""--check=full"" to Remove_Switch as well. -- -- A Switch with a parameter will never be grouped with another switch to -- avoid ambiguities as to what the parameter applies to. -- -- If the switch is part of a section, then it should be specified so that -- the switch is correctly placed in the command line, and the section -- added if not already present. For example, to add the -g switch into the -- -cargs section, you need to call (Cmd, ""-g"", Section => ""-cargs""). -- -- [Separator], if specified, overrides the separator that was defined -- through Define_Switch. For instance, if the switch was defined as -- ""-from:"", the separator defaults to a space. But if your application -- uses unusual separators not supported by GNAT.Command_Line (for instance -- it requires "":""), you can specify this separator here. -- -- For instance, -- Add_Switch(Cmd, ""-from"", ""bar"", ':') -- -- results in -- -from:bar -- -- rather than the default -- -from bar -- -- Note however that Getopt doesn't know how to handle "":"" as a separator. -- So the recommendation is to declare the switch as ""-from!"" (ie no -- space between the switch and its parameter). Then Getopt will return -- "":bar"" as the parameter, and you can trim the "":"" in your application. -- -- Invalid_Section is raised if Section was not defined in the -- configuration of the command line. -- -- Add_Before allows insertion of the switch at the beginning of the -- command line. procedure Add_Switch (Cmd : in out Command_Line; Switch : String; Parameter : String := """"; Separator : Character := ASCII.NUL; Section : String := """"; Add_Before : Boolean := False; Success : out Boolean); -- Same as above, returning the status of the operation procedure Remove_Switch (Cmd : in out Command_Line; Switch : String; Remove_All : Boolean := False; Has_Parameter : Boolean := False; Section : String := """"); -- Remove Switch from the command line, and ungroup existing switches if -- necessary. -- -- The actual parameter to the switches are ignored. If for instance -- you are removing ""-foo"", then ""-foo param1"" and ""-foo param2"" can -- be removed. -- -- If Remove_All is True, then all matching switches are removed, otherwise -- only the first matching one is removed. -- -- If Has_Parameter is set to True, then only switches having a parameter -- are removed. -- -- If the switch belongs to a section, then this section should be -- specified: Remove_Switch (Cmd_Line, ""-g"", Section => ""-cargs"") called -- on the command line ""-g -cargs -g"" will result in ""-g"", while if -- called with (Cmd_Line, ""-g"") this will result in ""-cargs -g"". -- If Remove_All is set, then both ""-g"" will be removed. procedure Remove_Switch (Cmd : in out Command_Line; Switch : String; Remove_All : Boolean := False; Has_Parameter : Boolean := False; Section : String := """"; Success : out Boolean); -- Same as above, reporting the success of the operation (Success is False -- if no switch was removed). procedure Remove_Switch (Cmd : in out Command_Line; Switch : String; Parameter : String; Section : String := """"); -- Remove a switch with a specific parameter. If Parameter is the empty -- string, then only a switch with no parameter will be removed. procedure Free (Cmd : in out Command_Line); -- Free the memory used by Cmd --------------- -- Iteration -- --------------- -- When a command line was created with the above, you can then iterate -- over its contents using the following iterator. type Command_Line_Iterator is private; procedure Start (Cmd : in out Command_Line; Iter : in out Command_Line_Iterator; Expanded : Boolean := False); -- Start iterating over the command line arguments. If Expanded is true, -- then the arguments are not grouped and no alias is used. For instance, -- ""-gnatwv"" and ""-gnatwu"" would be returned instead of ""-gnatwuv"". -- -- The iterator becomes invalid if the command line is changed through a -- call to Add_Switch, Remove_Switch or Set_Command_Line. function Current_Switch (Iter : Command_Line_Iterator) return String; function Is_New_Section (Iter : Command_Line_Iterator) return Boolean; function Current_Section (Iter : Command_Line_Iterator) return String; function Current_Separator (Iter : Command_Line_Iterator) return String; function Current_Parameter (Iter : Command_Line_Iterator) return String; -- Return the current switch and its parameter (or the empty string if -- there is no parameter or the switch was added through Add_Switch -- without specifying the parameter. -- -- Separator is the string that goes between the switch and its separator. -- It could be the empty string if they should be concatenated, or a space -- for instance. When printing, you should not add any other character. function Has_More (Iter : Command_Line_Iterator) return Boolean; -- Return True if there are more switches to be returned procedure Next (Iter : in out Command_Line_Iterator); -- Move to the next switch procedure Build (Line : in out Command_Line; Args : out GNAT.OS_Lib.Argument_List_Access; Expanded : Boolean := False; Switch_Char : Character := '-'); -- This is a wrapper using the Command_Line_Iterator. It provides a simple -- way to get all switches (grouped as much as possible), and possibly -- create an Opt_Parser. -- -- Args must be freed by the caller. -- -- Expanded has the same meaning as in Start. procedure Try_Help; -- Output a message on standard error to indicate how to get the usage for -- the executable. This procedure should only be called when the executable -- accepts switch --help. When this procedure is called by executable xxx, -- the following message is displayed on standard error: -- try ""xxx --help"" for more information. private Max_Depth : constant := 100; -- Maximum depth of subdirectories Max_Path_Length : constant := 1024; -- Maximum length of relative path type Depth is range 1 .. Max_Depth; type Level is record Name_Last : Natural := 0; Dir : GNAT.Directory_Operations.Dir_Type; end record; type Level_Array is array (Depth) of Level; type Section_Number is new Natural range 0 .. 65534; for Section_Number'Size use 16; type Parameter_Type is record Arg_Num : Positive; First : Positive; Last : Natural; Extra : Character; end record; type Is_Switch_Type is array (Natural range <>) of Boolean; pragma Pack (Is_Switch_Type); type Section_Type is array (Natural range <>) of Section_Number; pragma Pack (Section_Type); type Expansion_Iterator is limited record Start : Positive := 1; -- Position of the first character of the relative path to check against -- the pattern. Dir_Name : String (1 .. Max_Path_Length); Current_Depth : Depth := 1; Levels : Level_Array; Regexp : GNAT.Regexp.Regexp; -- Regular expression built with the pattern Maximum_Depth : Depth := 1; -- The maximum depth of directories, reflecting the number of directory -- separators in the pattern. end record; type Opt_Parser_Data (Arg_Count : Natural) is record Arguments : GNAT.OS_Lib.Argument_List_Access; -- null if reading from the command line The_Parameter : Parameter_Type; The_Separator : Character; The_Switch : Parameter_Type; -- This type and this variable are provided to store the current switch -- and parameter. Is_Switch : Is_Switch_Type (1 .. Arg_Count) := (others => False); -- Indicates wich arguments on the command line are considered not be -- switches or parameters to switches (leaving e.g. filenames,...) Section : Section_Type (1 .. Arg_Count) := (others => 1); -- Contains the number of the section associated with the current -- switch. If this number is 0, then it is a section delimiter, which is -- never returned by GetOpt. Current_Argument : Natural := 1; -- Number of the current argument parsed on the command line Current_Index : Natural := 1; -- Index in the current argument of the character to be processed Current_Section : Section_Number := 1; Expansion_It : aliased Expansion_Iterator; -- When Get_Argument is expanding a file name, this is the iterator used In_Expansion : Boolean := False; -- True if we are expanding a file Switch_Character : Character := '-'; -- The character at the beginning of the command line arguments, -- indicating the beginning of a switch. Stop_At_First : Boolean := False; -- If it is True then Getopt stops at the first non-switch argument end record; Command_Line_Parser_Data : aliased Opt_Parser_Data (Ada.Command_Line.Argument_Count); -- The internal data used when parsing the command line type Opt_Parser is access all Opt_Parser_Data; Command_Line_Parser : constant Opt_Parser := Command_Line_Parser_Data'Access; type Switch_Type is (Switch_Untyped, Switch_Boolean, Switch_Integer, Switch_String); type Switch_Definition (Typ : Switch_Type := Switch_Untyped) is record Switch : GNAT.OS_Lib.String_Access; Long_Switch : GNAT.OS_Lib.String_Access; Section : GNAT.OS_Lib.String_Access; Help : GNAT.OS_Lib.String_Access; Argument : GNAT.OS_Lib.String_Access; -- null if ""ARG"". -- Name of the argument for this switch. case Typ is when Switch_Untyped => null; when Switch_Boolean => Boolean_Output : access Boolean; Boolean_Value : Boolean; -- will set Output to that value when Switch_Integer => Integer_Output : access Integer; Integer_Initial : Integer; Integer_Default : Integer; when Switch_String => String_Output : access GNAT.Strings.String_Access; end case; end record; type Switch_Definitions is array (Natural range <>) of Switch_Definition; type Switch_Definitions_List is access all Switch_Definitions; -- [Switch] includes the leading '-' type Alias_Definition is record Alias : GNAT.OS_Lib.String_Access; Expansion : GNAT.OS_Lib.String_Access; Section : GNAT.OS_Lib.String_Access; end record; type Alias_Definitions is array (Natural range <>) of Alias_Definition; type Alias_Definitions_List is access all Alias_Definitions; type Command_Line_Configuration_Record is record Prefixes : GNAT.OS_Lib.Argument_List_Access; -- The list of prefixes Sections : GNAT.OS_Lib.Argument_List_Access; -- The list of sections Star_Switch : Boolean := False; -- Whether switches not described in this configuration should be -- returned to the user (True). If False, an exception Invalid_Switch -- is raised. Aliases : Alias_Definitions_List; Usage : GNAT.OS_Lib.String_Access; Help : GNAT.OS_Lib.String_Access; Help_Msg : GNAT.OS_Lib.String_Access; Switches : Switch_Definitions_List; -- List of expected switches (Used when expanding switch groups) end record; type Command_Line_Configuration is access Command_Line_Configuration_Record; type Command_Line is record Config : Command_Line_Configuration; Expanded : GNAT.OS_Lib.Argument_List_Access; Params : GNAT.OS_Lib.Argument_List_Access; -- Parameter for the corresponding switch in Expanded. The first -- character is the separator (or ASCII.NUL if there is no separator). Sections : GNAT.OS_Lib.Argument_List_Access; -- The list of sections Coalesce : GNAT.OS_Lib.Argument_List_Access; Coalesce_Params : GNAT.OS_Lib.Argument_List_Access; Coalesce_Sections : GNAT.OS_Lib.Argument_List_Access; -- Cached version of the command line. This is recomputed every time -- the command line changes. Switches are grouped as much as possible, -- and aliases are used to reduce the length of the command line. The -- parameters are not allocated, they point into Params, so they must -- not be freed. end record; type Command_Line_Iterator is record List : GNAT.OS_Lib.Argument_List_Access; Sections : GNAT.OS_Lib.Argument_List_Access; Params : GNAT.OS_Lib.Argument_List_Access; Current : Natural; end record; end GNAT.Command_Line; ",12291,False,2435.860711178196,median "------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- S Y S T E M . O S _ L I B -- -- -- -- S p e c -- -- -- -- Copyright (C) 1995-2020, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- As a special exception under Section 7 of GPL version 3, you are granted -- -- additional permissions described in the GCC Runtime Library Exception, -- -- version 3.1, as published by the Free Software Foundation. -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- . -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ -- Operating system interface facilities -- This package contains types and procedures for interfacing to the -- underlying OS. It is used by the GNAT compiler and by tools associated -- with the GNAT compiler, and therefore works for the various operating -- systems to which GNAT has been ported. This package will undoubtedly grow -- as new services are needed by various tools. -- This package tends to use fairly low-level Ada in order to not bring in -- large portions of the RTL. For example, functions return access to string -- as part of avoiding functions returning unconstrained types. -- Except where specifically noted, these routines are portable across all -- GNAT implementations on all supported operating systems. -- Note: this package is in the System hierarchy so that it can be directly -- be used by other predefined packages. User access to this package is via -- a renaming of this package in GNAT.OS_Lib (file g-os_lib.ads). pragma Compiler_Unit_Warning; with System; with System.Strings; package System.OS_Lib is pragma Preelaborate; ----------------------- -- String Operations -- ----------------------- -- These are reexported from package Strings (which was introduced to -- avoid different packages declaring different types unnecessarily). -- See package System.Strings for details. subtype String_Access is Strings.String_Access; function ""="" (Left : String_Access; Right : String_Access) return Boolean renames Strings.""=""; procedure Free (X : in out String_Access) renames Strings.Free; subtype String_List is Strings.String_List; function ""="" (Left : String_List; Right : String_List) return Boolean renames Strings.""=""; function ""&"" (Left : String_Access; Right : String_Access) return String_List renames Strings.""&""; function ""&"" (Left : String_Access; Right : String_List) return String_List renames Strings.""&""; function ""&"" (Left : String_List; Right : String_Access) return String_List renames Strings.""&""; function ""&"" (Left : String_List; Right : String_List) return String_List renames Strings.""&""; subtype String_List_Access is Strings.String_List_Access; function ""="" (Left : String_List_Access; Right : String_List_Access) return Boolean renames Strings.""=""; procedure Free (Arg : in out String_List_Access) renames Strings.Free; --------------------- -- Time/Date Stuff -- --------------------- type OS_Time is private; -- The OS's notion of time is represented by the private type OS_Time. This -- is the type returned by the File_Time_Stamp functions to obtain the time -- stamp of a specified file. Functions and a procedure (modeled after the -- similar subprograms in package Calendar) are provided for extracting -- information from a value of this type. Although these are called GM, the -- intention in the case of time stamps is not that they provide GMT times -- in all cases but rather the actual (time-zone independent) time stamp of -- the file (of course in Unix systems, this *is* in GMT form). Invalid_Time : constant OS_Time; -- A special unique value used to flag an invalid time stamp value function ""<"" (X : OS_Time; Y : OS_Time) return Boolean; function "">"" (X : OS_Time; Y : OS_Time) return Boolean; function "">="" (X : OS_Time; Y : OS_Time) return Boolean; function ""<="" (X : OS_Time; Y : OS_Time) return Boolean; -- Basic comparison operators on OS_Time with obvious meanings. Note that -- these have Intrinsic convention, so for example it is not permissible -- to create accesses to any of these functions. subtype Year_Type is Integer range 1900 .. 2099; subtype Month_Type is Integer range 1 .. 12; subtype Day_Type is Integer range 1 .. 31; subtype Hour_Type is Integer range 0 .. 23; subtype Minute_Type is Integer range 0 .. 59; subtype Second_Type is Integer range 0 .. 59; -- Declarations similar to those in Calendar, breaking down the time function Current_Time return OS_Time; -- Return the system clock value as OS_Time function Current_Time_String return String; -- Returns current local time in the form YYYY-MM-DD HH:MM:SS. The result -- has bounds 1 .. 19. function GM_Year (Date : OS_Time) return Year_Type; function GM_Month (Date : OS_Time) return Month_Type; function GM_Day (Date : OS_Time) return Day_Type; function GM_Hour (Date : OS_Time) return Hour_Type; function GM_Minute (Date : OS_Time) return Minute_Type; function GM_Second (Date : OS_Time) return Second_Type; -- Functions to extract information from OS_Time value in GMT form procedure GM_Split (Date : OS_Time; Year : out Year_Type; Month : out Month_Type; Day : out Day_Type; Hour : out Hour_Type; Minute : out Minute_Type; Second : out Second_Type); -- Analogous to the Split routine in Ada.Calendar, takes an OS_Time and -- provides a representation of it as a set of component parts, to be -- interpreted as a date point in UTC. function GM_Time_Of (Year : Year_Type; Month : Month_Type; Day : Day_Type; Hour : Hour_Type; Minute : Minute_Type; Second : Second_Type) return OS_Time; -- Analogous to the Time_Of routine in Ada.Calendar, takes a set of time -- component parts to be interpreted in the local time zone, and returns -- an OS_Time. Returns Invalid_Time if the creation fails. subtype time_t is Long_Integer; -- C time_t type of the time representation function To_C (Time : OS_Time) return time_t; -- Convert OS_Time to C time_t type function To_Ada (Time : time_t) return OS_Time; -- Convert C time_t type to OS_Time ---------------- -- File Stuff -- ---------------- -- These routines give access to the open/creat/close/read/write level of -- I/O routines in the typical C library (these functions are not part of -- the ANSI C standard, but are typically available in all systems). See -- also package Interfaces.C_Streams for access to the stream level -- routines. -- Note on file names. If a file name is passed as type String in any of -- the following specifications, then the name is a normal Ada string and -- need not be NUL-terminated. However, a trailing NUL character is -- permitted, and will be ignored (more accurately, the NUL and any -- characters that follow it will be ignored). type File_Descriptor is new Integer; -- Corresponds to the int file handle values used in the C routines Standin : constant File_Descriptor := 0; Standout : constant File_Descriptor := 1; Standerr : constant File_Descriptor := 2; -- File descriptors for standard input output files Invalid_FD : constant File_Descriptor := -1; -- File descriptor returned when error in opening/creating file Null_FD : constant File_Descriptor := -2; -- Uninitialized file descriptor procedure Close (FD : File_Descriptor; Status : out Boolean); -- Close file referenced by FD. Status is False if the underlying service -- failed. Reasons for failure include: disk full, disk quotas exceeded -- and invalid file descriptor (the file may have been closed twice). procedure Close (FD : File_Descriptor); -- Close file referenced by FD. This form is used when the caller wants to -- ignore any possible error (see above for error cases). type Copy_Mode is (Copy, -- Copy the file. It is an error if the target file already exists. The -- time stamps and other file attributes are preserved in the copy. Overwrite, -- If the target file exists, the file is replaced otherwise the file -- is just copied. The time stamps and other file attributes are -- preserved in the copy. Append); -- If the target file exists, the contents of the source file is -- appended at the end. Otherwise the source file is just copied. The -- time stamps and other file attributes are preserved if the -- destination file does not exist. type Attribute is (Time_Stamps, -- Copy time stamps from source file to target file. All other -- attributes are set to normal default values for file creation. Full, -- All attributes are copied from the source file to the target file. -- This includes the timestamps, and for example also includes -- read/write/execute attributes in Unix systems. None); -- No attributes are copied. All attributes including the time stamp -- values are set to normal default values for file creation. -- Note: The default is Time_Stamps, which corresponds to the normal -- default on Windows style systems. Full corresponds to the typical -- effect of ""cp -p"" on Unix systems, and None corresponds to the typical -- effect of ""cp"" on Unix systems. -- Note: Time_Stamps and Full are not supported on VxWorks 5 procedure Copy_File (Name : String; Pathname : String; Success : out Boolean; Mode : Copy_Mode := Copy; Preserve : Attribute := Time_Stamps); -- Copy a file. Name must designate a single file (no wildcards allowed). -- Pathname can be a filename or directory name. In the latter case Name -- is copied into the directory preserving the same file name. Mode -- defines the kind of copy, see above with the default being a normal -- copy in which the target file must not already exist. Success is set to -- True or False indicating if the copy is successful (depending on the -- specified Mode). procedure Copy_File_Attributes (From : String; To : String; Success : out Boolean; Copy_Timestamp : Boolean := True; Copy_Permissions : Boolean := True); -- Copy some of the file attributes from one file to another. Both files -- must exist, or Success is set to False. procedure Copy_Time_Stamps (Source : String; Dest : String; Success : out Boolean); -- Copy Source file time stamps (last modification and last access time -- stamps) to Dest file. Source and Dest must be valid filenames, -- furthermore Dest must be writable. Success will be set to True if the -- operation was successful and False otherwise. -- -- Note: this procedure is not supported on VxWorks 5. On this platform, -- Success is always set to False. type Mode is (Binary, Text); for Mode'Size use Integer'Size; for Mode use (Binary => 0, Text => 1); -- Used in all the Open and Create calls to specify if the file is to be -- opened in binary mode or text mode. In systems like Unix, this has no -- effect, but in systems capable of text mode translation, the use of -- Text as the mode parameter causes the system to do CR/LF translation -- and also to recognize the DOS end of file character on input. The use -- of Text where appropriate allows programs to take a portable Unix view -- of DOS-format files and process them appropriately. function Create_File (Name : String; Fmode : Mode) return File_Descriptor; -- Creates new file with given name for writing, returning file descriptor -- for subsequent use in Write calls. If the file already exists, it is -- overwritten. File descriptor returned is Invalid_FD if file cannot be -- successfully created. function Create_New_File (Name : String; Fmode : Mode) return File_Descriptor; -- Create new file with given name for writing, returning file descriptor -- for subsequent use in Write calls. This differs from Create_File in -- that it fails if the file already exists. File descriptor returned is -- Invalid_FD if the file exists or cannot be created. function Create_Output_Text_File (Name : String) return File_Descriptor; -- Creates new text file with given name suitable to redirect standard -- output, returning file descriptor. File descriptor returned is -- Invalid_FD if file cannot be successfully created. Temp_File_Len : constant Integer := 12; -- Length of name returned by Create_Temp_File call (GNAT-XXXXXX & NUL) subtype Temp_File_Name is String (1 .. Temp_File_Len); -- String subtype set by Create_Temp_File procedure Create_Temp_File (FD : out File_Descriptor; Name : out Temp_File_Name); -- Create and open for writing a temporary file in the current working -- directory. The name of the file and the File Descriptor are returned. -- The File Descriptor returned is Invalid_FD in the case of failure. No -- mode parameter is provided. Since this is a temporary file, there is no -- point in doing text translation on it. -- -- On some operating systems, the maximum number of temp files that can be -- created with this procedure may be limited. When the maximum is reached, -- this procedure returns Invalid_FD. On some operating systems, there may -- be a race condition between processes trying to create temp files at the -- same time in the same directory using this procedure. procedure Create_Temp_File (FD : out File_Descriptor; Name : out String_Access); -- Create and open for writing a temporary file in the current working -- directory. The name of the file and the File Descriptor are returned. -- It is the responsibility of the caller to deallocate the access value -- returned in Name. -- -- The file is opened in binary mode (no text translation). -- -- This procedure will always succeed if the current working directory is -- writable. If the current working directory is not writable, then -- Invalid_FD is returned for the file descriptor and null for the Name. -- There is no race condition problem between processes trying to create -- temp files at the same time in the same directory. procedure Create_Temp_Output_File (FD : out File_Descriptor; Name : out String_Access); -- Create and open for writing a temporary file in the current working -- directory suitable to redirect standard output. The name of the file and -- the File Descriptor are returned. It is the responsibility of the caller -- to deallocate the access value returned in Name. -- -- The file is opened in text mode -- -- This procedure will always succeed if the current working directory is -- writable. If the current working directory is not writable, then -- Invalid_FD is returned for the file descriptor and null for the Name. -- There is no race condition problem between processes trying to create -- temp files at the same time in the same directory. procedure Delete_File (Name : String; Success : out Boolean); -- Deletes file. Success is set True or False indicating if the delete is -- successful. function File_Length (FD : File_Descriptor) return Long_Integer; pragma Import (C, File_Length, ""__gnat_file_length_long""); type Large_File_Size is range -2**63 .. 2**63 - 1; -- Maximum supported size for a file (8 exabytes = 8 million terabytes, -- should be enough to accommodate all possible needs for quite a while). function File_Length64 (FD : File_Descriptor) return Large_File_Size; pragma Import (C, File_Length64, ""__gnat_file_length""); -- Get length of file from file descriptor FD function File_Time_Stamp (Name : String) return OS_Time; -- Given the name of a file or directory, Name, obtains and returns the -- time stamp. This function can be used for an unopened file. Returns -- Invalid_Time if Name doesn't correspond to an existing file. function File_Time_Stamp (FD : File_Descriptor) return OS_Time; -- Get time stamp of file from file descriptor FD Returns Invalid_Time is -- FD doesn't correspond to an existing file. function Get_Debuggable_Suffix return String_Access; -- Return the debuggable suffix convention. Usually this is the same as -- the convention for Get_Executable_Suffix. The result is allocated on -- the heap and should be freed after use to avoid storage leaks. function Get_Executable_Suffix return String_Access; -- Return the executable suffix convention. The result is allocated on the -- heap and should be freed after use to avoid storage leaks. function Get_Object_Suffix return String_Access; -- Return the object suffix convention. The result is allocated on the heap -- and should be freed after use to avoid storage leaks. function Get_Target_Debuggable_Suffix return String_Access; -- Return the target debuggable suffix convention. Usually this is the same -- as the convention for Get_Executable_Suffix. The result is allocated on -- the heap and should be freed after use to avoid storage leaks. function Get_Target_Executable_Suffix return String_Access; -- Return the target executable suffix convention. The result is allocated -- on the heap and should be freed after use to avoid storage leaks. function Get_Target_Object_Suffix return String_Access; -- Return the target object suffix convention. The result is allocated on -- the heap and should be freed after use to avoid storage leaks. function Is_Absolute_Path (Name : String) return Boolean; -- Returns True if Name is an absolute path name, i.e. it designates a -- file or directory absolutely rather than relative to another directory. function Is_Directory (Name : String) return Boolean; -- Determines if the given string, Name, is the name of a directory. -- Returns True if so, False otherwise. Name may be an absolute path -- name or a relative path name, including a simple file name. If it is -- a relative path name, it is relative to the current working directory. function Is_Executable_File (Name : String) return Boolean; -- Determines if the given string, Name, is the name of an existing file -- that is executable. Returns True if so, False otherwise. Note that this -- function simply interrogates the file attributes (e.g. using the C -- function stat), so it does not indicate a situation in which a file may -- not actually be readable due to some other process having exclusive -- access. function Is_Owner_Readable_File (Name : String) return Boolean; -- Determines if the given string, Name, is the name of an existing file -- that is readable. Returns True if so, False otherwise. Note that this -- function simply interrogates the file attributes (e.g. using the C -- function stat), so it does not indicate a situation in which a file may -- not actually be readable due to some other process having exclusive -- access. function Is_Regular_File (Name : String) return Boolean; -- Determines if the given string, Name, is the name of an existing -- regular file. Returns True if so, False otherwise. Name may be an -- absolute path name or a relative path name, including a simple file -- name. If it is a relative path name, it is relative to the current -- working directory. function Is_Symbolic_Link (Name : String) return Boolean; -- Determines if the given string, Name, is the path of a symbolic link on -- systems that support it. Returns True if so, False if the path is not a -- symbolic link or if the system does not support symbolic links. -- -- A symbolic link is an indirect pointer to a file; its directory entry -- contains the name of the file to which it is linked. Symbolic links may -- span file systems and may refer to directories. function Is_Owner_Writable_File (Name : String) return Boolean; -- Determines if the given string, Name, is the name of an existing file -- that is writable. Returns True if so, False otherwise. Note that this -- function simply interrogates the file attributes (e.g. using the C -- function stat), so it does not indicate a situation in which a file may -- not actually be writable due to some other process having exclusive -- access. function Is_Read_Accessible_File (Name : String) return Boolean; -- Determines if the given string, Name, is the name of an existing file -- that is readable. Returns True if so, False otherwise. function Is_Write_Accessible_File (Name : String) return Boolean; -- Determines if the given string, Name, is the name of an existing file -- that is writable. Returns True if so, False otherwise. function Is_Readable_File (Name : String) return Boolean renames Is_Read_Accessible_File; function Is_Writable_File (Name : String) return Boolean renames Is_Write_Accessible_File; -- These subprograms provided for backward compatibility and should not be -- used. Use Is_Owner_Readable_File/Is_Owner_Writable_File or -- Is_Read_Accessible_File/Is_Write_Accessible_File instead. function Locate_Exec_On_Path (Exec_Name : String) return String_Access; -- Try to locate an executable whose name is given by Exec_Name in the -- directories listed in the environment Path. If the Exec_Name does not -- have the executable suffix, it will be appended before the search. -- Otherwise works like Locate_Regular_File below. If the executable is -- not found, null is returned. -- -- Note that this function allocates memory for the returned value. This -- memory needs to be deallocated after use. function Locate_Regular_File (File_Name : String; Path : String) return String_Access; -- Try to locate a regular file whose name is given by File_Name in the -- directories listed in Path. If a file is found, its full pathname is -- returned; otherwise, a null pointer is returned. If the File_Name given -- is an absolute pathname, then Locate_Regular_File just checks that the -- file exists and is a regular file. Otherwise, if the File_Name given -- includes directory information, Locate_Regular_File first checks if the -- file exists relative to the current directory. If it does not, or if -- the File_Name given is a simple file name, the Path argument is parsed -- according to OS conventions, and for each directory in the Path a check -- is made if File_Name is a relative pathname of a regular file from that -- directory. -- -- Note that this function allocates some memory for the returned value. -- This memory needs to be deallocated after use. Seek_Cur : constant := 1; Seek_End : constant := 2; Seek_Set : constant := 0; -- Used to indicate origin for Lseek call procedure Lseek (FD : File_Descriptor; offset : Long_Integer; origin : Integer); pragma Import (C, Lseek, ""__gnat_lseek""); -- Sets the current file pointer to the indicated offset value, relative -- to the current position (origin = SEEK_CUR), end of file (origin = -- SEEK_END), or start of file (origin = SEEK_SET). function Normalize_Pathname (Name : String; Directory : String := """"; Resolve_Links : Boolean := True; Case_Sensitive : Boolean := True) return String; -- Returns a file name as an absolute path name, resolving all relative -- directories, and symbolic links. If Name is a relative path, it is -- interpreted relative to Directory, or to the current directory if -- Directory is the empty string (the default). The result returned is -- the normalized name of the file, containing no ""."" or "".."" components, -- and no duplicated directory separators. For most cases, if two file -- names designate the same file through different paths, -- Normalize_Pathname will return the same canonical name in both cases. -- However, there are cases when this is not true; for example, this is -- not true in Unix for two hard links designating the same file. -- -- On Windows, the returned path will start with a drive letter. If -- Directory is empty (the default) and Name is a relative path or an -- absolute path without drive letter, the letter of the current drive -- will start the returned path. If Case_Sensitive is True (the default), -- then this drive letter will be forced to upper case (""C:\\...""). -- -- If Resolve_Links is set to True, then the symbolic links, on systems -- that support them, will be fully converted to the name of the file or -- directory pointed to. This is slightly less efficient, since it -- requires system calls. -- -- If Name is empty or the path contains symbolic links that can't be -- resolved (for example there is a symbolic link circularity, -- e.g. A is a symbolic link for B, and B is a symbolic link for A), then -- Normalize_Pathname returns an empty string. -- -- For case-sensitive file systems, the value of Case_Sensitive parameter -- is ignored. For file systems that are not case-sensitive, such as -- Windows, if this parameter is set to False, then the file and directory -- names are folded to lower case. This allows checking whether two files -- are the same by applying this function to their names and comparing the -- results. If Case_Sensitive is set to True, this function does not change -- the casing of file and directory names. function Open_Append (Name : String; Fmode : Mode) return File_Descriptor; -- Opens file Name for appending, returning its file descriptor. File -- descriptor returned is Invalid_FD if the file cannot be successfully -- opened. function Open_Read (Name : String; Fmode : Mode) return File_Descriptor; -- Open file Name for reading, returning its file descriptor. File -- descriptor returned is Invalid_FD if the file cannot be opened. function Open_Read_Write (Name : String; Fmode : Mode) return File_Descriptor; -- Open file Name for both reading and writing, returning its file -- descriptor. File descriptor returned is Invalid_FD if the file -- cannot be opened. function Read (FD : File_Descriptor; A : System.Address; N : Integer) return Integer; -- Read N bytes to address A from file referenced by FD. Returned value is -- count of bytes actually read, which can be less than N at EOF. procedure Rename_File (Old_Name : String; New_Name : String; Success : out Boolean); -- Rename a file. Success is set True or False indicating if the rename is -- successful or not. -- -- WARNING: In one very important respect, this function is significantly -- non-portable. If New_Name already exists then on Unix systems, the call -- deletes the existing file, and the call signals success. On Windows, the -- call fails, without doing the rename operation. See also the procedure -- Ada.Directories.Rename, which portably provides the windows semantics, -- i.e. fails if the output file already exists. -- The following defines the mode for the Copy_File procedure below. Note -- that ""time stamps and other file attributes"" in the descriptions below -- refers to the creation and last modification times, and also the file -- access (read/write/execute) status flags. procedure Set_Close_On_Exec (FD : File_Descriptor; Close_On_Exec : Boolean; Status : out Boolean); -- When Close_On_Exec is True, mark FD to be closed automatically when new -- program is executed by the calling process (i.e. prevent FD from being -- inherited by child processes). When Close_On_Exec is False, mark FD to -- not be closed on exec (i.e. allow it to be inherited). Status is False -- if the operation could not be performed. S_Owner : constant := 1; S_Group : constant := 2; S_Others : constant := 4; -- Constants for use in Mode parameter to Set_Executable procedure Set_Executable (Name : String; Mode : Positive := S_Owner); -- Change permissions on the file given by Name to make it executable -- for its owner, group or others, according to the setting of Mode. -- As indicated, the default if no Mode parameter is given is owner. procedure Set_File_Last_Modify_Time_Stamp (Name : String; Time : OS_Time); -- Given the name of a file or directory, Name, set the last modification -- time stamp. This function must be used for an unopened file. procedure Set_Non_Readable (Name : String); -- Change permissions on the named file to make it non-readable for -- its owner. The writable and executable permissions are not -- modified. procedure Set_Non_Writable (Name : String); -- Change permissions on the named file to make it non-writable for its -- owner. The readable and executable permissions are not modified. procedure Set_Read_Only (Name : String) renames Set_Non_Writable; -- This renaming is provided for backwards compatibility with previous -- versions. The use of Set_Non_Writable is preferred (clearer name). procedure Set_Readable (Name : String); -- Change permissions on the named file to make it readable for its -- owner. procedure Set_Writable (Name : String); -- Change permissions on the named file to make it writable for its owner function Write (FD : File_Descriptor; A : System.Address; N : Integer) return Integer; -- Write N bytes from address A to file referenced by FD. The returned -- value is the number of bytes written, which can be less than N if a -- disk full condition was detected. -- The following section contains low-level routines using addresses to -- pass file name and executable name. In each routine the name must be -- Nul-Terminated. For complete documentation refer to the equivalent -- routine (using String in place of C_File_Name) defined above. subtype C_File_Name is System.Address; -- This subtype is used to document that a parameter is the address of a -- null-terminated string containing the name of a file. procedure Copy_File (Name : C_File_Name; Pathname : C_File_Name; Success : out Boolean; Mode : Copy_Mode := Copy; Preserve : Attribute := Time_Stamps); procedure Copy_Time_Stamps (Source : C_File_Name; Dest : C_File_Name; Success : out Boolean); function Create_File (Name : C_File_Name; Fmode : Mode) return File_Descriptor; function Create_New_File (Name : C_File_Name; Fmode : Mode) return File_Descriptor; procedure Delete_File (Name : C_File_Name; Success : out Boolean); function File_Time_Stamp (Name : C_File_Name) return OS_Time; function Is_Directory (Name : C_File_Name) return Boolean; function Is_Executable_File (Name : C_File_Name) return Boolean; function Is_Owner_Readable_File (Name : C_File_Name) return Boolean; function Is_Regular_File (Name : C_File_Name) return Boolean; function Is_Symbolic_Link (Name : C_File_Name) return Boolean; function Is_Owner_Writable_File (Name : C_File_Name) return Boolean; function Locate_Regular_File (File_Name : C_File_Name; Path : C_File_Name) return String_Access; function Open_Append (Name : C_File_Name; Fmode : Mode) return File_Descriptor; function Open_Read (Name : C_File_Name; Fmode : Mode) return File_Descriptor; function Open_Read_Write (Name : C_File_Name; Fmode : Mode) return File_Descriptor; procedure Rename_File (Old_Name : C_File_Name; New_Name : C_File_Name; Success : out Boolean); ------------------ -- Subprocesses -- ------------------ subtype Argument_List is String_List; -- Type used for argument list in call to Spawn. The lower bound of the -- array should be 1, and the length of the array indicates the number of -- arguments. subtype Argument_List_Access is String_List_Access; -- Type used to return Argument_List without dragging in secondary stack. -- Note that there is a Free procedure declared for this subtype which -- frees the array and all referenced strings. type Process_Id is private; -- A private type used to identify a process activated by the following -- non-blocking calls. The only meaningful operation on this type is a -- comparison for equality. Invalid_Pid : constant Process_Id; -- A special value used to indicate errors, as described below function Current_Process_Id return Process_Id; -- Returns the current process id or Invalid_Pid if not supported by the -- runtime. function Argument_String_To_List (Arg_String : String) return Argument_List_Access; -- Take a string that is a program and its arguments and parse it into an -- Argument_List. Note that the result is allocated on the heap, and must -- be freed by the programmer (when it is no longer needed) to avoid -- memory leaks. -- On Windows, backslashes are used as directory separators. On Unix, -- however, they are used to escape the following character, so that for -- instance ""-d=name\\ with\\ space"" is a single argument. In the result -- list, the backslashes have been cleaned up when needed. The previous -- example will thus result a single-element array, where the element is -- ""-d=name with space"" (Unix) or ""-d=name\\ with\\ space"" (windows). procedure Kill (Pid : Process_Id; Hard_Kill : Boolean := True); -- Kill the process designated by Pid. Does nothing if Pid is Invalid_Pid -- or on platforms where it is not supported, such as VxWorks. Hard_Kill -- is True by default, and when True the process is terminated immediately. -- If Hard_Kill is False, then a signal SIGINT is sent to the process on -- POSIX OS or a ctrl-C event on Windows, allowing the process a chance to -- terminate properly using a corresponding handler. procedure Kill_Process_Tree (Pid : Process_Id; Hard_Kill : Boolean := True); -- Kill the process designated by Pid and all it's children processes. -- Does nothing if Pid is Invalid_Pid or on platforms where it is not -- supported, such as VxWorks. Hard_Kill is True by default, and when True -- the processes are terminated immediately. If Hard_Kill is False, then a -- signal SIGINT is sent to the processes on POSIX OS or a ctrl-C event -- on Windows, allowing the processes a chance to terminate properly -- using a corresponding handler. -- -- Note that this routine is not atomic and is supported only on Linux -- and Windows. On other OS it will only kill the process identified by -- Pid. function Non_Blocking_Spawn (Program_Name : String; Args : Argument_List) return Process_Id; -- This is a non blocking call. The Process_Id of the spawned process is -- returned. Parameters are to be used as in Spawn. If Invalid_Pid is -- returned the program could not be spawned. -- -- Spawning processes from tasking programs is not recommended. See -- ""NOTE: Spawn in tasking programs"" below. -- -- This function will always return Invalid_Pid under VxWorks, since there -- is no notion of executables under this OS. function Non_Blocking_Spawn (Program_Name : String; Args : Argument_List; Output_File_Descriptor : File_Descriptor; Err_To_Out : Boolean := True) return Process_Id; -- Similar to the procedure above, but redirects the output to the file -- designated by Output_File_Descriptor. If Err_To_Out is True, then the -- Standard Error output is also redirected. Invalid_Pid is returned -- if the program could not be spawned successfully. -- -- Spawning processes from tasking programs is not recommended. See -- ""NOTE: Spawn in tasking programs"" below. -- -- This function will always return Invalid_Pid under VxWorks, since there -- is no notion of executables under this OS. function Non_Blocking_Spawn (Program_Name : String; Args : Argument_List; Output_File : String; Err_To_Out : Boolean := True) return Process_Id; -- Similar to the procedure above, but saves the output of the command to -- a file with the name Output_File. -- -- Invalid_Pid is returned if the output file could not be created or if -- the program could not be spawned successfully. -- -- Spawning processes from tasking programs is not recommended. See -- ""NOTE: Spawn in tasking programs"" below. -- -- This function will always return Invalid_Pid under VxWorks, since there -- is no notion of executables under this OS. function Non_Blocking_Spawn (Program_Name : String; Args : Argument_List; Stdout_File : String; Stderr_File : String) return Process_Id; -- Similar to the procedure above, but saves the standard output of the -- command to a file with the name Stdout_File and the standard output -- of the command to a file with the name Stderr_File. procedure Normalize_Arguments (Args : in out Argument_List); -- Normalize all arguments in the list. This ensure that the argument list -- is compatible with the running OS and will works fine with Spawn and -- Non_Blocking_Spawn for example. If Normalize_Arguments is called twice -- on the same list it will do nothing the second time. Note that Spawn -- and Non_Blocking_Spawn call Normalize_Arguments automatically, but -- since there is a guarantee that a second call does nothing, this -- internal call will have no effect if Normalize_Arguments is called -- before calling Spawn. The call to Normalize_Arguments assumes that the -- individual referenced arguments in Argument_List are on the heap, and -- may free them and reallocate if they are modified. function Pid_To_Integer (Pid : Process_Id) return Integer; -- Convert a process id to an Integer. Useful for writing hash functions -- for type Process_Id or to compare two Process_Id (e.g. for sorting). procedure Spawn (Program_Name : String; Args : Argument_List; Success : out Boolean); -- This procedure spawns a program with a given list of arguments. The -- first parameter of is the name of the executable. The second parameter -- contains the arguments to be passed to this program. Success is False -- if the named program could not be spawned or its execution completed -- unsuccessfully. Note that the caller will be blocked until the -- execution of the spawned program is complete. For maximum portability, -- use a full path name for the Program_Name argument. On some systems -- (notably Unix systems) a simple file name may also work (if the -- executable can be located in the path). -- -- Spawning processes from tasking programs is not recommended. See -- ""NOTE: Spawn in tasking programs"" below. -- -- Note: Arguments in Args that contain spaces and/or quotes such as -- ""--GCC=gcc -v"" or ""--GCC=""""gcc -v"""""" are not portable across all -- operating systems, and would not have the desired effect if they were -- passed directly to the operating system. To avoid this problem, Spawn -- makes an internal call to Normalize_Arguments, which ensures that such -- arguments are modified in a manner that ensures that the desired effect -- is obtained on all operating systems. The caller may call -- Normalize_Arguments explicitly before the call (e.g. to print out the -- exact form of arguments passed to the operating system). In this case -- the guarantee a second call to Normalize_Arguments has no effect -- ensures that the internal call will not affect the result. Note that -- the implicit call to Normalize_Arguments may free and reallocate some -- of the individual arguments. -- -- This function will always set Success to False under VxWorks and other -- similar operating systems which have no notion of the concept of -- dynamically executable file. Otherwise Success is set True if the exit -- status of the spawned process is zero. function Spawn (Program_Name : String; Args : Argument_List) return Integer; -- Similar to the above procedure, but returns the actual status returned -- by the operating system, or -1 under VxWorks and any other similar -- operating systems which have no notion of separately spawnable programs. -- -- Spawning processes from tasking programs is not recommended. See -- ""NOTE: Spawn in tasking programs"" below. procedure Spawn (Program_Name : String; Args : Argument_List; Output_File_Descriptor : File_Descriptor; Return_Code : out Integer; Err_To_Out : Boolean := True); -- Similar to the procedure above, but redirects the output to the file -- designated by Output_File_Descriptor. If Err_To_Out is True, then the -- Standard Error output is also redirected. -- Return_Code is set to the status code returned by the operating system -- -- Spawning processes from tasking programs is not recommended. See -- ""NOTE: Spawn in tasking programs"" below. procedure Spawn (Program_Name : String; Args : Argument_List; Output_File : String; Success : out Boolean; Return_Code : out Integer; Err_To_Out : Boolean := True); -- Similar to the procedure above, but saves the output of the command to -- a file with the name Output_File. -- -- Success is set to True if the command is executed and its output -- successfully written to the file. If Success is True, then Return_Code -- will be set to the status code returned by the operating system. -- Otherwise, Return_Code is undefined. -- -- Spawning processes from tasking programs is not recommended. See -- ""NOTE: Spawn in tasking programs"" below. procedure Wait_Process (Pid : out Process_Id; Success : out Boolean); -- Wait for the completion of any of the processes created by previous -- calls to Non_Blocking_Spawn. The caller will be suspended until one of -- these processes terminates (normally or abnormally). If any of these -- subprocesses terminates prior to the call to Wait_Process (and has not -- been returned by a previous call to Wait_Process), then the call to -- Wait_Process is immediate. Pid identifies the process that has -- terminated (matching the value returned from Non_Blocking_Spawn). -- Success is set to True if this sub-process terminated successfully. If -- Pid = Invalid_Pid, there were no subprocesses left to wait on. -- -- This function will always set success to False under VxWorks, since -- there is no notion of executables under this OS. procedure Non_Blocking_Wait_Process (Pid : out Process_Id; Success : out Boolean); -- Same as Wait_Process, except if there are no completed child processes, -- return immediately without blocking, and return Invalid_Pid in Pid. -- Not supported on all platforms; Success = False if not supported. ------------------------------------- -- NOTE: Spawn in Tasking Programs -- ------------------------------------- -- Spawning processes in tasking programs using the above Spawn and -- Non_Blocking_Spawn subprograms is not recommended, because there are -- subtle interactions between creating a process and signals/locks that -- can cause trouble. These issues are not specific to Ada; they depend -- primarily on the operating system. -- If you need to spawn processes in a tasking program, you will need to -- understand the semantics of your operating system, and you are likely to -- write non-portable code, because operating systems differ in this area. -- The Spawn and Non_Blocking_Spawn subprograms call the following -- operating system functions: -- On Windows: spawnvp (blocking) or CreateProcess (non-blocking) -- On Solaris: fork1, followed in the child process by execv -- On other Unix-like systems: fork, followed in the child -- process by execv. -- On vxworks, spawning of processes is not supported -- For details, look at the functions __gnat_portable_spawn and -- __gnat_portable_no_block_spawn in adaint.c. -- You should read the operating-system-specific documentation for the -- above functions, paying special attention to subtle interactions with -- threading, signals, locks, and file descriptors. Most of the issues are -- related to the fact that on Unix, there is a window of time between fork -- and execv; Windows does not have this problem, because spawning is done -- in a single operation. -- On Posix-compliant systems, such as Linux, fork duplicates just the -- calling thread. (On Solaris, fork1 is the Posix-compliant version of -- fork.) -- You should avoid using signals while spawning. This includes signals -- used internally by the Ada run-time system, such as timer signals used -- to implement delay statements. -- It is best to spawn any subprocesses very early, before the parent -- process creates tasks, locks, or installs signal handlers. Certainly -- avoid doing simultaneous spawns from multiple threads of the same -- process. -- There is no problem spawning a subprocess that uses tasking: the -- problems are caused only by tasking in the parent. -- If the parent is using tasking, and needs to spawn subprocesses at -- arbitrary times, one technique is for the parent to spawn (very early) -- a particular spawn-manager subprocess whose job is to spawn other -- processes. The spawn-manager must avoid tasking. The parent sends -- messages to the spawn-manager requesting it to spawn processes, using -- whatever inter-process communication mechanism you like, such as -- sockets. -- In short, mixing spawning of subprocesses with tasking is a tricky -- business, and should be avoided if possible, but if it is necessary, -- the above guidelines should be followed, and you should beware of -- portability problems. ------------------- -- Miscellaneous -- ------------------- function Errno return Integer; pragma Import (C, Errno, ""__get_errno""); -- Return the task-safe last error number function Errno_Message (Err : Integer := Errno; Default : String := """") return String; -- Return a message describing the given Errno value. If none is provided -- by the system, return Default if not empty, else return a generic -- message indicating the numeric errno value. function Getenv (Name : String) return String_Access; -- Get the value of the environment variable. Returns an access to the -- empty string if the environment variable does not exist or has an -- explicit null value (in some operating systems these are distinct -- cases, in others they are not; this interface abstracts away that -- difference. The argument is allocated on the heap (even in the null -- case), and needs to be freed explicitly when no longer needed to avoid -- memory leaks. procedure OS_Abort; pragma Import (C, OS_Abort, ""abort""); pragma No_Return (OS_Abort); -- Exit to OS signalling an abort (traceback or other appropriate -- diagnostic information should be given if possible, or entry made to -- the debugger if that is possible). procedure OS_Exit (Status : Integer); pragma No_Return (OS_Exit); -- Exit to OS with given status code (program is terminated). Note that -- this is abrupt termination. All tasks are immediately terminated. There -- are no finalization or other Ada-specific cleanup actions performed. On -- systems with atexit handlers (such as Unix and Windows), atexit handlers -- are called. type OS_Exit_Subprogram is access procedure (Status : Integer); procedure OS_Exit_Default (Status : Integer); pragma No_Return (OS_Exit_Default); -- Default implementation of procedure OS_Exit OS_Exit_Ptr : OS_Exit_Subprogram := OS_Exit_Default'Access; -- OS_Exit is implemented through this access value. It it then possible to -- change the implementation of OS_Exit by redirecting OS_Exit_Ptr to an -- other implementation. procedure Set_Errno (Errno : Integer); pragma Import (C, Set_Errno, ""__set_errno""); -- Set the task-safe error number procedure Setenv (Name : String; Value : String); -- Set the value of the environment variable Name to Value. This call -- modifies the current environment, but does not modify the parent -- process environment. After a call to Setenv, Getenv (Name) will always -- return a String_Access referencing the same String as Value. This is -- true also for the null string case (the actual effect may be to either -- set an explicit null as the value, or to remove the entry, this is -- operating system dependent). Note that any following calls to Spawn -- will pass an environment to the spawned process that includes the -- changes made by Setenv calls. Directory_Separator : constant Character; -- The character that is used to separate parts of a pathname Path_Separator : constant Character; -- The character to separate paths in an environment variable value private pragma Import (C, Path_Separator, ""__gnat_path_separator""); pragma Import (C, Directory_Separator, ""__gnat_dir_separator""); pragma Import (C, Current_Time, ""__gnat_current_time""); pragma Import (C, Current_Process_Id, ""__gnat_current_process_id""); type OS_Time is range -(2 ** (Standard'Address_Size - Integer'(1))) .. +(2 ** (Standard'Address_Size - Integer'(1)) - 1); -- Type used for timestamps in the compiler. This type is used to hold -- time stamps, but may have a different representation than C's time_t. -- This type needs to match the declaration of OS_Time in adaint.h. -- Add pragma Inline statements for comparison operations on OS_Time. It -- would actually be nice to use pragma Import (Intrinsic) here, but this -- was not properly supported till GNAT 3.15a, so that would cause -- bootstrap path problems. To be changed later ??? Invalid_Time : constant OS_Time := -1; -- This value should match the return value from __gnat_file_time_* pragma Inline (""<""); pragma Inline ("">""); pragma Inline (""<=""); pragma Inline ("">=""); pragma Inline (To_C); pragma Inline (To_Ada); type Process_Id is new Integer; Invalid_Pid : constant Process_Id := -1; end System.OS_Lib; ",12463,False,2323.252313705256,median "------------------------------------------------------------------------------ -- Copyright (c) 2015-2017, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED ""AS IS"" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ with Ada.Characters.Latin_1; with Ada.Streams; with Ada.Strings.Fixed; with Ada.Strings.Unbounded; with Natools.S_Expressions; with Natools.Smaz_256; with Natools.Smaz_4096; with Natools.Smaz_64; with Natools.Smaz_Generic; with Natools.Smaz_Implementations.Base_4096; with Natools.Smaz_Original; with Natools.Smaz_Test_Base_64_Hash; package body Natools.Smaz_Tests is generic with package Smaz is new Natools.Smaz_Generic (<>); with function Image (S : Ada.Streams.Stream_Element_Array) return String; procedure Generic_Roundtrip_Test (Test : in out NT.Test; Dict : in Smaz.Dictionary; Decompressed : in String; Compressed : in Ada.Streams.Stream_Element_Array); function Decimal_Image (S : Ada.Streams.Stream_Element_Array) return String; function Dictionary_256_Without_VLV return Smaz_256.Dictionary; function Dictionary_4096 (Variable_Length_Verbatim : in Boolean) return Natools.Smaz_4096.Dictionary; function Dictionary_4096_Hash (S : in String) return Natural; function Direct_Image (S : Ada.Streams.Stream_Element_Array) return String renames Natools.S_Expressions.To_String; function To_SEA (S : String) return Ada.Streams.Stream_Element_Array renames Natools.S_Expressions.To_Atom; procedure Impure_Stream_4096 (Report : in out NT.Reporter'Class; Dictionary : in Smaz_4096.Dictionary); procedure Sample_Strings_4096 (Report : in out NT.Reporter'Class; Dictionary : in Smaz_4096.Dictionary); procedure Sample_Strings_VLV_4096 (Report : in out NT.Reporter'Class; Dictionary : in Smaz_4096.Dictionary); procedure Test_Validity_4096 (Report : in out NT.Reporter'Class; Dictionary : in Smaz_4096.Dictionary); ----------------------- -- Test Dictionaries -- ----------------------- LF : constant Character := Ada.Characters.Latin_1.LF; Dict_64 : constant Natools.Smaz_64.Dictionary := (Last_Code => 59, Values_Last => 119, Variable_Length_Verbatim => False, Max_Word_Length => 6, Offsets => (2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 18, 20, 22, 24, 25, 26, 28, 30, 31, 32, 36, 38, 40, 42, 44, 45, 47, 49, 51, 53, 56, 60, 63, 65, 68, 70, 72, 74, 76, 80, 82, 84, 88, 90, 92, 94, 98, 101, 102, 103, 105, 111, 112, 114, 115, 118), Values => "" ee stainruos l dt enescm p"" & Character'Val (16#C3#) & Character'Val (16#A9#) & ""pd de lere ld"" & ""e"" & LF & ""on cqumede mentes aiquen teerou r sque , is m q"" & ""ue"" & Character'Val (16#C3#) & Character'Val (16#A0#) & "" v'tiweblogfanj."" & LF & LF & ""ch"", Hash => Natools.Smaz_Test_Base_64_Hash.Hash'Access); Dict_64_V : constant Natools.Smaz_64.Dictionary := (Last_Code => 59, Values_Last => 119, Variable_Length_Verbatim => True, Max_Word_Length => 6, Offsets => (2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 18, 20, 22, 24, 25, 26, 28, 30, 31, 32, 36, 38, 40, 42, 44, 45, 47, 49, 51, 53, 56, 60, 63, 65, 68, 70, 72, 74, 76, 80, 82, 84, 88, 90, 92, 94, 98, 101, 102, 103, 105, 111, 112, 114, 115, 118), Values => "" ee stainruos l dt enescm p"" & Character'Val (16#C3#) & Character'Val (16#A9#) & ""pd de lere ld"" & ""e"" & LF & ""on cqumede mentes aiquen teerou r sque , is m q"" & ""ue"" & Character'Val (16#C3#) & Character'Val (16#A0#) & "" v'tiweblogfanj."" & LF & LF & ""ch"", Hash => Natools.Smaz_Test_Base_64_Hash.Hash'Access); ------------------------------ -- Local Helper Subprograms -- ------------------------------ function Decimal_Image (S : Ada.Streams.Stream_Element_Array) return String is use Ada.Strings.Unbounded; Result : Unbounded_String; begin for I in S'Range loop Append (Result, Ada.Streams.Stream_Element'Image (S (I))); end loop; return To_String (Result); end Decimal_Image; function Dictionary_256_Without_VLV return Smaz_256.Dictionary is begin return Dict : Smaz_256.Dictionary := Smaz_Original.Dictionary do Dict.Variable_Length_Verbatim := False; end return; end Dictionary_256_Without_VLV; function Dictionary_4096 (Variable_Length_Verbatim : in Boolean) return Natools.Smaz_4096.Dictionary is subtype Letter_Rank is Natural range 1 .. 26; function Lower (N : Letter_Rank) return Character is (Character'Val (Character'Pos ('a') - 1 + N)); function Upper (N : Letter_Rank) return Character is (Character'Val (Character'Pos ('A') - 1 + N)); subtype Digit_Rank is Natural range 0 .. 9; function Image (N : Digit_Rank) return Character is (Character'Val (Character'Pos ('0') + N)); subtype Alphanum is Character with Static_Predicate => Alphanum in '0' .. '9' | 'A' .. 'Z' | 'a' .. 'z'; Current_Index : Smaz_Implementations.Base_4096.Base_4096_Digit := 0; Current_Offset : Positive := 1; use type Smaz_Implementations.Base_4096.Base_4096_Digit; procedure Push_Value (Dict : in out Natools.Smaz_4096.Dictionary; Value : in String); procedure Push_Value (Dict : in out Natools.Smaz_4096.Dictionary; Value : in String) is begin if Current_Index > 0 then Dict.Offsets (Current_Index) := Current_Offset; end if; Dict.Values (Current_Offset .. Current_Offset + Value'Length - 1) := Value; Current_Index := Current_Index + 1; Current_Offset := Current_Offset + Value'Length; end Push_Value; begin return Dict : Natools.Smaz_4096.Dictionary := (Last_Code => 4059, Values_Last => 9120, Variable_Length_Verbatim => Variable_Length_Verbatim, Max_Word_Length => 3, Offsets => <>, Values => <>, Hash => Dictionary_4096_Hash'Access) do -- 0 .. 61: space + letter for L in Alphanum loop Push_Value (Dict, (1 => ' ', 2 => L)); end loop; -- 62 .. 123: letter + space for L in Alphanum loop Push_Value (Dict, (1 => L, 2 => ' ')); end loop; -- 124 .. 185: letter + comma for L in Alphanum loop Push_Value (Dict, (1 => L, 2 => ',')); end loop; -- 186 .. 247: letter + period for L in Alphanum loop Push_Value (Dict, (1 => L, 2 => '.')); end loop; -- 248 .. 255: double punctuation for L in Character range ' ' .. ''' loop Push_Value (Dict, (1 => L, 2 => L)); end loop; -- 256 .. 355: two-digit numbers for U in Digit_Rank loop for V in Digit_Rank loop Push_Value (Dict, (1 => Image (U), 2 => Image (V))); end loop; end loop; -- 356 .. 1355: three-digit numbers for U in Digit_Rank loop for V in Digit_Rank loop for W in Digit_Rank loop Push_Value (Dict, (1 => Image (U), 2 => Image (V), 3 => Image (W))); end loop; end loop; end loop; -- 1356 .. 2031: two lower-case letters for M in Letter_Rank loop for N in Letter_Rank loop Push_Value (Dict, (1 => Lower (M), 2 => Lower (N))); end loop; end loop; -- 2032 .. 2707: lower-case then upper-case letter for M in Letter_Rank loop for N in Letter_Rank loop Push_Value (Dict, (1 => Lower (M), 2 => Upper (N))); end loop; end loop; -- 2708 .. 3383: upper-case then lower-case letter for M in Letter_Rank loop for N in Letter_Rank loop Push_Value (Dict, (1 => Upper (M), 2 => Lower (N))); end loop; end loop; -- 3384 .. 4059: two upper-case letters for M in Letter_Rank loop for N in Letter_Rank loop Push_Value (Dict, (1 => Upper (M), 2 => Upper (N))); end loop; end loop; pragma Assert (Current_Index = Dict.Last_Code + 1); pragma Assert (Current_Offset = Dict.Values_Last + 1); end return; end Dictionary_4096; function Dictionary_4096_Hash (S : in String) return Natural is function Rank (C : Character) return Natural is (case C is when '0' .. '9' => Character'Pos (C) - Character'Pos ('0'), when 'a' .. 'z' => Character'Pos (C) - Character'Pos ('a'), when 'A' .. 'Z' => Character'Pos (C) - Character'Pos ('A'), when others => raise Program_Error); begin case S'Length is when 2 => declare U : constant Character := S (S'First); V : constant Character := S (S'Last); begin if U = ' ' and then V in '0' .. '9' then return Rank (V); elsif U = ' ' and then V in 'A' .. 'Z' then return 10 + Rank (V); elsif U = ' ' and then V in 'a' .. 'z' then return 36 + Rank (V); elsif U in '0' .. '9' and then V in ' ' | ',' | '.' then return Rank (U) + (case V is when ' ' => 62, when ',' => 124, when '.' => 186, when others => raise Program_Error); elsif U in 'A' .. 'Z' and then V in ' ' | ',' | '.' then return Rank (U) + 10 + (case V is when ' ' => 62, when ',' => 124, when '.' => 186, when others => raise Program_Error); elsif U in 'a' .. 'z' and then V in ' ' | ',' | '.' then return Rank (U) + 36 + (case V is when ' ' => 62, when ',' => 124, when '.' => 186, when others => raise Program_Error); elsif U in ' ' .. ''' and then U = V then return 248 + Character'Pos (U) - Character'Pos (' '); elsif U in '0' .. '9' and then V in '0' .. '9' then return 256 + Rank (U) * 10 + Rank (V); elsif U in 'a' .. 'z' and then V in 'a' .. 'z' then return 1356 + Rank (U) * 26 + Rank (V); elsif U in 'a' .. 'z' and then V in 'A' .. 'Z' then return 2032 + Rank (U) * 26 + Rank (V); elsif U in 'A' .. 'Z' and then V in 'a' .. 'z' then return 2708 + Rank (U) * 26 + Rank (V); elsif U in 'A' .. 'Z' and then V in 'A' .. 'Z' then return 3384 + Rank (U) * 26 + Rank (V); else return 4096; end if; end; when 3 => declare U : constant Character := S (S'First); V : constant Character := S (S'First + 1); W : constant Character := S (S'First + 2); begin if U in '0' .. '9' and then V in '0' .. '9' and then W in '0' .. '9' then return 356 + Rank (U) * 100 + Rank (V) * 10 + Rank (W); else return 4096; end if; end; when others => return 4096; end case; end Dictionary_4096_Hash; procedure Generic_Roundtrip_Test (Test : in out NT.Test; Dict : in Smaz.Dictionary; Decompressed : in String; Compressed : in Ada.Streams.Stream_Element_Array) is use type Ada.Streams.Stream_Element_Array; use type Ada.Streams.Stream_Element_Offset; begin declare First_OK : Boolean := False; begin declare Buffer : constant Ada.Streams.Stream_Element_Array := Smaz.Compress (Dict, Decompressed); begin First_OK := True; if Buffer /= Compressed then Test.Fail (""Bad compression of """""" & Decompressed & '""'); Test.Info (""Found: "" & Image (Buffer)); Test.Info (""Expected:"" & Image (Compressed)); declare Round : constant String := Smaz.Decompress (Dict, Buffer); begin if Round /= Decompressed then Test.Info (""Roundtrip failed, got: """""" & Round & '""'); else Test.Info (""Roundtrip OK""); end if; end; end if; end; exception when Error : others => if not First_OK then Test.Info (""During compression of """""" & Decompressed & '""'); end if; Test.Report_Exception (Error, NT.Fail); end; declare First_OK : Boolean := False; begin declare Buffer : constant String := Smaz.Decompress (Dict, Compressed); begin First_OK := True; if Buffer /= Decompressed then Test.Fail (""Bad decompression of "" & Image (Compressed)); Test.Info (""Found: """""" & Buffer & '""'); Test.Info (""Expected:"""""" & Decompressed & '""'); declare Round : constant Ada.Streams.Stream_Element_Array := Smaz.Compress (Dict, Buffer); begin if Round /= Compressed then Test.Info (""Roundtrip failed, got: "" & Image (Round)); else Test.Info (""Roundtrip OK""); end if; end; end if; end; exception when Error : others => if not First_OK then Test.Info (""During decompression of "" & Image (Compressed)); end if; Test.Report_Exception (Error, NT.Fail); end; end Generic_Roundtrip_Test; procedure Roundtrip_Test is new Generic_Roundtrip_Test (Natools.Smaz_256, Decimal_Image); procedure Roundtrip_Test is new Generic_Roundtrip_Test (Natools.Smaz_4096, Direct_Image); procedure Roundtrip_Test is new Generic_Roundtrip_Test (Natools.Smaz_64, Direct_Image); ------------------------- -- Complete Test Suite -- ------------------------- procedure All_Tests (Report : in out NT.Reporter'Class) is begin Report.Section (""Base 256""); All_Tests_256 (Report); Report.End_Section; Report.Section (""Base 64""); All_Tests_64 (Report); Report.End_Section; Report.Section (""Base 4096""); All_Tests_4096 (Report); Report.End_Section; end All_Tests; ------------------------------ -- Test Suite for Each Base -- ------------------------------ procedure All_Tests_256 (Report : in out NT.Reporter'Class) is begin Test_Validity_256 (Report); Sample_Strings_256 (Report); Sample_Strings_VLV_256 (Report); end All_Tests_256; procedure All_Tests_4096 (Report : in out NT.Reporter'Class) is begin declare Dict : constant Smaz_4096.Dictionary := Dictionary_4096 (False); begin Report.Section (""Without variable-length verbatim""); Test_Validity_4096 (Report, Dict); Sample_Strings_4096 (Report, Dict); Impure_Stream_4096 (Report, Dict); Report.End_Section; end; declare Dict : constant Smaz_4096.Dictionary := Dictionary_4096 (True); begin Report.Section (""With variable-length verbatim""); Test_Validity_4096 (Report, Dict); Sample_Strings_VLV_4096 (Report, Dict); Report.End_Section; end; end All_Tests_4096; procedure All_Tests_64 (Report : in out NT.Reporter'Class) is begin Test_Validity_64 (Report); Sample_Strings_64 (Report); Sample_Strings_VLV_64 (Report); Impure_Stream_64 (Report); end All_Tests_64; ------------------------------- -- Individual Base-256 Tests -- ------------------------------- procedure Sample_Strings_256 (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item (""Roundtrip on sample strings without VLV""); Dict : constant Smaz_256.Dictionary := Dictionary_256_Without_VLV; begin Roundtrip_Test (Test, Dict, ""This is a small string"", (255, 84, 76, 56, 172, 62, 173, 152, 62, 195, 70)); Roundtrip_Test (Test, Dict, ""foobar"", (220, 6, 90, 79)); Roundtrip_Test (Test, Dict, ""the end"", (1, 171, 61)); Roundtrip_Test (Test, Dict, ""not-a-g00d-Exampl333"", (132, 204, 4, 204, 59, 254, 48, 48, 24, 204, 255, 69, 250, 4, 45, 60, 22, 254, 51, 51, 255, 51)); Roundtrip_Test (Test, Dict, ""Smaz is a simple compression library"", (255, 83, 173, 219, 56, 172, 62, 226, 60, 87, 161, 45, 60, 33, 166, 107, 205, 8, 90, 130, 12, 83)); Roundtrip_Test (Test, Dict, ""Nothing is more difficult, and therefore more precious, "" & ""than to be able to decide"", (255, 78, 223, 102, 99, 116, 45, 42, 11, 129, 44, 44, 131, 38, 22, 3, 148, 63, 210, 68, 11, 45, 42, 11, 60, 33, 28, 144, 164, 36, 203, 143, 96, 92, 25, 90, 87, 82, 165, 215, 237, 2)); Roundtrip_Test (Test, Dict, ""this is an example of what works very well with smaz"", (155, 56, 172, 41, 2, 250, 4, 45, 60, 87, 32, 159, 135, 65, 42, 255, 107, 23, 231, 71, 145, 152, 243, 227, 10, 173, 219)); Roundtrip_Test (Test, Dict, ""1000 numbers 2000 will 10 20 30 compress very little"", (254, 49, 48, 254, 48, 48, 236, 38, 45, 92, 221, 0, 254, 50, 48, 254, 48, 48, 243, 152, 0, 254, 49, 48, 0, 254, 50, 48, 0, 254, 51, 48, 161, 45, 60, 33, 166, 0, 231, 71, 151, 3, 3, 87)); Roundtrip_Test (Test, Dict, "": : : :"", (254, 58, 32, 254, 58, 32, 254, 58, 32, 255, 58)); exception when Error : others => Test.Report_Exception (Error); end Sample_Strings_256; procedure Sample_Strings_VLV_256 (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item (""Roundtrip on sample strings with variable-length verbatim""); begin Roundtrip_Test (Test, Smaz_Original.Dictionary, ""This is a small string"", (254, 84, 76, 56, 172, 62, 173, 152, 62, 195, 70)); Roundtrip_Test (Test, Smaz_Original.Dictionary, ""foobar"", (220, 6, 90, 79)); Roundtrip_Test (Test, Smaz_Original.Dictionary, ""the end"", (1, 171, 61)); Roundtrip_Test (Test, Smaz_Original.Dictionary, ""not-a-g00d-Exampl333"", (132, 204, 4, 204, 59, 255, 12, 48, 48, 100, 45, 69, 120, 97, 109, 112, 108, 51, 51, 51)); Roundtrip_Test (Test, Smaz_Original.Dictionary, ""Smaz is a simple compression library"", (254, 83, 173, 219, 56, 172, 62, 226, 60, 87, 161, 45, 60, 33, 166, 107, 205, 8, 90, 130, 12, 83)); Roundtrip_Test (Test, Smaz_Original.Dictionary, ""Nothing is more difficult, and therefore more precious, "" & ""than to be able to decide"", (254, 78, 223, 102, 99, 116, 45, 42, 11, 129, 44, 44, 131, 38, 22, 3, 148, 63, 210, 68, 11, 45, 42, 11, 60, 33, 28, 144, 164, 36, 203, 143, 96, 92, 25, 90, 87, 82, 165, 215, 237, 2)); Roundtrip_Test (Test, Smaz_Original.Dictionary, ""this is an example of what works very well with smaz"", (155, 56, 172, 41, 2, 250, 4, 45, 60, 87, 32, 159, 135, 65, 42, 254, 107, 23, 231, 71, 145, 152, 243, 227, 10, 173, 219)); Roundtrip_Test (Test, Smaz_Original.Dictionary, ""1000 numbers 2000 will 10 20 30 compress very little"", (255, 3, 49, 48, 48, 48, 236, 38, 45, 92, 221, 0, 255, 3, 50, 48, 48, 48, 243, 152, 0, 255, 7, 49, 48, 32, 50, 48, 32, 51, 48, 161, 45, 60, 33, 166, 0, 231, 71, 151, 3, 3, 87)); Roundtrip_Test (Test, Smaz_Original.Dictionary, "": : : :"", (255, 6, 58, 32, 58, 32, 58, 32, 58)); Roundtrip_Test (Test, Smaz_Original.Dictionary, (1 .. 300 => ':'), (1 .. 2 => 255, 3 .. 258 => 58, 259 => 255, 260 => 43, 261 .. 304 => 58)); exception when Error : others => Test.Report_Exception (Error); end Sample_Strings_VLV_256; procedure Test_Validity_256 (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item (""Test dictionary validity""); begin if not Natools.Smaz_256.Is_Valid (Smaz_Original.Dictionary) then Test.Fail; end if; exception when Error : others => Test.Report_Exception (Error); end Test_Validity_256; -------------------------------- -- Individual Base-4096 Tests -- -------------------------------- procedure Impure_Stream_4096 (Report : in out NT.Reporter'Class; Dictionary : in Smaz_4096.Dictionary) is Test : NT.Test := Report.Item (""Input stream with non-base-64 symbols""); begin declare CRLF : constant String := (Character'Val (13), Character'Val (10)); Input : constant Ada.Streams.Stream_Element_Array := To_SEA (""0vBdpYoBuYwAJbmB iWTXeYfdzCkAha3A"" & CRLF & ""GYKccXKcwAJbmBjb 2WqYmd//sA3ACYvB"" & CRLF & ""IdlAmBNVuZ3AwBeW IWeW"" & CRLF); Output : constant String := Smaz_4096.Decompress (Dictionary, Input); Expected : constant String := ""Nothing is more difficult, and therefore more precious, "" & ""than to be able to decide""; begin if Output /= Expected then Test.Fail (""Bad decompression""); Test.Info (""Found: """""" & Output & '""'); Test.Info (""Expected:"""""" & Expected & '""'); end if; end; exception when Error : others => Test.Report_Exception (Error); end Impure_Stream_4096; procedure Impure_Stream_4096 (Report : in out NT.Reporter'Class) is begin Impure_Stream_4096 (Report, Dictionary_4096 (False)); end Impure_Stream_4096; procedure Sample_Strings_4096 (Report : in out NT.Reporter'Class; Dictionary : in Smaz_4096.Dictionary) is Test : NT.Test := Report.Item (""Roundtrip on sample strings""); begin Roundtrip_Test (Test, Dictionary, ""This is a small string"", To_SEA (""JyuYsA0BiBscXVtBzcOcka"")); -- This is a small string Roundtrip_Test (Test, Dictionary, ""foobar"", To_SEA (""cX5adV"")); -- foobar Roundtrip_Test (Test, Dictionary, ""the end"", To_SEA (""BdmBBX//kB"")); -- the en Roundtrip_Test (Test, Dictionary, ""not-a-g00d-Exampl333"", To_SEA (""sa3/01SYtcGMwQWLTsYVdbxK"")); -- no< t-a -g0 0d->Exampl333 -- t-a 001011_10 1011_0100 10_000110 -- -g0 101101_00 1110_0110 00_001100 -- 0d- 000011_00 0010_0110 10_110100 Roundtrip_Test (Test, Dictionary, ""Smaz is a simple compression library"", To_SEA (""0xlVsA0BiBocTauZmAEbjbGXocFbvAdYGcec"")); -- Smaz is a simple compression library Roundtrip_Test (Test, Dictionary, ""Nothing is more difficult, and therefore more precious, "" & ""than to be able to decide"", To_SEA (""0vBdpYoBuYwAJbmBiWTXeYfdzCkAha3AGYKccXKcwAJbmBjb2WqYmd//sA"" -- Nothing is more difficult, and therefore more precious< ,> & ""3ACYvBIdlAmBNVuZ3AwBeWIWeW"")); -- than to be able to decide Roundtrip_Test (Test, Dictionary, ""this is an example of what works very well with smaz"", To_SEA (""BduYsA0BZVoAieTauZyAnBPefV6AJbiZ5AFX6BMe1Z6AvYpBsclV"")); -- this is an example of what works very well with smaz Roundtrip_Test (Test, Dictionary, ""1000 numbers 2000 will 10 20 30 compress very little"", To_SEA (""IH+AyaFaFX0BsI+AQe1ZBA+AUEDA+AOWTaKcyc5AFX6ByZNduZ"")); -- 1000 numbers 2*0 will 10 20 30 compress very little"", Roundtrip_Test (Test, Dictionary, "": : : :"", To_SEA (""5/6AiOgoDI6A"")); -- :_: 010111_00 0000_0100 01_011100 -- _:_ 000001_00 0101_1100 00_000100 -- : 010111_00 0000 Roundtrip_Test (Test, Dictionary, (1 .. 80 => ':'), To_SEA (Ada.Strings.Fixed.""*"" (2, ""c/"" & Ada.Strings.Fixed.""*"" (12, ""6ojO"")) & ""4/6ojO6ojO6oD"")); -- ::: 010111_00 0101_1100 01_011100 exception when Error : others => Test.Report_Exception (Error); end Sample_Strings_4096; procedure Sample_Strings_4096 (Report : in out NT.Reporter'Class) is begin Sample_Strings_4096 (Report, Dictionary_4096 (False)); end Sample_Strings_4096; procedure Sample_Strings_VLV_4096 (Report : in out NT.Reporter'Class; Dictionary : in Smaz_4096.Dictionary) is Test : NT.Test := Report.Item (""Roundtrip on sample strings""); begin Roundtrip_Test (Test, Dictionary, ""This is a small string"", To_SEA (""JyuYsA0BiBscXVtBzcOcka"")); -- This is a small string Roundtrip_Test (Test, Dictionary, ""foobar"", To_SEA (""cX5adV"")); -- foobar Roundtrip_Test (Test, Dictionary, ""the end"", To_SEA (""BdmBBX+/kB"")); -- the en Roundtrip_Test (Test, Dictionary, ""not-a-g00d-Exampl333"", To_SEA (""sa2/01SYtcGMwQWLTsYVdbxK"")); -- no< t-a -g0 0d->Exampl333 -- t-a 001011_10 1011_0100 10_000110 -- -g0 101101_00 1110_0110 00_001100 -- 0d- 000011_00 0010_0110 10_110100 Roundtrip_Test (Test, Dictionary, ""Smaz is a simple compression library"", To_SEA (""0xlVsA0BiBocTauZmAEbjbGXocFbvAdYGcec"")); -- Smaz is a simple compression library Roundtrip_Test (Test, Dictionary, ""Nothing is more difficult, and therefore more precious, "" & ""than to be able to decide"", To_SEA (""0vBdpYoBuYwAJbmBiWTXeYfdzCkAha3AGYKccXKcwAJbmBjb2WqYmd+/sA"" -- Nothing is more difficult, and therefore more precious< ,> & ""3ACYvBIdlAmBNVuZ3AwBeWIWeW"")); -- than to be able to decide Roundtrip_Test (Test, Dictionary, ""this is an example of what works very well with smaz"", To_SEA (""BduYsA0BZVoAieTauZyAnBPefV6AJbiZ5AFX6BMe1Z6AvYpBsclV"")); -- this is an example of what works very well with smaz Roundtrip_Test (Test, Dictionary, ""1000 numbers 2000 will 10 20 30 compress very little"", To_SEA (""IH+AyaFaFX0BsI+AQe1ZBA+AUEDA+AOWTaKcyc5AFX6ByZNduZ"")); -- 1000 numbers 2*0 will 10 20 30 compress very little"", Roundtrip_Test (Test, Dictionary, "": : : :"", To_SEA (""4/6AiOgoDI6A"")); -- :_: 010111_00 0000_0100 01_011100 -- _:_ 000001_00 0101_1100 00_000100 -- : 010111_00 0000 Roundtrip_Test (Test, Dictionary, (1 .. 4096 + 36 => ':'), To_SEA (""////"" & Ada.Strings.Fixed.""*"" (1377, ""6ojO"") & ""+/6A"")); -- ::: 010111_00 0101_1100 01_011100 exception when Error : others => Test.Report_Exception (Error); end Sample_Strings_VLV_4096; procedure Sample_Strings_VLV_4096 (Report : in out NT.Reporter'Class) is begin Sample_Strings_VLV_4096 (Report, Dictionary_4096 (True)); end Sample_Strings_VLV_4096; procedure Test_Validity_4096 (Report : in out NT.Reporter'Class; Dictionary : in Smaz_4096.Dictionary) is Test : NT.Test := Report.Item (""Test dictionary validity""); begin if not Smaz_4096.Is_Valid (Dictionary) then Test.Fail; end if; exception when Error : others => Test.Report_Exception (Error); end Test_Validity_4096; procedure Test_Validity_4096 (Report : in out NT.Reporter'Class) is begin Test_Validity_4096 (Report, Dictionary_4096 (False)); Test_Validity_4096 (Report, Dictionary_4096 (True)); end Test_Validity_4096; ------------------------------ -- Individual Base-64 Tests -- ------------------------------ procedure Impure_Stream_64 (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item (""Input stream with non-base-64 symbols""); begin declare CRLF : constant String := (Character'Val (13), Character'Val (10)); Input : constant Ada.Streams.Stream_Element_Array := To_SEA (""090kTgIW enLK3NFE FAEKs/Ao"" & CRLF & ""92dAFAzo +iBF1Sep HOvDJB0=""); Output : constant String := Smaz_64.Decompress (Dict_64, Input); Expected : constant String := ""'49 bytes of data to show a verbatim count issue'""; begin if Output /= Expected then Test.Fail (""Bad decompression""); Test.Info (""Found: """""" & Output & '""'); Test.Info (""Expected:"""""" & Expected & '""'); end if; end; exception when Error : others => Test.Report_Exception (Error); end Impure_Stream_64; procedure Sample_Strings_64 (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item (""Roundtrip on sample strings""); begin Roundtrip_Test (Test, Dict_64, ""Simple Test"", To_SEA (""+TBGSVYA+UBQE"")); -- imp* *t Roundtrip_Test (Test, Dict_64, ""SiT"", To_SEA (""/ATlGV"")); -- smaller than i (""+TBG+UB"") Roundtrip_Test (Test, Dict_64, ""sIMple TEST_WITH_14_B"", To_SEA (""D9J1EVYA8UVETR1XXlEVI9VM08lQ"")); -- sp* -- TE 001010_10 1010_0010 00 -- ST_ 110010_10 0010_1010 11_111010 -- WIT 111010_10 1001_0010 00_101010 -- H_1 000100_10 1111_1010 10_001100 -- 4_B 001011_00 1111_1010 01_000010 Roundtrip_Test (Test, Dict_64, ""'7B_Verbatim'"", To_SEA (""0+3IC9lVlJnYF1S0"")); -- '<7B_Verb >a*m' -- 7 111011_00 0100 -- B_V 010000_10 1111_1010 01_101010 -- erb 101001_10 0100_1110 01_000110 -- ""erb"" could have been encoded separately as ""o+iB"", which has -- the same length, but the tie is broken in favor of the longer -- verbatim fragment to help with corner cases. Roundtrip_Test (Test, Dict_64, ""'49 bytes of data to show a verbatim count issue'"", To_SEA (""090kTgIWenLK3NFEFAEKs/Ao92dAFAzo+iBF1SepHOvDJB0"")); -- '<49 by >tsof_ata_to_< how>_a_veatm_ontisue' -- e_ d s r i cu _s -- 49 001011_00 1001_1100 10 -- by 000001_00 0100_0110 10_011110 -- how 000101_10 1111_0110 11_101110 -- b 010001_10 0000 Roundtrip_Test (Test, Dict_64, Character'Val (16#C3#) & Character'Val (16#A9#) & 'v' & Character'Val (16#C3#) & Character'Val (16#A8#) & ""nement"", To_SEA (""Uz9DjKHBi"")); -- év<è >nement -- è 110000_11 0001_0101 00 Roundtrip_Test (Test, Dict_64, ""12345345345345345345345345"", To_SEA (""8xIzzQTNzQTNzQTNzQTNzQTNzQTNzQTN/AzQTN"")); -- Smallest 3n+2 that requires multiple verbatim blocks -- 12 100011_00 0100_1100 nn -- 345 110011_00 0010_1100 10_101100 exception when Error : others => Test.Report_Exception (Error); end Sample_Strings_64; procedure Sample_Strings_VLV_64 (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item (""Roundtrip on sample strings with variable-length verbatim""); begin Roundtrip_Test (Test, Dict_64_V, ""Simple Test"", To_SEA (""+TBGSVYA+UBQE"")); -- imp* *t Roundtrip_Test (Test, Dict_64_V, ""SiT"", To_SEA (""8TlGV"")); -- smaller than i (""+TBG+UB"") Roundtrip_Test (Test, Dict_64_V, ""sIMple TEST_WITH_14_B"", To_SEA (""D9J1EVYA/KUVETR1XXlEVI9VM08lQ"")); -- sp* < TE ST_ WIT H_1 4_B> -- TE 001010_10 1010_0010 00 -- ST_ 110010_10 0010_1010 11_111010 -- WIT 111010_10 1001_0010 00_101010 -- H_1 000100_10 1111_1010 10_001100 -- 4_B 001011_00 1111_1010 01_000010 Roundtrip_Test (Test, Dict_64_V, ""'7B_Verbatim'"", To_SEA (""0/D3AC9lVlJnYF1S0"")); -- '< 7B_Verb >a*m' -- 7 111011_00 0000 -- B_V 010000_10 1111_1010 01_101010 -- erb 101001_10 0100_1110 01_000110 exception when Error : others => Test.Report_Exception (Error); end Sample_Strings_VLV_64; procedure Test_Validity_64 (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item (""Test dictionary validity""); begin if not Natools.Smaz_64.Is_Valid (Dict_64) then Test.Fail; end if; if not Natools.Smaz_64.Is_Valid (Dict_64_V) then Test.Fail; end if; exception when Error : others => Test.Report_Exception (Error); end Test_Validity_64; end Natools.Smaz_Tests; ",12047,False,2119.8715380357253,median "[id=""buildconfig-build-openshift-io-v1""] = BuildConfig [build.openshift.io/v1] ifdef::product-title[] include::modules/common-attributes.adoc[] endif::[] toc::[] Description:: + -- Build configurations define a build process for new container images. There are three types of builds possible - a container image build using a Dockerfile, a Source-to-Image build that uses a specially prepared base image that accepts source code that it can make runnable, and a custom build that can run // arbitrary container images as a base and accept the build parameters. Builds run on the cluster and on completion are pushed to the container image registry specified in the ""output"" section. A build can be triggered via a webhook, when the base image changes, or when a user manually requests a new build be // created. Each build created by a build configuration is numbered and refers back to its parent configuration. Multiple builds can be triggered at once. Builds that do not have ""output"" set can be used to test code or run a verification build. -- Type:: `object` Required:: - `spec` == 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`] | | `spec` | `object` | BuildConfigSpec describes when and how builds are created | `status` | `object` | BuildConfigStatus contains current state of the build config object. |=== ..spec Description:: + -- BuildConfigSpec describes when and how builds are created -- Type:: `object` Required:: - `strategy` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `completionDeadlineSeconds` | `integer` | completionDeadlineSeconds is an optional duration in seconds, counted from the time when a build pod gets scheduled in the system, that the build may be active on a node before the system actively tries to terminate the build; value must be positive integer | `failedBuildsHistoryLimit` | `integer` | failedBuildsHistoryLimit is the number of old failed builds to retain. When a BuildConfig is created, the 5 most recent failed builds are retained unless this value is set. If removed after the BuildConfig has been created, all failed builds are retained. | `mountTrustedCA` | `boolean` | mountTrustedCA bind mounts the cluster's trusted certificate authorities, as defined in the cluster's proxy configuration, into the build. This lets processes within a build trust components signed by custom PKI certificate authorities, such as private artifact repositories and HTTPS proxies. When this field is set to true, the contents of `/etc/pki/ca-trust` within the build are managed by the build container, and any changes to this directory or its subdirectories (for example - within a Dockerfile `RUN` instruction) are not persisted in the build's output image. | `nodeSelector` | `object (string)` | nodeSelector is a selector which must be true for the build pod to fit on a node If nil, it can be overridden by default build nodeselector values for the cluster. If set to an empty map or a map with any values, default build nodeselector values are ignored. | `output` | `object` | BuildOutput is input to a build strategy and describes the container image that the strategy should produce. | `postCommit` | `object` | A BuildPostCommitSpec holds a build post commit hook specification. The hook executes a command in a temporary container running the build output image, immediately after the last layer of the image is committed and before the image is pushed to a registry. The command is executed with the current working directory ($PWD) set to the image's WORKDIR. The build will be marked as failed if the hook execution fails. It will fail if the script or command return a non-zero exit code, or if there is any other error related to starting the temporary container. There are five different ways to configure the hook. As an example, all forms below are equivalent and will execute `rake test --verbose`. 1. Shell script: ""postCommit"": { ""script"": ""rake test --verbose"", } The above is a convenient form which is equivalent to: ""postCommit"": { ""command"": [""/bin/sh"", ""-ic""], ""args"": [""rake test --verbose""] } 2. A command as the image entrypoint: ""postCommit"": { ""commit"": [""rake"", ""test"", ""--verbose""] } Command overrides the image entrypoint in the exec form, as documented in Docker: https://docs.docker.com/engine/reference/builder/#entrypoint. 3. Pass arguments to the default entrypoint: ""postCommit"": { ""args"": [""rake"", ""test"", ""--verbose""] } This form is only useful if the image entrypoint can handle arguments. 4. Shell script with arguments: ""postCommit"": { ""script"": ""rake test $1"", ""args"": [""--verbose""] } This form is useful if you need to pass arguments that would otherwise be hard to quote properly in the shell script. In the script, $0 will be ""/bin/sh"" and $1, $2, etc, are the positional arguments from Args. 5. Command with arguments: ""postCommit"": { ""command"": [""rake"", ""test""], ""args"": [""--verbose""] } This form is equivalent to appending the arguments to the Command slice. It is invalid to provide both Script and Command simultaneously. If none of the fields are specified, the hook is not executed. | `resources` | xref:../objects/index.adoc#resourcerequirements-core-v1[`ResourceRequirements core/v1`] | resources computes resource requirements to execute the build. | `revision` | `object` | SourceRevision is the revision or commit information from the source for the build | `runPolicy` | `string` | RunPolicy describes how the new build created from this build configuration will be scheduled for execution. This is optional, if not specified we default to ""Serial"". | `serviceAccount` | `string` | serviceAccount is the name of the ServiceAccount to use to run the pod created by this build. The pod will be allowed to use secrets referenced by the ServiceAccount | `source` | `object` | BuildSource is the SCM used for the build. | `strategy` | `object` | BuildStrategy contains the details of how to perform a build. | `successfulBuildsHistoryLimit` | `integer` | successfulBuildsHistoryLimit is the number of old successful builds to retain. When a BuildConfig is created, the 5 most recent successful builds are retained unless this value is set. If removed after the BuildConfig has been created, all successful builds are retained. | `triggers` | `array` | triggers determine how new Builds can be launched from a BuildConfig. If no triggers are defined, a new build can only occur as a result of an explicit client build creation. | `triggers[]` | `object` | BuildTriggerPolicy describes a policy for a single trigger that results in a new Build. |=== ..spec.output Description:: + -- BuildOutput is input to a build strategy and describes the container image that the strategy should produce. -- Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `imageLabels` | `array` | imageLabels define a list of labels that are applied to the resulting image. If there are multiple labels with the same name then the last one in the list is used. | `imageLabels[]` | `object` | ImageLabel represents a label applied to the resulting image. | `pushSecret` | xref:../objects/index.adoc#localobjectreference-core-v1[`LocalObjectReference core/v1`] | PushSecret is the name of a Secret that would be used for setting up the authentication for executing the Docker push to authentication enabled Docker Registry (or Docker Hub). | `to` | xref:../objects/index.adoc#objectreference-core-v1[`ObjectReference core/v1`] | to defines an optional location to push the output of this build to. Kind must be one of 'ImageStreamTag' or 'DockerImage'. This value will be used to look up a container image repository to push to. In the case of an ImageStreamTag, the ImageStreamTag will be looked for in the namespace of the build unless Namespace is specified. |=== ..spec.output.imageLabels Description:: + -- imageLabels define a list of labels that are applied to the resulting image. If there are multiple labels with the same name then the last one in the list is used. -- Type:: `array` ..spec.output.imageLabels[] Description:: + -- ImageLabel represents a label applied to the resulting image. -- Type:: `object` Required:: - `name` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `name` | `string` | name defines the name of the label. It must have non-zero length. | `value` | `string` | value defines the literal value of the label. |=== ..spec.postCommit Description:: + -- A BuildPostCommitSpec holds a build post commit hook specification. The hook executes a command in a temporary container running the build output image, immediately after the last layer of the image is committed and before the image is pushed to a registry. The command is executed with the current working directory ($PWD) set to the image's WORKDIR. The build will be marked as failed if the hook execution fails. It will fail if the script or command return a non-zero exit code, or if there is any other error related to starting the temporary container. There are five different ways to configure the hook. As an example, all forms below are equivalent and will execute `rake test --verbose`. 1. Shell script: ""postCommit"": { ""script"": ""rake test --verbose"", } The above is a convenient form which is equivalent to: ""postCommit"": { ""command"": [""/bin/sh"", ""-ic""], ""args"": [""rake test --verbose""] } 2. A command as the image entrypoint: ""postCommit"": { ""commit"": [""rake"", ""test"", ""--verbose""] } Command overrides the image entrypoint in the exec form, as documented in Docker: https://docs.docker.com/engine/reference/builder/#entrypoint. 3. Pass arguments to the default entrypoint: ""postCommit"": { ""args"": [""rake"", ""test"", ""--verbose""] } This form is only useful if the image entrypoint can handle arguments. 4. Shell script with arguments: ""postCommit"": { ""script"": ""rake test $1"", ""args"": [""--verbose""] } This form is useful if you need to pass arguments that would otherwise be hard to quote properly in the shell script. In the script, $0 will be ""/bin/sh"" and $1, $2, etc, are the positional arguments from Args. 5. Command with arguments: ""postCommit"": { ""command"": [""rake"", ""test""], ""args"": [""--verbose""] } This form is equivalent to appending the arguments to the Command slice. It is invalid to provide both Script and Command simultaneously. If none of the fields are specified, the hook is not executed. -- Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `args` | `array (string)` | args is a list of arguments that are provided to either Command, Script or the container image's default entrypoint. The arguments are placed immediately after the command to be run. | `command` | `array (string)` | command is the command to run. It may not be specified with Script. This might be needed if the image doesn't have `/bin/sh`, or if you do not want to use a shell. In all other cases, using Script might be more convenient. | `script` | `string` | script is a shell script to be run with `/bin/sh -ic`. It may not be specified with Command. Use Script when a shell script is appropriate to execute the post build hook, for example for running unit tests with `rake test`. If you need control over the image entrypoint, or if the image does not have `/bin/sh`, use Command and/or Args. The `-i` flag is needed to support CentOS and RHEL images that use Software Collections (SCL), in order to have the appropriate collections enabled in the shell. E.g., in the Ruby image, this is necessary to make `ruby`, `bundle` and other binaries available in the PATH. |=== ..spec.revision Description:: + -- SourceRevision is the revision or commit information from the source for the build -- Type:: `object` Required:: - `type` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `git` | `object` | GitSourceRevision is the commit information from a git source for a build | `type` | `string` | type of the build source, may be one of 'Source', 'Dockerfile', 'Binary', or 'Images' |=== ..spec.revision.git Description:: + -- GitSourceRevision is the commit information from a git source for a build -- Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `author` | `object` | SourceControlUser defines the identity of a user of source control | `commit` | `string` | commit is the commit hash identifying a specific commit | `committer` | `object` | SourceControlUser defines the identity of a user of source control | `message` | `string` | message is the description of a specific commit |=== ..spec.revision.git.author Description:: + -- SourceControlUser defines the identity of a user of source control -- Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `email` | `string` | email of the source control user | `name` | `string` | name of the source control user |=== ..spec.revision.git.committer Description:: + -- SourceControlUser defines the identity of a user of source control -- Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `email` | `string` | email of the source control user | `name` | `string` | name of the source control user |=== ..spec.source Description:: + -- BuildSource is the SCM used for the build. -- Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `binary` | `object` | BinaryBuildSource describes a binary file to be used for the Docker and Source build strategies, where the file will be extracted and used as the build source. | `configMaps` | `array` | configMaps represents a list of configMaps and their destinations that will be used for the build. | `configMaps[]` | `object` | ConfigMapBuildSource describes a configmap and its destination directory that will be used only at the build time. The content of the configmap referenced here will be copied into the destination directory instead of mounting. | `contextDir` | `string` | contextDir specifies the sub-directory where the source code for the application exists. This allows to have buildable sources in directory other than root of repository. | `dockerfile` | `string` | dockerfile is the raw contents of a Dockerfile which should be built. When this option is specified, the FROM may be modified based on your strategy base image and additional ENV stanzas from your strategy environment will be added after the FROM, but before the rest of your Dockerfile stanzas. The Dockerfile source type may be used with other options like git - in those cases the Git repo will have any innate Dockerfile replaced in the context dir. | `git` | `object` | GitBuildSource defines the parameters of a Git SCM | `images` | `array` | images describes a set of images to be used to provide source for the build | `images[]` | `object` | ImageSource is used to describe build source that will be extracted from an image or used during a multi stage build. A reference of type ImageStreamTag, ImageStreamImage or DockerImage may be used. A pull secret can be specified to pull the image from an external registry or override the default service account secret if pulling from the internal registry. Image sources can either be used to extract content from an image and place it into the build context along with the repository source, or used directly during a multi-stage container image build to allow content to be copied without overwriting the contents of the repository source (see the 'paths' and 'as' fields). | `secrets` | `array` | secrets represents a list of secrets and their destinations that will be used only for the build. | `secrets[]` | `object` | SecretBuildSource describes a secret and its destination directory that will be used only at the build time. The content of the secret referenced here will be copied into the destination directory instead of mounting. | `sourceSecret` | xref:../objects/index.adoc#localobjectreference-core-v1[`LocalObjectReference core/v1`] | sourceSecret is the name of a Secret that would be used for setting up the authentication for cloning private repository. The secret contains valid credentials for remote repository, where the data's key represent the authentication method to be used and value is the base64 encoded credentials. Supported auth methods are: ssh-privatekey. | `type` | `string` | type of build input to accept |=== ..spec.source.binary Description:: + -- BinaryBuildSource describes a binary file to be used for the Docker and Source build strategies, where the file will be extracted and used as the build source. -- Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `asFile` | `string` | asFile indicates that the provided binary input should be considered a single file within the build input. For example, specifying ""webapp.war"" would place the provided binary as `/webapp.war` for the builder. If left empty, the Docker and Source build strategies assume this file is a zip, tar, or tar.gz file and extract it as the source. The custom strategy receives this binary as standard input. This filename may not contain slashes or be '..' or '.'. |=== ..spec.source.configMaps Description:: + -- configMaps represents a list of configMaps and their destinations that will be used for the build. -- Type:: `array` ..spec.source.configMaps[] Description:: + -- ConfigMapBuildSource describes a configmap and its destination directory that will be used only at the build time. The content of the configmap referenced here will be copied into the destination directory instead of mounting. -- Type:: `object` Required:: - `configMap` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `configMap` | xref:../objects/index.adoc#localobjectreference-core-v1[`LocalObjectReference core/v1`] | configMap is a reference to an existing configmap that you want to use in your build. | `destinationDir` | `string` | destinationDir is the directory where the files from the configmap should be available for the build time. For the Source build strategy, these will be injected into a container where the assemble script runs. For the container image build strategy, these will be copied into the build directory, where the Dockerfile is located, so users can ADD or COPY them during container image build. |=== ..spec.source.git Description:: + -- GitBuildSource defines the parameters of a Git SCM -- Type:: `object` Required:: - `uri` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `httpProxy` | `string` | httpProxy is a proxy used to reach the git repository over http | `httpsProxy` | `string` | httpsProxy is a proxy used to reach the git repository over https | `noProxy` | `string` | noProxy is the list of domains for which the proxy should not be used | `ref` | `string` | ref is the branch/tag/ref to build. | `uri` | `string` | uri points to the source that will be built. The structure of the source will depend on the type of build to run |=== ..spec.source.images Description:: + -- images describes a set of images to be used to provide source for the build -- Type:: `array` ..spec.source.images[] Description:: + -- ImageSource is used to describe build source that will be extracted from an image or used during a multi stage build. A reference of type ImageStreamTag, ImageStreamImage or DockerImage may be used. A pull secret can be specified to pull the image from an external registry or override the default service account secret if pulling from the internal registry. Image sources can either be used to extract content from an image and place it into the build context along with the repository source, or used directly during a multi-stage container image build to allow content to be copied without overwriting the contents of the repository source (see the 'paths' and 'as' fields). -- Type:: `object` Required:: - `from` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `as` | `array (string)` | A list of image names that this source will be used in place of during a multi-stage container image build. For instance, a Dockerfile that uses ""COPY --from=nginx:latest"" will first check for an image source that has ""nginx:latest"" in this field before attempting to pull directly. If the Dockerfile does not reference an image source it is ignored. This field and paths may both be set, in which case the contents will be used twice. | `from` | xref:../objects/index.adoc#objectreference-core-v1[`ObjectReference core/v1`] | from is a reference to an ImageStreamTag, ImageStreamImage, or DockerImage to copy source from. | `paths` | `array` | paths is a list of source and destination paths to copy from the image. This content will be copied into the build context prior to starting the build. If no paths are set, the build context will not be altered. | `paths[]` | `object` | ImageSourcePath describes a path to be copied from a source image and its destination within the build directory. | `pullSecret` | xref:../objects/index.adoc#localobjectreference-core-v1[`LocalObjectReference core/v1`] | pullSecret is a reference to a secret to be used to pull the image from a registry If the image is pulled from the OpenShift registry, this field does not need to be set. |=== ..spec.source.images[].paths Description:: + -- paths is a list of source and destination paths to copy from the image. This content will be copied into the build context prior to starting the build. If no paths are set, the build context will not be altered. -- Type:: `array` ..spec.source.images[].paths[] Description:: + -- ImageSourcePath describes a path to be copied from a source image and its destination within the build directory. -- Type:: `object` Required:: - `sourcePath` - `destinationDir` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `destinationDir` | `string` | destinationDir is the relative directory within the build directory where files copied from the image are placed. | `sourcePath` | `string` | sourcePath is the absolute path of the file or directory inside the image to copy to the build directory. If the source path ends in /. then the content of the directory will be copied, but the directory itself will not be created at the destination. |=== ..spec.source.secrets Description:: + -- secrets represents a list of secrets and their destinations that will be used only for the build. -- Type:: `array` ..spec.source.secrets[] Description:: + -- SecretBuildSource describes a secret and its destination directory that will be used only at the build time. The content of the secret referenced here will be copied into the destination directory instead of mounting. -- Type:: `object` Required:: - `secret` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `destinationDir` | `string` | destinationDir is the directory where the files from the secret should be available for the build time. For the Source build strategy, these will be injected into a container where the assemble script runs. Later, when the script finishes, all files injected will be truncated to zero length. For the container image build strategy, these will be copied into the build directory, where the Dockerfile is located, so users can ADD or COPY them during container image build. | `secret` | xref:../objects/index.adoc#localobjectreference-core-v1[`LocalObjectReference core/v1`] | secret is a reference to an existing secret that you want to use in your build. |=== ..spec.strategy Description:: + -- BuildStrategy contains the details of how to perform a build. -- Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `customStrategy` | `object` | CustomBuildStrategy defines input parameters specific to Custom build. | `dockerStrategy` | `object` | DockerBuildStrategy defines input parameters specific to container image build. | `jenkinsPipelineStrategy` | `object` | JenkinsPipelineBuildStrategy holds parameters specific to a Jenkins Pipeline build. Deprecated: use OpenShift Pipelines | `sourceStrategy` | `object` | SourceBuildStrategy defines input parameters specific to an Source build. | `type` | `string` | type is the kind of build strategy. |=== ..spec.strategy.customStrategy Description:: + -- CustomBuildStrategy defines input parameters specific to Custom build. -- Type:: `object` Required:: - `from` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `buildAPIVersion` | `string` | buildAPIVersion is the requested API version for the Build object serialized and passed to the custom builder | `env` | xref:../objects/index.adoc#envvar-core-v1[`array (EnvVar core/v1)`] | env contains additional environment variables you want to pass into a builder container. | `exposeDockerSocket` | `boolean` | exposeDockerSocket will allow running Docker commands (and build container images) from inside the container. | `forcePull` | `boolean` | forcePull describes if the controller should configure the build pod to always pull the images for the builder or only pull if it is not present locally | `from` | xref:../objects/index.adoc#objectreference-core-v1[`ObjectReference core/v1`] | from is reference to an DockerImage, ImageStreamTag, or ImageStreamImage from which the container image should be pulled | `pullSecret` | xref:../objects/index.adoc#localobjectreference-core-v1[`LocalObjectReference core/v1`] | pullSecret is the name of a Secret that would be used for setting up the authentication for pulling the container images from the private Docker registries | `secrets` | `array` | secrets is a list of additional secrets that will be included in the build pod | `secrets[]` | `object` | SecretSpec specifies a secret to be included in a build pod and its corresponding mount point |=== ..spec.strategy.customStrategy.secrets Description:: + -- secrets is a list of additional secrets that will be included in the build pod -- Type:: `array` ..spec.strategy.customStrategy.secrets[] Description:: + -- SecretSpec specifies a secret to be included in a build pod and its corresponding mount point -- Type:: `object` Required:: - `secretSource` - `mountPath` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `mountPath` | `string` | mountPath is the path at which to mount the secret | `secretSource` | xref:../objects/index.adoc#localobjectreference-core-v1[`LocalObjectReference core/v1`] | secretSource is a reference to the secret |=== ..spec.strategy.dockerStrategy Description:: + -- DockerBuildStrategy defines input parameters specific to container image build. -- Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `buildArgs` | xref:../objects/index.adoc#envvar-core-v1[`array (EnvVar core/v1)`] | buildArgs contains build arguments that will be resolved in the Dockerfile. See https://docs.docker.com/engine/reference/builder/#/arg for more details. | `dockerfilePath` | `string` | dockerfilePath is the path of the Dockerfile that will be used to build the container image, relative to the root of the context (contextDir). Defaults to `Dockerfile` if unset. | `env` | xref:../objects/index.adoc#envvar-core-v1[`array (EnvVar core/v1)`] | env contains additional environment variables you want to pass into a builder container. | `forcePull` | `boolean` | forcePull describes if the builder should pull the images from registry prior to building. | `from` | xref:../objects/index.adoc#objectreference-core-v1[`ObjectReference core/v1`] | from is a reference to an DockerImage, ImageStreamTag, or ImageStreamImage which overrides the FROM image in the Dockerfile for the build. If the Dockerfile uses multi-stage builds, this will replace the image in the last FROM directive of the file. | `imageOptimizationPolicy` | `string` | imageOptimizationPolicy describes what optimizations the system can use when building images to reduce the final size or time spent building the image. The default policy is 'None' which means the final build image will be equivalent to an image created by the container image build API. The experimental policy 'SkipLayers' will avoid commiting new layers in between each image step, and will fail if the Dockerfile cannot provide compatibility with the 'None' policy. An additional experimental policy 'SkipLayersAndWarn' is the same as 'SkipLayers' but simply warns if compatibility cannot be preserved. | `noCache` | `boolean` | noCache if set to true indicates that the container image build must be executed with the --no-cache=true flag | `pullSecret` | xref:../objects/index.adoc#localobjectreference-core-v1[`LocalObjectReference core/v1`] | pullSecret is the name of a Secret that would be used for setting up the authentication for pulling the container images from the private Docker registries |=== ..spec.strategy.jenkinsPipelineStrategy Description:: + -- JenkinsPipelineBuildStrategy holds parameters specific to a Jenkins Pipeline build. Deprecated: use OpenShift Pipelines -- Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `env` | xref:../objects/index.adoc#envvar-core-v1[`array (EnvVar core/v1)`] | env contains additional environment variables you want to pass into a build pipeline. | `jenkinsfile` | `string` | Jenkinsfile defines the optional raw contents of a Jenkinsfile which defines a Jenkins pipeline build. | `jenkinsfilePath` | `string` | JenkinsfilePath is the optional path of the Jenkinsfile that will be used to configure the pipeline relative to the root of the context (contextDir). If both JenkinsfilePath & Jenkinsfile are both not specified, this defaults to Jenkinsfile in the root of the specified contextDir. |=== ..spec.strategy.sourceStrategy Description:: + -- SourceBuildStrategy defines input parameters specific to an Source build. -- Type:: `object` Required:: - `from` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `env` | xref:../objects/index.adoc#envvar-core-v1[`array (EnvVar core/v1)`] | env contains additional environment variables you want to pass into a builder container. | `forcePull` | `boolean` | forcePull describes if the builder should pull the images from registry prior to building. | `from` | xref:../objects/index.adoc#objectreference-core-v1[`ObjectReference core/v1`] | from is reference to an DockerImage, ImageStreamTag, or ImageStreamImage from which the container image should be pulled | `incremental` | `boolean` | incremental flag forces the Source build to do incremental builds if true. | `pullSecret` | xref:../objects/index.adoc#localobjectreference-core-v1[`LocalObjectReference core/v1`] | pullSecret is the name of a Secret that would be used for setting up the authentication for pulling the container images from the private Docker registries | `scripts` | `string` | scripts is the location of Source scripts |=== ..spec.triggers Description:: + -- triggers determine how new Builds can be launched from a BuildConfig. If no triggers are defined, a new build can only occur as a result of an explicit client build creation. -- Type:: `array` ..spec.triggers[] Description:: + -- BuildTriggerPolicy describes a policy for a single trigger that results in a new Build. -- Type:: `object` Required:: - `type` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `bitbucket` | `object` | WebHookTrigger is a trigger that gets invoked using a webhook type of post | `generic` | `object` | WebHookTrigger is a trigger that gets invoked using a webhook type of post | `github` | `object` | WebHookTrigger is a trigger that gets invoked using a webhook type of post | `gitlab` | `object` | WebHookTrigger is a trigger that gets invoked using a webhook type of post | `imageChange` | `object` | ImageChangeTrigger allows builds to be triggered when an ImageStream changes | `type` | `string` | type is the type of build trigger. Valid values: - GitHub GitHubWebHookBuildTriggerType represents a trigger that launches builds on GitHub webhook invocations - Generic GenericWebHookBuildTriggerType represents a trigger that launches builds on generic webhook invocations - GitLab GitLabWebHookBuildTriggerType represents a trigger that launches builds on GitLab webhook invocations - Bitbucket BitbucketWebHookBuildTriggerType represents a trigger that launches builds on Bitbucket webhook invocations - ImageChange ImageChangeBuildTriggerType represents a trigger that launches builds on availability of a new version of an image - ConfigChange ConfigChangeBuildTriggerType will trigger a build on an initial build config creation WARNING: In the future the behavior will change to trigger a build on any config change |=== ..spec.triggers[].bitbucket Description:: + -- WebHookTrigger is a trigger that gets invoked using a webhook type of post -- Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `allowEnv` | `boolean` | allowEnv determines whether the webhook can set environment variables; can only be set to true for GenericWebHook. | `secret` | `string` | secret used to validate requests. Deprecated: use SecretReference instead. | `secretReference` | `object` | SecretLocalReference contains information that points to the local secret being used |=== ..spec.triggers[].bitbucket.secretReference Description:: + -- SecretLocalReference contains information that points to the local secret being used -- Type:: `object` Required:: - `name` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `name` | `string` | Name is the name of the resource in the same namespace being referenced |=== ..spec.triggers[].generic Description:: + -- WebHookTrigger is a trigger that gets invoked using a webhook type of post -- Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `allowEnv` | `boolean` | allowEnv determines whether the webhook can set environment variables; can only be set to true for GenericWebHook. | `secret` | `string` | secret used to validate requests. Deprecated: use SecretReference instead. | `secretReference` | `object` | SecretLocalReference contains information that points to the local secret being used |=== ..spec.triggers[].generic.secretReference Description:: + -- SecretLocalReference contains information that points to the local secret being used -- Type:: `object` Required:: - `name` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `name` | `string` | Name is the name of the resource in the same namespace being referenced |=== ..spec.triggers[].github Description:: + -- WebHookTrigger is a trigger that gets invoked using a webhook type of post -- Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `allowEnv` | `boolean` | allowEnv determines whether the webhook can set environment variables; can only be set to true for GenericWebHook. | `secret` | `string` | secret used to validate requests. Deprecated: use SecretReference instead. | `secretReference` | `object` | SecretLocalReference contains information that points to the local secret being used |=== ..spec.triggers[].github.secretReference Description:: + -- SecretLocalReference contains information that points to the local secret being used -- Type:: `object` Required:: - `name` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `name` | `string` | Name is the name of the resource in the same namespace being referenced |=== ..spec.triggers[].gitlab Description:: + -- WebHookTrigger is a trigger that gets invoked using a webhook type of post -- Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `allowEnv` | `boolean` | allowEnv determines whether the webhook can set environment variables; can only be set to true for GenericWebHook. | `secret` | `string` | secret used to validate requests. Deprecated: use SecretReference instead. | `secretReference` | `object` | SecretLocalReference contains information that points to the local secret being used |=== ..spec.triggers[].gitlab.secretReference Description:: + -- SecretLocalReference contains information that points to the local secret being used -- Type:: `object` Required:: - `name` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `name` | `string` | Name is the name of the resource in the same namespace being referenced |=== ..spec.triggers[].imageChange Description:: + -- ImageChangeTrigger allows builds to be triggered when an ImageStream changes -- Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `from` | xref:../objects/index.adoc#objectreference-core-v1[`ObjectReference core/v1`] | from is a reference to an ImageStreamTag that will trigger a build when updated It is optional. If no From is specified, the From image from the build strategy will be used. Only one ImageChangeTrigger with an empty From reference is allowed in a build configuration. | `lastTriggeredImageID` | `string` | lastTriggeredImageID is used internally by the ImageChangeController to save last used image ID for build This field is deprecated and will be removed in a future release. Deprecated | `paused` | `boolean` | paused is true if this trigger is temporarily disabled. Optional. |=== ..status Description:: + -- BuildConfigStatus contains current state of the build config object. -- Type:: `object` Required:: - `lastVersion` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `imageChangeTriggers` | `array` | ImageChangeTriggers captures the runtime state of any ImageChangeTrigger specified in the BuildConfigSpec, including the value reconciled by the OpenShift APIServer for the lastTriggeredImageID. There is a single entry in this array for each image change trigger in spec. Each trigger status references the ImageStreamTag that acts as the source of the trigger. | `imageChangeTriggers[]` | `object` | ImageChangeTriggerStatus tracks the latest resolved status of the associated ImageChangeTrigger policy specified in the BuildConfigSpec.Triggers struct. | `lastVersion` | `integer` | lastVersion is used to inform about number of last triggered build. |=== ..status.imageChangeTriggers Description:: + -- ImageChangeTriggers captures the runtime state of any ImageChangeTrigger specified in the BuildConfigSpec, including the value reconciled by the OpenShift APIServer for the lastTriggeredImageID. There is a single entry in this array for each image change trigger in spec. Each trigger status references the ImageStreamTag that acts as the source of the trigger. -- Type:: `array` ..status.imageChangeTriggers[] Description:: + -- ImageChangeTriggerStatus tracks the latest resolved status of the associated ImageChangeTrigger policy specified in the BuildConfigSpec.Triggers struct. -- Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `from` | `object` | ImageStreamTagReference references the ImageStreamTag in an image change trigger by namespace and name. | `lastTriggerTime` | xref:../objects/index.adoc#time-meta-v1[`Time meta/v1`] | lastTriggerTime is the last time this particular ImageStreamTag triggered a Build to start. This field is only updated when this trigger specifically started a Build. | `lastTriggeredImageID` | `string` | lastTriggeredImageID represents the sha/id of the ImageStreamTag when a Build for this BuildConfig was started. The lastTriggeredImageID is updated each time a Build for this BuildConfig is started, even if this ImageStreamTag is not the reason the Build is started. |=== ..status.imageChangeTriggers[].from Description:: + -- ImageStreamTagReference references the ImageStreamTag in an image change trigger by namespace and name. -- Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `name` | `string` | name is the name of the ImageStreamTag for an ImageChangeTrigger | `namespace` | `string` | namespace is the namespace where the ImageStreamTag for an ImageChangeTrigger is located |=== == API endpoints The following API endpoints are available: * `/apis/build.openshift.io/v1/buildconfigs` - `GET`: list or watch objects of kind BuildConfig * `/apis/build.openshift.io/v1/namespaces/{namespace}/buildconfigs` - `DELETE`: delete collection of BuildConfig - `GET`: list or watch objects of kind BuildConfig - `POST`: create a BuildConfig * `/apis/build.openshift.io/v1/namespaces/{namespace}/buildconfigs/{name}` - `DELETE`: delete a BuildConfig - `GET`: read the specified BuildConfig - `PATCH`: partially update the specified BuildConfig - `PUT`: replace the specified BuildConfig * `/apis/build.openshift.io/v1/namespaces/{namespace}/buildconfigs/{name}/webhooks` - `POST`: connect POST requests to webhooks of BuildConfig * `/apis/build.openshift.io/v1/namespaces/{namespace}/buildconfigs/{name}/instantiate` - `POST`: create instantiate of a BuildConfig * `/apis/build.openshift.io/v1/namespaces/{namespace}/buildconfigs/{name}/webhooks/{path}` - `POST`: connect POST requests to webhooks of BuildConfig * `/apis/build.openshift.io/v1/namespaces/{namespace}/buildconfigs/{name}/instantiatebinary` - `POST`: connect POST requests to instantiatebinary of BuildConfig === /apis/build.openshift.io/v1/buildconfigs .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. 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` | 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:: list or watch objects of kind BuildConfig .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#buildconfiglist-build-openshift-io-v1[`BuildConfigList build.openshift.io/v1`] |=== === /apis/build.openshift.io/v1/namespaces/{namespace}/buildconfigs .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 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 BuildConfig .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#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`] |=== HTTP method:: `GET` Description:: list or watch objects of kind BuildConfig .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` | 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#buildconfiglist-build-openshift-io-v1[`BuildConfigList build.openshift.io/v1`] |=== HTTP method:: `POST` Description:: create a BuildConfig .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:../workloads_apis/buildconfig-build-openshift-io-v1.adoc#buildconfig-build-openshift-io-v1[`BuildConfig build.openshift.io/v1`] | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../workloads_apis/buildconfig-build-openshift-io-v1.adoc#buildconfig-build-openshift-io-v1[`BuildConfig build.openshift.io/v1`] |=== === /apis/build.openshift.io/v1/namespaces/{namespace}/buildconfigs/{name} .Global path parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `name` | `string` | name of the BuildConfig | `namespace` | `string` | object name and auth scope, such as for teams and projects |=== .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 BuildConfig .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`] |=== HTTP method:: `GET` Description:: read the specified BuildConfig .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../workloads_apis/buildconfig-build-openshift-io-v1.adoc#buildconfig-build-openshift-io-v1[`BuildConfig build.openshift.io/v1`] |=== HTTP method:: `PATCH` Description:: partially update the specified BuildConfig .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#patch-meta-v1[`Patch meta/v1`] | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../workloads_apis/buildconfig-build-openshift-io-v1.adoc#buildconfig-build-openshift-io-v1[`BuildConfig build.openshift.io/v1`] |=== HTTP method:: `PUT` Description:: replace the specified BuildConfig .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:../workloads_apis/buildconfig-build-openshift-io-v1.adoc#buildconfig-build-openshift-io-v1[`BuildConfig build.openshift.io/v1`] | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../workloads_apis/buildconfig-build-openshift-io-v1.adoc#buildconfig-build-openshift-io-v1[`BuildConfig build.openshift.io/v1`] |=== === /apis/build.openshift.io/v1/namespaces/{namespace}/buildconfigs/{name}/webhooks .Global path parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `name` | `string` | name of the Build | `namespace` | `string` | object name and auth scope, such as for teams and projects |=== .Global query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `path` | `string` | Path is the URL path to use for the current proxy request to pod. |=== HTTP method:: `POST` Description:: connect POST requests to webhooks of BuildConfig .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | `string` |=== === /apis/build.openshift.io/v1/namespaces/{namespace}/buildconfigs/{name}/instantiate .Global path parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `name` | `string` | name of the BuildRequest | `namespace` | `string` | object name and auth scope, such as for teams and projects |=== .Global 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. | `pretty` | `string` | If 'true', then the output is pretty printed. |=== HTTP method:: `POST` Description:: create instantiate of a BuildConfig .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../objects/index.adoc#buildrequest-build-openshift-io-v1[`BuildRequest build.openshift.io/v1`] | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../workloads_apis/build-build-openshift-io-v1.adoc#build-build-openshift-io-v1[`Build build.openshift.io/v1`] |=== === /apis/build.openshift.io/v1/namespaces/{namespace}/buildconfigs/{name}/webhooks/{path} .Global path parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `name` | `string` | name of the Build | `namespace` | `string` | object name and auth scope, such as for teams and projects | `path` | `string` | path to the resource |=== .Global query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `path` | `string` | Path is the URL path to use for the current proxy request to pod. |=== HTTP method:: `POST` Description:: connect POST requests to webhooks of BuildConfig .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | `string` |=== === /apis/build.openshift.io/v1/namespaces/{namespace}/buildconfigs/{name}/instantiatebinary .Global path parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `name` | `string` | name of the BinaryBuildRequestOptions | `namespace` | `string` | object name and auth scope, such as for teams and projects |=== .Global query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `asFile` | `string` | asFile determines if the binary should be created as a file within the source rather than extracted as an archive | `revision.authorEmail` | `string` | revision.authorEmail of the source control user | `revision.authorName` | `string` | revision.authorName of the source control user | `revision.commit` | `string` | revision.commit is the value identifying a specific commit | `revision.committerEmail` | `string` | revision.committerEmail of the source control user | `revision.committerName` | `string` | revision.committerName of the source control user | `revision.message` | `string` | revision.message is the description of a specific commit |=== HTTP method:: `POST` Description:: connect POST requests to instantiatebinary of BuildConfig .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../workloads_apis/build-build-openshift-io-v1.adoc#build-build-openshift-io-v1[`Build build.openshift.io/v1`] |=== ",16231,True,3030.120163521554,median " -1 dilate_0_0_2160_3840_0_3_3_1_1_s 0 4 0 1 1 imgHelper2_4102 0 0 0 FIFO_SRL 49 8 0 3 0 0 0 1 2 imgHelper3_4103 0 0 0 FIFO_SRL 49 8 1 3 0 0 0 1 3 p_src_rows 0 0 0 FIFO_SRL 49 32 0 3 0 0 0 1 4 p_src_cols 0 0 0 FIFO_SRL 52 32 0 3 0 0 0 6 0 0 11 p_src_rows_read /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip/vitis_lib/vision/L1/include/imgproc/xf_dilation.hpp .. 340 dilate&lt;0, 0, 2160, 3840, 0, 3, 3, 1, 1&gt; dilate_0_0_2160_3840_0_3_3_1_1_s 1 0 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip 1 0 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip/vitis_lib/vision/L1/include/imgproc/xf_dilation.hpp dilate&lt;0, 0, 2160, 3840, 0, 3, 3, 1, 1&gt; 340 auto fifo srl FIFO_SRL 81 32 2 0 19 20 read 0 0 0 0 3.28 1 -1 0 12 p_src_cols_read /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip/vitis_lib/vision/L1/include/imgproc/xf_dilation.hpp .. 341 dilate&lt;0, 0, 2160, 3840, 0, 3, 3, 1, 1&gt; dilate_0_0_2160_3840_0_3_3_1_1_s 1 0 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip 1 0 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip/vitis_lib/vision/L1/include/imgproc/xf_dilation.hpp dilate&lt;0, 0, 2160, 3840, 0, 3, 3, 1, 1&gt; 341 auto fifo srl FIFO_SRL 81 32 2 0 21 22 read 0 0 0 0 3.28 2 -1 0 13 trunc_ln340 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip/vitis_lib/vision/L1/include/imgproc/xf_dilation.hpp .. 340 dilate&lt;0, 0, 2160, 3840, 0, 3, 3, 1, 1&gt; dilate_0_0_2160_3840_0_3_3_1_1_s 1 0 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip 1 0 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip/vitis_lib/vision/L1/include/imgproc/xf_dilation.hpp dilate&lt;0, 0, 2160, 3840, 0, 3, 3, 1, 1&gt; 340 trunc_ln340_fu_52_p1 113 16 1 0 23 trunc 0 0 0 0 0.00 3 -1 0 14 trunc_ln341 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip/vitis_lib/vision/L1/include/imgproc/xf_dilation.hpp .. 341 dilate&lt;0, 0, 2160, 3840, 0, 3, 3, 1, 1&gt; dilate_0_0_2160_3840_0_3_3_1_1_s 1 0 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip 1 0 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip/vitis_lib/vision/L1/include/imgproc/xf_dilation.hpp dilate&lt;0, 0, 2160, 3840, 0, 3, 3, 1, 1&gt; 341 trunc_ln341_fu_57_p1 113 16 1 0 24 trunc 0 0 0 0 0.00 4 -1 0 15 _ln376 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip/vitis_lib/vision/L1/include/imgproc/xf_dilation.hpp .. 376 dilate&lt;0, 0, 2160, 3840, 0, 3, 3, 1, 1&gt; dilate_0_0_2160_3840_0_3_3_1_1_s 1 0 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip 1 0 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip/vitis_lib/vision/L1/include/imgproc/xf_dilation.hpp dilate&lt;0, 0, 2160, 3840, 0, 3, 3, 1, 1&gt; 376 grp_xfdilate_2160_3840_1_0_1_0_3841_3_3_s_fu_42 113 0 5 0 26 27 28 29 30 call 0 0 0 0 0.00 5 -1 0 16 _ln0 0 0 0 49 0 0 0 ret 0 0 0 0 0.00 6 -1 1 0 2 25 xfdilate_2160_3840_1_0_1_0_3841_3_3_s 0 0 0 97 0 6 <constant:xfdilate<2160, 3840, 1, 0, 1, 0, 3841, 3, 3>> 1 0 3 17 dilate<0, 0, 2160, 3840, 0, 3, 3, 1, 1> 0 0 0 1768189039 6 0 11 12 13 14 15 16 9 0 20 1 3 11 0 22 1 4 12 0 23 1 11 13 0 24 1 12 14 0 26 1 25 15 0 27 1 1 15 0 28 1 2 15 0 29 1 13 15 0 30 1 14 15 0 1 0 1 dilate<0, 0, 2160, 3840, 0, 3, 3, 1, 1> dilate_0_0_2160_3840_0_3_3_1_1_s 0 0 0 1 0 17 -1 -1 -1 -1 13 8319373 0 2 0 1 5 0 11 1 1 12 1 1 13 1 1 14 1 1 15 2 2 2 8 0 5 1 1 6 1 1 7 1 1 8 1 1 9 1 1 10 1 1 15 1 2 16 1 1 1 0 1 2 -1 1 0 0 0 1 0 grp_xfdilate_2160_3840_1_0_1_0_3841_3_3_s_fu_42 (xfdilate_2160_3840_1_0_1_0_3841_3_3_s) 3 0 BRAM 6 FF 611 LUT 819 1 0 ap_block_state1 ( or ) 4 0 (0P0) 1 (1P1) 1 FF 0 LUT 1 0 0 0 0 6 0 ap_NS_fsm 4 0 (0Size) 3 (1Bits) 1 (2Count) 3 LUT 13 ap_done 4 0 (0Size) 2 (1Bits) 1 (2Count) 2 LUT 9 imgHelper2_4102_read 4 0 (0Size) 2 (1Bits) 1 (2Count) 2 LUT 9 imgHelper3_4103_write 4 0 (0Size) 2 (1Bits) 1 (2Count) 2 LUT 9 p_src_cols_blk_n 4 0 (0Size) 2 (1Bits) 1 (2Count) 2 LUT 9 p_src_rows_blk_n 4 0 (0Size) 2 (1Bits) 1 (2Count) 2 LUT 9 5 0 ap_CS_fsm 3 0 (Bits) 2 (Consts) 0 FF 2 ap_done_reg 3 0 (Bits) 1 (Consts) 0 FF 1 grp_xfdilate_2160_3840_1_0_1_0_3841_3_3_s_fu_42_ap_start_reg 3 0 (Bits) 1 (Consts) 0 FF 1 trunc_ln340_reg_62 3 0 (Bits) 16 (Consts) 0 FF 16 trunc_ln341_reg_67 3 0 (Bits) 16 (Consts) 0 FF 16 1 0 grp_xfdilate_2160_3840_1_0_1_0_3841_3_3_s_fu_42 0 0 1 0 grp_xfdilate_2160_3840_1_0_1_0_3841_3_3_s_fu_42 (xfdilate_2160_3840_1_0_1_0_3841_3_3_s) 1 0 15 0 0 0 0 0 0 6 0 11 0 0 12 0 0 13 0 0 14 0 0 15 0 1 16 1 0 1 0 17 0 1 0 0 5 0 30 1 0 11 36 1 0 12 42 2 0 15 15 52 1 0 13 57 1 0 14 2 0 trunc_ln340_fu_52 1 0 13 trunc_ln341_fu_57 1 0 14 1 0 grp_xfdilate_2160_3840_1_0_1_0_3841_3_3_s_fu_42 2 0 15 15 2 0 p_src_cols_read_read_fu_36 1 0 12 p_src_rows_read_read_fu_30 1 0 11 0 0 0 0 2 0 62 1 0 13 67 1 0 14 2 0 trunc_ln340_reg_62 1 0 13 trunc_ln341_reg_67 1 0 14 0 0 0 0 4 0 imgHelper2_4102 1 0 call 1 0 15 imgHelper3_4103 1 0 call 1 0 15 p_src_cols 1 0 read 1 0 12 p_src_rows 1 0 read 1 0 11 4 0 1 1150 10 2 1151 10 3 1150 10 4 1150 10 3 0 11 1150 10 12 1150 10 15 -1 -1 ",12486,False,2232.2504816125997,median "pragma Style_Checks (Off); -- This spec has been automatically generated from ATSAMD51G19A.svd pragma Restrictions (No_Elaboration_Code); with HAL; with System; package SAM_SVD.OSCCTRL is pragma Preelaborate; --------------- -- Registers -- --------------- -- OSCCTRL_EVCTRL_CFDEO array type OSCCTRL_EVCTRL_CFDEO_Field_Array is array (0 .. 1) of Boolean with Component_Size => 1, Size => 2; -- Type definition for OSCCTRL_EVCTRL_CFDEO type OSCCTRL_EVCTRL_CFDEO_Field (As_Array : Boolean := False) is record case As_Array is when False => -- CFDEO as a value Val : HAL.UInt2; when True => -- CFDEO as an array Arr : OSCCTRL_EVCTRL_CFDEO_Field_Array; end case; end record with Unchecked_Union, Size => 2; for OSCCTRL_EVCTRL_CFDEO_Field use record Val at 0 range 0 .. 1; Arr at 0 range 0 .. 1; end record; -- Event Control type OSCCTRL_EVCTRL_Register is record -- Clock 0 Failure Detector Event Output Enable CFDEO : OSCCTRL_EVCTRL_CFDEO_Field := (As_Array => False, Val => 16#0#); -- unspecified Reserved_2_7 : HAL.UInt6 := 16#0#; end record with Volatile_Full_Access, Object_Size => 8, Bit_Order => System.Low_Order_First; for OSCCTRL_EVCTRL_Register use record CFDEO at 0 range 0 .. 1; Reserved_2_7 at 0 range 2 .. 7; end record; -- OSCCTRL_INTENCLR_XOSCRDY array type OSCCTRL_INTENCLR_XOSCRDY_Field_Array is array (0 .. 1) of Boolean with Component_Size => 1, Size => 2; -- Type definition for OSCCTRL_INTENCLR_XOSCRDY type OSCCTRL_INTENCLR_XOSCRDY_Field (As_Array : Boolean := False) is record case As_Array is when False => -- XOSCRDY as a value Val : HAL.UInt2; when True => -- XOSCRDY as an array Arr : OSCCTRL_INTENCLR_XOSCRDY_Field_Array; end case; end record with Unchecked_Union, Size => 2; for OSCCTRL_INTENCLR_XOSCRDY_Field use record Val at 0 range 0 .. 1; Arr at 0 range 0 .. 1; end record; -- OSCCTRL_INTENCLR_XOSCFAIL array type OSCCTRL_INTENCLR_XOSCFAIL_Field_Array is array (0 .. 1) of Boolean with Component_Size => 1, Size => 2; -- Type definition for OSCCTRL_INTENCLR_XOSCFAIL type OSCCTRL_INTENCLR_XOSCFAIL_Field (As_Array : Boolean := False) is record case As_Array is when False => -- XOSCFAIL as a value Val : HAL.UInt2; when True => -- XOSCFAIL as an array Arr : OSCCTRL_INTENCLR_XOSCFAIL_Field_Array; end case; end record with Unchecked_Union, Size => 2; for OSCCTRL_INTENCLR_XOSCFAIL_Field use record Val at 0 range 0 .. 1; Arr at 0 range 0 .. 1; end record; -- Interrupt Enable Clear type OSCCTRL_INTENCLR_Register is record -- XOSC 0 Ready Interrupt Enable XOSCRDY : OSCCTRL_INTENCLR_XOSCRDY_Field := (As_Array => False, Val => 16#0#); -- XOSC 0 Clock Failure Detector Interrupt Enable XOSCFAIL : OSCCTRL_INTENCLR_XOSCFAIL_Field := (As_Array => False, Val => 16#0#); -- unspecified Reserved_4_7 : HAL.UInt4 := 16#0#; -- DFLL Ready Interrupt Enable DFLLRDY : Boolean := False; -- DFLL Out Of Bounds Interrupt Enable DFLLOOB : Boolean := False; -- DFLL Lock Fine Interrupt Enable DFLLLCKF : Boolean := False; -- DFLL Lock Coarse Interrupt Enable DFLLLCKC : Boolean := False; -- DFLL Reference Clock Stopped Interrupt Enable DFLLRCS : Boolean := False; -- unspecified Reserved_13_15 : HAL.UInt3 := 16#0#; -- DPLL0 Lock Rise Interrupt Enable DPLL0LCKR : Boolean := False; -- DPLL0 Lock Fall Interrupt Enable DPLL0LCKF : Boolean := False; -- DPLL0 Lock Timeout Interrupt Enable DPLL0LTO : Boolean := False; -- DPLL0 Loop Divider Ratio Update Complete Interrupt Enable DPLL0LDRTO : Boolean := False; -- unspecified Reserved_20_23 : HAL.UInt4 := 16#0#; -- DPLL1 Lock Rise Interrupt Enable DPLL1LCKR : Boolean := False; -- DPLL1 Lock Fall Interrupt Enable DPLL1LCKF : Boolean := False; -- DPLL1 Lock Timeout Interrupt Enable DPLL1LTO : Boolean := False; -- DPLL1 Loop Divider Ratio Update Complete Interrupt Enable DPLL1LDRTO : Boolean := False; -- unspecified Reserved_28_31 : HAL.UInt4 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for OSCCTRL_INTENCLR_Register use record XOSCRDY at 0 range 0 .. 1; XOSCFAIL at 0 range 2 .. 3; Reserved_4_7 at 0 range 4 .. 7; DFLLRDY at 0 range 8 .. 8; DFLLOOB at 0 range 9 .. 9; DFLLLCKF at 0 range 10 .. 10; DFLLLCKC at 0 range 11 .. 11; DFLLRCS at 0 range 12 .. 12; Reserved_13_15 at 0 range 13 .. 15; DPLL0LCKR at 0 range 16 .. 16; DPLL0LCKF at 0 range 17 .. 17; DPLL0LTO at 0 range 18 .. 18; DPLL0LDRTO at 0 range 19 .. 19; Reserved_20_23 at 0 range 20 .. 23; DPLL1LCKR at 0 range 24 .. 24; DPLL1LCKF at 0 range 25 .. 25; DPLL1LTO at 0 range 26 .. 26; DPLL1LDRTO at 0 range 27 .. 27; Reserved_28_31 at 0 range 28 .. 31; end record; -- OSCCTRL_INTENSET_XOSCRDY array type OSCCTRL_INTENSET_XOSCRDY_Field_Array is array (0 .. 1) of Boolean with Component_Size => 1, Size => 2; -- Type definition for OSCCTRL_INTENSET_XOSCRDY type OSCCTRL_INTENSET_XOSCRDY_Field (As_Array : Boolean := False) is record case As_Array is when False => -- XOSCRDY as a value Val : HAL.UInt2; when True => -- XOSCRDY as an array Arr : OSCCTRL_INTENSET_XOSCRDY_Field_Array; end case; end record with Unchecked_Union, Size => 2; for OSCCTRL_INTENSET_XOSCRDY_Field use record Val at 0 range 0 .. 1; Arr at 0 range 0 .. 1; end record; -- OSCCTRL_INTENSET_XOSCFAIL array type OSCCTRL_INTENSET_XOSCFAIL_Field_Array is array (0 .. 1) of Boolean with Component_Size => 1, Size => 2; -- Type definition for OSCCTRL_INTENSET_XOSCFAIL type OSCCTRL_INTENSET_XOSCFAIL_Field (As_Array : Boolean := False) is record case As_Array is when False => -- XOSCFAIL as a value Val : HAL.UInt2; when True => -- XOSCFAIL as an array Arr : OSCCTRL_INTENSET_XOSCFAIL_Field_Array; end case; end record with Unchecked_Union, Size => 2; for OSCCTRL_INTENSET_XOSCFAIL_Field use record Val at 0 range 0 .. 1; Arr at 0 range 0 .. 1; end record; -- Interrupt Enable Set type OSCCTRL_INTENSET_Register is record -- XOSC 0 Ready Interrupt Enable XOSCRDY : OSCCTRL_INTENSET_XOSCRDY_Field := (As_Array => False, Val => 16#0#); -- XOSC 0 Clock Failure Detector Interrupt Enable XOSCFAIL : OSCCTRL_INTENSET_XOSCFAIL_Field := (As_Array => False, Val => 16#0#); -- unspecified Reserved_4_7 : HAL.UInt4 := 16#0#; -- DFLL Ready Interrupt Enable DFLLRDY : Boolean := False; -- DFLL Out Of Bounds Interrupt Enable DFLLOOB : Boolean := False; -- DFLL Lock Fine Interrupt Enable DFLLLCKF : Boolean := False; -- DFLL Lock Coarse Interrupt Enable DFLLLCKC : Boolean := False; -- DFLL Reference Clock Stopped Interrupt Enable DFLLRCS : Boolean := False; -- unspecified Reserved_13_15 : HAL.UInt3 := 16#0#; -- DPLL0 Lock Rise Interrupt Enable DPLL0LCKR : Boolean := False; -- DPLL0 Lock Fall Interrupt Enable DPLL0LCKF : Boolean := False; -- DPLL0 Lock Timeout Interrupt Enable DPLL0LTO : Boolean := False; -- DPLL0 Loop Divider Ratio Update Complete Interrupt Enable DPLL0LDRTO : Boolean := False; -- unspecified Reserved_20_23 : HAL.UInt4 := 16#0#; -- DPLL1 Lock Rise Interrupt Enable DPLL1LCKR : Boolean := False; -- DPLL1 Lock Fall Interrupt Enable DPLL1LCKF : Boolean := False; -- DPLL1 Lock Timeout Interrupt Enable DPLL1LTO : Boolean := False; -- DPLL1 Loop Divider Ratio Update Complete Interrupt Enable DPLL1LDRTO : Boolean := False; -- unspecified Reserved_28_31 : HAL.UInt4 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for OSCCTRL_INTENSET_Register use record XOSCRDY at 0 range 0 .. 1; XOSCFAIL at 0 range 2 .. 3; Reserved_4_7 at 0 range 4 .. 7; DFLLRDY at 0 range 8 .. 8; DFLLOOB at 0 range 9 .. 9; DFLLLCKF at 0 range 10 .. 10; DFLLLCKC at 0 range 11 .. 11; DFLLRCS at 0 range 12 .. 12; Reserved_13_15 at 0 range 13 .. 15; DPLL0LCKR at 0 range 16 .. 16; DPLL0LCKF at 0 range 17 .. 17; DPLL0LTO at 0 range 18 .. 18; DPLL0LDRTO at 0 range 19 .. 19; Reserved_20_23 at 0 range 20 .. 23; DPLL1LCKR at 0 range 24 .. 24; DPLL1LCKF at 0 range 25 .. 25; DPLL1LTO at 0 range 26 .. 26; DPLL1LDRTO at 0 range 27 .. 27; Reserved_28_31 at 0 range 28 .. 31; end record; -- OSCCTRL_INTFLAG_XOSCRDY array type OSCCTRL_INTFLAG_XOSCRDY_Field_Array is array (0 .. 1) of Boolean with Component_Size => 1, Size => 2; -- Type definition for OSCCTRL_INTFLAG_XOSCRDY type OSCCTRL_INTFLAG_XOSCRDY_Field (As_Array : Boolean := False) is record case As_Array is when False => -- XOSCRDY as a value Val : HAL.UInt2; when True => -- XOSCRDY as an array Arr : OSCCTRL_INTFLAG_XOSCRDY_Field_Array; end case; end record with Unchecked_Union, Size => 2; for OSCCTRL_INTFLAG_XOSCRDY_Field use record Val at 0 range 0 .. 1; Arr at 0 range 0 .. 1; end record; -- OSCCTRL_INTFLAG_XOSCFAIL array type OSCCTRL_INTFLAG_XOSCFAIL_Field_Array is array (0 .. 1) of Boolean with Component_Size => 1, Size => 2; -- Type definition for OSCCTRL_INTFLAG_XOSCFAIL type OSCCTRL_INTFLAG_XOSCFAIL_Field (As_Array : Boolean := False) is record case As_Array is when False => -- XOSCFAIL as a value Val : HAL.UInt2; when True => -- XOSCFAIL as an array Arr : OSCCTRL_INTFLAG_XOSCFAIL_Field_Array; end case; end record with Unchecked_Union, Size => 2; for OSCCTRL_INTFLAG_XOSCFAIL_Field use record Val at 0 range 0 .. 1; Arr at 0 range 0 .. 1; end record; -- Interrupt Flag Status and Clear type OSCCTRL_INTFLAG_Register is record -- XOSC 0 Ready XOSCRDY : OSCCTRL_INTFLAG_XOSCRDY_Field := (As_Array => False, Val => 16#0#); -- XOSC 0 Clock Failure Detector XOSCFAIL : OSCCTRL_INTFLAG_XOSCFAIL_Field := (As_Array => False, Val => 16#0#); -- unspecified Reserved_4_7 : HAL.UInt4 := 16#0#; -- DFLL Ready DFLLRDY : Boolean := False; -- DFLL Out Of Bounds DFLLOOB : Boolean := False; -- DFLL Lock Fine DFLLLCKF : Boolean := False; -- DFLL Lock Coarse DFLLLCKC : Boolean := False; -- DFLL Reference Clock Stopped DFLLRCS : Boolean := False; -- unspecified Reserved_13_15 : HAL.UInt3 := 16#0#; -- DPLL0 Lock Rise DPLL0LCKR : Boolean := False; -- DPLL0 Lock Fall DPLL0LCKF : Boolean := False; -- DPLL0 Lock Timeout DPLL0LTO : Boolean := False; -- DPLL0 Loop Divider Ratio Update Complete DPLL0LDRTO : Boolean := False; -- unspecified Reserved_20_23 : HAL.UInt4 := 16#0#; -- DPLL1 Lock Rise DPLL1LCKR : Boolean := False; -- DPLL1 Lock Fall DPLL1LCKF : Boolean := False; -- DPLL1 Lock Timeout DPLL1LTO : Boolean := False; -- DPLL1 Loop Divider Ratio Update Complete DPLL1LDRTO : Boolean := False; -- unspecified Reserved_28_31 : HAL.UInt4 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for OSCCTRL_INTFLAG_Register use record XOSCRDY at 0 range 0 .. 1; XOSCFAIL at 0 range 2 .. 3; Reserved_4_7 at 0 range 4 .. 7; DFLLRDY at 0 range 8 .. 8; DFLLOOB at 0 range 9 .. 9; DFLLLCKF at 0 range 10 .. 10; DFLLLCKC at 0 range 11 .. 11; DFLLRCS at 0 range 12 .. 12; Reserved_13_15 at 0 range 13 .. 15; DPLL0LCKR at 0 range 16 .. 16; DPLL0LCKF at 0 range 17 .. 17; DPLL0LTO at 0 range 18 .. 18; DPLL0LDRTO at 0 range 19 .. 19; Reserved_20_23 at 0 range 20 .. 23; DPLL1LCKR at 0 range 24 .. 24; DPLL1LCKF at 0 range 25 .. 25; DPLL1LTO at 0 range 26 .. 26; DPLL1LDRTO at 0 range 27 .. 27; Reserved_28_31 at 0 range 28 .. 31; end record; -- OSCCTRL_STATUS_XOSCRDY array type OSCCTRL_STATUS_XOSCRDY_Field_Array is array (0 .. 1) of Boolean with Component_Size => 1, Size => 2; -- Type definition for OSCCTRL_STATUS_XOSCRDY type OSCCTRL_STATUS_XOSCRDY_Field (As_Array : Boolean := False) is record case As_Array is when False => -- XOSCRDY as a value Val : HAL.UInt2; when True => -- XOSCRDY as an array Arr : OSCCTRL_STATUS_XOSCRDY_Field_Array; end case; end record with Unchecked_Union, Size => 2; for OSCCTRL_STATUS_XOSCRDY_Field use record Val at 0 range 0 .. 1; Arr at 0 range 0 .. 1; end record; -- OSCCTRL_STATUS_XOSCFAIL array type OSCCTRL_STATUS_XOSCFAIL_Field_Array is array (0 .. 1) of Boolean with Component_Size => 1, Size => 2; -- Type definition for OSCCTRL_STATUS_XOSCFAIL type OSCCTRL_STATUS_XOSCFAIL_Field (As_Array : Boolean := False) is record case As_Array is when False => -- XOSCFAIL as a value Val : HAL.UInt2; when True => -- XOSCFAIL as an array Arr : OSCCTRL_STATUS_XOSCFAIL_Field_Array; end case; end record with Unchecked_Union, Size => 2; for OSCCTRL_STATUS_XOSCFAIL_Field use record Val at 0 range 0 .. 1; Arr at 0 range 0 .. 1; end record; -- OSCCTRL_STATUS_XOSCCKSW array type OSCCTRL_STATUS_XOSCCKSW_Field_Array is array (0 .. 1) of Boolean with Component_Size => 1, Size => 2; -- Type definition for OSCCTRL_STATUS_XOSCCKSW type OSCCTRL_STATUS_XOSCCKSW_Field (As_Array : Boolean := False) is record case As_Array is when False => -- XOSCCKSW as a value Val : HAL.UInt2; when True => -- XOSCCKSW as an array Arr : OSCCTRL_STATUS_XOSCCKSW_Field_Array; end case; end record with Unchecked_Union, Size => 2; for OSCCTRL_STATUS_XOSCCKSW_Field use record Val at 0 range 0 .. 1; Arr at 0 range 0 .. 1; end record; -- Status type OSCCTRL_STATUS_Register is record -- Read-only. XOSC 0 Ready XOSCRDY : OSCCTRL_STATUS_XOSCRDY_Field; -- Read-only. XOSC 0 Clock Failure Detector XOSCFAIL : OSCCTRL_STATUS_XOSCFAIL_Field; -- Read-only. XOSC 0 Clock Switch XOSCCKSW : OSCCTRL_STATUS_XOSCCKSW_Field; -- unspecified Reserved_6_7 : HAL.UInt2; -- Read-only. DFLL Ready DFLLRDY : Boolean; -- Read-only. DFLL Out Of Bounds DFLLOOB : Boolean; -- Read-only. DFLL Lock Fine DFLLLCKF : Boolean; -- Read-only. DFLL Lock Coarse DFLLLCKC : Boolean; -- Read-only. DFLL Reference Clock Stopped DFLLRCS : Boolean; -- unspecified Reserved_13_15 : HAL.UInt3; -- Read-only. DPLL0 Lock Rise DPLL0LCKR : Boolean; -- Read-only. DPLL0 Lock Fall DPLL0LCKF : Boolean; -- Read-only. DPLL0 Timeout DPLL0TO : Boolean; -- Read-only. DPLL0 Loop Divider Ratio Update Complete DPLL0LDRTO : Boolean; -- unspecified Reserved_20_23 : HAL.UInt4; -- Read-only. DPLL1 Lock Rise DPLL1LCKR : Boolean; -- Read-only. DPLL1 Lock Fall DPLL1LCKF : Boolean; -- Read-only. DPLL1 Timeout DPLL1TO : Boolean; -- Read-only. DPLL1 Loop Divider Ratio Update Complete DPLL1LDRTO : Boolean; -- unspecified Reserved_28_31 : HAL.UInt4; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for OSCCTRL_STATUS_Register use record XOSCRDY at 0 range 0 .. 1; XOSCFAIL at 0 range 2 .. 3; XOSCCKSW at 0 range 4 .. 5; Reserved_6_7 at 0 range 6 .. 7; DFLLRDY at 0 range 8 .. 8; DFLLOOB at 0 range 9 .. 9; DFLLLCKF at 0 range 10 .. 10; DFLLLCKC at 0 range 11 .. 11; DFLLRCS at 0 range 12 .. 12; Reserved_13_15 at 0 range 13 .. 15; DPLL0LCKR at 0 range 16 .. 16; DPLL0LCKF at 0 range 17 .. 17; DPLL0TO at 0 range 18 .. 18; DPLL0LDRTO at 0 range 19 .. 19; Reserved_20_23 at 0 range 20 .. 23; DPLL1LCKR at 0 range 24 .. 24; DPLL1LCKF at 0 range 25 .. 25; DPLL1TO at 0 range 26 .. 26; DPLL1LDRTO at 0 range 27 .. 27; Reserved_28_31 at 0 range 28 .. 31; end record; subtype OSCCTRL_XOSCCTRL_IPTAT_Field is HAL.UInt2; subtype OSCCTRL_XOSCCTRL_IMULT_Field is HAL.UInt4; -- Start-Up Time type XOSCCTRL_STARTUPSelect is (-- 31 us CYCLE1, -- 61 us CYCLE2, -- 122 us CYCLE4, -- 244 us CYCLE8, -- 488 us CYCLE16, -- 977 us CYCLE32, -- 1953 us CYCLE64, -- 3906 us CYCLE128, -- 7813 us CYCLE256, -- 15625 us CYCLE512, -- 31250 us CYCLE1024, -- 62500 us CYCLE2048, -- 125000 us CYCLE4096, -- 250000 us CYCLE8192, -- 500000 us CYCLE16384, -- 1000000 us CYCLE32768) with Size => 4; for XOSCCTRL_STARTUPSelect use (CYCLE1 => 0, CYCLE2 => 1, CYCLE4 => 2, CYCLE8 => 3, CYCLE16 => 4, CYCLE32 => 5, CYCLE64 => 6, CYCLE128 => 7, CYCLE256 => 8, CYCLE512 => 9, CYCLE1024 => 10, CYCLE2048 => 11, CYCLE4096 => 12, CYCLE8192 => 13, CYCLE16384 => 14, CYCLE32768 => 15); -- Clock Failure Detector Prescaler type XOSCCTRL_CFDPRESCSelect is (-- 48 MHz DIV1, -- 24 MHz DIV2, -- 12 MHz DIV4, -- 6 MHz DIV8, -- 3 MHz DIV16, -- 1.5 MHz DIV32, -- 0.75 MHz DIV64, -- 0.3125 MHz DIV128) with Size => 4; for XOSCCTRL_CFDPRESCSelect use (DIV1 => 0, DIV2 => 1, DIV4 => 2, DIV8 => 3, DIV16 => 4, DIV32 => 5, DIV64 => 6, DIV128 => 7); -- External Multipurpose Crystal Oscillator Control type OSCCTRL_XOSCCTRL_Register is record -- unspecified Reserved_0_0 : HAL.Bit := 16#0#; -- Oscillator Enable ENABLE : Boolean := False; -- Crystal Oscillator Enable XTALEN : Boolean := False; -- unspecified Reserved_3_5 : HAL.UInt3 := 16#0#; -- Run in Standby RUNSTDBY : Boolean := False; -- On Demand Control ONDEMAND : Boolean := True; -- Low Buffer Gain Enable LOWBUFGAIN : Boolean := False; -- Oscillator Current Reference IPTAT : OSCCTRL_XOSCCTRL_IPTAT_Field := 16#0#; -- Oscillator Current Multiplier IMULT : OSCCTRL_XOSCCTRL_IMULT_Field := 16#0#; -- Automatic Loop Control Enable ENALC : Boolean := False; -- Clock Failure Detector Enable CFDEN : Boolean := False; -- Xosc Clock Switch Enable SWBEN : Boolean := False; -- unspecified Reserved_18_19 : HAL.UInt2 := 16#0#; -- Start-Up Time STARTUP : XOSCCTRL_STARTUPSelect := SAM_SVD.OSCCTRL.CYCLE1; -- Clock Failure Detector Prescaler CFDPRESC : XOSCCTRL_CFDPRESCSelect := SAM_SVD.OSCCTRL.DIV1; -- unspecified Reserved_28_31 : HAL.UInt4 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for OSCCTRL_XOSCCTRL_Register use record Reserved_0_0 at 0 range 0 .. 0; ENABLE at 0 range 1 .. 1; XTALEN at 0 range 2 .. 2; Reserved_3_5 at 0 range 3 .. 5; RUNSTDBY at 0 range 6 .. 6; ONDEMAND at 0 range 7 .. 7; LOWBUFGAIN at 0 range 8 .. 8; IPTAT at 0 range 9 .. 10; IMULT at 0 range 11 .. 14; ENALC at 0 range 15 .. 15; CFDEN at 0 range 16 .. 16; SWBEN at 0 range 17 .. 17; Reserved_18_19 at 0 range 18 .. 19; STARTUP at 0 range 20 .. 23; CFDPRESC at 0 range 24 .. 27; Reserved_28_31 at 0 range 28 .. 31; end record; -- External Multipurpose Crystal Oscillator Control type OSCCTRL_XOSCCTRL_Registers is array (0 .. 1) of OSCCTRL_XOSCCTRL_Register; -- DFLL48M Control A type OSCCTRL_DFLLCTRLA_Register is record -- unspecified Reserved_0_0 : HAL.Bit := 16#0#; -- DFLL Enable ENABLE : Boolean := True; -- unspecified Reserved_2_5 : HAL.UInt4 := 16#0#; -- Run in Standby RUNSTDBY : Boolean := False; -- On Demand Control ONDEMAND : Boolean := True; end record with Volatile_Full_Access, Object_Size => 8, Bit_Order => System.Low_Order_First; for OSCCTRL_DFLLCTRLA_Register use record Reserved_0_0 at 0 range 0 .. 0; ENABLE at 0 range 1 .. 1; Reserved_2_5 at 0 range 2 .. 5; RUNSTDBY at 0 range 6 .. 6; ONDEMAND at 0 range 7 .. 7; end record; -- DFLL48M Control B type OSCCTRL_DFLLCTRLB_Register is record -- Operating Mode Selection MODE : Boolean := False; -- Stable DFLL Frequency STABLE : Boolean := False; -- Lose Lock After Wake LLAW : Boolean := False; -- USB Clock Recovery Mode USBCRM : Boolean := False; -- Chill Cycle Disable CCDIS : Boolean := False; -- Quick Lock Disable QLDIS : Boolean := False; -- Bypass Coarse Lock BPLCKC : Boolean := False; -- Wait Lock WAITLOCK : Boolean := False; end record with Volatile_Full_Access, Object_Size => 8, Bit_Order => System.Low_Order_First; for OSCCTRL_DFLLCTRLB_Register use record MODE at 0 range 0 .. 0; STABLE at 0 range 1 .. 1; LLAW at 0 range 2 .. 2; USBCRM at 0 range 3 .. 3; CCDIS at 0 range 4 .. 4; QLDIS at 0 range 5 .. 5; BPLCKC at 0 range 6 .. 6; WAITLOCK at 0 range 7 .. 7; end record; subtype OSCCTRL_DFLLVAL_FINE_Field is HAL.UInt8; subtype OSCCTRL_DFLLVAL_COARSE_Field is HAL.UInt6; subtype OSCCTRL_DFLLVAL_DIFF_Field is HAL.UInt16; -- DFLL48M Value type OSCCTRL_DFLLVAL_Register is record -- Fine Value FINE : OSCCTRL_DFLLVAL_FINE_Field := 16#0#; -- unspecified Reserved_8_9 : HAL.UInt2 := 16#0#; -- Coarse Value COARSE : OSCCTRL_DFLLVAL_COARSE_Field := 16#0#; -- Multiplication Ratio Difference DIFF : OSCCTRL_DFLLVAL_DIFF_Field := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for OSCCTRL_DFLLVAL_Register use record FINE at 0 range 0 .. 7; Reserved_8_9 at 0 range 8 .. 9; COARSE at 0 range 10 .. 15; DIFF at 0 range 16 .. 31; end record; subtype OSCCTRL_DFLLMUL_MUL_Field is HAL.UInt16; subtype OSCCTRL_DFLLMUL_FSTEP_Field is HAL.UInt8; subtype OSCCTRL_DFLLMUL_CSTEP_Field is HAL.UInt6; -- DFLL48M Multiplier type OSCCTRL_DFLLMUL_Register is record -- DFLL Multiply Factor MUL : OSCCTRL_DFLLMUL_MUL_Field := 16#0#; -- Fine Maximum Step FSTEP : OSCCTRL_DFLLMUL_FSTEP_Field := 16#0#; -- unspecified Reserved_24_25 : HAL.UInt2 := 16#0#; -- Coarse Maximum Step CSTEP : OSCCTRL_DFLLMUL_CSTEP_Field := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for OSCCTRL_DFLLMUL_Register use record MUL at 0 range 0 .. 15; FSTEP at 0 range 16 .. 23; Reserved_24_25 at 0 range 24 .. 25; CSTEP at 0 range 26 .. 31; end record; -- DFLL48M Synchronization type OSCCTRL_DFLLSYNC_Register is record -- unspecified Reserved_0_0 : HAL.Bit := 16#0#; -- ENABLE Synchronization Busy ENABLE : Boolean := False; -- DFLLCTRLB Synchronization Busy DFLLCTRLB : Boolean := False; -- DFLLVAL Synchronization Busy DFLLVAL : Boolean := False; -- DFLLMUL Synchronization Busy DFLLMUL : Boolean := False; -- unspecified Reserved_5_7 : HAL.UInt3 := 16#0#; end record with Volatile_Full_Access, Object_Size => 8, Bit_Order => System.Low_Order_First; for OSCCTRL_DFLLSYNC_Register use record Reserved_0_0 at 0 range 0 .. 0; ENABLE at 0 range 1 .. 1; DFLLCTRLB at 0 range 2 .. 2; DFLLVAL at 0 range 3 .. 3; DFLLMUL at 0 range 4 .. 4; Reserved_5_7 at 0 range 5 .. 7; end record; -------------------------------------- -- OSCCTRL_DPLL cluster's Registers -- -------------------------------------- -- DPLL Control A type OSCCTRL_DPLLCTRLA_OSCCTRL_DPLL_Register is record -- unspecified Reserved_0_0 : HAL.Bit := 16#0#; -- DPLL Enable ENABLE : Boolean := False; -- unspecified Reserved_2_5 : HAL.UInt4 := 16#0#; -- Run in Standby RUNSTDBY : Boolean := False; -- On Demand Control ONDEMAND : Boolean := True; end record with Volatile_Full_Access, Object_Size => 8, Bit_Order => System.Low_Order_First; for OSCCTRL_DPLLCTRLA_OSCCTRL_DPLL_Register use record Reserved_0_0 at 0 range 0 .. 0; ENABLE at 0 range 1 .. 1; Reserved_2_5 at 0 range 2 .. 5; RUNSTDBY at 0 range 6 .. 6; ONDEMAND at 0 range 7 .. 7; end record; subtype OSCCTRL_DPLLRATIO_OSCCTRL_DPLL_LDR_Field is HAL.UInt13; subtype OSCCTRL_DPLLRATIO_OSCCTRL_DPLL_LDRFRAC_Field is HAL.UInt5; -- DPLL Ratio Control type OSCCTRL_DPLLRATIO_OSCCTRL_DPLL_Register is record -- Loop Divider Ratio LDR : OSCCTRL_DPLLRATIO_OSCCTRL_DPLL_LDR_Field := 16#0#; -- unspecified Reserved_13_15 : HAL.UInt3 := 16#0#; -- Loop Divider Ratio Fractional Part LDRFRAC : OSCCTRL_DPLLRATIO_OSCCTRL_DPLL_LDRFRAC_Field := 16#0#; -- unspecified Reserved_21_31 : HAL.UInt11 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for OSCCTRL_DPLLRATIO_OSCCTRL_DPLL_Register use record LDR at 0 range 0 .. 12; Reserved_13_15 at 0 range 13 .. 15; LDRFRAC at 0 range 16 .. 20; Reserved_21_31 at 0 range 21 .. 31; end record; -- Proportional Integral Filter Selection type DPLLCTRLB_FILTERSelect is (-- Bandwidth = 92.7Khz and Damping Factor = 0.76 FILTER1, -- Bandwidth = 131Khz and Damping Factor = 1.08 FILTER2, -- Bandwidth = 46.4Khz and Damping Factor = 0.38 FILTER3, -- Bandwidth = 65.6Khz and Damping Factor = 0.54 FILTER4, -- Bandwidth = 131Khz and Damping Factor = 0.56 FILTER5, -- Bandwidth = 185Khz and Damping Factor = 0.79 FILTER6, -- Bandwidth = 65.6Khz and Damping Factor = 0.28 FILTER7, -- Bandwidth = 92.7Khz and Damping Factor = 0.39 FILTER8, -- Bandwidth = 46.4Khz and Damping Factor = 1.49 FILTER9, -- Bandwidth = 65.6Khz and Damping Factor = 2.11 FILTER10, -- Bandwidth = 23.2Khz and Damping Factor = 0.75 FILTER11, -- Bandwidth = 32.8Khz and Damping Factor = 1.06 FILTER12, -- Bandwidth = 65.6Khz and Damping Factor = 1.07 FILTER13, -- Bandwidth = 92.7Khz and Damping Factor = 1.51 FILTER14, -- Bandwidth = 32.8Khz and Damping Factor = 0.53 FILTER15, -- Bandwidth = 46.4Khz and Damping Factor = 0.75 FILTER16) with Size => 4; for DPLLCTRLB_FILTERSelect use (FILTER1 => 0, FILTER2 => 1, FILTER3 => 2, FILTER4 => 3, FILTER5 => 4, FILTER6 => 5, FILTER7 => 6, FILTER8 => 7, FILTER9 => 8, FILTER10 => 9, FILTER11 => 10, FILTER12 => 11, FILTER13 => 12, FILTER14 => 13, FILTER15 => 14, FILTER16 => 15); -- Reference Clock Selection type DPLLCTRLB_REFCLKSelect is (-- Dedicated GCLK clock reference GCLK, -- XOSC32K clock reference XOSC32, -- XOSC0 clock reference XOSC0, -- XOSC1 clock reference XOSC1) with Size => 3; for DPLLCTRLB_REFCLKSelect use (GCLK => 0, XOSC32 => 1, XOSC0 => 2, XOSC1 => 3); -- Lock Time type DPLLCTRLB_LTIMESelect is (-- No time-out. Automatic lock DEFAULT, -- Time-out if no lock within 800us Val_800US, -- Time-out if no lock within 900us Val_900US, -- Time-out if no lock within 1ms Val_1MS, -- Time-out if no lock within 1.1ms Val_1P1MS) with Size => 3; for DPLLCTRLB_LTIMESelect use (DEFAULT => 0, Val_800US => 4, Val_900US => 5, Val_1MS => 6, Val_1P1MS => 7); -- Sigma-Delta DCO Filter Selection type DPLLCTRLB_DCOFILTERSelect is (-- Capacitor(pF) = 0.5 and Bandwidth Fn (MHz) = 3.21 FILTER1, -- Capacitor(pF) = 1 and Bandwidth Fn (MHz) = 1.6 FILTER2, -- Capacitor(pF) = 1.5 and Bandwidth Fn (MHz) = 1.1 FILTER3, -- Capacitor(pF) = 2 and Bandwidth Fn (MHz) = 0.8 FILTER4, -- Capacitor(pF) = 2.5 and Bandwidth Fn (MHz) = 0.64 FILTER5, -- Capacitor(pF) = 3 and Bandwidth Fn (MHz) = 0.55 FILTER6, -- Capacitor(pF) = 3.5 and Bandwidth Fn (MHz) = 0.45 FILTER7, -- Capacitor(pF) = 4 and Bandwidth Fn (MHz) = 0.4 FILTER8) with Size => 3; for DPLLCTRLB_DCOFILTERSelect use (FILTER1 => 0, FILTER2 => 1, FILTER3 => 2, FILTER4 => 3, FILTER5 => 4, FILTER6 => 5, FILTER7 => 6, FILTER8 => 7); subtype OSCCTRL_DPLLCTRLB_OSCCTRL_DPLL_DIV_Field is HAL.UInt11; -- DPLL Control B type OSCCTRL_DPLLCTRLB_OSCCTRL_DPLL_Register is record -- Proportional Integral Filter Selection FILTER : DPLLCTRLB_FILTERSelect := SAM_SVD.OSCCTRL.FILTER1; -- Wake Up Fast WUF : Boolean := False; -- Reference Clock Selection REFCLK : DPLLCTRLB_REFCLKSelect := SAM_SVD.OSCCTRL.XOSC32; -- Lock Time LTIME : DPLLCTRLB_LTIMESelect := SAM_SVD.OSCCTRL.DEFAULT; -- Lock Bypass LBYPASS : Boolean := False; -- Sigma-Delta DCO Filter Selection DCOFILTER : DPLLCTRLB_DCOFILTERSelect := SAM_SVD.OSCCTRL.FILTER1; -- DCO Filter Enable DCOEN : Boolean := False; -- Clock Divider DIV : OSCCTRL_DPLLCTRLB_OSCCTRL_DPLL_DIV_Field := 16#0#; -- unspecified Reserved_27_31 : HAL.UInt5 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for OSCCTRL_DPLLCTRLB_OSCCTRL_DPLL_Register use record FILTER at 0 range 0 .. 3; WUF at 0 range 4 .. 4; REFCLK at 0 range 5 .. 7; LTIME at 0 range 8 .. 10; LBYPASS at 0 range 11 .. 11; DCOFILTER at 0 range 12 .. 14; DCOEN at 0 range 15 .. 15; DIV at 0 range 16 .. 26; Reserved_27_31 at 0 range 27 .. 31; end record; -- DPLL Synchronization Busy type OSCCTRL_DPLLSYNCBUSY_OSCCTRL_DPLL_Register is record -- unspecified Reserved_0_0 : HAL.Bit; -- Read-only. DPLL Enable Synchronization Status ENABLE : Boolean; -- Read-only. DPLL Loop Divider Ratio Synchronization Status DPLLRATIO : Boolean; -- unspecified Reserved_3_31 : HAL.UInt29; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for OSCCTRL_DPLLSYNCBUSY_OSCCTRL_DPLL_Register use record Reserved_0_0 at 0 range 0 .. 0; ENABLE at 0 range 1 .. 1; DPLLRATIO at 0 range 2 .. 2; Reserved_3_31 at 0 range 3 .. 31; end record; -- DPLL Status type OSCCTRL_DPLLSTATUS_OSCCTRL_DPLL_Register is record -- Read-only. DPLL Lock Status LOCK : Boolean; -- Read-only. DPLL Clock Ready CLKRDY : Boolean; -- unspecified Reserved_2_31 : HAL.UInt30; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for OSCCTRL_DPLLSTATUS_OSCCTRL_DPLL_Register use record LOCK at 0 range 0 .. 0; CLKRDY at 0 range 1 .. 1; Reserved_2_31 at 0 range 2 .. 31; end record; type OSCCTRL_DPLL_Cluster is record -- DPLL Control A DPLLCTRLA : aliased OSCCTRL_DPLLCTRLA_OSCCTRL_DPLL_Register; -- DPLL Ratio Control DPLLRATIO : aliased OSCCTRL_DPLLRATIO_OSCCTRL_DPLL_Register; -- DPLL Control B DPLLCTRLB : aliased OSCCTRL_DPLLCTRLB_OSCCTRL_DPLL_Register; -- DPLL Synchronization Busy DPLLSYNCBUSY : aliased OSCCTRL_DPLLSYNCBUSY_OSCCTRL_DPLL_Register; -- DPLL Status DPLLSTATUS : aliased OSCCTRL_DPLLSTATUS_OSCCTRL_DPLL_Register; end record with Size => 160; for OSCCTRL_DPLL_Cluster use record DPLLCTRLA at 16#0# range 0 .. 7; DPLLRATIO at 16#4# range 0 .. 31; DPLLCTRLB at 16#8# range 0 .. 31; DPLLSYNCBUSY at 16#C# range 0 .. 31; DPLLSTATUS at 16#10# range 0 .. 31; end record; type OSCCTRL_DPLL_Clusters is array (0 .. 1) of OSCCTRL_DPLL_Cluster; ----------------- -- Peripherals -- ----------------- -- Oscillators Control type OSCCTRL_Peripheral is record -- Event Control EVCTRL : aliased OSCCTRL_EVCTRL_Register; -- Interrupt Enable Clear INTENCLR : aliased OSCCTRL_INTENCLR_Register; -- Interrupt Enable Set INTENSET : aliased OSCCTRL_INTENSET_Register; -- Interrupt Flag Status and Clear INTFLAG : aliased OSCCTRL_INTFLAG_Register; -- Status STATUS : aliased OSCCTRL_STATUS_Register; -- External Multipurpose Crystal Oscillator Control XOSCCTRL : aliased OSCCTRL_XOSCCTRL_Registers; -- DFLL48M Control A DFLLCTRLA : aliased OSCCTRL_DFLLCTRLA_Register; -- DFLL48M Control B DFLLCTRLB : aliased OSCCTRL_DFLLCTRLB_Register; -- DFLL48M Value DFLLVAL : aliased OSCCTRL_DFLLVAL_Register; -- DFLL48M Multiplier DFLLMUL : aliased OSCCTRL_DFLLMUL_Register; -- DFLL48M Synchronization DFLLSYNC : aliased OSCCTRL_DFLLSYNC_Register; OSCCTRL_DPLL : aliased OSCCTRL_DPLL_Clusters; end record with Volatile; for OSCCTRL_Peripheral use record EVCTRL at 16#0# range 0 .. 7; INTENCLR at 16#4# range 0 .. 31; INTENSET at 16#8# range 0 .. 31; INTFLAG at 16#C# range 0 .. 31; STATUS at 16#10# range 0 .. 31; XOSCCTRL at 16#14# range 0 .. 63; DFLLCTRLA at 16#1C# range 0 .. 7; DFLLCTRLB at 16#20# range 0 .. 7; DFLLVAL at 16#24# range 0 .. 31; DFLLMUL at 16#28# range 0 .. 31; DFLLSYNC at 16#2C# range 0 .. 7; OSCCTRL_DPLL at 16#30# range 0 .. 319; end record; -- Oscillators Control OSCCTRL_Periph : aliased OSCCTRL_Peripheral with Import, Address => OSCCTRL_Base; end SAM_SVD.OSCCTRL; ",12307,True,2788.433990887808,median "= Spring Cloud Config :github: https://github.com/spring-cloud/spring-cloud-config :githubmaster: {github}/tree/master :docslink: {githubmaster}/docs/src/main/asciidoc :toc: :nofooter: :special-string: _ *{spring-cloud-version}* include::intro.adoc[] == Quick Start include::quickstart.adoc[] == Spring Cloud Config Server Spring Cloud Config Server provides an HTTP resource-based API for external configuration (name-value pairs or equivalent YAML content). The server is embeddable in a Spring Boot application, by using the `@EnableConfigServer` annotation. Consequently, the following application is a config server: .ConfigServer.java [source,java] ---- @SpringBootApplication @EnableConfigServer public class ConfigServer { public static void main(String[] args) { SpringApplication.run(ConfigServer.class, args); } } ---- Like all Spring Boot applications, it runs on port 8080 by default, but you can switch it to the more conventional port 8888 in various ways. The easiest, which also sets a default configuration repository, is by launching it with `spring.config.name=configserver` (there is a `configserver.yml` in the Config Server jar). Another is to use your own `application.properties`, as shown in the following example: .application.properties [source,properties] ---- server.port: 8888 spring.cloud.config.server.git.uri: file://${user.home}/config-repo ---- where `${user.home}/config-repo` is a git repository containing YAML and properties files. NOTE: On Windows, you need an extra ""/"" in the file URL if it is absolute with a drive prefix (for example,`file:///${user.home}/config-repo`). [TIP] ==== The following listing shows a recipe for creating the git repository in the preceding example: ---- $ cd $HOME $ mkdir config-repo $ cd config-repo $ git init . $ echo info.foo: bar > application.properties $ git add -A . $ git commit -m ""Add application.properties"" ---- ==== WARNING: Using the local filesystem for your git repository is intended for testing only. You should use a server to host your configuration repositories in production. WARNING: The initial clone of your configuration repository can be quick and efficient if you keep only text files in it. If you store binary files, especially large ones, you may experience delays on the first request for configuration or encounter out of memory errors in the server. === Environment Repository Where should you store the configuration data for the Config Server? The strategy that governs this behaviour is the `EnvironmentRepository`, serving `Environment` objects. This `Environment` is a shallow copy of the domain from the Spring `Environment` (including `propertySources` as the main feature). The `Environment` resources are parametrized by three variables: * `{application}`, which maps to `spring.application.name` on the client side. * `{profile}`, which maps to `spring.profiles.active` on the client (comma-separated list). * `{label}`, which is a server side feature labelling a ""versioned"" set of config files. Repository implementations generally behave like a Spring Boot application, loading configuration files from a `spring.config.name` equal to the `{application}` parameter, and `spring.profiles.active` equal to the `{profiles}` parameter. Precedence rules for profiles are also the same as in a regular Spring Boot application: Active profiles take precedence over defaults, and, if there are multiple profiles, the last one wins (similar to adding entries to a `Map`). The following sample client application has this bootstrap configuration: .bootstrap.yml [source,yaml] ---- spring: application: name: foo profiles: active: dev,mysql ---- (As usual with a Spring Boot application, these properties could also be set by environment variables or command line arguments). If the repository is file-based, the server creates an `Environment` from `application.yml` (shared between all clients) and `foo.yml` (with `foo.yml` taking precedence). If the YAML files have documents inside them that point to Spring profiles, those are applied with higher precedence (in order of the profiles listed). If there are profile-specific YAML (or properties) files, these are also applied with higher precedence than the defaults. Higher precedence translates to a `PropertySource` listed earlier in the `Environment`. (These same rules apply in a standalone Spring Boot application.) You can set spring.cloud.config.server.accept-empty to false so that Server would return a HTTP 404 status, if the application is not found.By default, this flag is set to true. ==== Git Backend The default implementation of `EnvironmentRepository` uses a Git backend, which is very convenient for managing upgrades and physical environments and for auditing changes. To change the location of the repository, you can set the `spring.cloud.config.server.git.uri` configuration property in the Config Server (for example in `application.yml`). If you set it with a `file:` prefix, it should work from a local repository so that you can get started quickly and easily without a server. However, in that case, the server operates directly on the local repository without cloning it (it does not matter if it is not bare because the Config Server never makes changes to the ""remote"" repository). To scale the Config Server up and make it highly available, you need to have all instances of the server pointing to the same repository, so only a shared file system would work. Even in that case, it is better to use the `ssh:` protocol for a shared filesystem repository, so that the server can clone it and use a local working copy as a cache. This repository implementation maps the `{label}` parameter of the HTTP resource to a git label (commit id, branch name, or tag). If the git branch or tag name contains a slash (`/`), then the label in the HTTP URL should instead be specified with the special string `({special-string})` (to avoid ambiguity with other URL paths). For example, if the label is `foo/bar`, replacing the slash would result in the following label: `foo({special-string})bar`. The inclusion of the special string `({special-string})` can also be applied to the `{application}` parameter. If you use a command-line client such as curl, be careful with the brackets in the URL -- you should escape them from the shell with single quotes (''). ===== Skipping SSL Certificate Validation The configuration server's validation of the Git server's SSL certificate can be disabled by setting the `git.skipSslValidation` property to `true` (default is `false`). [source,yaml] ---- spring: cloud: config: server: git: uri: https://example.com/my/repo skipSslValidation: true ---- ===== Setting HTTP Connection Timeout You can configure the time, in seconds, that the configuration server will wait to acquire an HTTP connection. Use the `git.timeout` property. [source,yaml] ---- spring: cloud: config: server: git: uri: https://example.com/my/repo timeout: 4 ---- ===== Placeholders in Git URI Spring Cloud Config Server supports a git repository URL with placeholders for the `{application}` and `{profile}` (and `{label}` if you need it, but remember that the label is applied as a git label anyway). So you can support a ""`one repository per application`"" policy by using a structure similar to the following: [source,yaml] ---- spring: cloud: config: server: git: uri: https://github.com/myorg/{application} ---- You can also support a ""`one repository per profile`"" policy by using a similar pattern but with `{profile}`. Additionally, using the special string ""({special-string})"" within your `{application}` parameters can enable support for multiple organizations, as shown in the following example: [source,yaml] ---- spring: cloud: config: server: git: uri: https://github.com/{application} ---- where `{application}` is provided at request time in the following format: `organization({special-string})application`. ===== Pattern Matching and Multiple Repositories Spring Cloud Config also includes support for more complex requirements with pattern matching on the application and profile name. The pattern format is a comma-separated list of `{application}/{profile}` names with wildcards (note that a pattern beginning with a wildcard may need to be quoted), as shown in the following example: [source,yaml] ---- spring: cloud: config: server: git: uri: https://github.com/spring-cloud-samples/config-repo repos: simple: https://github.com/simple/config-repo special: pattern: special*/dev*,*special*/dev* uri: https://github.com/special/config-repo local: pattern: local* uri: file:/home/configsvc/config-repo ---- If `{application}/{profile}` does not match any of the patterns, it uses the default URI defined under `spring.cloud.config.server.git.uri`. In the above example, for the ""`simple`"" repository, the pattern is `simple/\\*` (it only matches one application named `simple` in all profiles). The ""`local`"" repository matches all application names beginning with `local` in all profiles (the `/*` suffix is added automatically to any pattern that does not have a profile matcher). NOTE: The ""`one-liner`"" short cut used in the ""`simple`"" example can be used only if the only property to be set is the URI. If you need to set anything else (credentials, pattern, and so on) you need to use the full form. The `pattern` property in the repo is actually an array, so you can use a YAML array (or `[0]`, `[1]`, etc. suffixes in properties files) to bind to multiple patterns. You may need to do so if you are going to run apps with multiple profiles, as shown in the following example: [source,yaml] ---- spring: cloud: config: server: git: uri: https://github.com/spring-cloud-samples/config-repo repos: development: pattern: - '*/development' - '*/staging' uri: https://github.com/development/config-repo staging: pattern: - '*/qa' - '*/production' uri: https://github.com/staging/config-repo ---- NOTE: Spring Cloud guesses that a pattern containing a profile that does not end in `\\*` implies that you actually want to match a list of profiles starting with this pattern (so `*/staging` is a shortcut for `[""\\*/staging"", ""*/staging,*""]`, and so on). This is common where, for instance, you need to run applications in the ""`development`"" profile locally but also the ""`cloud`"" profile remotely. Every repository can also optionally store config files in sub-directories, and patterns to search for those directories can be specified as `searchPaths`. The following example shows a config file at the top level: [source,yaml] ---- spring: cloud: config: server: git: uri: https://github.com/spring-cloud-samples/config-repo searchPaths: foo,bar* ---- In the preceding example, the server searches for config files in the top level and in the `foo/` sub-directory and also any sub-directory whose name begins with `bar`. By default, the server clones remote repositories when configuration is first requested. The server can be configured to clone the repositories at startup, as shown in the following top-level example: [source,yaml] ---- spring: cloud: config: server: git: uri: https://git/common/config-repo.git repos: team-a: pattern: team-a-* cloneOnStart: true uri: http://git/team-a/config-repo.git team-b: pattern: team-b-* cloneOnStart: false uri: http://git/team-b/config-repo.git team-c: pattern: team-c-* uri: http://git/team-a/config-repo.git ---- In the preceding example, the server clones team-a's config-repo on startup, before it accepts any requests. All other repositories are not cloned until configuration from the repository is requested. NOTE: Setting a repository to be cloned when the Config Server starts up can help to identify a misconfigured configuration source (such as an invalid repository URI) quickly, while the Config Server is starting up. With `cloneOnStart` not enabled for a configuration source, the Config Server may start successfully with a misconfigured or invalid configuration source and not detect an error until an application requests configuration from that configuration source. ===== Authentication To use HTTP basic authentication on the remote repository, add the `username` and `password` properties separately (not in the URL), as shown in the following example: [source,yaml] ---- spring: cloud: config: server: git: uri: https://github.com/spring-cloud-samples/config-repo username: trolley password: strongpassword ---- If you do not use HTTPS and user credentials, SSH should also work out of the box when you store keys in the default directories (`~/.ssh`) and the URI points to an SSH location, such as `git@github.com:configuration/cloud-configuration`. It is important that an entry for the Git server be present in the `~/.ssh/known_hosts` file and that it is in `ssh-rsa` format. Other formats (such as `ecdsa-sha2-nistp256`) are not supported. To avoid surprises, you should ensure that only one entry is present in the `known_hosts` file for the Git server and that it matches the URL you provided to the config server. If you use a hostname in the URL, you want to have exactly that (not the IP) in the `known_hosts` file. The repository is accessed by using JGit, so any documentation you find on that should be applicable. HTTPS proxy settings can be set in `~/.git/config` or (in the same way as for any other JVM process) with system properties (`-Dhttps.proxyHost` and `-Dhttps.proxyPort`). TIP: If you do not know where your `~/.git` directory is, use `git config --global` to manipulate the settings (for example, `git config --global http.sslVerify false`). ===== Authentication with AWS CodeCommit Spring Cloud Config Server also supports http://docs.aws.amazon.com/codecommit/latest/userguide/welcome.html[AWS CodeCommit] authentication. AWS CodeCommit uses an authentication helper when using Git from the command line. This helper is not used with the JGit library, so a JGit CredentialProvider for AWS CodeCommit is created if the Git URI matches the AWS CodeCommit pattern. AWS CodeCommit URIs follow this pattern://git-codecommit.${AWS_REGION}.amazonaws.com/${repopath}. If you provide a username and password with an AWS CodeCommit URI, they must be the http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSGettingStartedGuide/AWSCredentials.html[AWS accessKeyId and secretAccessKey] that provide access to the repository. If you do not specify a username and password, the accessKeyId and secretAccessKey are retrieved by using the http://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/credentials.html[AWS Default Credential Provider Chain]. If your Git URI matches the CodeCommit URI pattern (shown earlier), you must provide valid AWS credentials in the username and password or in one of the locations supported by the default credential provider chain. AWS EC2 instances may use http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html[IAM Roles for EC2 Instances]. NOTE: The `aws-java-sdk-core` jar is an optional dependency. If the `aws-java-sdk-core` jar is not on your classpath, the AWS Code Commit credential provider is not created, regardless of the git server URI. ===== Git SSH configuration using properties By default, the JGit library used by Spring Cloud Config Server uses SSH configuration files such as `~/.ssh/known_hosts` and `/etc/ssh/ssh_config` when connecting to Git repositories by using an SSH URI. In cloud environments such as Cloud Foundry, the local filesystem may be ephemeral or not easily accessible. For those cases, SSH configuration can be set by using Java properties. In order to activate property-based SSH configuration, the `spring.cloud.config.server.git.ignoreLocalSshSettings` property must be set to `true`, as shown in the following example: [source,yaml] ---- spring: cloud: config: server: git: uri: git@gitserver.com:team/repo1.git ignoreLocalSshSettings: true hostKey: someHostKey hostKeyAlgorithm: ssh-rsa privateKey: | -----BEGIN RSA PRIVATE KEY----- MIIEpgIBAAKCAQEAx4UbaDzY5xjW6hc9jwN0mX33XpTDVW9WqHp5AKaRbtAC3DqX IXFMPgw3K45jxRb93f8tv9vL3rD9CUG1Gv4FM+o7ds7FRES5RTjv2RT/JVNJCoqF ol8+ngLqRZCyBtQN7zYByWMRirPGoDUqdPYrj2yq+ObBBNhg5N+hOwKjjpzdj2Ud 1l7R+wxIqmJo1IYyy16xS8WsjyQuyC0lL456qkd5BDZ0Ag8j2X9H9D5220Ln7s9i oezTipXipS7p7Jekf3Ywx6abJwOmB0rX79dV4qiNcGgzATnG1PkXxqt76VhcGa0W DDVHEEYGbSQ6hIGSh0I7BQun0aLRZojfE3gqHQIDAQABAoIBAQCZmGrk8BK6tXCd fY6yTiKxFzwb38IQP0ojIUWNrq0+9Xt+NsypviLHkXfXXCKKU4zUHeIGVRq5MN9b BO56/RrcQHHOoJdUWuOV2qMqJvPUtC0CpGkD+valhfD75MxoXU7s3FK7yjxy3rsG EmfA6tHV8/4a5umo5TqSd2YTm5B19AhRqiuUVI1wTB41DjULUGiMYrnYrhzQlVvj 5MjnKTlYu3V8PoYDfv1GmxPPh6vlpafXEeEYN8VB97e5x3DGHjZ5UrurAmTLTdO8 +AahyoKsIY612TkkQthJlt7FJAwnCGMgY6podzzvzICLFmmTXYiZ/28I4BX/mOSe pZVnfRixAoGBAO6Uiwt40/PKs53mCEWngslSCsh9oGAaLTf/XdvMns5VmuyyAyKG ti8Ol5wqBMi4GIUzjbgUvSUt+IowIrG3f5tN85wpjQ1UGVcpTnl5Qo9xaS1PFScQ xrtWZ9eNj2TsIAMp/svJsyGG3OibxfnuAIpSXNQiJPwRlW3irzpGgVx/AoGBANYW dnhshUcEHMJi3aXwR12OTDnaLoanVGLwLnkqLSYUZA7ZegpKq90UAuBdcEfgdpyi PhKpeaeIiAaNnFo8m9aoTKr+7I6/uMTlwrVnfrsVTZv3orxjwQV20YIBCVRKD1uX VhE0ozPZxwwKSPAFocpyWpGHGreGF1AIYBE9UBtjAoGBAI8bfPgJpyFyMiGBjO6z FwlJc/xlFqDusrcHL7abW5qq0L4v3R+FrJw3ZYufzLTVcKfdj6GelwJJO+8wBm+R gTKYJItEhT48duLIfTDyIpHGVm9+I1MGhh5zKuCqIhxIYr9jHloBB7kRm0rPvYY4 VAykcNgyDvtAVODP+4m6JvhjAoGBALbtTqErKN47V0+JJpapLnF0KxGrqeGIjIRV cYA6V4WYGr7NeIfesecfOC356PyhgPfpcVyEztwlvwTKb3RzIT1TZN8fH4YBr6Ee KTbTjefRFhVUjQqnucAvfGi29f+9oE3Ei9f7wA+H35ocF6JvTYUsHNMIO/3gZ38N CPjyCMa9AoGBAMhsITNe3QcbsXAbdUR00dDsIFVROzyFJ2m40i4KCRM35bC/BIBs q0TY3we+ERB40U8Z2BvU61QuwaunJ2+uGadHo58VSVdggqAo0BSkH58innKKt96J 69pcVH/4rmLbXdcmNYGm6iu+MlPQk4BUZknHSmVHIFdJ0EPupVaQ8RHT -----END RSA PRIVATE KEY----- ---- The following table describes the SSH configuration properties. .SSH Configuration Properties |=== |Property Name |Remarks |*ignoreLocalSshSettings* |If `true`, use property-based instead of file-based SSH config. Must be set at as `spring.cloud.config.server.git.ignoreLocalSshSettings`, *not* inside a repository definition. |*privateKey* |Valid SSH private key. Must be set if `ignoreLocalSshSettings` is true and Git URI is SSH format. |*hostKey* |Valid SSH host key. Must be set if `hostKeyAlgorithm` is also set. |*hostKeyAlgorithm* |One of `ssh-dss, ssh-rsa, ecdsa-sha2-nistp256, ecdsa-sha2-nistp384, or ecdsa-sha2-nistp521`. Must be set if `hostKey` is also set. |*strictHostKeyChecking* |`true` or `false`. If false, ignore errors with host key. |*knownHostsFile* |Location of custom `.known_hosts` file. |*preferredAuthentications* |Override server authentication method order. This should allow for evading login prompts if server has keyboard-interactive authentication before the `publickey` method. |=== ===== Placeholders in Git Search Paths Spring Cloud Config Server also supports a search path with placeholders for the `{application}` and `{profile}` (and `{label}` if you need it), as shown in the following example: [source,yaml] ---- spring: cloud: config: server: git: uri: https://github.com/spring-cloud-samples/config-repo searchPaths: '{application}' ---- The preceding listing causes a search of the repository for files in the same name as the directory (as well as the top level). Wildcards are also valid in a search path with placeholders (any matching directory is included in the search). ===== Force pull in Git Repositories As mentioned earlier, Spring Cloud Config Server makes a clone of the remote git repository in case the local copy gets dirty (for example, folder content changes by an OS process) such that Spring Cloud Config Server cannot update the local copy from remote repository. To solve this issue, there is a `force-pull` property that makes Spring Cloud Config Server force pull from the remote repository if the local copy is dirty, as shown in the following example: [source,yaml] ---- spring: cloud: config: server: git: uri: https://github.com/spring-cloud-samples/config-repo force-pull: true ---- If you have a multiple-repositories configuration, you can configure the `force-pull` property per repository, as shown in the following example: [source,yaml] ---- spring: cloud: config: server: git: uri: https://git/common/config-repo.git force-pull: true repos: team-a: pattern: team-a-* uri: http://git/team-a/config-repo.git force-pull: true team-b: pattern: team-b-* uri: http://git/team-b/config-repo.git force-pull: true team-c: pattern: team-c-* uri: http://git/team-a/config-repo.git ---- NOTE: The default value for `force-pull` property is `false`. ===== Deleting untracked branches in Git Repositories As Spring Cloud Config Server has a clone of the remote git repository after check-outing branch to local repo (e.g fetching properties by label) it will keep this branch forever or till the next server restart (which creates new local repo). So there could be a case when remote branch is deleted but local copy of it is still available for fetching. And if Spring Cloud Config Server client service starts with `--spring.cloud.config.label=deletedRemoteBranch,master` it will fetch properties from `deletedRemoteBranch` local branch, but not from `master`. In order to keep local repository branches clean and up to remote - `deleteUntrackedBranches` property could be set. It will make Spring Cloud Config Server *force* delete untracked branches from local repository. Example: [source,yaml] ---- spring: cloud: config: server: git: uri: https://github.com/spring-cloud-samples/config-repo deleteUntrackedBranches: true ---- NOTE: The default value for `deleteUntrackedBranches` property is `false`. ===== Git Refresh Rate You can control how often the config server will fetch updated configuration data from your Git backend by using `spring.cloud.config.server.git.refreshRate`. The value of this property is specified in seconds. By default the value is 0, meaning the config server will fetch updated configuration from the Git repo every time it is requested. ==== Version Control Backend Filesystem Use WARNING: With VCS-based backends (git, svn), files are checked out or cloned to the local filesystem. By default, they are put in the system temporary directory with a prefix of `config-repo-`. On linux, for example, it could be `/tmp/config-repo-`. Some operating systems http://serverfault.com/questions/377348/when-does-tmp-get-cleared/377349#377349[routinely clean out] temporary directories. This can lead to unexpected behavior, such as missing properties. To avoid this problem, change the directory that Config Server uses by setting `spring.cloud.config.server.git.basedir` or `spring.cloud.config.server.svn.basedir` to a directory that does not reside in the system temp structure. ==== File System Backend There is also a ""`native`"" profile in the Config Server that does not use Git but loads the config files from the local classpath or file system (any static URL you want to point to with `spring.cloud.config.server.native.searchLocations`). To use the native profile, launch the Config Server with `spring.profiles.active=native`. NOTE: Remember to use the `file:` prefix for file resources (the default without a prefix is usually the classpath). As with any Spring Boot configuration, you can embed `${}`-style environment placeholders, but remember that absolute paths in Windows require an extra `/` (for example, `file:///${user.home}/config-repo`). WARNING: The default value of the `searchLocations` is identical to a local Spring Boot application (that is, `[classpath:/, classpath:/config, file:./, file:./config]`). This does not expose the `application.properties` from the server to all clients, because any property sources present in the server are removed before being sent to the client. TIP: A filesystem backend is great for getting started quickly and for testing. To use it in production, you need to be sure that the file system is reliable and shared across all instances of the Config Server. The search locations can contain placeholders for `{application}`, `{profile}`, and `{label}`. In this way, you can segregate the directories in the path and choose a strategy that makes sense for you (such as subdirectory per application or subdirectory per profile). If you do not use placeholders in the search locations, this repository also appends the `{label}` parameter of the HTTP resource to a suffix on the search path, so properties files are loaded from each search location *and* a subdirectory with the same name as the label (the labelled properties take precedence in the Spring Environment). Thus, the default behaviour with no placeholders is the same as adding a search location ending with `/{label}/`. For example, `file:/tmp/config` is the same as `file:/tmp/config,file:/tmp/config/{label}`. This behavior can be disabled by setting `spring.cloud.config.server.native.addLabelLocations=false`. [[vault-backend]] ==== Vault Backend Spring Cloud Config Server also supports https://www.vaultproject.io[Vault] as a backend. **** Vault is a tool for securely accessing secrets. A secret is anything that to which you want to tightly control access, such as API keys, passwords, certificates, and other sensitive information. Vault provides a unified interface to any secret while providing tight access control and recording a detailed audit log. **** For more information on Vault, see the https://learn.hashicorp.com/vault/?track=getting-started#getting-started[Vault quick start guide]. To enable the config server to use a Vault backend, you can run your config server with the `vault` profile. For example, in your config server's `application.properties`, you can add `spring.profiles.active=vault`. By default, the config server assumes that your Vault server runs at `http://127.0.0.1:8200`. It also assumes that the name of backend is `secret` and the key is `application`. All of these defaults can be configured in your config server's `application.properties`. The following table describes configurable Vault properties: |=== |Name |Default Value |host |127.0.0.1 |port |8200 |scheme |http |backend |secret |defaultKey |application |profileSeparator |, |kvVersion |1 |skipSslValidation |false |timeout |5 |=== IMPORTANT: All of the properties in the preceding table must be prefixed with `spring.cloud.config.server.vault`. All configurable properties can be found in `org.springframework.cloud.config.server.environment.VaultEnvironmentRepository`. Vault 0.10.0 introduced a versioned key-value backend (k/v backend version 2) that exposes a different API than earlier versions, it now requires a `data/` between the mount path and the actual context path and wraps secrets in a `data` object. Setting `kvVersion=2` will take this into account. With your config server running, you can make HTTP requests to the server to retrieve values from the Vault backend. To do so, you need a token for your Vault server. First, place some data in you Vault, as shown in the following example: [source,sh] ---- $ vault kv put secret/application foo=bar baz=bam $ vault kv put secret/myapp foo=myappsbar ---- Second, make an HTTP request to your config server to retrieve the values, as shown in the following example: `$ curl -X ""GET"" ""http://localhost:8888/myapp/default"" -H ""X-Config-Token: yourtoken""` You should see a response similar to the following: [source,json] ---- { ""name"":""myapp"", ""profiles"":[ ""default"" ], ""label"":null, ""version"":null, ""state"":null, ""propertySources"":[ { ""name"":""vault:myapp"", ""source"":{ ""foo"":""myappsbar"" } }, { ""name"":""vault:application"", ""source"":{ ""baz"":""bam"", ""foo"":""bar"" } } ] } ---- ===== Multiple Properties Sources When using Vault, you can provide your applications with multiple properties sources. For example, assume you have written data to the following paths in Vault: [source,sh] ---- secret/myApp,dev secret/myApp secret/application,dev secret/application ---- Properties written to `secret/application` are available to <<_vault_server,all applications using the Config Server>>. An application with the name, `myApp`, would have any properties written to `secret/myApp` and `secret/application` available to it. When `myApp` has the `dev` profile enabled, properties written to all of the above paths would be available to it, with properties in the first path in the list taking priority over the others. ==== Accessing Backends Through a Proxy The configuration server can access a Git or Vault backend through an HTTP or HTTPS proxy. This behavior is controlled for either Git or Vault by settings under `proxy.http` and `proxy.https`. These settings are per repository, so if you are using a <> you must configure proxy settings for each backend in the composite individually. If using a network which requires separate proxy servers for HTTP and HTTPS URLs, you can configure both the HTTP and the HTTPS proxy settings for a single backend. The following table describes the proxy configuration properties for both HTTP and HTTPS proxies. All of these properties must be prefixed by `proxy.http` or `proxy.https`. .Proxy Configuration Properties |=== |Property Name |Remarks |*host* |The host of the proxy. |*port* |The port with which to access the proxy. |*nonProxyHosts* |Any hosts which the configuration server should access outside the proxy. If values are provided for both `proxy.http.nonProxyHosts` and `proxy.https.nonProxyHosts`, the `proxy.http` value will be used. |*username* |The username with which to authenticate to the proxy. If values are provided for both `proxy.http.username` and `proxy.https.username`, the `proxy.http` value will be used. |*password* |The password with which to authenticate to the proxy. If values are provided for both `proxy.http.password` and `proxy.https.password`, the `proxy.http` value will be used. |=== The following configuration uses an HTTPS proxy to access a Git repository. [source,yaml] ---- spring: profiles: active: git cloud: config: server: git: uri: https://github.com/spring-cloud-samples/config-repo proxy: https: host: my-proxy.host.io password: myproxypassword port: '3128' username: myproxyusername nonProxyHosts: example.com ---- ==== Sharing Configuration With All Applications Sharing configuration between all applications varies according to which approach you take, as described in the following topics: * <> * <> [[spring-cloud-config-server-file-based-repositories]] ===== File Based Repositories With file-based (git, svn, and native) repositories, resources with file names in `application*` (`application.properties`, `application.yml`, `application-*.properties`, and so on) are shared between all client applications. You can use resources with these file names to configure global defaults and have them be overridden by application-specific files as necessary. The #_property_overrides[property overrides] feature can also be used for setting global defaults, with placeholders applications allowed to override them locally. TIP: With the ""`native`"" profile (a local file system backend) , you should use an explicit search location that is not part of the server's own configuration. Otherwise, the `application*` resources in the default search locations get removed because they are part of the server. [[spring-cloud-config-server-vault-server]] ===== Vault Server When using Vault as a backend, you can share configuration with all applications by placing configuration in `secret/application`. For example, if you run the following Vault command, all applications using the config server will have the properties `foo` and `baz` available to them: [source,sh] ---- $ vault write secret/application foo=bar baz=bam ---- ==== JDBC Backend Spring Cloud Config Server supports JDBC (relational database) as a backend for configuration properties. You can enable this feature by adding `spring-jdbc` to the classpath and using the `jdbc` profile or by adding a bean of type `JdbcEnvironmentRepository`. If you include the right dependencies on the classpath (see the user guide for more details on that), Spring Boot configures a data source. // TODO Which user guide? When we know that, we should add a link to it. The database needs to have a table called `PROPERTIES` with columns called `APPLICATION`, `PROFILE`, and `LABEL` (with the usual `Environment` meaning), plus `KEY` and `VALUE` for the key and value pairs in `Properties` style. All fields are of type String in Java, so you can make them `VARCHAR` of whatever length you need. Property values behave in the same way as they would if they came from Spring Boot properties files named `{application}-{profile}.properties`, including all the encryption and decryption, which will be applied as post-processing steps (that is, not in the repository implementation directly). ==== CredHub Backend Spring Cloud Config Server supports link:https://docs.cloudfoundry.org/credhub[CredHub] as a backend for configuration properties. You can enable this feature by adding a dependency to link:https://spring.io/projects/spring-credhub[Spring CredHub]. [source,xml,indent=0] .pom.xml ---- org.springframework.credhub spring-credhub-starter ---- The following configuration uses mutual TLS to access a CredHub: [source,yaml] ---- spring: profiles: active: credhub cloud: config: server: credhub: url: https://credhub:8844 ---- The properties should be stored as JSON, such as: [source,sh] ---- credhub set --name ""/demo-app/default/master/toggles"" --type=json value: {""toggle.button"": ""blue"", ""toggle.link"": ""red""} ---- [source,sh] ---- credhub set --name ""/demo-app/default/master/abs"" --type=json value: {""marketing.enabled"": true, ""external.enabled"": false} ---- All client applications with the name `spring.cloud.config.name=demo-app` will have the following properties available to them: ---- { toggle.button: ""blue"", toggle.link: ""red"", marketing.enabled: true, external.enabled: false } ---- NOTE: When no profile is specified `default` will be used and when no label is specified `master` will be used as a default value. ===== OAuth 2.0 You can authenticate with link:https://oauth.net/2/[OAuth 2.0] using link:https://docs.cloudfoundry.org/concepts/architecture/uaa.html[UAA] as a provider. [source,xml,indent=0] .pom.xml ---- org.springframework.security spring-security-config org.springframework.security spring-security-oauth2-client ---- The following configuration uses OAuth 2.0 and UAA to access a CredHub: [source,yaml] ---- spring: profiles: active: credhub cloud: config: server: credhub: url: https://credhub:8844 oauth2: registration-id: credhub-client security: oauth2: client: registration: credhub-client: provider: uaa client-id: credhub_config_server client-secret: asecret authorization-grant-type: client_credentials provider: uaa: token-uri: https://uaa:8443/oauth/token ---- NOTE: The used UAA client-id should have `credhub.read` as scope. [[composite-environment-repositories]] ==== Composite Environment Repositories In some scenarios, you may wish to pull configuration data from multiple environment repositories. To do so, you can enable the `composite` profile in your configuration server's application properties or YAML file. If, for example, you want to pull configuration data from a Subversion repository as well as two Git repositories, you can set the following properties for your configuration server: [source,yaml] ---- spring: profiles: active: composite cloud: config: server: composite: - type: svn uri: file:///path/to/svn/repo - type: git uri: file:///path/to/rex/git/repo - type: git uri: file:///path/to/walter/git/repo ---- Using this configuration, precedence is determined by the order in which repositories are listed under the `composite` key. In the above example, the Subversion repository is listed first, so a value found in the Subversion repository will override values found for the same property in one of the Git repositories. A value found in the `rex` Git repository will be used before a value found for the same property in the `walter` Git repository. If you want to pull configuration data only from repositories that are each of distinct types, you can enable the corresponding profiles, rather than the `composite` profile, in your configuration server's application properties or YAML file. If, for example, you want to pull configuration data from a single Git repository and a single HashiCorp Vault server, you can set the following properties for your configuration server: [source,yaml] ---- spring: profiles: active: git, vault cloud: config: server: git: uri: file:///path/to/git/repo order: 2 vault: host: 127.0.0.1 port: 8200 order: 1 ---- Using this configuration, precedence can be determined by an `order` property. You can use the `order` property to specify the priority order for all your repositories. The lower the numerical value of the `order` property, the higher priority it has. The priority order of a repository helps resolve any potential conflicts between repositories that contain values for the same properties. NOTE: If your composite environment includes a Vault server as in the previous example, you must include a Vault token in every request made to the configuration server. See <>. NOTE: Any type of failure when retrieving values from an environment repository results in a failure for the entire composite environment. NOTE: When using a composite environment, it is important that all repositories contain the same labels. If you have an environment similar to those in the preceding examples and you request configuration data with the `master` label but the Subversion repository does not contain a branch called `master`, the entire request fails. ===== Custom Composite Environment Repositories In addition to using one of the environment repositories from Spring Cloud, you can also provide your own `EnvironmentRepository` bean to be included as part of a composite environment. To do so, your bean must implement the `EnvironmentRepository` interface. If you want to control the priority of your custom `EnvironmentRepository` within the composite environment, you should also implement the `Ordered` interface and override the `getOrdered` method. If you do not implement the `Ordered` interface, your `EnvironmentRepository` is given the lowest priority. ==== Property Overrides The Config Server has an ""`overrides`"" feature that lets the operator provide configuration properties to all applications. The overridden properties cannot be accidentally changed by the application with the normal Spring Boot hooks. To declare overrides, add a map of name-value pairs to `spring.cloud.config.server.overrides`, as shown in the following example: [source,yaml] ---- spring: cloud: config: server: overrides: foo: bar ---- The preceding examples causes all applications that are config clients to read `foo=bar`, independent of their own configuration. NOTE: A configuration system cannot force an application to use configuration data in any particular way. Consequently, overrides are not enforceable. However, they do provide useful default behavior for Spring Cloud Config clients. TIP: Normally, Spring environment placeholders with `${}` can be escaped (and resolved on the client) by using backslash (`\\`) to escape the `$` or the `{`. For example, `\\${app.foo:bar}` resolves to `bar`, unless the app provides its own `app.foo`. NOTE: In YAML, you do not need to escape the backslash itself. However, in properties files, you do need to escape the backslash, when you configure the overrides on the server. You can change the priority of all overrides in the client to be more like default values, letting applications supply their own values in environment variables or System properties, by setting the `spring.cloud.config.overrideNone=true` flag (the default is false) in the remote repository. === Health Indicator Config Server comes with a Health Indicator that checks whether the configured `EnvironmentRepository` is working. By default, it asks the `EnvironmentRepository` for an application named `app`, the `default` profile, and the default label provided by the `EnvironmentRepository` implementation. You can configure the Health Indicator to check more applications along with custom profiles and custom labels, as shown in the following example: [source,yaml] ---- spring: cloud: config: server: health: repositories: myservice: label: mylabel myservice-dev: name: myservice profiles: development ---- You can disable the Health Indicator by setting `spring.cloud.config.server.health.enabled=false`. === Security You can secure your Config Server in any way that makes sense to you (from physical network security to OAuth2 bearer tokens), because Spring Security and Spring Boot offer support for many security arrangements. To use the default Spring Boot-configured HTTP Basic security, include Spring Security on the classpath (for example, through `spring-boot-starter-security`). The default is a username of `user` and a randomly generated password. A random password is not useful in practice, so we recommend you configure the password (by setting `spring.security.user.password`) and encrypt it (see below for instructions on how to do that). === Encryption and Decryption IMPORTANT: To use the encryption and decryption features you need the full-strength JCE installed in your JVM (it is not included by default). You can download the ""`Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files`"" from Oracle and follow the installation instructions (essentially, you need to replace the two policy files in the JRE lib/security directory with the ones that you downloaded). If the remote property sources contain encrypted content (values starting with `{cipher}`), they are decrypted before sending to clients over HTTP. The main advantage of this setup is that the property values need not be in plain text when they are ""`at rest`"" (for example, in a git repository). If a value cannot be decrypted, it is removed from the property source and an additional property is added with the same key but prefixed with `invalid` and a value that means ""`not applicable`"" (usually ``). This is largely to prevent cipher text being used as a password and accidentally leaking. If you set up a remote config repository for config client applications, it might contain an `application.yml` similar to the following: .application.yml [source,yaml] ---- spring: datasource: username: dbuser password: '{cipher}FKSAJDFGYOS8F7GLHAKERGFHLSAJ' ---- Encrypted values in a .properties file must not be wrapped in quotes. Otherwise, the value is not decrypted. The following example shows values that would work: .application.properties ---- spring.datasource.username: dbuser spring.datasource.password: {cipher}FKSAJDFGYOS8F7GLHAKERGFHLSAJ ---- You can safely push this plain text to a shared git repository, and the secret password remains protected. The server also exposes `/encrypt` and `/decrypt` endpoints (on the assumption that these are secured and only accessed by authorized agents). If you edit a remote config file, you can use the Config Server to encrypt values by POSTing to the `/encrypt` endpoint, as shown in the following example: ---- $ curl localhost:8888/encrypt -d mysecret 682bc583f4641835fa2db009355293665d2647dade3375c0ee201de2a49f7bda ---- NOTE: If the value you encrypt has characters in it that need to be URL encoded, you should use the `--data-urlencode` option to `curl` to make sure they are encoded properly. TIP: Be sure not to include any of the curl command statistics in the encrypted value. Outputting the value to a file can help avoid this problem. The inverse operation is also available through `/decrypt` (provided the server is configured with a symmetric key or a full key pair), as shown in the following example: ---- $ curl localhost:8888/decrypt -d 682bc583f4641835fa2db009355293665d2647dade3375c0ee201de2a49f7bda mysecret ---- TIP: If you testing with curl, then use `--data-urlencode` (instead of `-d`) or set an explicit `Content-Type: text/plain` to make sure curl encodes the data correctly when there are special characters ('+' is particularly tricky). Take the encrypted value and add the `{cipher}` prefix before you put it in the YAML or properties file and before you commit and push it to a remote (potentially insecure) store. The `/encrypt` and `/decrypt` endpoints also both accept paths in the form of `/*/{name}/{profiles}`, which can be used to control cryptography on a per-application (name) and per-profile basis when clients call into the main environment resource. NOTE: To control the cryptography in this granular way, you must also provide a `@Bean` of type `TextEncryptorLocator` that creates a different encryptor per name and profiles. The one that is provided by default does not do so (all encryptions use the same key). The `spring` command line client (with Spring Cloud CLI extensions installed) can also be used to encrypt and decrypt, as shown in the following example: ---- $ spring encrypt mysecret --key foo 682bc583f4641835fa2db009355293665d2647dade3375c0ee201de2a49f7bda $ spring decrypt --key foo 682bc583f4641835fa2db009355293665d2647dade3375c0ee201de2a49f7bda mysecret ---- To use a key in a file (such as an RSA public key for encryption), prepend the key value with ""@"" and provide the file path, as shown in the following example: ---- $ spring encrypt mysecret --key @${HOME}/.ssh/id_rsa.pub AQAjPgt3eFZQXwt8tsHAVv/QHiY5sI2dRcR+... ---- NOTE: The `--key` argument is mandatory (despite having a `--` prefix). === Key Management The Config Server can use a symmetric (shared) key or an asymmetric one (RSA key pair). The asymmetric choice is superior in terms of security, but it is often more convenient to use a symmetric key since it is a single property value to configure in the `bootstrap.properties`. To configure a symmetric key, you need to set `encrypt.key` to a secret String (or use the `ENCRYPT_KEY` environment variable to keep it out of plain-text configuration files). NOTE: You cannot configure an asymmetric key using `encrypt.key`. To configure an asymmetric key use a keystore (e.g. as created by the `keytool` utility that comes with the JDK). The keystore properties are `encrypt.keyStore.\\*` with `*` equal to [options=""header""] |=== ^|Property ^|Description |`encrypt.keyStore.location`|Contains a `Resource` location |`encrypt.keyStore.password`|Holds the password that unlocks the keystore |`encrypt.keyStore.alias`|Identifies which key in the store to use |=== The encryption is done with the public key, and a private key is needed for decryption. Thus, in principle, you can configure only the public key in the server if you want to only encrypt (and are prepared to decrypt the values yourself locally with the private key). In practice, you might not want to do decrypt locally, because it spreads the key management process around all the clients, instead of concentrating it in the server. On the other hand, it can be a useful option if your config server is relatively insecure and only a handful of clients need the encrypted properties. === Creating a Key Store for Testing To create a keystore for testing, you can use a command resembling the following: ---- $ keytool -genkeypair -alias mytestkey -keyalg RSA \\ -dname ""CN=Web Server,OU=Unit,O=Organization,L=City,S=State,C=US"" \\ -keypass changeme -keystore server.jks -storepass letmein ---- Put the `server.jks` file in the classpath (for instance) and then, in your `bootstrap.yml`, for the Config Server, create the following settings: [source,yaml] ---- encrypt: keyStore: location: classpath:/server.jks password: letmein alias: mytestkey secret: changeme ---- === Using Multiple Keys and Key Rotation In addition to the `{cipher}` prefix in encrypted property values, the Config Server looks for zero or more `{name:value}` prefixes before the start of the (Base64 encoded) cipher text. The keys are passed to a `TextEncryptorLocator`, which can do whatever logic it needs to locate a `TextEncryptor` for the cipher. If you have configured a keystore (`encrypt.keystore.location`), the default locator looks for keys with aliases supplied by the `key` prefix, with a cipher text like resembling the following: [source,yaml] ---- foo: bar: `{cipher}{key:testkey}...` ---- The locator looks for a key named ""testkey"". A secret can also be supplied by using a `{secret:...}` value in the prefix. However, if it is not supplied, the default is to use the keystore password (which is what you get when you build a keystore and do not specify a secret). If you do supply a secret, you should also encrypt the secret using a custom `SecretLocator`. When the keys are being used only to encrypt a few bytes of configuration data (that is, they are not being used elsewhere), key rotation is hardly ever necessary on cryptographic grounds. However, you might occasionally need to change the keys (for example, in the event of a security breach). In that case, all the clients would need to change their source config files (for example, in git) and use a new `{key:...}` prefix in all the ciphers. Note that the clients need to first check that the key alias is available in the Config Server keystore. TIP: If you want to let the Config Server handle all encryption as well as decryption, the `{name:value}` prefixes can also be added as plain text posted to the `/encrypt` endpoint, . === Serving Encrypted Properties Sometimes you want the clients to decrypt the configuration locally, instead of doing it in the server. In that case, if you provide the `encrypt.*` configuration to locate a key, you can still have `/encrypt` and `/decrypt` endpoints, but you need to explicitly switch off the decryption of outgoing properties by placing `spring.cloud.config.server.encrypt.enabled=false` in `bootstrap.[yml|properties]`. If you do not care about the endpoints, it should work if you do not configure either the key or the enabled flag. == Serving Alternative Formats The default JSON format from the environment endpoints is perfect for consumption by Spring applications, because it maps directly onto the `Environment` abstraction. If you prefer, you can consume the same data as YAML or Java properties by adding a suffix ("".yml"", "".yaml"" or "".properties"") to the resource path. This can be useful for consumption by applications that do not care about the structure of the JSON endpoints or the extra metadata they provide (for example, an application that is not using Spring might benefit from the simplicity of this approach). The YAML and properties representations have an additional flag (provided as a boolean query parameter called `resolvePlaceholders`) to signal that placeholders in the source documents (in the standard Spring `${...}` form) should be resolved in the output before rendering, where possible. This is a useful feature for consumers that do not know about the Spring placeholder conventions. NOTE: There are limitations in using the YAML or properties formats, mainly in relation to the loss of metadata. For example, the JSON is structured as an ordered list of property sources, with names that correlate with the source. The YAML and properties forms are coalesced into a single map, even if the origin of the values has multiple sources, and the names of the original source files are lost. Also, the YAML representation is not necessarily a faithful representation of the YAML source in a backing repository either. It is constructed from a list of flat property sources, and assumptions have to be made about the form of the keys. == Serving Plain Text Instead of using the `Environment` abstraction (or one of the alternative representations of it in YAML or properties format), your applications might need generic plain-text configuration files that are tailored to their environment. The Config Server provides these through an additional endpoint at `/{name}/{profile}/{label}/{path}`, where `name`, `profile`, and `label` have the same meaning as the regular environment endpoint, but `path` is a file name (such as `log.xml`). The source files for this endpoint are located in the same way as for the environment endpoints. The same search path is used for properties and YAML files. However, instead of aggregating all matching resources, only the first one to match is returned. After a resource is located, placeholders in the normal format (`${...}`) are resolved by using the effective `Environment` for the supplied application name, profile, and label. In this way, the resource endpoint is tightly integrated with the environment endpoints. Consider the following example for a GIT or SVN repository: ---- application.yml nginx.conf ---- where `nginx.conf` looks like this: ---- server { listen 80; server_name ${nginx.server.name}; } ---- and `application.yml` like this: [source,yaml] ---- nginx: server: name: example.com --- spring: profiles: development nginx: server: name: develop.com ---- The `/foo/default/master/nginx.conf` resource might be as follows: ---- server { listen 80; server_name example.com; } ---- and `/foo/development/master/nginx.conf` like this: ---- server { listen 80; server_name develop.com; } ---- NOTE: As with the source files for environment configuration, the `profile` is used to resolve the file name. So, if you want a profile-specific file, `/\\*/development/*/logback.xml` can be resolved by a file called `logback-development.xml` (in preference to `logback.xml`). NOTE: If you do not want to supply the `label` and let the server use the default label, you can supply a `useDefaultLabel` request parameter. So, the preceding example for the `default` profile could be `/foo/default/nginx.conf?useDefaultLabel`. == Embedding the Config Server The Config Server runs best as a standalone application. However, if need be, you can embed it in another application. To do so, use the `@EnableConfigServer` annotation. An optional property named `spring.cloud.config.server.bootstrap` can be useful in this case. It is a flag to indicate whether the server should configure itself from its own remote repository. By default, the flag is off, because it can delay startup. However, when embedded in another application, it makes sense to initialize the same way as any other application. When setting `spring.cloud.config.server.bootstrap` to `true` you must also use a <>. For example [source,yaml] ---- spring: application: name: configserver profiles: active: composite cloud: config: server: composite: - type: native search-locations: ${HOME}/Desktop/config bootstrap: true ---- NOTE: If you use the bootstrap flag, the config server needs to have its name and repository URI configured in `bootstrap.yml`. To change the location of the server endpoints, you can (optionally) set `spring.cloud.config.server.prefix` (for example, `/config`), to serve the resources under a prefix. The prefix should start but not end with a `/`. It is applied to the `@RequestMappings` in the Config Server (that is, underneath the Spring Boot `server.servletPath` and `server.contextPath` prefixes). If you want to read the configuration for an application directly from the backend repository (instead of from the config server), you basically want an embedded config server with no endpoints. You can switch off the endpoints entirely by not using the `@EnableConfigServer` annotation (set `spring.cloud.config.server.bootstrap=true`). == Push Notifications and Spring Cloud Bus Many source code repository providers (such as Github, Gitlab, Gitea, Gitee, Gogs, or Bitbucket) notify you of changes in a repository through a webhook. You can configure the webhook through the provider's user interface as a URL and a set of events in which you are interested. For instance, https://developer.github.com/v3/activity/events/types/#pushevent[Github] uses a POST to the webhook with a JSON body containing a list of commits and a header (`X-Github-Event`) set to `push`. If you add a dependency on the `spring-cloud-config-monitor` library and activate the Spring Cloud Bus in your Config Server, then a `/monitor` endpoint is enabled. When the webhook is activated, the Config Server sends a `RefreshRemoteApplicationEvent` targeted at the applications it thinks might have changed. The change detection can be strategized. However, by default, it looks for changes in files that match the application name (for example, `foo.properties` is targeted at the `foo` application, while `application.properties` is targeted at all applications). The strategy to use when you want to override the behavior is `PropertyPathNotificationExtractor`, which accepts the request headers and body as parameters and returns a list of file paths that changed. The default configuration works out of the box with Github, Gitlab, Gitea, Gitee, Gogs or Bitbucket. In addition to the JSON notifications from Github, Gitlab, Gitee, or Bitbucket, you can trigger a change notification by POSTing to `/monitor` with form-encoded body parameters in the pattern of `path={name}`. Doing so broadcasts to applications matching the `{name}` pattern (which can contain wildcards). NOTE: The `RefreshRemoteApplicationEvent` is transmitted only if the `spring-cloud-bus` is activated in both the Config Server and in the client application. NOTE: The default configuration also detects filesystem changes in local git repositories. In that case, the webhook is not used. However, as soon as you edit a config file, a refresh is broadcast. == Spring Cloud Config Client A Spring Boot application can take immediate advantage of the Spring Config Server (or other external property sources provided by the application developer). It also picks up some additional useful features related to `Environment` change events. [[config-first-bootstrap]] === Config First Bootstrap The default behavior for any application that has the Spring Cloud Config Client on the classpath is as follows: When a config client starts, it binds to the Config Server (through the `spring.cloud.config.uri` bootstrap configuration property) and initializes Spring `Environment` with remote property sources. The net result of this behavior is that all client applications that want to consume the Config Server need a `bootstrap.yml` (or an environment variable) with the server address set in `spring.cloud.config.uri` (it defaults to ""http://localhost:8888""). [[discovery-first-bootstrap]] === Discovery First Bootstrap If you use a `DiscoveryClient` implementation, such as Spring Cloud Netflix and Eureka Service Discovery or Spring Cloud Consul, you can have the Config Server register with the Discovery Service. However, in the default ""`Config First`"" mode, clients cannot take advantage of the registration. If you prefer to use `DiscoveryClient` to locate the Config Server, you can do so by setting `spring.cloud.config.discovery.enabled=true` (the default is `false`). The net result of doing so is that client applications all need a `bootstrap.yml` (or an environment variable) with the appropriate discovery configuration. For example, with Spring Cloud Netflix, you need to define the Eureka server address (for example, in `eureka.client.serviceUrl.defaultZone`). The price for using this option is an extra network round trip on startup, to locate the service registration. The benefit is that, as long as the Discovery Service is a fixed point, the Config Server can change its coordinates. The default service ID is `configserver`, but you can change that on the client by setting `spring.cloud.config.discovery.serviceId` (and on the server, in the usual way for a service, such as by setting `spring.application.name`). The discovery client implementations all support some kind of metadata map (for example, we have `eureka.instance.metadataMap` for Eureka). Some additional properties of the Config Server may need to be configured in its service registration metadata so that clients can connect correctly. If the Config Server is secured with HTTP Basic, you can configure the credentials as `user` and `password`. Also, if the Config Server has a context path, you can set `configPath`. For example, the following YAML file is for a Config Server that is a Eureka client: .bootstrap.yml [source,yaml] ---- eureka: instance: ... metadataMap: user: osufhalskjrtl password: lviuhlszvaorhvlo5847 configPath: /config ---- [[config-client-fail-fast]] === Config Client Fail Fast In some cases, you may want to fail startup of a service if it cannot connect to the Config Server. If this is the desired behavior, set the bootstrap configuration property `spring.cloud.config.fail-fast=true` to make the client halt with an Exception. [[config-client-retry]] === Config Client Retry If you expect that the config server may occasionally be unavailable when your application starts, you can make it keep trying after a failure. First, you need to set `spring.cloud.config.fail-fast=false`. Then you need to add `spring-retry` and `spring-boot-starter-aop` to your classpath. The default behavior is to retry six times with an initial backoff interval of 1000ms and an exponential multiplier of 1.1 for subsequent backoffs. You can configure these properties (and others) by setting the `spring.cloud.config.retry.*` configuration properties. TIP: To take full control of the retry behavior, add a `@Bean` of type `RetryOperationsInterceptor` with an ID of `configServerRetryInterceptor`. Spring Retry has a `RetryInterceptorBuilder` that supports creating one. === Locating Remote Configuration Resources The Config Service serves property sources from `/{name}/{profile}/{label}`, where the default bindings in the client app are as follows: * ""name"" = `${spring.application.name}` * ""profile"" = `${spring.profiles.active}` (actually `Environment.getActiveProfiles()`) * ""label"" = ""master"" NOTE: When setting the property `${spring.application.name}` do not prefix your app name with the reserved word `application-` to prevent issues resolving the correct property source. You can override all of them by setting `spring.cloud.config.\\*` (where `*` is `name`, `profile` or `label`). The `label` is useful for rolling back to previous versions of configuration. With the default Config Server implementation, it can be a git label, branch name, or commit ID. Label can also be provided as a comma-separated list. In that case, the items in the list are tried one by one until one succeeds. This behavior can be useful when working on a feature branch. For instance, you might want to align the config label with your branch but make it optional (in that case, use `spring.cloud.config.label=myfeature,develop`). === Specifying Multiple Urls for the Config Server To ensure high availability when you have multiple instances of Config Server deployed and expect one or more instances to be unavailable from time to time, you can either specify multiple URLs (as a comma-separated list under the `spring.cloud.config.uri` property) or have all your instances register in a Service Registry like Eureka ( if using Discovery-First Bootstrap mode ). Note that doing so ensures high availability only when the Config Server is not running (that is, when the application has exited) or when a connection timeout has occurred. For example, if the Config Server returns a 500 (Internal Server Error) response or the Config Client receives a 401 from the Config Server (due to bad credentials or other causes), the Config Client does not try to fetch properties from other URLs. An error of that kind indicates a user issue rather than an availability problem. If you use HTTP basic security on your Config Server, it is currently possible to support per-Config Server auth credentials only if you embed the credentials in each URL you specify under the `spring.cloud.config.uri` property. If you use any other kind of security mechanism, you cannot (currently) support per-Config Server authentication and authorization. === Configuring Read Timeouts If you want to configure read timeout, this can be done by using the property `spring.cloud.config.request-read-timeout`. === Security If you use HTTP Basic security on the server, clients need to know the password (and username if it is not the default). You can specify the username and password through the config server URI or via separate username and password properties, as shown in the following example: .bootstrap.yml [source,yaml] ---- spring: cloud: config: uri: https://user:secret@myconfig.mycompany.com ---- The following example shows an alternate way to pass the same information: .bootstrap.yml [source,yaml] ---- spring: cloud: config: uri: https://myconfig.mycompany.com username: user password: secret ---- The `spring.cloud.config.password` and `spring.cloud.config.username` values override anything that is provided in the URI. If you deploy your apps on Cloud Foundry, the best way to provide the password is through service credentials (such as in the URI, since it does not need to be in a config file). The following example works locally and for a user-provided service on Cloud Foundry named `configserver`: .bootstrap.yml [source,yaml] ---- spring: cloud: config: uri: ${vcap.services.configserver.credentials.uri:http://user:password@localhost:8888} ---- If you use another form of security, you might need to <> to the `ConfigServicePropertySourceLocator` (for example, by grabbing it in the bootstrap context and injecting it). ==== Health Indicator The Config Client supplies a Spring Boot Health Indicator that attempts to load configuration from the Config Server. The health indicator can be disabled by setting `health.config.enabled=false`. The response is also cached for performance reasons. The default cache time to live is 5 minutes. To change that value, set the `health.config.time-to-live` property (in milliseconds). [[custom-rest-template]] ==== Providing A Custom RestTemplate In some cases, you might need to customize the requests made to the config server from the client. Typically, doing so involves passing special `Authorization` headers to authenticate requests to the server. To provide a custom `RestTemplate`: 1. Create a new configuration bean with an implementation of `PropertySourceLocator`, as shown in the following example: .CustomConfigServiceBootstrapConfiguration.java [source,java] ---- @Configuration public class CustomConfigServiceBootstrapConfiguration { @Bean public ConfigServicePropertySourceLocator configServicePropertySourceLocator() { ConfigClientProperties clientProperties = configClientProperties(); ConfigServicePropertySourceLocator configServicePropertySourceLocator = new ConfigServicePropertySourceLocator(clientProperties); configServicePropertySourceLocator.setRestTemplate(customRestTemplate(clientProperties)); return configServicePropertySourceLocator; } } ---- 2. In `resources/META-INF`, create a file called `spring.factories` and specify your custom configuration, as shown in the following example: .spring.factories [source,properties] ---- org.springframework.cloud.bootstrap.BootstrapConfiguration = com.my.config.client.CustomConfigServiceBootstrapConfiguration ---- ==== Vault When using Vault as a backend to your config server, the client needs to supply a token for the server to retrieve values from Vault. This token can be provided within the client by setting `spring.cloud.config.token` in `bootstrap.yml`, as shown in the following example: .bootstrap.yml [source,yaml] ---- spring: cloud: config: token: YourVaultToken ---- === Nested Keys In Vault Vault supports the ability to nest keys in a value stored in Vault, as shown in the following example: `echo -n '{""appA"": {""secret"": ""appAsecret""}, ""bar"": ""baz""}' | vault write secret/myapp -` This command writes a JSON object to your Vault. To access these values in Spring, you would use the traditional dot(`.`) annotation, as shown in the following example [source,java] ---- @Value(""${appA.secret}"") String name = ""World""; ---- The preceding code would sets the value of the `name` variable to `appAsecret`. ",16334,True,2841.1309494859775,median "= Cheatsheets [[AddressResolverOptions]] == AddressResolverOptions ++++ Configuration options for Vert.x hostname resolver. The resolver uses the local hosts file and performs DNS A and AAAA queries. ++++ ''' [cols="">25%,^25%,50%""] [frame=""topbot""] |=== ^|Name | Type ^| Description |[[cacheMaxTimeToLive]]`cacheMaxTimeToLive`|`Number (int)`| +++ Set the cache maximum TTL value in seconds. After successful resolution IP addresses are cached with their DNS response TTL, use this to set a maximum value to all responses TTL. +++ |[[cacheMinTimeToLive]]`cacheMinTimeToLive`|`Number (int)`| +++ Set the cache minimum TTL value in seconds. After resolution successful IP addresses are cached with their DNS response TTL, use this to set a minimum value to all responses TTL. +++ |[[cacheNegativeTimeToLive]]`cacheNegativeTimeToLive`|`Number (int)`| +++ Set the negative cache TTL value in seconds. After a failed hostname resolution, DNS queries won't be retried for a period of time equals to the negative TTL. This allows to reduce the response time of negative replies and reduce the amount of messages to DNS servers. +++ |[[hostsPath]]`hostsPath`|`String`| +++ Set the path of an alternate hosts configuration file to use instead of the one provided by the os.

The default value is null, so the operating system hosts config is used. +++ |[[hostsValue]]`hostsValue`|`Buffer`| +++ Set an alternate hosts configuration file to use instead of the one provided by the os.

The value should contain the hosts content literaly, for instance 127.0.0.1 localhost

The default value is null, so the operating system hosts config is used. +++ |[[maxQueries]]`maxQueries`|`Number (int)`| +++ Set the maximum number of queries when an hostname is resolved. +++ |[[ndots]]`ndots`|`Number (int)`| +++ Set the ndots value used when resolving using search domains, the default value is -1 which determines the value from the OS on Linux or uses the value 1. +++ |[[optResourceEnabled]]`optResourceEnabled`|`Boolean`| +++ Set to true to enable the automatic inclusion in DNS queries of an optional record that hints the remote DNS server about how much data the resolver can read per response. +++ |[[queryTimeout]]`queryTimeout`|`Number (long)`| +++ Set the query timeout in milliseconds, i.e the amount of time after a query is considered to be failed. +++ |[[rdFlag]]`rdFlag`|`Boolean`| +++ Set the DNS queries Recursion Desired flag value. +++ |[[searchDomains]]`searchDomains`|`Array of String`| +++ Set the lists of DNS search domains.

When the search domain list is null, the effective search domain list will be populated using the system DNS search domains. +++ |[[servers]]`servers`|`Array of String`| +++ Set the list of DNS server addresses, an address is the IP of the dns server, followed by an optional colon and a port, e.g 8.8.8.8 or {code 192.168.0.1:40000}. When the list is empty, the resolver will use the list of the system DNS server addresses from the environment, if that list cannot be retrieved it will use Google's public DNS servers ""8.8.8.8"" and ""8.8.4.4"". +++ |=== [[Argument]] == Argument ++++ Defines a command line argument. Unlike options, argument don't have names and are identified using an index. The first index is 0 (because we are in the computer world). ++++ ''' [cols="">25%,^25%,50%""] [frame=""topbot""] |=== ^|Name | Type ^| Description |[[argName]]`argName`|`String`| +++ Sets the argument name of this link. +++ |[[defaultValue]]`defaultValue`|`String`| +++ Sets the default value of this link. +++ |[[description]]`description`|`String`| +++ Sets the description of the link. +++ |[[hidden]]`hidden`|`Boolean`| +++ Sets whether or not the current link is hidden. +++ |[[index]]`index`|`Number (int)`| +++ Sets the argument index. +++ |[[multiValued]]`multiValued`|`Boolean`| +++ Sets whether or not the argument can receive several values. Only the last argument can receive several values. +++ |[[required]]`required`|`Boolean`| +++ Sets whether or not the current link is required. +++ |=== [[ClientOptionsBase]] == ClientOptionsBase ++++ Base class for Client options ++++ ''' [cols="">25%,^25%,50%""] [frame=""topbot""] |=== ^|Name | Type ^| Description |[[connectTimeout]]`connectTimeout`|`Number (int)`| +++ Set the connect timeout +++ |[[crlPaths]]`crlPaths`|`Array of String`| +++ Add a CRL path +++ |[[crlValues]]`crlValues`|`Array of Buffer`| +++ Add a CRL value +++ |[[enabledCipherSuites]]`enabledCipherSuites`|`Array of String`| +++ Add an enabled cipher suite, appended to the ordered suites. +++ |[[enabledSecureTransportProtocols]]`enabledSecureTransportProtocols`|`Array of String`| +++ Add an enabled SSL/TLS protocols, appended to the ordered protocols. +++ |[[idleTimeout]]`idleTimeout`|`Number (int)`| +++ Set the idle timeout, in seconds. zero means don't timeout. This determines if a connection will timeout and be closed if no data is received within the timeout. +++ |[[jdkSslEngineOptions]]`jdkSslEngineOptions`|`link:dataobjects.html#JdkSSLEngineOptions[JdkSSLEngineOptions]`|- |[[keyStoreOptions]]`keyStoreOptions`|`link:dataobjects.html#JksOptions[JksOptions]`| +++ Set the key/cert options in jks format, aka Java keystore. +++ |[[localAddress]]`localAddress`|`String`| +++ Set the local interface to bind for network connections. When the local address is null, it will pick any local address, the default local address is null. +++ |[[logActivity]]`logActivity`|`Boolean`| +++ Set to true to enabled network activity logging: Netty's pipeline is configured for logging on Netty's logger. +++ |[[metricsName]]`metricsName`|`String`| +++ Set the metrics name identifying the reported metrics, useful for grouping metrics with the same name. +++ |[[openSslEngineOptions]]`openSslEngineOptions`|`link:dataobjects.html#OpenSSLEngineOptions[OpenSSLEngineOptions]`|- |[[pemKeyCertOptions]]`pemKeyCertOptions`|`link:dataobjects.html#PemKeyCertOptions[PemKeyCertOptions]`| +++ Set the key/cert store options in pem format. +++ |[[pemTrustOptions]]`pemTrustOptions`|`link:dataobjects.html#PemTrustOptions[PemTrustOptions]`| +++ Set the trust options in pem format +++ |[[pfxKeyCertOptions]]`pfxKeyCertOptions`|`link:dataobjects.html#PfxOptions[PfxOptions]`| +++ Set the key/cert options in pfx format. +++ |[[pfxTrustOptions]]`pfxTrustOptions`|`link:dataobjects.html#PfxOptions[PfxOptions]`| +++ Set the trust options in pfx format +++ |[[proxyOptions]]`proxyOptions`|`link:dataobjects.html#ProxyOptions[ProxyOptions]`| +++ Set proxy options for connections via CONNECT proxy (e.g. Squid) or a SOCKS proxy. +++ |[[receiveBufferSize]]`receiveBufferSize`|`Number (int)`| +++ Set the TCP receive buffer size +++ |[[reuseAddress]]`reuseAddress`|`Boolean`| +++ Set the value of reuse address +++ |[[sendBufferSize]]`sendBufferSize`|`Number (int)`| +++ Set the TCP send buffer size +++ |[[soLinger]]`soLinger`|`Number (int)`| +++ Set whether SO_linger keep alive is enabled +++ |[[ssl]]`ssl`|`Boolean`| +++ Set whether SSL/TLS is enabled +++ |[[tcpKeepAlive]]`tcpKeepAlive`|`Boolean`| +++ Set whether TCP keep alive is enabled +++ |[[tcpNoDelay]]`tcpNoDelay`|`Boolean`| +++ Set whether TCP no delay is enabled +++ |[[trafficClass]]`trafficClass`|`Number (int)`| +++ Set the value of traffic class +++ |[[trustAll]]`trustAll`|`Boolean`| +++ Set whether all server certificates should be trusted +++ |[[trustStoreOptions]]`trustStoreOptions`|`link:dataobjects.html#JksOptions[JksOptions]`| +++ Set the trust options in jks format, aka Java trustore +++ |[[useAlpn]]`useAlpn`|`Boolean`| +++ Set the ALPN usage. +++ |[[usePooledBuffers]]`usePooledBuffers`|`Boolean`| +++ Set whether Netty pooled buffers are enabled +++ |=== [[DatagramSocketOptions]] == DatagramSocketOptions ++++ Options used to configure a datagram socket. ++++ ''' [cols="">25%,^25%,50%""] [frame=""topbot""] |=== ^|Name | Type ^| Description |[[broadcast]]`broadcast`|`Boolean`| +++ Set if the socket can receive broadcast packets +++ |[[ipV6]]`ipV6`|`Boolean`| +++ Set if IP v6 should be used +++ |[[logActivity]]`logActivity`|`Boolean`| +++ Set to true to enabled network activity logging: Netty's pipeline is configured for logging on Netty's logger. +++ |[[loopbackModeDisabled]]`loopbackModeDisabled`|`Boolean`| +++ Set if loopback mode is disabled +++ |[[multicastNetworkInterface]]`multicastNetworkInterface`|`String`| +++ Set the multicast network interface address +++ |[[multicastTimeToLive]]`multicastTimeToLive`|`Number (int)`| +++ Set the multicast ttl value +++ |[[receiveBufferSize]]`receiveBufferSize`|`Number (int)`| +++ Set the TCP receive buffer size +++ |[[reuseAddress]]`reuseAddress`|`Boolean`| +++ Set the value of reuse address +++ |[[sendBufferSize]]`sendBufferSize`|`Number (int)`| +++ Set the TCP send buffer size +++ |[[trafficClass]]`trafficClass`|`Number (int)`| +++ Set the value of traffic class +++ |=== [[DeliveryOptions]] == DeliveryOptions ++++ Delivery options are used to configure message delivery.

Delivery options allow to configure delivery timeout and message codec name, and to provide any headers that you wish to send with the message. ++++ ''' [cols="">25%,^25%,50%""] [frame=""topbot""] |=== ^|Name | Type ^| Description |[[codecName]]`codecName`|`String`| +++ Set the codec name. +++ |[[headers]]`headers`|`String`| +++ Add a message header.

Message headers can be sent with any message and will be accessible with link at the recipient. +++ |[[sendTimeout]]`sendTimeout`|`Number (long)`| +++ Set the send timeout. +++ |=== [[DeploymentOptions]] == DeploymentOptions ++++ Options for configuring a verticle deployment.

++++ ''' [cols="">25%,^25%,50%""] [frame=""topbot""] |=== ^|Name | Type ^| Description |[[config]]`config`|`Json object`| +++ Set the JSON configuration that will be passed to the verticle(s) when it's deployed +++ |[[extraClasspath]]`extraClasspath`|`Array of String`| +++ Set any extra classpath to be used when deploying the verticle.

Ignored if no isolation group is set. +++ |[[ha]]`ha`|`Boolean`| +++ Set whether the verticle(s) will be deployed as HA. +++ |[[instances]]`instances`|`Number (int)`| +++ Set the number of instances that should be deployed. +++ |[[isolatedClasses]]`isolatedClasses`|`Array of String`| +++ Set the isolated class names. +++ |[[isolationGroup]]`isolationGroup`|`String`| +++ Set the isolation group that will be used when deploying the verticle(s) +++ |[[maxWorkerExecuteTime]]`maxWorkerExecuteTime`|`Number (long)`| +++ Sets the value of max worker execute time, in ns. +++ |[[multiThreaded]]`multiThreaded`|`Boolean`| +++ Set whether the verticle(s) should be deployed as a multi-threaded worker verticle +++ |[[worker]]`worker`|`Boolean`| +++ Set whether the verticle(s) should be deployed as a worker verticle +++ |[[workerPoolName]]`workerPoolName`|`String`| +++ Set the worker pool name to use for this verticle. When no name is set, the Vert.x worker pool will be used, when a name is set, the verticle will use a named worker pool. +++ |[[workerPoolSize]]`workerPoolSize`|`Number (int)`| +++ Set the maximum number of worker threads to be used by the Vert.x instance. +++ |=== [[EventBusOptions]] == EventBusOptions ++++ Options to configure the event bus. ++++ ''' [cols="">25%,^25%,50%""] [frame=""topbot""] |=== ^|Name | Type ^| Description |[[acceptBacklog]]`acceptBacklog`|`Number (int)`| +++ Set the accept back log. +++ |[[clientAuth]]`clientAuth`|`link:enums.html#ClientAuth[ClientAuth]`| +++ Set whether client auth is required +++ |[[clusterPingInterval]]`clusterPingInterval`|`Number (long)`| +++ Set the value of cluster ping interval, in ms. +++ |[[clusterPingReplyInterval]]`clusterPingReplyInterval`|`Number (long)`| +++ Set the value of cluster ping reply interval, in ms. +++ |[[clusterPublicHost]]`clusterPublicHost`|`String`| +++ Set the public facing hostname to be used for clustering. Sometimes, e.g. when running on certain clouds, the local address the server listens on for clustering is not the same address that other nodes connect to it at, as the OS / cloud infrastructure does some kind of proxying. If this is the case you can specify a public hostname which is different from the hostname the server listens at.

The default value is null which means use the same as the cluster hostname. +++ |[[clusterPublicPort]]`clusterPublicPort`|`Number (int)`| +++ See link for an explanation. +++ |[[clustered]]`clustered`|`Boolean`| +++ Sets whether or not the event bus is clustered. +++ |[[connectTimeout]]`connectTimeout`|`Number (int)`| +++ Sets the connect timeout +++ |[[crlPaths]]`crlPaths`|`Array of String`| +++ Add a CRL path +++ |[[crlValues]]`crlValues`|`Array of Buffer`| +++ Add a CRL value +++ |[[enabledCipherSuites]]`enabledCipherSuites`|`Array of String`| +++ Add an enabled cipher suite, appended to the ordered suites. +++ |[[enabledSecureTransportProtocols]]`enabledSecureTransportProtocols`|`Array of String`| +++ Add an enabled SSL/TLS protocols, appended to the ordered protocols. +++ |[[host]]`host`|`String`| +++ Sets the host. +++ |[[idleTimeout]]`idleTimeout`|`Number (int)`| +++ Set the idle timeout, in seconds. zero means don't timeout. This determines if a connection will timeout and be closed if no data is received within the timeout. +++ |[[jdkSslEngineOptions]]`jdkSslEngineOptions`|`link:dataobjects.html#JdkSSLEngineOptions[JdkSSLEngineOptions]`|- |[[keyStoreOptions]]`keyStoreOptions`|`link:dataobjects.html#JksOptions[JksOptions]`| +++ Set the key/cert options in jks format, aka Java keystore. +++ |[[logActivity]]`logActivity`|`Boolean`| +++ Set to true to enabled network activity logging: Netty's pipeline is configured for logging on Netty's logger. +++ |[[openSslEngineOptions]]`openSslEngineOptions`|`link:dataobjects.html#OpenSSLEngineOptions[OpenSSLEngineOptions]`|- |[[pemKeyCertOptions]]`pemKeyCertOptions`|`link:dataobjects.html#PemKeyCertOptions[PemKeyCertOptions]`| +++ Set the key/cert store options in pem format. +++ |[[pemTrustOptions]]`pemTrustOptions`|`link:dataobjects.html#PemTrustOptions[PemTrustOptions]`| +++ Set the trust options in pem format +++ |[[pfxKeyCertOptions]]`pfxKeyCertOptions`|`link:dataobjects.html#PfxOptions[PfxOptions]`| +++ Set the key/cert options in pfx format. +++ |[[pfxTrustOptions]]`pfxTrustOptions`|`link:dataobjects.html#PfxOptions[PfxOptions]`| +++ Set the trust options in pfx format +++ |[[port]]`port`|`Number (int)`| +++ Sets the port. +++ |[[receiveBufferSize]]`receiveBufferSize`|`Number (int)`| +++ Set the TCP receive buffer size +++ |[[reconnectAttempts]]`reconnectAttempts`|`Number (int)`| +++ Sets the value of reconnect attempts. +++ |[[reconnectInterval]]`reconnectInterval`|`Number (long)`| +++ Set the reconnect interval. +++ |[[reuseAddress]]`reuseAddress`|`Boolean`| +++ Set the value of reuse address +++ |[[sendBufferSize]]`sendBufferSize`|`Number (int)`| +++ Set the TCP send buffer size +++ |[[soLinger]]`soLinger`|`Number (int)`| +++ Set whether SO_linger keep alive is enabled +++ |[[ssl]]`ssl`|`Boolean`| +++ Set whether SSL/TLS is enabled +++ |[[tcpKeepAlive]]`tcpKeepAlive`|`Boolean`| +++ Set whether TCP keep alive is enabled +++ |[[tcpNoDelay]]`tcpNoDelay`|`Boolean`| +++ Set whether TCP no delay is enabled +++ |[[trafficClass]]`trafficClass`|`Number (int)`| +++ Set the value of traffic class +++ |[[trustAll]]`trustAll`|`Boolean`| +++ Set whether all server certificates should be trusted. +++ |[[trustStoreOptions]]`trustStoreOptions`|`link:dataobjects.html#JksOptions[JksOptions]`| +++ Set the trust options in jks format, aka Java trustore +++ |[[useAlpn]]`useAlpn`|`Boolean`| +++ Set the ALPN usage. +++ |[[usePooledBuffers]]`usePooledBuffers`|`Boolean`| +++ Set whether Netty pooled buffers are enabled +++ |=== [[GoAway]] == GoAway ++++ A frame. ++++ ''' [cols="">25%,^25%,50%""] [frame=""topbot""] |=== ^|Name | Type ^| Description |[[debugData]]`debugData`|`Buffer`| +++ Set the additional debug data +++ |[[errorCode]]`errorCode`|`Number (long)`| +++ +++ |[[lastStreamId]]`lastStreamId`|`Number (int)`| +++ Set the last stream id. +++ |=== [[Http2Settings]] == Http2Settings ++++ HTTP2 settings, the settings is initialized with the default HTTP/2 values.

The settings expose the parameters defined by the HTTP/2 specification, as well as extra settings for protocol extensions. ++++ ''' [cols="">25%,^25%,50%""] [frame=""topbot""] |=== ^|Name | Type ^| Description |[[headerTableSize]]`headerTableSize`|`Number (long)`| +++ Set HTTP/2 setting. +++ |[[initialWindowSize]]`initialWindowSize`|`Number (int)`| +++ Set the HTTP/2 setting +++ |[[maxConcurrentStreams]]`maxConcurrentStreams`|`Number (long)`| +++ Set the HTTP/2 setting +++ |[[maxFrameSize]]`maxFrameSize`|`Number (int)`| +++ Set the HTTP/2 setting +++ |[[maxHeaderListSize]]`maxHeaderListSize`|`Number (long)`| +++ Set the HTTP/2 setting +++ |[[pushEnabled]]`pushEnabled`|`Boolean`| +++ Set the HTTP/2 setting +++ |=== [[HttpClientOptions]] == HttpClientOptions ++++ Options describing how an link will make connections. ++++ ''' [cols="">25%,^25%,50%""] [frame=""topbot""] |=== ^|Name | Type ^| Description |[[alpnVersions]]`alpnVersions`|`Array of link:enums.html#HttpVersion[HttpVersion]`| +++ Set the list of protocol versions to provide to the server during the Application-Layer Protocol Negotiation. When the list is empty, the client provides a best effort list according to link:

  • : [ ""h2"", ""http/1.1"" ]
  • otherwise: [link]
+++ |[[connectTimeout]]`connectTimeout`|`Number (int)`| +++ Set the connect timeout +++ |[[crlPaths]]`crlPaths`|`Array of String`| +++ Add a CRL path +++ |[[crlValues]]`crlValues`|`Array of Buffer`| +++ Add a CRL value +++ |[[defaultHost]]`defaultHost`|`String`| +++ Set the default host name to be used by this client in requests if none is provided when making the request. +++ |[[defaultPort]]`defaultPort`|`Number (int)`| +++ Set the default port to be used by this client in requests if none is provided when making the request. +++ |[[enabledCipherSuites]]`enabledCipherSuites`|`Array of String`| +++ Add an enabled cipher suite, appended to the ordered suites. +++ |[[enabledSecureTransportProtocols]]`enabledSecureTransportProtocols`|`Array of String`| +++ Add an enabled SSL/TLS protocols, appended to the ordered protocols. +++ |[[http2ClearTextUpgrade]]`http2ClearTextUpgrade`|`Boolean`| +++ Set to true when an h2c connection is established using an HTTP/1.1 upgrade request, and false when an h2c connection is established directly (with prior knowledge). +++ |[[http2ConnectionWindowSize]]`http2ConnectionWindowSize`|`Number (int)`| +++ Set the default HTTP/2 connection window size. It overrides the initial window size set by link, so the connection window size is greater than for its streams, in order the data throughput.

A value of -1 reuses the initial window size setting. +++ |[[http2MaxPoolSize]]`http2MaxPoolSize`|`Number (int)`| +++ Set the maximum pool size for HTTP/2 connections +++ |[[http2MultiplexingLimit]]`http2MultiplexingLimit`|`Number (int)`| +++ Set a client limit of the number concurrent streams for each HTTP/2 connection, this limits the number of streams the client can create for a connection. The effective number of streams for a connection is the min of this value and the server's initial settings.

Setting the value to -1 means to use the value sent by the server's initial settings. -1 is the default value. +++ |[[idleTimeout]]`idleTimeout`|`Number (int)`| +++ Set the idle timeout, in seconds. zero means don't timeout. This determines if a connection will timeout and be closed if no data is received within the timeout. +++ |[[initialSettings]]`initialSettings`|`link:dataobjects.html#Http2Settings[Http2Settings]`| +++ Set the HTTP/2 connection settings immediately sent by to the server when the client connects. +++ |[[jdkSslEngineOptions]]`jdkSslEngineOptions`|`link:dataobjects.html#JdkSSLEngineOptions[JdkSSLEngineOptions]`|- |[[keepAlive]]`keepAlive`|`Boolean`| +++ Set whether keep alive is enabled on the client +++ |[[keyStoreOptions]]`keyStoreOptions`|`link:dataobjects.html#JksOptions[JksOptions]`| +++ Set the key/cert options in jks format, aka Java keystore. +++ |[[localAddress]]`localAddress`|`String`| +++ Set the local interface to bind for network connections. When the local address is null, it will pick any local address, the default local address is null. +++ |[[logActivity]]`logActivity`|`Boolean`| +++ Set to true to enabled network activity logging: Netty's pipeline is configured for logging on Netty's logger. +++ |[[maxChunkSize]]`maxChunkSize`|`Number (int)`| +++ Set the maximum HTTP chunk size +++ |[[maxHeaderSize]]`maxHeaderSize`|`Number (int)`| +++ Set the maximum length of all headers for HTTP/1.x . +++ |[[maxInitialLineLength]]`maxInitialLineLength`|`Number (int)`| +++ Set the maximum length of the initial line for HTTP/1.x (e.g. ""HTTP/1.1 200 OK"") +++ |[[maxPoolSize]]`maxPoolSize`|`Number (int)`| +++ Set the maximum pool size for connections +++ |[[maxRedirects]]`maxRedirects`|`Number (int)`| +++ Set to maxRedirects the maximum number of redirection a request can follow. +++ |[[maxWaitQueueSize]]`maxWaitQueueSize`|`Number (int)`| +++ Set the maximum requests allowed in the wait queue, any requests beyond the max size will result in a ConnectionPoolTooBusyException. If the value is set to a negative number then the queue will be unbounded. +++ |[[maxWebsocketFrameSize]]`maxWebsocketFrameSize`|`Number (int)`| +++ Set the max websocket frame size +++ |[[metricsName]]`metricsName`|`String`| +++ Set the metrics name identifying the reported metrics, useful for grouping metrics with the same name. +++ |[[openSslEngineOptions]]`openSslEngineOptions`|`link:dataobjects.html#OpenSSLEngineOptions[OpenSSLEngineOptions]`|- |[[pemKeyCertOptions]]`pemKeyCertOptions`|`link:dataobjects.html#PemKeyCertOptions[PemKeyCertOptions]`| +++ Set the key/cert store options in pem format. +++ |[[pemTrustOptions]]`pemTrustOptions`|`link:dataobjects.html#PemTrustOptions[PemTrustOptions]`| +++ Set the trust options in pem format +++ |[[pfxKeyCertOptions]]`pfxKeyCertOptions`|`link:dataobjects.html#PfxOptions[PfxOptions]`| +++ Set the key/cert options in pfx format. +++ |[[pfxTrustOptions]]`pfxTrustOptions`|`link:dataobjects.html#PfxOptions[PfxOptions]`| +++ Set the trust options in pfx format +++ |[[pipelining]]`pipelining`|`Boolean`| +++ Set whether pipe-lining is enabled on the client +++ |[[pipeliningLimit]]`pipeliningLimit`|`Number (int)`| +++ Set the limit of pending requests a pipe-lined HTTP/1 connection can send. +++ |[[protocolVersion]]`protocolVersion`|`link:enums.html#HttpVersion[HttpVersion]`| +++ Set the protocol version. +++ |[[proxyOptions]]`proxyOptions`|`link:dataobjects.html#ProxyOptions[ProxyOptions]`| +++ Set proxy options for connections via CONNECT proxy (e.g. Squid) or a SOCKS proxy. +++ |[[receiveBufferSize]]`receiveBufferSize`|`Number (int)`| +++ Set the TCP receive buffer size +++ |[[reuseAddress]]`reuseAddress`|`Boolean`| +++ Set the value of reuse address +++ |[[sendBufferSize]]`sendBufferSize`|`Number (int)`| +++ Set the TCP send buffer size +++ |[[sendUnmaskedFrames]]`sendUnmaskedFrames`|`Boolean`| +++ Set true when the client wants to skip frame masking. You may want to set it true on server by server websocket communication: In this case you are by passing RFC6455 protocol. It's false as default. +++ |[[soLinger]]`soLinger`|`Number (int)`| +++ Set whether SO_linger keep alive is enabled +++ |[[ssl]]`ssl`|`Boolean`| +++ Set whether SSL/TLS is enabled +++ |[[tcpKeepAlive]]`tcpKeepAlive`|`Boolean`| +++ Set whether TCP keep alive is enabled +++ |[[tcpNoDelay]]`tcpNoDelay`|`Boolean`| +++ Set whether TCP no delay is enabled +++ |[[trafficClass]]`trafficClass`|`Number (int)`| +++ Set the value of traffic class +++ |[[trustAll]]`trustAll`|`Boolean`| +++ Set whether all server certificates should be trusted +++ |[[trustStoreOptions]]`trustStoreOptions`|`link:dataobjects.html#JksOptions[JksOptions]`| +++ Set the trust options in jks format, aka Java trustore +++ |[[tryUseCompression]]`tryUseCompression`|`Boolean`| +++ Set whether compression is enabled +++ |[[useAlpn]]`useAlpn`|`Boolean`| +++ Set the ALPN usage. +++ |[[usePooledBuffers]]`usePooledBuffers`|`Boolean`| +++ Set whether Netty pooled buffers are enabled +++ |[[verifyHost]]`verifyHost`|`Boolean`| +++ Set whether hostname verification is enabled +++ |=== [[HttpServerOptions]] == HttpServerOptions ++++ Represents options used by an link instance ++++ ''' [cols="">25%,^25%,50%""] [frame=""topbot""] |=== ^|Name | Type ^| Description |[[acceptBacklog]]`acceptBacklog`|`Number (int)`| +++ Set the accept back log +++ |[[acceptUnmaskedFrames]]`acceptUnmaskedFrames`|`Boolean`| +++ Set true when the server accepts unmasked frame. As default Server doesn't accept unmasked frame, you can bypass this behaviour (RFC 6455) setting true It's set to false as default. +++ |[[alpnVersions]]`alpnVersions`|`Array of link:enums.html#HttpVersion[HttpVersion]`| +++ Set the list of protocol versions to provide to the server during the Application-Layer Protocol Negotiatiation. +++ |[[clientAuth]]`clientAuth`|`link:enums.html#ClientAuth[ClientAuth]`| +++ Set whether client auth is required +++ |[[clientAuthRequired]]`clientAuthRequired`|`Boolean`| +++ Set whether client auth is required +++ |[[compressionLevel]]`compressionLevel`|`Number (int)`| +++ This method allows to set the compression level to be used in http1.x/2 response bodies when compression support is turned on (@see setCompressionSupported) and the client advertises to support deflate/gzip compression in the Accept-Encoding header default value is : 6 (Netty legacy) The compression level determines how much the data is compressed on a scale from 1 to 9, where '9' is trying to achieve the maximum compression ratio while '1' instead is giving priority to speed instead of compression ratio using some algorithm optimizations and skipping pedantic loops that usually gives just little improvements While one can think that best value is always the maximum compression ratio, there's a trade-off to consider: the most compressed level requires the most computatinal work to compress/decompress data, e.g. more dictionary lookups and loops. E.g. you have it set fairly high on a high-volume website, you may experience performance degradation and latency on resource serving due to CPU overload, and, however - as the comptational work is required also client side while decompressing - setting an higher compression level can result in an overall higher page load time especially nowadays when many clients are handled mobile devices with a low CPU profile. see also: http://www.gzip.org/algorithm.txt +++ |[[compressionSupported]]`compressionSupported`|`Boolean`| +++ Set whether the server should support gzip/deflate compression (serving compressed responses to clients advertising support for them with Accept-Encoding header) +++ |[[crlPaths]]`crlPaths`|`Array of String`| +++ Add a CRL path +++ |[[crlValues]]`crlValues`|`Array of Buffer`| +++ Add a CRL value +++ |[[decompressionSupported]]`decompressionSupported`|`Boolean`| +++ Set whether the server supports decompression +++ |[[enabledCipherSuites]]`enabledCipherSuites`|`Array of String`| +++ Add an enabled cipher suite, appended to the ordered suites. +++ |[[enabledSecureTransportProtocols]]`enabledSecureTransportProtocols`|`Array of String`| +++ Add an enabled SSL/TLS protocols, appended to the ordered protocols. +++ |[[handle100ContinueAutomatically]]`handle100ContinueAutomatically`|`Boolean`| +++ Set whether 100 Continue should be handled automatically +++ |[[host]]`host`|`String`| +++ Set the host +++ |[[http2ConnectionWindowSize]]`http2ConnectionWindowSize`|`Number (int)`| +++ Set the default HTTP/2 connection window size. It overrides the initial window size set by link, so the connection window size is greater than for its streams, in order the data throughput.

A value of -1 reuses the initial window size setting. +++ |[[idleTimeout]]`idleTimeout`|`Number (int)`| +++ Set the idle timeout, in seconds. zero means don't timeout. This determines if a connection will timeout and be closed if no data is received within the timeout. +++ |[[initialSettings]]`initialSettings`|`link:dataobjects.html#Http2Settings[Http2Settings]`| +++ Set the HTTP/2 connection settings immediatly sent by the server when a client connects. +++ |[[jdkSslEngineOptions]]`jdkSslEngineOptions`|`link:dataobjects.html#JdkSSLEngineOptions[JdkSSLEngineOptions]`|- |[[keyStoreOptions]]`keyStoreOptions`|`link:dataobjects.html#JksOptions[JksOptions]`| +++ Set the key/cert options in jks format, aka Java keystore. +++ |[[logActivity]]`logActivity`|`Boolean`| +++ Set to true to enabled network activity logging: Netty's pipeline is configured for logging on Netty's logger. +++ |[[maxChunkSize]]`maxChunkSize`|`Number (int)`| +++ Set the maximum HTTP chunk size +++ |[[maxHeaderSize]]`maxHeaderSize`|`Number (int)`| +++ Set the maximum length of all headers for HTTP/1.x . +++ |[[maxInitialLineLength]]`maxInitialLineLength`|`Number (int)`| +++ Set the maximum length of the initial line for HTTP/1.x (e.g. ""GET / HTTP/1.0"") +++ |[[maxWebsocketFrameSize]]`maxWebsocketFrameSize`|`Number (int)`| +++ Set the maximum websocket frames size +++ |[[openSslEngineOptions]]`openSslEngineOptions`|`link:dataobjects.html#OpenSSLEngineOptions[OpenSSLEngineOptions]`|- |[[pemKeyCertOptions]]`pemKeyCertOptions`|`link:dataobjects.html#PemKeyCertOptions[PemKeyCertOptions]`| +++ Set the key/cert store options in pem format. +++ |[[pemTrustOptions]]`pemTrustOptions`|`link:dataobjects.html#PemTrustOptions[PemTrustOptions]`| +++ Set the trust options in pem format +++ |[[pfxKeyCertOptions]]`pfxKeyCertOptions`|`link:dataobjects.html#PfxOptions[PfxOptions]`| +++ Set the key/cert options in pfx format. +++ |[[pfxTrustOptions]]`pfxTrustOptions`|`link:dataobjects.html#PfxOptions[PfxOptions]`| +++ Set the trust options in pfx format +++ |[[port]]`port`|`Number (int)`| +++ Set the port +++ |[[receiveBufferSize]]`receiveBufferSize`|`Number (int)`| +++ Set the TCP receive buffer size +++ |[[reuseAddress]]`reuseAddress`|`Boolean`| +++ Set the value of reuse address +++ |[[sendBufferSize]]`sendBufferSize`|`Number (int)`| +++ Set the TCP send buffer size +++ |[[soLinger]]`soLinger`|`Number (int)`| +++ Set whether SO_linger keep alive is enabled +++ |[[ssl]]`ssl`|`Boolean`| +++ Set whether SSL/TLS is enabled +++ |[[tcpKeepAlive]]`tcpKeepAlive`|`Boolean`| +++ Set whether TCP keep alive is enabled +++ |[[tcpNoDelay]]`tcpNoDelay`|`Boolean`| +++ Set whether TCP no delay is enabled +++ |[[trafficClass]]`trafficClass`|`Number (int)`| +++ Set the value of traffic class +++ |[[trustStoreOptions]]`trustStoreOptions`|`link:dataobjects.html#JksOptions[JksOptions]`| +++ Set the trust options in jks format, aka Java trustore +++ |[[useAlpn]]`useAlpn`|`Boolean`| +++ Set the ALPN usage. +++ |[[usePooledBuffers]]`usePooledBuffers`|`Boolean`| +++ Set whether Netty pooled buffers are enabled +++ |[[websocketSubProtocols]]`websocketSubProtocols`|`String`| +++ Set the websocket subprotocols supported by the server. +++ |=== [[JdkSSLEngineOptions]] == JdkSSLEngineOptions ++++ Configures a link to use the JDK ssl engine implementation. ++++ ''' [cols="">25%,^25%,50%""] [frame=""topbot""] |=== ^|Name | Type ^| Description |[[alpnAvailable]]`alpnAvailable`|`Boolean`| +++ +++ |=== [[JksOptions]] == JksOptions ++++ Key or trust store options configuring private key and/or certificates based on Java Keystore files.

When used as a key store, it should point to a store containing a private key and its certificate. When used as a trust store, it should point to a store containing a list of trusted certificates.

The store can either be loaded by Vert.x from the filesystem:

 HttpServerOptions options = HttpServerOptions.httpServerOptions();
 options.setKeyStore(new JKSOptions().setPath(""/mykeystore.jks"").setPassword(""foo""));
 
Or directly provided as a buffer:

 Buffer store = vertx.fileSystem().readFileSync(""/mykeystore.jks"");
 options.setKeyStore(new JKSOptions().setValue(store).setPassword(""foo""));
 
++++ ''' [cols="">25%,^25%,50%""] [frame=""topbot""] |=== ^|Name | Type ^| Description |[[password]]`password`|`String`| +++ Set the password for the key store +++ |[[path]]`path`|`String`| +++ Set the path to the key store +++ |[[value]]`value`|`Buffer`| +++ Set the key store as a buffer +++ |=== [[MetricsOptions]] == MetricsOptions ++++ Vert.x metrics base configuration, this class can be extended by provider implementations to configure those specific implementations. ++++ ''' [cols="">25%,^25%,50%""] [frame=""topbot""] |=== ^|Name | Type ^| Description |[[enabled]]`enabled`|`Boolean`| +++ Set whether metrics will be enabled on the Vert.x instance. +++ |=== [[NetClientOptions]] == NetClientOptions ++++ Options for configuring a link. ++++ ''' [cols="">25%,^25%,50%""] [frame=""topbot""] |=== ^|Name | Type ^| Description |[[connectTimeout]]`connectTimeout`|`Number (int)`| +++ Set the connect timeout +++ |[[crlPaths]]`crlPaths`|`Array of String`| +++ Add a CRL path +++ |[[crlValues]]`crlValues`|`Array of Buffer`| +++ Add a CRL value +++ |[[enabledCipherSuites]]`enabledCipherSuites`|`Array of String`| +++ Add an enabled cipher suite, appended to the ordered suites. +++ |[[enabledSecureTransportProtocols]]`enabledSecureTransportProtocols`|`Array of String`| +++ Add an enabled SSL/TLS protocols, appended to the ordered protocols. +++ |[[hostnameVerificationAlgorithm]]`hostnameVerificationAlgorithm`|`String`| +++ Set the hostname verification algorithm interval To disable hostname verification, set hostnameVerificationAlgorithm to an empty String +++ |[[idleTimeout]]`idleTimeout`|`Number (int)`| +++ Set the idle timeout, in seconds. zero means don't timeout. This determines if a connection will timeout and be closed if no data is received within the timeout. +++ |[[jdkSslEngineOptions]]`jdkSslEngineOptions`|`link:dataobjects.html#JdkSSLEngineOptions[JdkSSLEngineOptions]`|- |[[keyStoreOptions]]`keyStoreOptions`|`link:dataobjects.html#JksOptions[JksOptions]`| +++ Set the key/cert options in jks format, aka Java keystore. +++ |[[localAddress]]`localAddress`|`String`| +++ Set the local interface to bind for network connections. When the local address is null, it will pick any local address, the default local address is null. +++ |[[logActivity]]`logActivity`|`Boolean`| +++ Set to true to enabled network activity logging: Netty's pipeline is configured for logging on Netty's logger. +++ |[[metricsName]]`metricsName`|`String`| +++ Set the metrics name identifying the reported metrics, useful for grouping metrics with the same name. +++ |[[openSslEngineOptions]]`openSslEngineOptions`|`link:dataobjects.html#OpenSSLEngineOptions[OpenSSLEngineOptions]`|- |[[pemKeyCertOptions]]`pemKeyCertOptions`|`link:dataobjects.html#PemKeyCertOptions[PemKeyCertOptions]`| +++ Set the key/cert store options in pem format. +++ |[[pemTrustOptions]]`pemTrustOptions`|`link:dataobjects.html#PemTrustOptions[PemTrustOptions]`| +++ Set the trust options in pem format +++ |[[pfxKeyCertOptions]]`pfxKeyCertOptions`|`link:dataobjects.html#PfxOptions[PfxOptions]`| +++ Set the key/cert options in pfx format. +++ |[[pfxTrustOptions]]`pfxTrustOptions`|`link:dataobjects.html#PfxOptions[PfxOptions]`| +++ Set the trust options in pfx format +++ |[[proxyOptions]]`proxyOptions`|`link:dataobjects.html#ProxyOptions[ProxyOptions]`| +++ Set proxy options for connections via CONNECT proxy (e.g. Squid) or a SOCKS proxy. +++ |[[receiveBufferSize]]`receiveBufferSize`|`Number (int)`| +++ Set the TCP receive buffer size +++ |[[reconnectAttempts]]`reconnectAttempts`|`Number (int)`| +++ Set the value of reconnect attempts +++ |[[reconnectInterval]]`reconnectInterval`|`Number (long)`| +++ Set the reconnect interval +++ |[[reuseAddress]]`reuseAddress`|`Boolean`| +++ Set the value of reuse address +++ |[[sendBufferSize]]`sendBufferSize`|`Number (int)`| +++ Set the TCP send buffer size +++ |[[soLinger]]`soLinger`|`Number (int)`| +++ Set whether SO_linger keep alive is enabled +++ |[[ssl]]`ssl`|`Boolean`| +++ Set whether SSL/TLS is enabled +++ |[[tcpKeepAlive]]`tcpKeepAlive`|`Boolean`| +++ Set whether TCP keep alive is enabled +++ |[[tcpNoDelay]]`tcpNoDelay`|`Boolean`| +++ Set whether TCP no delay is enabled +++ |[[trafficClass]]`trafficClass`|`Number (int)`| +++ Set the value of traffic class +++ |[[trustAll]]`trustAll`|`Boolean`| +++ Set whether all server certificates should be trusted +++ |[[trustStoreOptions]]`trustStoreOptions`|`link:dataobjects.html#JksOptions[JksOptions]`| +++ Set the trust options in jks format, aka Java trustore +++ |[[useAlpn]]`useAlpn`|`Boolean`| +++ Set the ALPN usage. +++ |[[usePooledBuffers]]`usePooledBuffers`|`Boolean`| +++ Set whether Netty pooled buffers are enabled +++ |=== [[NetServerOptions]] == NetServerOptions ++++ Options for configuring a link. ++++ ''' [cols="">25%,^25%,50%""] [frame=""topbot""] |=== ^|Name | Type ^| Description |[[acceptBacklog]]`acceptBacklog`|`Number (int)`| +++ Set the accept back log +++ |[[clientAuth]]`clientAuth`|`link:enums.html#ClientAuth[ClientAuth]`| +++ Set whether client auth is required +++ |[[clientAuthRequired]]`clientAuthRequired`|`Boolean`| +++ Set whether client auth is required +++ |[[crlPaths]]`crlPaths`|`Array of String`| +++ Add a CRL path +++ |[[crlValues]]`crlValues`|`Array of Buffer`| +++ Add a CRL value +++ |[[enabledCipherSuites]]`enabledCipherSuites`|`Array of String`| +++ Add an enabled cipher suite, appended to the ordered suites. +++ |[[enabledSecureTransportProtocols]]`enabledSecureTransportProtocols`|`Array of String`| +++ Add an enabled SSL/TLS protocols, appended to the ordered protocols. +++ |[[host]]`host`|`String`| +++ Set the host +++ |[[idleTimeout]]`idleTimeout`|`Number (int)`| +++ Set the idle timeout, in seconds. zero means don't timeout. This determines if a connection will timeout and be closed if no data is received within the timeout. +++ |[[jdkSslEngineOptions]]`jdkSslEngineOptions`|`link:dataobjects.html#JdkSSLEngineOptions[JdkSSLEngineOptions]`|- |[[keyStoreOptions]]`keyStoreOptions`|`link:dataobjects.html#JksOptions[JksOptions]`| +++ Set the key/cert options in jks format, aka Java keystore. +++ |[[logActivity]]`logActivity`|`Boolean`| +++ Set to true to enabled network activity logging: Netty's pipeline is configured for logging on Netty's logger. +++ |[[openSslEngineOptions]]`openSslEngineOptions`|`link:dataobjects.html#OpenSSLEngineOptions[OpenSSLEngineOptions]`|- |[[pemKeyCertOptions]]`pemKeyCertOptions`|`link:dataobjects.html#PemKeyCertOptions[PemKeyCertOptions]`| +++ Set the key/cert store options in pem format. +++ |[[pemTrustOptions]]`pemTrustOptions`|`link:dataobjects.html#PemTrustOptions[PemTrustOptions]`| +++ Set the trust options in pem format +++ |[[pfxKeyCertOptions]]`pfxKeyCertOptions`|`link:dataobjects.html#PfxOptions[PfxOptions]`| +++ Set the key/cert options in pfx format. +++ |[[pfxTrustOptions]]`pfxTrustOptions`|`link:dataobjects.html#PfxOptions[PfxOptions]`| +++ Set the trust options in pfx format +++ |[[port]]`port`|`Number (int)`| +++ Set the port +++ |[[receiveBufferSize]]`receiveBufferSize`|`Number (int)`| +++ Set the TCP receive buffer size +++ |[[reuseAddress]]`reuseAddress`|`Boolean`| +++ Set the value of reuse address +++ |[[sendBufferSize]]`sendBufferSize`|`Number (int)`| +++ Set the TCP send buffer size +++ |[[soLinger]]`soLinger`|`Number (int)`| +++ Set whether SO_linger keep alive is enabled +++ |[[ssl]]`ssl`|`Boolean`| +++ Set whether SSL/TLS is enabled +++ |[[tcpKeepAlive]]`tcpKeepAlive`|`Boolean`| +++ Set whether TCP keep alive is enabled +++ |[[tcpNoDelay]]`tcpNoDelay`|`Boolean`| +++ Set whether TCP no delay is enabled +++ |[[trafficClass]]`trafficClass`|`Number (int)`| +++ Set the value of traffic class +++ |[[trustStoreOptions]]`trustStoreOptions`|`link:dataobjects.html#JksOptions[JksOptions]`| +++ Set the trust options in jks format, aka Java trustore +++ |[[useAlpn]]`useAlpn`|`Boolean`| +++ Set the ALPN usage. +++ |[[usePooledBuffers]]`usePooledBuffers`|`Boolean`| +++ Set whether Netty pooled buffers are enabled +++ |=== [[NetworkOptions]] == NetworkOptions ++++ ++++ ''' [cols="">25%,^25%,50%""] [frame=""topbot""] |=== ^|Name | Type ^| Description |[[logActivity]]`logActivity`|`Boolean`| +++ Set to true to enabled network activity logging: Netty's pipeline is configured for logging on Netty's logger. +++ |[[receiveBufferSize]]`receiveBufferSize`|`Number (int)`| +++ Set the TCP receive buffer size +++ |[[reuseAddress]]`reuseAddress`|`Boolean`| +++ Set the value of reuse address +++ |[[sendBufferSize]]`sendBufferSize`|`Number (int)`| +++ Set the TCP send buffer size +++ |[[trafficClass]]`trafficClass`|`Number (int)`| +++ Set the value of traffic class +++ |=== [[OpenOptions]] == OpenOptions ++++ Describes how an link should be opened. ++++ ''' [cols="">25%,^25%,50%""] [frame=""topbot""] |=== ^|Name | Type ^| Description |[[create]]`create`|`Boolean`| +++ Set whether the file should be created if it does not already exist. +++ |[[createNew]]`createNew`|`Boolean`| +++ Set whether the file should be created and fail if it does exist already. +++ |[[deleteOnClose]]`deleteOnClose`|`Boolean`| +++ Set whether the file should be deleted when it's closed, or the JVM is shutdown. +++ |[[dsync]]`dsync`|`Boolean`| +++ Set whether every write to the file's content ill be written synchronously to the underlying hardware. +++ |[[perms]]`perms`|`String`| +++ Set the permissions string +++ |[[read]]`read`|`Boolean`| +++ Set whether the file is to be opened for reading +++ |[[sparse]]`sparse`|`Boolean`| +++ Set whether a hint should be provided that the file to created is sparse +++ |[[sync]]`sync`|`Boolean`| +++ Set whether every write to the file's content and meta-data will be written synchronously to the underlying hardware. +++ |[[truncateExisting]]`truncateExisting`|`Boolean`| +++ Set whether the file should be truncated to zero length on opening if it exists and is opened for write +++ |[[write]]`write`|`Boolean`| +++ Set whether the file is to be opened for writing +++ |=== [[OpenSSLEngineOptions]] == OpenSSLEngineOptions ++++ Configures a link to use OpenSsl. ++++ ''' [cols="">25%,^25%,50%""] [frame=""topbot""] |=== ^|Name | Type ^| Description |[[alpnAvailable]]`alpnAvailable`|`Boolean`| +++ +++ |[[available]]`available`|`Boolean`| +++ +++ |[[sessionCacheEnabled]]`sessionCacheEnabled`|`Boolean`| +++ Set whether session cache is enabled in open SSL session server context +++ |=== [[Option]] == Option ++++ Models command line options. Options are values passed to a command line interface using -x or --x. Supported syntaxes depend on the parser.

Short name is generally used with a single dash, while long name requires a double-dash. ++++ ''' [cols="">25%,^25%,50%""] [frame=""topbot""] |=== ^|Name | Type ^| Description |[[argName]]`argName`|`String`| +++ Sets te arg name for this option. +++ |[[choices]]`choices`|`Array of String`| +++ Sets the list of values accepted by this option. If the value set by the user does not match once of these values, a link exception is thrown. +++ |[[defaultValue]]`defaultValue`|`String`| +++ Sets the default value of this option +++ |[[description]]`description`|`String`| +++ Sets te description of this option. +++ |[[flag]]`flag`|`Boolean`| +++ Configures the current link to be a flag. It will be evaluated to true if it's found in the command line. If you need a flag that may receive a value, use, in this order:

   option.setFlag(true).setSingleValued(true)
 
+++ |[[help]]`help`|`Boolean`| +++ Sets whether or not this option is a ""help"" option +++ |[[hidden]]`hidden`|`Boolean`| +++ Sets whether or not this option should be hidden +++ |[[longName]]`longName`|`String`| +++ Sets the long name of this option. +++ |[[multiValued]]`multiValued`|`Boolean`| +++ Sets whether or not this option can receive several values. +++ |[[name]]`name`|`String`| +++ +++ |[[required]]`required`|`Boolean`| +++ Sets whether or not this option is mandatory. +++ |[[shortName]]`shortName`|`String`| +++ Sets the short name of this option. +++ |[[singleValued]]`singleValued`|`Boolean`| +++ Sets whether or not this option can receive a value. +++ |=== [[PemKeyCertOptions]] == PemKeyCertOptions ++++ Key store options configuring a private key and its certificate based on Privacy-enhanced Electronic Email (PEM) files.

The key file must contain a non encrypted private key in PKCS8 format wrapped in a PEM block, for example:

 -----BEGIN PRIVATE KEY-----
 MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDV6zPk5WqLwS0a
 ...
 K5xBhtm1AhdnZjx5KfW3BecE
 -----END PRIVATE KEY-----
 

The certificate file must contain an X.509 certificate wrapped in a PEM block, for example:

 -----BEGIN CERTIFICATE-----
 MIIDezCCAmOgAwIBAgIEZOI/3TANBgkqhkiG9w0BAQsFADBuMRAwDgYDVQQGEwdV
 ...
 +tmLSvYS39O2nqIzzAUfztkYnUlZmB0l/mKkVqbGJA==
 -----END CERTIFICATE-----
 
The key and certificate can either be loaded by Vert.x from the filesystem:

 HttpServerOptions options = new HttpServerOptions();
 options.setPemKeyCertOptions(new PemKeyCertOptions().setKeyPath(""/mykey.pem"").setCertPath(""/mycert.pem""));
 
Or directly provided as a buffer:

 Buffer key = vertx.fileSystem().readFileSync(""/mykey.pem"");
 Buffer cert = vertx.fileSystem().readFileSync(""/mycert.pem"");
 options.setPemKeyCertOptions(new PemKeyCertOptions().setKeyValue(key).setCertValue(cert));
 
++++ ''' [cols="">25%,^25%,50%""] [frame=""topbot""] |=== ^|Name | Type ^| Description |[[certPath]]`certPath`|`String`| +++ Set the path to the certificate +++ |[[certValue]]`certValue`|`Buffer`| +++ Set the certificate as a buffer +++ |[[keyPath]]`keyPath`|`String`| +++ Set the path to the key file +++ |[[keyValue]]`keyValue`|`Buffer`| +++ Set the key a a buffer +++ |=== [[PemTrustOptions]] == PemTrustOptions ++++ Certificate Authority options configuring certificates based on Privacy-enhanced Electronic Email (PEM) files. The options is configured with a list of validating certificates.

Validating certificates must contain X.509 certificates wrapped in a PEM block:

 -----BEGIN CERTIFICATE-----
 MIIDezCCAmOgAwIBAgIEVmLkwTANBgkqhkiG9w0BAQsFADBuMRAwDgYDVQQGEwdV
 ...
 z5+DuODBJUQst141Jmgq8bS543IU/5apcKQeGNxEyQ==
 -----END CERTIFICATE-----
 
The certificates can either be loaded by Vert.x from the filesystem:

 HttpServerOptions options = new HttpServerOptions();
 options.setPemTrustOptions(new PemTrustOptions().addCertPath(""/cert.pem""));
 
Or directly provided as a buffer:

 Buffer cert = vertx.fileSystem().readFileSync(""/cert.pem"");
 HttpServerOptions options = new HttpServerOptions();
 options.setPemTrustOptions(new PemTrustOptions().addCertValue(cert));
 
++++ ''' [cols="">25%,^25%,50%""] [frame=""topbot""] |=== ^|Name | Type ^| Description |[[certPaths]]`certPaths`|`Array of String`| +++ Add a certificate path +++ |[[certValues]]`certValues`|`Array of Buffer`| +++ Add a certificate value +++ |=== [[PfxOptions]] == PfxOptions ++++ Key or trust store options configuring private key and/or certificates based on PKCS#12 files.

When used as a key store, it should point to a store containing a private key and its certificate. When used as a trust store, it should point to a store containing a list of accepted certificates.

The store can either be loaded by Vert.x from the filesystem:

 HttpServerOptions options = new HttpServerOptions();
 options.setPfxKeyCertOptions(new PfxOptions().setPath(""/mykeystore.p12"").setPassword(""foo""));
 
Or directly provided as a buffer:

 Buffer store = vertx.fileSystem().readFileSync(""/mykeystore.p12"");
 options.setPfxKeyCertOptions(new PfxOptions().setValue(store).setPassword(""foo""));
 
++++ ''' [cols="">25%,^25%,50%""] [frame=""topbot""] |=== ^|Name | Type ^| Description |[[password]]`password`|`String`| +++ Set the password +++ |[[path]]`path`|`String`| +++ Set the path +++ |[[value]]`value`|`Buffer`| +++ Set the store as a buffer +++ |=== [[ProxyOptions]] == ProxyOptions ++++ Proxy options for a net client or a net client. ++++ ''' [cols="">25%,^25%,50%""] [frame=""topbot""] |=== ^|Name | Type ^| Description |[[host]]`host`|`String`| +++ Set proxy host. +++ |[[password]]`password`|`String`| +++ Set proxy password. +++ |[[port]]`port`|`Number (int)`| +++ Set proxy port. +++ |[[type]]`type`|`link:enums.html#ProxyType[ProxyType]`| +++ Set proxy type.

ProxyType can be HTTP, SOCKS4 and SOCKS5 +++ |[[username]]`username`|`String`| +++ Set proxy username. +++ |=== [[RequestOptions]] == RequestOptions ++++ Options describing how an link will make connect to make a request. ++++ ''' [cols="">25%,^25%,50%""] [frame=""topbot""] |=== ^|Name | Type ^| Description |[[host]]`host`|`String`| +++ Set the host name to be used by the client request. +++ |[[port]]`port`|`Number (int)`| +++ Set the port to be used by the client request. +++ |[[ssl]]`ssl`|`Boolean`| +++ Set whether SSL/TLS is enabled +++ |[[uri]]`uri`|`String`| +++ Set the request relative URI +++ |=== [[TCPSSLOptions]] == TCPSSLOptions ++++ Base class. TCP and SSL related options ++++ ''' [cols="">25%,^25%,50%""] [frame=""topbot""] |=== ^|Name | Type ^| Description |[[crlPaths]]`crlPaths`|`Array of String`| +++ Add a CRL path +++ |[[crlValues]]`crlValues`|`Array of Buffer`| +++ Add a CRL value +++ |[[enabledCipherSuites]]`enabledCipherSuites`|`Array of String`| +++ Add an enabled cipher suite, appended to the ordered suites. +++ |[[enabledSecureTransportProtocols]]`enabledSecureTransportProtocols`|`Array of String`| +++ Add an enabled SSL/TLS protocols, appended to the ordered protocols. +++ |[[idleTimeout]]`idleTimeout`|`Number (int)`| +++ Set the idle timeout, in seconds. zero means don't timeout. This determines if a connection will timeout and be closed if no data is received within the timeout. +++ |[[jdkSslEngineOptions]]`jdkSslEngineOptions`|`link:dataobjects.html#JdkSSLEngineOptions[JdkSSLEngineOptions]`|- |[[keyStoreOptions]]`keyStoreOptions`|`link:dataobjects.html#JksOptions[JksOptions]`| +++ Set the key/cert options in jks format, aka Java keystore. +++ |[[logActivity]]`logActivity`|`Boolean`| +++ Set to true to enabled network activity logging: Netty's pipeline is configured for logging on Netty's logger. +++ |[[openSslEngineOptions]]`openSslEngineOptions`|`link:dataobjects.html#OpenSSLEngineOptions[OpenSSLEngineOptions]`|- |[[pemKeyCertOptions]]`pemKeyCertOptions`|`link:dataobjects.html#PemKeyCertOptions[PemKeyCertOptions]`| +++ Set the key/cert store options in pem format. +++ |[[pemTrustOptions]]`pemTrustOptions`|`link:dataobjects.html#PemTrustOptions[PemTrustOptions]`| +++ Set the trust options in pem format +++ |[[pfxKeyCertOptions]]`pfxKeyCertOptions`|`link:dataobjects.html#PfxOptions[PfxOptions]`| +++ Set the key/cert options in pfx format. +++ |[[pfxTrustOptions]]`pfxTrustOptions`|`link:dataobjects.html#PfxOptions[PfxOptions]`| +++ Set the trust options in pfx format +++ |[[receiveBufferSize]]`receiveBufferSize`|`Number (int)`| +++ Set the TCP receive buffer size +++ |[[reuseAddress]]`reuseAddress`|`Boolean`| +++ Set the value of reuse address +++ |[[sendBufferSize]]`sendBufferSize`|`Number (int)`| +++ Set the TCP send buffer size +++ |[[soLinger]]`soLinger`|`Number (int)`| +++ Set whether SO_linger keep alive is enabled +++ |[[ssl]]`ssl`|`Boolean`| +++ Set whether SSL/TLS is enabled +++ |[[tcpKeepAlive]]`tcpKeepAlive`|`Boolean`| +++ Set whether TCP keep alive is enabled +++ |[[tcpNoDelay]]`tcpNoDelay`|`Boolean`| +++ Set whether TCP no delay is enabled +++ |[[trafficClass]]`trafficClass`|`Number (int)`| +++ Set the value of traffic class +++ |[[trustStoreOptions]]`trustStoreOptions`|`link:dataobjects.html#JksOptions[JksOptions]`| +++ Set the trust options in jks format, aka Java trustore +++ |[[useAlpn]]`useAlpn`|`Boolean`| +++ Set the ALPN usage. +++ |[[usePooledBuffers]]`usePooledBuffers`|`Boolean`| +++ Set whether Netty pooled buffers are enabled +++ |=== [[VertxOptions]] == VertxOptions ++++ Instances of this class are used to configure link instances. ++++ ''' [cols="">25%,^25%,50%""] [frame=""topbot""] |=== ^|Name | Type ^| Description |[[addressResolverOptions]]`addressResolverOptions`|`link:dataobjects.html#AddressResolverOptions[AddressResolverOptions]`| +++ Sets the address resolver configuration to configure resolving DNS servers, cache TTL, etc... +++ |[[blockedThreadCheckInterval]]`blockedThreadCheckInterval`|`Number (long)`| +++ Sets the value of blocked thread check period, in ms. +++ |[[clusterHost]]`clusterHost`|`String`| +++ Set the hostname to be used for clustering. +++ |[[clusterPingInterval]]`clusterPingInterval`|`Number (long)`| +++ Set the value of cluster ping interval, in ms. +++ |[[clusterPingReplyInterval]]`clusterPingReplyInterval`|`Number (long)`| +++ Set the value of cluster ping reply interval, in ms. +++ |[[clusterPort]]`clusterPort`|`Number (int)`| +++ Set the port to be used for clustering. +++ |[[clusterPublicHost]]`clusterPublicHost`|`String`| +++ Set the public facing hostname to be used for clustering. Sometimes, e.g. when running on certain clouds, the local address the server listens on for clustering is not the same address that other nodes connect to it at, as the OS / cloud infrastructure does some kind of proxying. If this is the case you can specify a public hostname which is different from the hostname the server listens at. The default value is null which means use the same as the cluster hostname. +++ |[[clusterPublicPort]]`clusterPublicPort`|`Number (int)`| +++ See link for an explanation. +++ |[[clustered]]`clustered`|`Boolean`| +++ Set whether or not the Vert.x instance will be clustered. +++ |[[eventBusOptions]]`eventBusOptions`|`link:dataobjects.html#EventBusOptions[EventBusOptions]`| +++ Sets the event bus configuration to configure the host, port, ssl... +++ |[[eventLoopPoolSize]]`eventLoopPoolSize`|`Number (int)`| +++ Set the number of event loop threads to be used by the Vert.x instance. +++ |[[haEnabled]]`haEnabled`|`Boolean`| +++ Set whether HA will be enabled on the Vert.x instance. +++ |[[haGroup]]`haGroup`|`String`| +++ Set the HA group to be used when HA is enabled. +++ |[[internalBlockingPoolSize]]`internalBlockingPoolSize`|`Number (int)`| +++ Set the value of internal blocking pool size +++ |[[maxEventLoopExecuteTime]]`maxEventLoopExecuteTime`|`Number (long)`| +++ Sets the value of max event loop execute time, in ns. +++ |[[maxWorkerExecuteTime]]`maxWorkerExecuteTime`|`Number (long)`| +++ Sets the value of max worker execute time, in ns. +++ |[[metricsOptions]]`metricsOptions`|`link:dataobjects.html#MetricsOptions[MetricsOptions]`| +++ Set the metrics options +++ |[[quorumSize]]`quorumSize`|`Number (int)`| +++ Set the quorum size to be used when HA is enabled. +++ |[[warningExceptionTime]]`warningExceptionTime`|`Number (long)`| +++ Set the threshold value above this, the blocked warning contains a stack trace. +++ |[[workerPoolSize]]`workerPoolSize`|`Number (int)`| +++ Set the maximum number of worker threads to be used by the Vert.x instance. +++ |=== ",16293,True,3923.1590510731075,median "------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- S Y S T E M . O S _ L I B -- -- -- -- S p e c -- -- -- -- Copyright (C) 1995-2016, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- As a special exception under Section 7 of GPL version 3, you are granted -- -- additional permissions described in the GCC Runtime Library Exception, -- -- version 3.1, as published by the Free Software Foundation. -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- . -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ -- Operating system interface facilities -- This package contains types and procedures for interfacing to the -- underlying OS. It is used by the GNAT compiler and by tools associated -- with the GNAT compiler, and therefore works for the various operating -- systems to which GNAT has been ported. This package will undoubtedly grow -- as new services are needed by various tools. -- This package tends to use fairly low-level Ada in order to not bring in -- large portions of the RTL. For example, functions return access to string -- as part of avoiding functions returning unconstrained types. -- Except where specifically noted, these routines are portable across all -- GNAT implementations on all supported operating systems. -- Note: this package is in the System hierarchy so that it can be directly -- be used by other predefined packages. User access to this package is via -- a renaming of this package in GNAT.OS_Lib (file g-os_lib.ads). pragma Compiler_Unit_Warning; with System; with System.Strings; package System.OS_Lib is pragma Preelaborate; ----------------------- -- String Operations -- ----------------------- -- These are reexported from package Strings (which was introduced to -- avoid different packages declaring different types unnecessarily). -- See package System.Strings for details. subtype String_Access is Strings.String_Access; function ""="" (Left : String_Access; Right : String_Access) return Boolean renames Strings.""=""; procedure Free (X : in out String_Access) renames Strings.Free; subtype String_List is Strings.String_List; function ""="" (Left : String_List; Right : String_List) return Boolean renames Strings.""=""; function ""&"" (Left : String_Access; Right : String_Access) return String_List renames Strings.""&""; function ""&"" (Left : String_Access; Right : String_List) return String_List renames Strings.""&""; function ""&"" (Left : String_List; Right : String_Access) return String_List renames Strings.""&""; function ""&"" (Left : String_List; Right : String_List) return String_List renames Strings.""&""; subtype String_List_Access is Strings.String_List_Access; function ""="" (Left : String_List_Access; Right : String_List_Access) return Boolean renames Strings.""=""; procedure Free (Arg : in out String_List_Access) renames Strings.Free; --------------------- -- Time/Date Stuff -- --------------------- type OS_Time is private; -- The OS's notion of time is represented by the private type OS_Time. This -- is the type returned by the File_Time_Stamp functions to obtain the time -- stamp of a specified file. Functions and a procedure (modeled after the -- similar subprograms in package Calendar) are provided for extracting -- information from a value of this type. Although these are called GM, the -- intention in the case of time stamps is not that they provide GMT times -- in all cases but rather the actual (time-zone independent) time stamp of -- the file (of course in Unix systems, this *is* in GMT form). Invalid_Time : constant OS_Time; -- A special unique value used to flag an invalid time stamp value function ""<"" (X : OS_Time; Y : OS_Time) return Boolean; function "">"" (X : OS_Time; Y : OS_Time) return Boolean; function "">="" (X : OS_Time; Y : OS_Time) return Boolean; function ""<="" (X : OS_Time; Y : OS_Time) return Boolean; -- Basic comparison operators on OS_Time with obvious meanings. Note that -- these have Intrinsic convention, so for example it is not permissible -- to create accesses to any of these functions. subtype Year_Type is Integer range 1900 .. 2099; subtype Month_Type is Integer range 1 .. 12; subtype Day_Type is Integer range 1 .. 31; subtype Hour_Type is Integer range 0 .. 23; subtype Minute_Type is Integer range 0 .. 59; subtype Second_Type is Integer range 0 .. 59; -- Declarations similar to those in Calendar, breaking down the time function Current_Time return OS_Time; -- Return the system clock value as OS_Time function Current_Time_String return String; -- Returns current local time in the form YYYY-MM-DD HH:MM:SS. The result -- has bounds 1 .. 19. function GM_Year (Date : OS_Time) return Year_Type; function GM_Month (Date : OS_Time) return Month_Type; function GM_Day (Date : OS_Time) return Day_Type; function GM_Hour (Date : OS_Time) return Hour_Type; function GM_Minute (Date : OS_Time) return Minute_Type; function GM_Second (Date : OS_Time) return Second_Type; -- Functions to extract information from OS_Time value in GMT form procedure GM_Split (Date : OS_Time; Year : out Year_Type; Month : out Month_Type; Day : out Day_Type; Hour : out Hour_Type; Minute : out Minute_Type; Second : out Second_Type); -- Analogous to the Split routine in Ada.Calendar, takes an OS_Time and -- provides a representation of it as a set of component parts, to be -- interpreted as a date point in UTC. function GM_Time_Of (Year : Year_Type; Month : Month_Type; Day : Day_Type; Hour : Hour_Type; Minute : Minute_Type; Second : Second_Type) return OS_Time; -- Analogous to the Time_Of routine in Ada.Calendar, takes a set of time -- component parts to be interpreted in the local time zone, and returns -- an OS_Time. Returns Invalid_Time if the creation fails. ---------------- -- File Stuff -- ---------------- -- These routines give access to the open/creat/close/read/write level of -- I/O routines in the typical C library (these functions are not part of -- the ANSI C standard, but are typically available in all systems). See -- also package Interfaces.C_Streams for access to the stream level -- routines. -- Note on file names. If a file name is passed as type String in any of -- the following specifications, then the name is a normal Ada string and -- need not be NUL-terminated. However, a trailing NUL character is -- permitted, and will be ignored (more accurately, the NUL and any -- characters that follow it will be ignored). type File_Descriptor is new Integer; -- Corresponds to the int file handle values used in the C routines Standin : constant File_Descriptor := 0; Standout : constant File_Descriptor := 1; Standerr : constant File_Descriptor := 2; -- File descriptors for standard input output files Invalid_FD : constant File_Descriptor := -1; -- File descriptor returned when error in opening/creating file procedure Close (FD : File_Descriptor; Status : out Boolean); -- Close file referenced by FD. Status is False if the underlying service -- failed. Reasons for failure include: disk full, disk quotas exceeded -- and invalid file descriptor (the file may have been closed twice). procedure Close (FD : File_Descriptor); -- Close file referenced by FD. This form is used when the caller wants to -- ignore any possible error (see above for error cases). type Copy_Mode is (Copy, -- Copy the file. It is an error if the target file already exists. The -- time stamps and other file attributes are preserved in the copy. Overwrite, -- If the target file exists, the file is replaced otherwise the file -- is just copied. The time stamps and other file attributes are -- preserved in the copy. Append); -- If the target file exists, the contents of the source file is -- appended at the end. Otherwise the source file is just copied. The -- time stamps and other file attributes are preserved if the -- destination file does not exist. type Attribute is (Time_Stamps, -- Copy time stamps from source file to target file. All other -- attributes are set to normal default values for file creation. Full, -- All attributes are copied from the source file to the target file. -- This includes the timestamps, and for example also includes -- read/write/execute attributes in Unix systems. None); -- No attributes are copied. All attributes including the time stamp -- values are set to normal default values for file creation. -- Note: The default is Time_Stamps, which corresponds to the normal -- default on Windows style systems. Full corresponds to the typical -- effect of ""cp -p"" on Unix systems, and None corresponds to the typical -- effect of ""cp"" on Unix systems. -- Note: Time_Stamps and Full are not supported on VxWorks 5 procedure Copy_File (Name : String; Pathname : String; Success : out Boolean; Mode : Copy_Mode := Copy; Preserve : Attribute := Time_Stamps); -- Copy a file. Name must designate a single file (no wild cards allowed). -- Pathname can be a filename or directory name. In the latter case Name -- is copied into the directory preserving the same file name. Mode -- defines the kind of copy, see above with the default being a normal -- copy in which the target file must not already exist. Success is set to -- True or False indicating if the copy is successful (depending on the -- specified Mode). procedure Copy_File_Attributes (From : String; To : String; Success : out Boolean; Copy_Timestamp : Boolean := True; Copy_Permissions : Boolean := True); -- Copy some of the file attributes from one file to another. Both files -- must exist, or Success is set to False. procedure Copy_Time_Stamps (Source : String; Dest : String; Success : out Boolean); -- Copy Source file time stamps (last modification and last access time -- stamps) to Dest file. Source and Dest must be valid filenames, -- furthermore Dest must be writable. Success will be set to True if the -- operation was successful and False otherwise. -- -- Note: this procedure is not supported on VxWorks 5. On this platform, -- Success is always set to False. type Mode is (Binary, Text); for Mode'Size use Integer'Size; for Mode use (Binary => 0, Text => 1); -- Used in all the Open and Create calls to specify if the file is to be -- opened in binary mode or text mode. In systems like Unix, this has no -- effect, but in systems capable of text mode translation, the use of -- Text as the mode parameter causes the system to do CR/LF translation -- and also to recognize the DOS end of file character on input. The use -- of Text where appropriate allows programs to take a portable Unix view -- of DOS-format files and process them appropriately. function Create_File (Name : String; Fmode : Mode) return File_Descriptor; -- Creates new file with given name for writing, returning file descriptor -- for subsequent use in Write calls. If the file already exists, it is -- overwritten. File descriptor returned is Invalid_FD if file cannot be -- successfully created. function Create_New_File (Name : String; Fmode : Mode) return File_Descriptor; -- Create new file with given name for writing, returning file descriptor -- for subsequent use in Write calls. This differs from Create_File in -- that it fails if the file already exists. File descriptor returned is -- Invalid_FD if the file exists or cannot be created. function Create_Output_Text_File (Name : String) return File_Descriptor; -- Creates new text file with given name suitable to redirect standard -- output, returning file descriptor. File descriptor returned is -- Invalid_FD if file cannot be successfully created. Temp_File_Len : constant Integer := 12; -- Length of name returned by Create_Temp_File call (GNAT-XXXXXX & NUL) subtype Temp_File_Name is String (1 .. Temp_File_Len); -- String subtype set by Create_Temp_File procedure Create_Temp_File (FD : out File_Descriptor; Name : out Temp_File_Name); -- Create and open for writing a temporary file in the current working -- directory. The name of the file and the File Descriptor are returned. -- The File Descriptor returned is Invalid_FD in the case of failure. No -- mode parameter is provided. Since this is a temporary file, there is no -- point in doing text translation on it. -- -- On some operating systems, the maximum number of temp files that can be -- created with this procedure may be limited. When the maximum is reached, -- this procedure returns Invalid_FD. On some operating systems, there may -- be a race condition between processes trying to create temp files at the -- same time in the same directory using this procedure. procedure Create_Temp_File (FD : out File_Descriptor; Name : out String_Access); -- Create and open for writing a temporary file in the current working -- directory. The name of the file and the File Descriptor are returned. -- It is the responsibility of the caller to deallocate the access value -- returned in Name. -- -- The file is opened in binary mode (no text translation). -- -- This procedure will always succeed if the current working directory is -- writable. If the current working directory is not writable, then -- Invalid_FD is returned for the file descriptor and null for the Name. -- There is no race condition problem between processes trying to create -- temp files at the same time in the same directory. procedure Create_Temp_Output_File (FD : out File_Descriptor; Name : out String_Access); -- Create and open for writing a temporary file in the current working -- directory suitable to redirect standard output. The name of the file and -- the File Descriptor are returned. It is the responsibility of the caller -- to deallocate the access value returned in Name. -- -- The file is opened in text mode -- -- This procedure will always succeed if the current working directory is -- writable. If the current working directory is not writable, then -- Invalid_FD is returned for the file descriptor and null for the Name. -- There is no race condition problem between processes trying to create -- temp files at the same time in the same directory. procedure Delete_File (Name : String; Success : out Boolean); -- Deletes file. Success is set True or False indicating if the delete is -- successful. function File_Length (FD : File_Descriptor) return Long_Integer; pragma Import (C, File_Length, ""__gnat_file_length_long""); type Large_File_Size is range -2**63 .. 2**63 - 1; -- Maximum supported size for a file (8 exabytes = 8 million terabytes, -- should be enough to accomodate all possible needs for quite a while). function File_Length64 (FD : File_Descriptor) return Large_File_Size; pragma Import (C, File_Length64, ""__gnat_file_length""); -- Get length of file from file descriptor FD function File_Time_Stamp (Name : String) return OS_Time; -- Given the name of a file or directory, Name, obtains and returns the -- time stamp. This function can be used for an unopened file. Returns -- Invalid_Time if Name doesn't correspond to an existing file. function File_Time_Stamp (FD : File_Descriptor) return OS_Time; -- Get time stamp of file from file descriptor FD Returns Invalid_Time is -- FD doesn't correspond to an existing file. function Get_Debuggable_Suffix return String_Access; -- Return the debuggable suffix convention. Usually this is the same as -- the convention for Get_Executable_Suffix. The result is allocated on -- the heap and should be freed after use to avoid storage leaks. function Get_Executable_Suffix return String_Access; -- Return the executable suffix convention. The result is allocated on the -- heap and should be freed after use to avoid storage leaks. function Get_Object_Suffix return String_Access; -- Return the object suffix convention. The result is allocated on the heap -- and should be freed after use to avoid storage leaks. function Get_Target_Debuggable_Suffix return String_Access; -- Return the target debuggable suffix convention. Usually this is the same -- as the convention for Get_Executable_Suffix. The result is allocated on -- the heap and should be freed after use to avoid storage leaks. function Get_Target_Executable_Suffix return String_Access; -- Return the target executable suffix convention. The result is allocated -- on the heap and should be freed after use to avoid storage leaks. function Get_Target_Object_Suffix return String_Access; -- Return the target object suffix convention. The result is allocated on -- the heap and should be freed after use to avoid storage leaks. function Is_Absolute_Path (Name : String) return Boolean; -- Returns True if Name is an absolute path name, i.e. it designates a -- file or directory absolutely rather than relative to another directory. function Is_Directory (Name : String) return Boolean; -- Determines if the given string, Name, is the name of a directory. -- Returns True if so, False otherwise. Name may be an absolute path -- name or a relative path name, including a simple file name. If it is -- a relative path name, it is relative to the current working directory. function Is_Executable_File (Name : String) return Boolean; -- Determines if the given string, Name, is the name of an existing file -- that is executable. Returns True if so, False otherwise. Note that this -- function simply interrogates the file attributes (e.g. using the C -- function stat), so it does not indicate a situation in which a file may -- not actually be readable due to some other process having exclusive -- access. function Is_Owner_Readable_File (Name : String) return Boolean; -- Determines if the given string, Name, is the name of an existing file -- that is readable. Returns True if so, False otherwise. Note that this -- function simply interrogates the file attributes (e.g. using the C -- function stat), so it does not indicate a situation in which a file may -- not actually be readable due to some other process having exclusive -- access. function Is_Regular_File (Name : String) return Boolean; -- Determines if the given string, Name, is the name of an existing -- regular file. Returns True if so, False otherwise. Name may be an -- absolute path name or a relative path name, including a simple file -- name. If it is a relative path name, it is relative to the current -- working directory. function Is_Symbolic_Link (Name : String) return Boolean; -- Determines if the given string, Name, is the path of a symbolic link on -- systems that support it. Returns True if so, False if the path is not a -- symbolic link or if the system does not support symbolic links. -- -- A symbolic link is an indirect pointer to a file; its directory entry -- contains the name of the file to which it is linked. Symbolic links may -- span file systems and may refer to directories. function Is_Owner_Writable_File (Name : String) return Boolean; -- Determines if the given string, Name, is the name of an existing file -- that is writable. Returns True if so, False otherwise. Note that this -- function simply interrogates the file attributes (e.g. using the C -- function stat), so it does not indicate a situation in which a file may -- not actually be writable due to some other process having exclusive -- access. function Is_Read_Accessible_File (Name : String) return Boolean; -- Determines if the given string, Name, is the name of an existing file -- that is readable. Returns True if so, False otherwise. function Is_Write_Accessible_File (Name : String) return Boolean; -- Determines if the given string, Name, is the name of an existing file -- that is writable. Returns True if so, False otherwise. function Is_Readable_File (Name : String) return Boolean renames Is_Read_Accessible_File; function Is_Writable_File (Name : String) return Boolean renames Is_Write_Accessible_File; -- These subprograms provided for backward compatibility and should not be -- used. Use Is_Owner_Readable_File/Is_Owner_Writable_File or -- Is_Read_Accessible_File/Is_Write_Accessible_File instead. function Locate_Exec_On_Path (Exec_Name : String) return String_Access; -- Try to locate an executable whose name is given by Exec_Name in the -- directories listed in the environment Path. If the Exec_Name does not -- have the executable suffix, it will be appended before the search. -- Otherwise works like Locate_Regular_File below. If the executable is -- not found, null is returned. -- -- Note that this function allocates memory for the returned value. This -- memory needs to be deallocated after use. function Locate_Regular_File (File_Name : String; Path : String) return String_Access; -- Try to locate a regular file whose name is given by File_Name in the -- directories listed in Path. If a file is found, its full pathname is -- returned; otherwise, a null pointer is returned. If the File_Name given -- is an absolute pathname, then Locate_Regular_File just checks that the -- file exists and is a regular file. Otherwise, if the File_Name given -- includes directory information, Locate_Regular_File first checks if the -- file exists relative to the current directory. If it does not, or if -- the File_Name given is a simple file name, the Path argument is parsed -- according to OS conventions, and for each directory in the Path a check -- is made if File_Name is a relative pathname of a regular file from that -- directory. -- -- Note that this function allocates some memory for the returned value. -- This memory needs to be deallocated after use. Seek_Cur : constant := 1; Seek_End : constant := 2; Seek_Set : constant := 0; -- Used to indicate origin for Lseek call procedure Lseek (FD : File_Descriptor; offset : Long_Integer; origin : Integer); pragma Import (C, Lseek, ""__gnat_lseek""); -- Sets the current file pointer to the indicated offset value, relative -- to the current position (origin = SEEK_CUR), end of file (origin = -- SEEK_END), or start of file (origin = SEEK_SET). function Normalize_Pathname (Name : String; Directory : String := """"; Resolve_Links : Boolean := True; Case_Sensitive : Boolean := True) return String; -- Returns a file name as an absolute path name, resolving all relative -- directories, and symbolic links. If Name is a relative path, it is -- interpreted relative to Directory, or to the current directory if -- Directory is the empty string (the default). The result returned is -- the normalized name of the file, containing no ""."" or "".."" components, -- and no duplicated directory separators. For most cases, if two file -- names designate the same file through different paths, -- Normalize_Pathname will return the same canonical name in both cases. -- However, there are cases when this is not true; for example, this is -- not true in Unix for two hard links designating the same file. -- -- On Windows, the returned path will start with a drive letter. If -- Directory is empty (the default) and Name is a relative path or an -- absolute path without drive letter, the letter of the current drive -- will start the returned path. If Case_Sensitive is True (the default), -- then this drive letter will be forced to upper case (""C:\\...""). -- -- If Resolve_Links is set to True, then the symbolic links, on systems -- that support them, will be fully converted to the name of the file or -- directory pointed to. This is slightly less efficient, since it -- requires system calls. -- -- If Name cannot be resolved, is invalid (for example if it is too big) or -- is null on entry (for example if there is symbolic link circularity, -- e.g. A is a symbolic link for B, and B is a symbolic link for A), then -- Normalize_Pathname returns an empty string. -- -- For case-sensitive file systems, the value of Case_Sensitive parameter -- is ignored. For file systems that are not case-sensitive, such as -- Windows, if this parameter is set to False, then the file and directory -- names are folded to lower case. This allows checking whether two files -- are the same by applying this function to their names and comparing the -- results. If Case_Sensitive is set to True, this function does not change -- the casing of file and directory names. function Open_Append (Name : String; Fmode : Mode) return File_Descriptor; -- Opens file Name for appending, returning its file descriptor. File -- descriptor returned is Invalid_FD if the file cannot be successfully -- opened. function Open_Read (Name : String; Fmode : Mode) return File_Descriptor; -- Open file Name for reading, returning its file descriptor. File -- descriptor returned is Invalid_FD if the file cannot be opened. function Open_Read_Write (Name : String; Fmode : Mode) return File_Descriptor; -- Open file Name for both reading and writing, returning its file -- descriptor. File descriptor returned is Invalid_FD if the file -- cannot be opened. function Read (FD : File_Descriptor; A : System.Address; N : Integer) return Integer; -- Read N bytes to address A from file referenced by FD. Returned value is -- count of bytes actually read, which can be less than N at EOF. procedure Rename_File (Old_Name : String; New_Name : String; Success : out Boolean); -- Rename a file. Success is set True or False indicating if the rename is -- successful or not. -- -- WARNING: In one very important respect, this function is significantly -- non-portable. If New_Name already exists then on Unix systems, the call -- deletes the existing file, and the call signals success. On Windows, the -- call fails, without doing the rename operation. See also the procedure -- Ada.Directories.Rename, which portably provides the windows semantics, -- i.e. fails if the output file already exists. -- The following defines the mode for the Copy_File procedure below. Note -- that ""time stamps and other file attributes"" in the descriptions below -- refers to the creation and last modification times, and also the file -- access (read/write/execute) status flags. procedure Set_Close_On_Exec (FD : File_Descriptor; Close_On_Exec : Boolean; Status : out Boolean); -- When Close_On_Exec is True, mark FD to be closed automatically when new -- program is executed by the calling process (i.e. prevent FD from being -- inherited by child processes). When Close_On_Exec is False, mark FD to -- not be closed on exec (i.e. allow it to be inherited). Status is False -- if the operation could not be performed. S_Owner : constant := 1; S_Group : constant := 2; S_Others : constant := 4; -- Constants for use in Mode parameter to Set_Executable procedure Set_Executable (Name : String; Mode : Positive := S_Owner); -- Change permissions on the file given by Name to make it executable -- for its owner, group or others, according to the setting of Mode. -- As indicated, the default if no Mode parameter is given is owner. procedure Set_File_Last_Modify_Time_Stamp (Name : String; Time : OS_Time); -- Given the name of a file or directory, Name, set the last modification -- time stamp. This function must be used for an unopened file. procedure Set_Non_Readable (Name : String); -- Change permissions on the named file to make it non-readable for -- its owner. The writable and executable permissions are not -- modified. procedure Set_Non_Writable (Name : String); -- Change permissions on the named file to make it non-writable for its -- owner. The readable and executable permissions are not modified. procedure Set_Read_Only (Name : String) renames Set_Non_Writable; -- This renaming is provided for backwards compatibility with previous -- versions. The use of Set_Non_Writable is preferred (clearer name). procedure Set_Readable (Name : String); -- Change permissions on the named file to make it readable for its -- owner. procedure Set_Writable (Name : String); -- Change permissions on the named file to make it writable for its owner function Write (FD : File_Descriptor; A : System.Address; N : Integer) return Integer; -- Write N bytes from address A to file referenced by FD. The returned -- value is the number of bytes written, which can be less than N if a -- disk full condition was detected. -- The following section contains low-level routines using addresses to -- pass file name and executable name. In each routine the name must be -- Nul-Terminated. For complete documentation refer to the equivalent -- routine (using String in place of C_File_Name) defined above. subtype C_File_Name is System.Address; -- This subtype is used to document that a parameter is the address of a -- null-terminated string containing the name of a file. procedure Copy_File (Name : C_File_Name; Pathname : C_File_Name; Success : out Boolean; Mode : Copy_Mode := Copy; Preserve : Attribute := Time_Stamps); procedure Copy_Time_Stamps (Source : C_File_Name; Dest : C_File_Name; Success : out Boolean); function Create_File (Name : C_File_Name; Fmode : Mode) return File_Descriptor; function Create_New_File (Name : C_File_Name; Fmode : Mode) return File_Descriptor; procedure Delete_File (Name : C_File_Name; Success : out Boolean); function File_Time_Stamp (Name : C_File_Name) return OS_Time; function Is_Directory (Name : C_File_Name) return Boolean; function Is_Executable_File (Name : C_File_Name) return Boolean; function Is_Owner_Readable_File (Name : C_File_Name) return Boolean; function Is_Regular_File (Name : C_File_Name) return Boolean; function Is_Symbolic_Link (Name : C_File_Name) return Boolean; function Is_Owner_Writable_File (Name : C_File_Name) return Boolean; function Locate_Regular_File (File_Name : C_File_Name; Path : C_File_Name) return String_Access; function Open_Append (Name : C_File_Name; Fmode : Mode) return File_Descriptor; function Open_Read (Name : C_File_Name; Fmode : Mode) return File_Descriptor; function Open_Read_Write (Name : C_File_Name; Fmode : Mode) return File_Descriptor; procedure Rename_File (Old_Name : C_File_Name; New_Name : C_File_Name; Success : out Boolean); ------------------ -- Subprocesses -- ------------------ subtype Argument_List is String_List; -- Type used for argument list in call to Spawn. The lower bound of the -- array should be 1, and the length of the array indicates the number of -- arguments. subtype Argument_List_Access is String_List_Access; -- Type used to return Argument_List without dragging in secondary stack. -- Note that there is a Free procedure declared for this subtype which -- frees the array and all referenced strings. type Process_Id is private; -- A private type used to identify a process activated by the following -- non-blocking calls. The only meaningful operation on this type is a -- comparison for equality. Invalid_Pid : constant Process_Id; -- A special value used to indicate errors, as described below function Current_Process_Id return Process_Id; -- Returns the current process id or Invalid_Pid if not supported by the -- runtime. function Argument_String_To_List (Arg_String : String) return Argument_List_Access; -- Take a string that is a program and its arguments and parse it into an -- Argument_List. Note that the result is allocated on the heap, and must -- be freed by the programmer (when it is no longer needed) to avoid -- memory leaks. -- On Windows, backslashes are used as directory separators. On Unix, -- however, they are used to escape the following character, so that for -- instance ""-d=name\\ with\\ space"" is a single argument. In the result -- list, the backslashes have been cleaned up when needed. The previous -- example will thus result a single-element array, where the element is -- ""-d=name with space"" (Unix) or ""-d=name\\ with\\ space"" (windows). procedure Kill (Pid : Process_Id; Hard_Kill : Boolean := True); -- Kill the process designated by Pid. Does nothing if Pid is Invalid_Pid -- or on platforms where it is not supported, such as VxWorks. Hard_Kill -- is True by default, and when True the process is terminated immediately. -- If Hard_Kill is False, then a signal SIGINT is sent to the process on -- POSIX OS or a ctrl-C event on Windows, allowing the process a chance to -- terminate properly using a corresponding handler. procedure Kill_Process_Tree (Pid : Process_Id; Hard_Kill : Boolean := True); -- Kill the process designated by Pid and all it's children processes. -- Does nothing if Pid is Invalid_Pid or on platforms where it is not -- supported, such as VxWorks. Hard_Kill is True by default, and when True -- the processes are terminated immediately. If Hard_Kill is False, then a -- signal SIGINT is sent to the processes on POSIX OS or a ctrl-C event -- on Windows, allowing the processes a chance to terminate properly -- using a corresponding handler. -- -- Note that this routine is not atomic and is supported only on Linux -- and Windows. On other OS it will only kill the process identified by -- Pid. function Non_Blocking_Spawn (Program_Name : String; Args : Argument_List) return Process_Id; -- This is a non blocking call. The Process_Id of the spawned process is -- returned. Parameters are to be used as in Spawn. If Invalid_Pid is -- returned the program could not be spawned. -- -- Spawning processes from tasking programs is not recommended. See -- ""NOTE: Spawn in tasking programs"" below. -- -- This function will always return Invalid_Pid under VxWorks, since there -- is no notion of executables under this OS. function Non_Blocking_Spawn (Program_Name : String; Args : Argument_List; Output_File_Descriptor : File_Descriptor; Err_To_Out : Boolean := True) return Process_Id; -- Similar to the procedure above, but redirects the output to the file -- designated by Output_File_Descriptor. If Err_To_Out is True, then the -- Standard Error output is also redirected. Invalid_Pid is returned -- if the program could not be spawned successfully. -- -- Spawning processes from tasking programs is not recommended. See -- ""NOTE: Spawn in tasking programs"" below. -- -- This function will always return Invalid_Pid under VxWorks, since there -- is no notion of executables under this OS. function Non_Blocking_Spawn (Program_Name : String; Args : Argument_List; Output_File : String; Err_To_Out : Boolean := True) return Process_Id; -- Similar to the procedure above, but saves the output of the command to -- a file with the name Output_File. -- -- Invalid_Pid is returned if the output file could not be created or if -- the program could not be spawned successfully. -- -- Spawning processes from tasking programs is not recommended. See -- ""NOTE: Spawn in tasking programs"" below. -- -- This function will always return Invalid_Pid under VxWorks, since there -- is no notion of executables under this OS. function Non_Blocking_Spawn (Program_Name : String; Args : Argument_List; Stdout_File : String; Stderr_File : String) return Process_Id; -- Similar to the procedure above, but saves the standard output of the -- command to a file with the name Stdout_File and the standard output -- of the command to a file with the name Stderr_File. procedure Normalize_Arguments (Args : in out Argument_List); -- Normalize all arguments in the list. This ensure that the argument list -- is compatible with the running OS and will works fine with Spawn and -- Non_Blocking_Spawn for example. If Normalize_Arguments is called twice -- on the same list it will do nothing the second time. Note that Spawn -- and Non_Blocking_Spawn call Normalize_Arguments automatically, but -- since there is a guarantee that a second call does nothing, this -- internal call will have no effect if Normalize_Arguments is called -- before calling Spawn. The call to Normalize_Arguments assumes that the -- individual referenced arguments in Argument_List are on the heap, and -- may free them and reallocate if they are modified. function Pid_To_Integer (Pid : Process_Id) return Integer; -- Convert a process id to an Integer. Useful for writing hash functions -- for type Process_Id or to compare two Process_Id (e.g. for sorting). procedure Spawn (Program_Name : String; Args : Argument_List; Success : out Boolean); -- This procedure spawns a program with a given list of arguments. The -- first parameter of is the name of the executable. The second parameter -- contains the arguments to be passed to this program. Success is False -- if the named program could not be spawned or its execution completed -- unsuccessfully. Note that the caller will be blocked until the -- execution of the spawned program is complete. For maximum portability, -- use a full path name for the Program_Name argument. On some systems -- (notably Unix systems) a simple file name may also work (if the -- executable can be located in the path). -- -- Spawning processes from tasking programs is not recommended. See -- ""NOTE: Spawn in tasking programs"" below. -- -- Note: Arguments in Args that contain spaces and/or quotes such as -- ""--GCC=gcc -v"" or ""--GCC=""""gcc -v"""""" are not portable across all -- operating systems, and would not have the desired effect if they were -- passed directly to the operating system. To avoid this problem, Spawn -- makes an internal call to Normalize_Arguments, which ensures that such -- arguments are modified in a manner that ensures that the desired effect -- is obtained on all operating systems. The caller may call -- Normalize_Arguments explicitly before the call (e.g. to print out the -- exact form of arguments passed to the operating system). In this case -- the guarantee a second call to Normalize_Arguments has no effect -- ensures that the internal call will not affect the result. Note that -- the implicit call to Normalize_Arguments may free and reallocate some -- of the individual arguments. -- -- This function will always set Success to False under VxWorks and other -- similar operating systems which have no notion of the concept of -- dynamically executable file. Otherwise Success is set True if the exit -- status of the spawned process is zero. function Spawn (Program_Name : String; Args : Argument_List) return Integer; -- Similar to the above procedure, but returns the actual status returned -- by the operating system, or -1 under VxWorks and any other similar -- operating systems which have no notion of separately spawnable programs. -- -- Spawning processes from tasking programs is not recommended. See -- ""NOTE: Spawn in tasking programs"" below. procedure Spawn (Program_Name : String; Args : Argument_List; Output_File_Descriptor : File_Descriptor; Return_Code : out Integer; Err_To_Out : Boolean := True); -- Similar to the procedure above, but redirects the output to the file -- designated by Output_File_Descriptor. If Err_To_Out is True, then the -- Standard Error output is also redirected. -- Return_Code is set to the status code returned by the operating system -- -- Spawning processes from tasking programs is not recommended. See -- ""NOTE: Spawn in tasking programs"" below. procedure Spawn (Program_Name : String; Args : Argument_List; Output_File : String; Success : out Boolean; Return_Code : out Integer; Err_To_Out : Boolean := True); -- Similar to the procedure above, but saves the output of the command to -- a file with the name Output_File. -- -- Success is set to True if the command is executed and its output -- successfully written to the file. If Success is True, then Return_Code -- will be set to the status code returned by the operating system. -- Otherwise, Return_Code is undefined. -- -- Spawning processes from tasking programs is not recommended. See -- ""NOTE: Spawn in tasking programs"" below. procedure Wait_Process (Pid : out Process_Id; Success : out Boolean); -- Wait for the completion of any of the processes created by previous -- calls to Non_Blocking_Spawn. The caller will be suspended until one of -- these processes terminates (normally or abnormally). If any of these -- subprocesses terminates prior to the call to Wait_Process (and has not -- been returned by a previous call to Wait_Process), then the call to -- Wait_Process is immediate. Pid identifies the process that has -- terminated (matching the value returned from Non_Blocking_Spawn). -- Success is set to True if this sub-process terminated successfully. If -- Pid = Invalid_Pid, there were no subprocesses left to wait on. -- -- This function will always set success to False under VxWorks, since -- there is no notion of executables under this OS. ------------------------------------- -- NOTE: Spawn in Tasking Programs -- ------------------------------------- -- Spawning processes in tasking programs using the above Spawn and -- Non_Blocking_Spawn subprograms is not recommended, because there are -- subtle interactions between creating a process and signals/locks that -- can cause trouble. These issues are not specific to Ada; they depend -- primarily on the operating system. -- If you need to spawn processes in a tasking program, you will need to -- understand the semantics of your operating system, and you are likely to -- write non-portable code, because operating systems differ in this area. -- The Spawn and Non_Blocking_Spawn subprograms call the following -- operating system functions: -- On Windows: spawnvp (blocking) or CreateProcess (non-blocking) -- On Solaris: fork1, followed in the child process by execv -- On other Unix-like systems: fork, followed in the child -- process by execv. -- On vxworks, spawning of processes is not supported -- For details, look at the functions __gnat_portable_spawn and -- __gnat_portable_no_block_spawn in adaint.c. -- You should read the operating-system-specific documentation for the -- above functions, paying special attention to subtle interactions with -- threading, signals, locks, and file descriptors. Most of the issues are -- related to the fact that on Unix, there is a window of time between fork -- and execv; Windows does not have this problem, because spawning is done -- in a single operation. -- On Posix-compliant systems, such as Linux, fork duplicates just the -- calling thread. (On Solaris, fork1 is the Posix-compliant version of -- fork.) -- You should avoid using signals while spawning. This includes signals -- used internally by the Ada run-time system, such as timer signals used -- to implement delay statements. -- It is best to spawn any subprocesses very early, before the parent -- process creates tasks, locks, or installs signal handlers. Certainly -- avoid doing simultaneous spawns from multiple threads of the same -- process. -- There is no problem spawning a subprocess that uses tasking: the -- problems are caused only by tasking in the parent. -- If the parent is using tasking, and needs to spawn subprocesses at -- arbitrary times, one technique is for the parent to spawn (very early) -- a particular spawn-manager subprocess whose job is to spawn other -- processes. The spawn-manager must avoid tasking. The parent sends -- messages to the spawn-manager requesting it to spawn processes, using -- whatever inter-process communication mechanism you like, such as -- sockets. -- In short, mixing spawning of subprocesses with tasking is a tricky -- business, and should be avoided if possible, but if it is necessary, -- the above guidelines should be followed, and you should beware of -- portability problems. ------------------- -- Miscellaneous -- ------------------- function Errno return Integer; pragma Import (C, Errno, ""__get_errno""); -- Return the task-safe last error number function Errno_Message (Err : Integer := Errno; Default : String := """") return String; -- Return a message describing the given Errno value. If none is provided -- by the system, return Default if not empty, else return a generic -- message indicating the numeric errno value. function Getenv (Name : String) return String_Access; -- Get the value of the environment variable. Returns an access to the -- empty string if the environment variable does not exist or has an -- explicit null value (in some operating systems these are distinct -- cases, in others they are not; this interface abstracts away that -- difference. The argument is allocated on the heap (even in the null -- case), and needs to be freed explicitly when no longer needed to avoid -- memory leaks. procedure OS_Abort; pragma Import (C, OS_Abort, ""abort""); pragma No_Return (OS_Abort); -- Exit to OS signalling an abort (traceback or other appropriate -- diagnostic information should be given if possible, or entry made to -- the debugger if that is possible). procedure OS_Exit (Status : Integer); pragma No_Return (OS_Exit); -- Exit to OS with given status code (program is terminated). Note that -- this is abrupt termination. All tasks are immediately terminated. There -- are no finalization or other Ada-specific cleanup actions performed. On -- systems with atexit handlers (such as Unix and Windows), atexit handlers -- are called. type OS_Exit_Subprogram is access procedure (Status : Integer); procedure OS_Exit_Default (Status : Integer); pragma No_Return (OS_Exit_Default); -- Default implementation of procedure OS_Exit OS_Exit_Ptr : OS_Exit_Subprogram := OS_Exit_Default'Access; -- OS_Exit is implemented through this access value. It it then possible to -- change the implementation of OS_Exit by redirecting OS_Exit_Ptr to an -- other implementation. procedure Set_Errno (Errno : Integer); pragma Import (C, Set_Errno, ""__set_errno""); -- Set the task-safe error number procedure Setenv (Name : String; Value : String); -- Set the value of the environment variable Name to Value. This call -- modifies the current environment, but does not modify the parent -- process environment. After a call to Setenv, Getenv (Name) will always -- return a String_Access referencing the same String as Value. This is -- true also for the null string case (the actual effect may be to either -- set an explicit null as the value, or to remove the entry, this is -- operating system dependent). Note that any following calls to Spawn -- will pass an environment to the spawned process that includes the -- changes made by Setenv calls. Directory_Separator : constant Character; -- The character that is used to separate parts of a pathname Path_Separator : constant Character; -- The character to separate paths in an environment variable value private pragma Import (C, Path_Separator, ""__gnat_path_separator""); pragma Import (C, Directory_Separator, ""__gnat_dir_separator""); pragma Import (C, Current_Time, ""__gnat_current_time""); pragma Import (C, Current_Process_Id, ""__gnat_current_process_id""); type OS_Time is range -(2 ** (Standard'Address_Size - Integer'(1))) .. +(2 ** (Standard'Address_Size - Integer'(1)) - 1); -- Type used for timestamps in the compiler. This type is used to hold -- time stamps, but may have a different representation than C's time_t. -- This type needs to match the declaration of OS_Time in adaint.h. -- Add pragma Inline statements for comparison operations on OS_Time. It -- would actually be nice to use pragma Import (Intrinsic) here, but this -- was not properly supported till GNAT 3.15a, so that would cause -- bootstrap path problems. To be changed later ??? Invalid_Time : constant OS_Time := -1; -- This value should match the return value from __gnat_file_time_* pragma Inline (""<""); pragma Inline ("">""); pragma Inline (""<=""); pragma Inline ("">=""); type Process_Id is new Integer; Invalid_Pid : constant Process_Id := -1; end System.OS_Lib; ",12292,False,2288.811223118507,median "// tag::HeaderFullDisplayName[] = sqlparse.ftv_sqlparse_with_some_children - IF // end::HeaderFullDisplayName[] == existing_properties // tag::existing_properties[] :ExistsProperty--antorareferencinglist: :ExistsProperty--is_repo_managed: :ExistsProperty--is_ssas: :ExistsProperty--sql_modules_definition: :ExistsProperty--AntoraParameterList: :ExistsProperty--Columns: // end::existing_properties[] == RepoObject_guid // tag::RepoObject_guid[] 2F90291C-9D61-EB11-84DC-A81E8446D5B0 // end::RepoObject_guid[] == RepoObject_FullDisplayName2 // tag::RepoObject_FullDisplayName2[] sqlparse.ftv_sqlparse_with_some_children // end::RepoObject_FullDisplayName2[] == SysObject_type // tag::SysObject_type[] IF // end::SysObject_type[] == SysObject_type_name // tag::SysObject_type_name[] inline function // end::SysObject_type_name[] == SysObject_id // tag::SysObject_id[] 834102012 // end::SysObject_id[] == SysObject_modify_date // tag::SysObject_modify_date[] 2021-04-13 19:02:37 // end::SysObject_modify_date[] == AntoraColumnDetails // tag::AntoraColumnDetails[] [discrete] == _ [#column-child0underlinechildren] === child0_children [cols=""d,8a,m,m,m""] |=== | |child0_children |nvarchar(max) |NULL | |=== [#column-child0underlineclass] === child0_class [cols=""d,8a,m,m,m""] |=== | |child0_class |nvarchar(500) |NULL | |=== [#column-child0underlineisunderlinegroup] === child0_is_group [cols=""d,8a,m,m,m""] |=== | |child0_is_group |bit |NULL | |=== [#column-child0underlineisunderlinekeyword] === child0_is_keyword [cols=""d,8a,m,m,m""] |=== | |child0_is_keyword |bit |NULL | |=== [#column-child0underlineisunderlinewhitespace] === child0_is_whitespace [cols=""d,8a,m,m,m""] |=== | |child0_is_whitespace |bit |NULL | |=== [#column-child0underlinenormalized] === child0_normalized [cols=""d,8a,m,m,m""] |=== | |child0_normalized |nvarchar(max) |NULL | |=== [#column-child1underlinechildren] === child1_children [cols=""d,8a,m,m,m""] |=== | |child1_children |nvarchar(max) |NULL | |=== [#column-child1underlineclass] === child1_class [cols=""d,8a,m,m,m""] |=== | |child1_class |nvarchar(500) |NULL | |=== [#column-child1underlineisunderlinegroup] === child1_is_group [cols=""d,8a,m,m,m""] |=== | |child1_is_group |bit |NULL | |=== [#column-child1underlineisunderlinekeyword] === child1_is_keyword [cols=""d,8a,m,m,m""] |=== | |child1_is_keyword |bit |NULL | |=== [#column-child1underlineisunderlinewhitespace] === child1_is_whitespace [cols=""d,8a,m,m,m""] |=== | |child1_is_whitespace |bit |NULL | |=== [#column-child1underlinenormalized] === child1_normalized [cols=""d,8a,m,m,m""] |=== | |child1_normalized |nvarchar(max) |NULL | |=== [#column-child2underlinechildren] === child2_children [cols=""d,8a,m,m,m""] |=== | |child2_children |nvarchar(max) |NULL | |=== [#column-child2underlineclass] === child2_class [cols=""d,8a,m,m,m""] |=== | |child2_class |nvarchar(500) |NULL | |=== [#column-child2underlineisunderlinegroup] === child2_is_group [cols=""d,8a,m,m,m""] |=== | |child2_is_group |bit |NULL | |=== [#column-child2underlineisunderlinekeyword] === child2_is_keyword [cols=""d,8a,m,m,m""] |=== | |child2_is_keyword |bit |NULL | |=== [#column-child2underlineisunderlinewhitespace] === child2_is_whitespace [cols=""d,8a,m,m,m""] |=== | |child2_is_whitespace |bit |NULL | |=== [#column-child2underlinenormalized] === child2_normalized [cols=""d,8a,m,m,m""] |=== | |child2_normalized |nvarchar(max) |NULL | |=== [#column-child3underlinechildren] === child3_children [cols=""d,8a,m,m,m""] |=== | |child3_children |nvarchar(max) |NULL | |=== [#column-child3underlineclass] === child3_class [cols=""d,8a,m,m,m""] |=== | |child3_class |nvarchar(500) |NULL | |=== [#column-child3underlineisunderlinegroup] === child3_is_group [cols=""d,8a,m,m,m""] |=== | |child3_is_group |bit |NULL | |=== [#column-child3underlineisunderlinekeyword] === child3_is_keyword [cols=""d,8a,m,m,m""] |=== | |child3_is_keyword |bit |NULL | |=== [#column-child3underlineisunderlinewhitespace] === child3_is_whitespace [cols=""d,8a,m,m,m""] |=== | |child3_is_whitespace |bit |NULL | |=== [#column-child3underlinenormalized] === child3_normalized [cols=""d,8a,m,m,m""] |=== | |child3_normalized |nvarchar(max) |NULL | |=== [#column-child4underlinechildren] === child4_children [cols=""d,8a,m,m,m""] |=== | |child4_children |nvarchar(max) |NULL | |=== [#column-child4underlineclass] === child4_class [cols=""d,8a,m,m,m""] |=== | |child4_class |nvarchar(500) |NULL | |=== [#column-child4underlineisunderlinegroup] === child4_is_group [cols=""d,8a,m,m,m""] |=== | |child4_is_group |bit |NULL | |=== [#column-child4underlineisunderlinekeyword] === child4_is_keyword [cols=""d,8a,m,m,m""] |=== | |child4_is_keyword |bit |NULL | |=== [#column-child4underlineisunderlinewhitespace] === child4_is_whitespace [cols=""d,8a,m,m,m""] |=== | |child4_is_whitespace |bit |NULL | |=== [#column-child4underlinenormalized] === child4_normalized [cols=""d,8a,m,m,m""] |=== | |child4_normalized |nvarchar(max) |NULL | |=== [#column-children] === children [cols=""d,8a,m,m,m""] |=== | |children |nvarchar(max) |NULL | |=== [#column-class] === class [cols=""d,8a,m,m,m""] |=== | |class |nvarchar(500) |NULL | |=== [#column-isunderlinegroup] === is_group [cols=""d,8a,m,m,m""] |=== | |is_group |bit |NULL | |=== [#column-isunderlinekeyword] === is_keyword [cols=""d,8a,m,m,m""] |=== | |is_keyword |bit |NULL | |=== [#column-isunderlinewhitespace] === is_whitespace [cols=""d,8a,m,m,m""] |=== | |is_whitespace |bit |NULL | |=== [#column-jsonunderlinekey] === json_key [cols=""d,8a,m,m,m""] |=== | |json_key |nvarchar(4000) |NOT NULL | |=== [#column-normalized] === normalized [cols=""d,8a,m,m,m""] |=== | |normalized |nvarchar(max) |NULL | |=== // end::AntoraColumnDetails[] == AntoraPkColumnTableRows // tag::AntoraPkColumnTableRows[] // end::AntoraPkColumnTableRows[] == AntoraNonPkColumnTableRows // tag::AntoraNonPkColumnTableRows[] | |<> |nvarchar(max) |NULL | | |<> |nvarchar(500) |NULL | | |<> |bit |NULL | | |<> |bit |NULL | | |<> |bit |NULL | | |<> |nvarchar(max) |NULL | | |<> |nvarchar(max) |NULL | | |<> |nvarchar(500) |NULL | | |<> |bit |NULL | | |<> |bit |NULL | | |<> |bit |NULL | | |<> |nvarchar(max) |NULL | | |<> |nvarchar(max) |NULL | | |<> |nvarchar(500) |NULL | | |<> |bit |NULL | | |<> |bit |NULL | | |<> |bit |NULL | | |<> |nvarchar(max) |NULL | | |<> |nvarchar(max) |NULL | | |<> |nvarchar(500) |NULL | | |<> |bit |NULL | | |<> |bit |NULL | | |<> |bit |NULL | | |<> |nvarchar(max) |NULL | | |<> |nvarchar(max) |NULL | | |<> |nvarchar(500) |NULL | | |<> |bit |NULL | | |<> |bit |NULL | | |<> |bit |NULL | | |<> |nvarchar(max) |NULL | | |<> |nvarchar(max) |NULL | | |<> |nvarchar(500) |NULL | | |<> |bit |NULL | | |<> |bit |NULL | | |<> |bit |NULL | | |<> |nvarchar(4000) |NOT NULL | | |<> |nvarchar(max) |NULL | // end::AntoraNonPkColumnTableRows[] == AntoraIndexList // tag::AntoraIndexList[] // end::AntoraIndexList[] == AntoraMeasureDetails // tag::AntoraMeasureDetails[] // end::AntoraMeasureDetails[] == AntoraMeasureDescriptions == AntoraParameterList // tag::AntoraParameterList[] * @json_array (nvarchar(max)) // end::AntoraParameterList[] == AntoraXrefCulturesList // tag::AntoraXrefCulturesList[] * xref:dhw:sqldb:sqlparse.ftv_sqlparse_with_some_children.adoc[] - // end::AntoraXrefCulturesList[] == cultures_count // tag::cultures_count[] 1 // end::cultures_count[] == Other tags source: property.RepoObjectProperty_cross As rop_cross === additional_reference_csv // tag::additional_reference_csv[] // end::additional_reference_csv[] === AdocUspSteps // tag::adocuspsteps[] // end::adocuspsteps[] === AntoraReferencedList // tag::antorareferencedlist[] // end::antorareferencedlist[] === AntoraReferencingList // tag::antorareferencinglist[] * xref:dhw:sqldb:sqlparse.ftv_sqlparse_identifierlist__testonly.adoc[] * xref:dhw:sqldb:sqlparse.repoobject_sqlmodules_20_statement_children.adoc[] * xref:dhw:sqldb:sqlparse.repoobject_sqlmodules_24_identifierlist_children.adoc[] // end::antorareferencinglist[] === Description // tag::description[] // end::description[] === exampleUsage // tag::exampleusage[] // end::exampleusage[] === exampleUsage_2 // tag::exampleusage_2[] // end::exampleusage_2[] === exampleUsage_3 // tag::exampleusage_3[] // end::exampleusage_3[] === exampleUsage_4 // tag::exampleusage_4[] // end::exampleusage_4[] === exampleUsage_5 // tag::exampleusage_5[] // end::exampleusage_5[] === exampleWrong_Usage // tag::examplewrong_usage[] // end::examplewrong_usage[] === has_execution_plan_issue // tag::has_execution_plan_issue[] // end::has_execution_plan_issue[] === has_get_referenced_issue // tag::has_get_referenced_issue[] // end::has_get_referenced_issue[] === has_history // tag::has_history[] // end::has_history[] === has_history_columns // tag::has_history_columns[] // end::has_history_columns[] === InheritanceType // tag::inheritancetype[] // end::inheritancetype[] === is_persistence // tag::is_persistence[] // end::is_persistence[] === is_persistence_check_duplicate_per_pk // tag::is_persistence_check_duplicate_per_pk[] // end::is_persistence_check_duplicate_per_pk[] === is_persistence_check_for_empty_source // tag::is_persistence_check_for_empty_source[] // end::is_persistence_check_for_empty_source[] === is_persistence_delete_changed // tag::is_persistence_delete_changed[] // end::is_persistence_delete_changed[] === is_persistence_delete_missing // tag::is_persistence_delete_missing[] // end::is_persistence_delete_missing[] === is_persistence_insert // tag::is_persistence_insert[] // end::is_persistence_insert[] === is_persistence_truncate // tag::is_persistence_truncate[] // end::is_persistence_truncate[] === is_persistence_update_changed // tag::is_persistence_update_changed[] // end::is_persistence_update_changed[] === is_repo_managed // tag::is_repo_managed[] 0 // end::is_repo_managed[] === is_ssas // tag::is_ssas[] 0 // end::is_ssas[] === microsoft_database_tools_support // tag::microsoft_database_tools_support[] // end::microsoft_database_tools_support[] === MS_Description // tag::ms_description[] // end::ms_description[] === persistence_source_RepoObject_fullname // tag::persistence_source_repoobject_fullname[] // end::persistence_source_repoobject_fullname[] === persistence_source_RepoObject_fullname2 // tag::persistence_source_repoobject_fullname2[] // end::persistence_source_repoobject_fullname2[] === persistence_source_RepoObject_guid // tag::persistence_source_repoobject_guid[] // end::persistence_source_repoobject_guid[] === persistence_source_RepoObject_xref // tag::persistence_source_repoobject_xref[] // end::persistence_source_repoobject_xref[] === pk_index_guid // tag::pk_index_guid[] // end::pk_index_guid[] === pk_IndexPatternColumnDatatype // tag::pk_indexpatterncolumndatatype[] // end::pk_indexpatterncolumndatatype[] === pk_IndexPatternColumnName // tag::pk_indexpatterncolumnname[] // end::pk_indexpatterncolumnname[] === pk_IndexSemanticGroup // tag::pk_indexsemanticgroup[] // end::pk_indexsemanticgroup[] === ReferencedObjectList // tag::referencedobjectlist[] // end::referencedobjectlist[] === usp_persistence_RepoObject_guid // tag::usp_persistence_repoobject_guid[] // end::usp_persistence_repoobject_guid[] === UspExamples // tag::uspexamples[] // end::uspexamples[] === uspgenerator_usp_id // tag::uspgenerator_usp_id[] // end::uspgenerator_usp_id[] === UspParameters // tag::uspparameters[] // end::uspparameters[] == Boolean Attributes source: property.RepoObjectProperty WHERE property_int = 1 // tag::boolean_attributes[] // end::boolean_attributes[] == PlantUML diagrams === PlantUML Entity // tag::puml_entity[] [plantuml, entity-{docname}, svg, subs=macros] .... 'Left to right direction top to bottom direction hide circle 'avoide ""."" issues: set namespaceSeparator none skinparam class { BackgroundColor White BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<> LightGray BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<

> Aqua BackgroundColor<> Aqua BackgroundColor<> Yellow BackgroundColor<> SlateBlue BackgroundColor<> LightGray BackgroundColor<> Tomato BackgroundColor<> White BackgroundColor<> WhiteSmoke BackgroundColor<> Aqua BackgroundColor<> AliceBlue } entity ""puml-link:dhw:sqldb:sqlparse.ftv_sqlparse_with_some_children.adoc[]"" as sqlparse.ftv_sqlparse_with_some_children << IF >> { child0_children : (nvarchar(max)) child0_class : (nvarchar(500)) child0_is_group : (bit) child0_is_keyword : (bit) child0_is_whitespace : (bit) child0_normalized : (nvarchar(max)) child1_children : (nvarchar(max)) child1_class : (nvarchar(500)) child1_is_group : (bit) child1_is_keyword : (bit) child1_is_whitespace : (bit) child1_normalized : (nvarchar(max)) child2_children : (nvarchar(max)) child2_class : (nvarchar(500)) child2_is_group : (bit) child2_is_keyword : (bit) child2_is_whitespace : (bit) child2_normalized : (nvarchar(max)) child3_children : (nvarchar(max)) child3_class : (nvarchar(500)) child3_is_group : (bit) child3_is_keyword : (bit) child3_is_whitespace : (bit) child3_normalized : (nvarchar(max)) child4_children : (nvarchar(max)) child4_class : (nvarchar(500)) child4_is_group : (bit) child4_is_keyword : (bit) child4_is_whitespace : (bit) child4_normalized : (nvarchar(max)) children : (nvarchar(max)) class : (nvarchar(500)) is_group : (bit) is_keyword : (bit) is_whitespace : (bit) - json_key : (nvarchar(4000)) normalized : (nvarchar(max)) -- } .... // end::puml_entity[] === PlantUML Entity 1 1 FK // tag::puml_entity_1_1_fk[] [plantuml, entity_1_1_fk-{docname}, svg, subs=macros] .... @startuml left to right direction 'top to bottom direction hide circle 'avoide ""."" issues: set namespaceSeparator none skinparam class { BackgroundColor White BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<> LightGray BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<

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

> Aqua BackgroundColor<> Aqua BackgroundColor<> Yellow BackgroundColor<> SlateBlue BackgroundColor<> LightGray BackgroundColor<> Tomato BackgroundColor<> White BackgroundColor<> WhiteSmoke BackgroundColor<> Aqua BackgroundColor<> AliceBlue } entity ""puml-link:dhw:sqldb:sqlparse.ftv_sqlparse_identifierlist__testonly.adoc[]"" as sqlparse.ftv_sqlparse_IdentifierList__TestOnly << IF >> { -- } entity ""puml-link:dhw:sqldb:sqlparse.ftv_sqlparse_with_some_children.adoc[]"" as sqlparse.ftv_sqlparse_with_some_children << IF >> { -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_20_statement_children.adoc[]"" as sqlparse.RepoObject_SqlModules_20_statement_children << V >> { - **RepoObject_guid** : (uniqueidentifier) - **json_key** : (nvarchar(4000)) -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_24_identifierlist_children.adoc[]"" as sqlparse.RepoObject_SqlModules_24_IdentifierList_children << V >> { - **RepoObject_guid** : (uniqueidentifier) - **json_key** : (nvarchar(4000)) - **T2_json_key** : (nvarchar(4000)) -- } sqlparse.ftv_sqlparse_with_some_children <.. sqlparse.ftv_sqlparse_IdentifierList__TestOnly sqlparse.ftv_sqlparse_with_some_children <.. sqlparse.RepoObject_SqlModules_20_statement_children sqlparse.ftv_sqlparse_with_some_children <.. sqlparse.RepoObject_SqlModules_24_IdentifierList_children footer The diagram is interactive and contains links. @enduml .... // end::puml_entity_1_1_objectref[] === PlantUML 30 0 ObjectRef // tag::puml_entity_30_0_objectref[] [plantuml, entity_30_0_objectref-{docname}, svg, subs=macros] .... @startuml 'Left to right direction top to bottom direction hide circle 'avoide ""."" issues: set namespaceSeparator none skinparam class { BackgroundColor White BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<> LightGray BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<

> Aqua BackgroundColor<> Aqua BackgroundColor<> Yellow BackgroundColor<> SlateBlue BackgroundColor<> LightGray BackgroundColor<> Tomato BackgroundColor<> White BackgroundColor<> WhiteSmoke BackgroundColor<> Aqua BackgroundColor<> AliceBlue } entity ""puml-link:dhw:sqldb:sqlparse.ftv_sqlparse_with_some_children.adoc[]"" as sqlparse.ftv_sqlparse_with_some_children << IF >> { -- } footer The diagram is interactive and contains links. @enduml .... // end::puml_entity_30_0_objectref[] === PlantUML 0 30 ObjectRef // tag::puml_entity_0_30_objectref[] [plantuml, entity_0_30_objectref-{docname}, svg, subs=macros] .... @startuml 'Left to right direction top to bottom direction hide circle 'avoide ""."" issues: set namespaceSeparator none skinparam class { BackgroundColor White BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<> LightGray BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<

> Aqua BackgroundColor<> Aqua BackgroundColor<> Yellow BackgroundColor<> SlateBlue BackgroundColor<> LightGray BackgroundColor<> Tomato BackgroundColor<> White BackgroundColor<> WhiteSmoke BackgroundColor<> Aqua BackgroundColor<> AliceBlue } entity ""puml-link:dhw:sqldb:docs.antoranavlistpage_by_schema.adoc[]"" as docs.AntoraNavListPage_by_schema << V >> { -- } entity ""puml-link:dhw:sqldb:docs.ftv_repoobject_reference_plantuml_entityreflist.adoc[]"" as docs.ftv_RepoObject_Reference_PlantUml_EntityRefList << IF >> { -- } entity ""puml-link:dhw:sqldb:docs.objectrefcyclic.adoc[]"" as docs.ObjectRefCyclic << V >> { -- } entity ""puml-link:dhw:sqldb:docs.objectrefcyclic_entitylist.adoc[]"" as docs.ObjectRefCyclic_EntityList << V >> { -- } entity ""puml-link:dhw:sqldb:docs.repoobject_adoc.adoc[]"" as docs.RepoObject_Adoc << V >> { -- } entity ""puml-link:dhw:sqldb:docs.repoobject_adoc_t.adoc[]"" as docs.RepoObject_Adoc_T << U >> { - **RepoObject_guid** : (uniqueidentifier) - **cultures_name** : (nvarchar(10)) -- } entity ""puml-link:dhw:sqldb:docs.repoobject_columnlist.adoc[]"" as docs.RepoObject_ColumnList << V >> { -- } entity ""puml-link:dhw:sqldb:docs.repoobject_columnlist_t.adoc[]"" as docs.RepoObject_ColumnList_T << U >> { - **RepoObject_guid** : (uniqueidentifier) - **cultures_name** : (nvarchar(10)) -- } entity ""puml-link:dhw:sqldb:docs.repoobject_plantuml.adoc[]"" as docs.RepoObject_Plantuml << V >> { - **RepoObject_guid** : (uniqueidentifier) **cultures_name** : (nvarchar(10)) -- } entity ""puml-link:dhw:sqldb:docs.repoobject_plantuml_colreflist_1_1.adoc[]"" as docs.RepoObject_Plantuml_ColRefList_1_1 << V >> { -- } entity ""puml-link:dhw:sqldb:docs.repoobject_plantuml_entity.adoc[]"" as docs.RepoObject_Plantuml_Entity << V >> { -- } entity ""puml-link:dhw:sqldb:docs.repoobject_plantuml_entity_t.adoc[]"" as docs.RepoObject_Plantuml_Entity_T << U >> { - **RepoObject_guid** : (uniqueidentifier) - **cultures_name** : (nvarchar(10)) -- } entity ""puml-link:dhw:sqldb:docs.repoobject_plantuml_pumlentityfklist.adoc[]"" as docs.RepoObject_PlantUml_PumlEntityFkList << V >> { **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:docs.repoobject_plantuml_t.adoc[]"" as docs.RepoObject_Plantuml_T << U >> { - **RepoObject_guid** : (uniqueidentifier) **cultures_name** : (nvarchar(10)) -- } entity ""puml-link:dhw:sqldb:docs.schema_entitylist.adoc[]"" as docs.Schema_EntityList << V >> { - **RepoObject_schema_name** : (nvarchar(128)) - **cultures_name** : (nvarchar(10)) -- } entity ""puml-link:dhw:sqldb:docs.schema_puml.adoc[]"" as docs.Schema_puml << V >> { - **RepoSchema_guid** : (uniqueidentifier) **cultures_name** : (nvarchar(10)) -- } entity ""puml-link:dhw:sqldb:docs.usp_antoraexport.adoc[]"" as docs.usp_AntoraExport << P >> { -- } entity ""puml-link:dhw:sqldb:docs.usp_antoraexport_objectpartialscontent.adoc[]"" as docs.usp_AntoraExport_ObjectPartialsContent << P >> { -- } entity ""puml-link:dhw:sqldb:docs.usp_antoraexport_objectpuml.adoc[]"" as docs.usp_AntoraExport_ObjectPuml << P >> { -- } entity ""puml-link:dhw:sqldb:docs.usp_persist_repoobject_adoc_t.adoc[]"" as docs.usp_PERSIST_RepoObject_Adoc_T << P >> { -- } entity ""puml-link:dhw:sqldb:docs.usp_persist_repoobject_columnlist_t.adoc[]"" as docs.usp_PERSIST_RepoObject_ColumnList_T << P >> { -- } entity ""puml-link:dhw:sqldb:docs.usp_persist_repoobject_plantuml_entity_t.adoc[]"" as docs.usp_PERSIST_RepoObject_Plantuml_Entity_T << P >> { -- } entity ""puml-link:dhw:sqldb:docs.usp_persist_repoobject_plantuml_t.adoc[]"" as docs.usp_PERSIST_RepoObject_Plantuml_T << P >> { -- } entity ""puml-link:dhw:sqldb:property.repoobjectproperty_collect_source_rogross.adoc[]"" as property.RepoObjectProperty_Collect_source_ROGross << V >> { - **RepoObject_guid** : (uniqueidentifier) - **property_name** : (varchar(39)) -- } entity ""puml-link:dhw:sqldb:property.usp_repoobject_inheritance.adoc[]"" as property.usp_RepoObject_Inheritance << P >> { -- } entity ""puml-link:dhw:sqldb:property.usp_repoobjectproperty_collect.adoc[]"" as property.usp_RepoObjectProperty_collect << P >> { -- } entity ""puml-link:dhw:sqldb:reference.ftv_repoobject_columreferencerepoobject.adoc[]"" as reference.ftv_RepoObject_ColumReferenceRepoObject << IF >> { -- } entity ""puml-link:dhw:sqldb:reference.ftv_repoobject_dbmlcolumnrelation.adoc[]"" as reference.ftv_RepoObject_DbmlColumnRelation << IF >> { -- } entity ""puml-link:dhw:sqldb:reference.ftv_repoobjectcolumn_referencetree.adoc[]"" as reference.ftv_RepoObjectColumn_ReferenceTree << IF >> { -- } entity ""puml-link:dhw:sqldb:reference.repoobjectcolumn_reference.adoc[]"" as reference.RepoObjectColumn_reference << V >> { **referenced_RepoObjectColumn_guid** : (uniqueidentifier) **referencing_RepoObjectColumn_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:reference.repoobjectcolumn_reference_sqlmodules.adoc[]"" as reference.RepoObjectColumn_reference_SqlModules << V >> { **referencing_id** : (int) **referencing_minor_id** : (int) **referenced_id** : (int) **referenced_minor_id** : (int) -- } entity ""puml-link:dhw:sqldb:reference.repoobjectcolumn_reference_t.adoc[]"" as reference.RepoObjectColumn_reference_T << U >> { **referenced_RepoObjectColumn_guid** : (uniqueidentifier) **referencing_RepoObjectColumn_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:reference.repoobjectcolumn_reference_union.adoc[]"" as reference.RepoObjectColumn_reference_union << V >> { -- } entity ""puml-link:dhw:sqldb:reference.repoobjectcolumn_referencedlist.adoc[]"" as reference.RepoObjectColumn_ReferencedList << V >> { -- } entity ""puml-link:dhw:sqldb:reference.repoobjectcolumn_referencedreferencing.adoc[]"" as reference.RepoObjectColumn_ReferencedReferencing << V >> { -- } entity ""puml-link:dhw:sqldb:reference.repoobjectcolumn_referencetree.adoc[]"" as reference.RepoObjectColumn_ReferenceTree << V >> { -- } entity ""puml-link:dhw:sqldb:reference.repoobjectcolumn_referencinglist.adoc[]"" as reference.RepoObjectColumn_ReferencingList << V >> { -- } entity ""puml-link:dhw:sqldb:reference.repoobjectcolumn_relationscript.adoc[]"" as reference.RepoObjectColumn_RelationScript << V >> { -- } entity ""puml-link:dhw:sqldb:reference.usp_persist_repoobjectcolumn_reference_t.adoc[]"" as reference.usp_PERSIST_RepoObjectColumn_reference_T << P >> { -- } entity ""puml-link:dhw:sqldb:repo.check_indexcolumn_virtual_referenced_setpoint.adoc[]"" as repo.check_IndexColumn_virtual_referenced_setpoint << V >> { -- } entity ""puml-link:dhw:sqldb:repo.index_referencing_indexpatterncolumnguid.adoc[]"" as repo.Index_referencing_IndexPatternColumnGuid << V >> { **source_index_guid** : (uniqueidentifier) **referencing_RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.indexcolumn_referencedreferencing_hasfullcolumnsinreferencing.adoc[]"" as repo.IndexColumn_ReferencedReferencing_HasFullColumnsInReferencing << V >> { - **index_guid** : (uniqueidentifier) - **index_column_id** : (int) **RowNumberInReferencing** : (bigint) -- } entity ""puml-link:dhw:sqldb:repo.indexcolumn_referencedreferencing_hasfullcolumnsinreferencing_check.adoc[]"" as repo.IndexColumn_ReferencedReferencing_HasFullColumnsInReferencing_check << V >> { -- } entity ""puml-link:dhw:sqldb:repo.indexcolumn_referencedreferencing_hasfullcolumnsinreferencing_t.adoc[]"" as repo.IndexColumn_ReferencedReferencing_HasFullColumnsInReferencing_T << U >> { **index_guid** : (uniqueidentifier) - **index_column_id** : (int) **RowNumberInReferencing** : (bigint) -- } entity ""puml-link:dhw:sqldb:repo.indexcolumn_virtual_referenced_setpoint.adoc[]"" as repo.IndexColumn_virtual_referenced_setpoint << V >> { - **index_guid** : (uniqueidentifier) - **index_column_id** : (int) -- } entity ""puml-link:dhw:sqldb:repo.indexreferencedreferencing_hasfullcolumnsinreferencing.adoc[]"" as repo.IndexReferencedReferencing_HasFullColumnsInReferencing << V >> { -- } entity ""puml-link:dhw:sqldb:repo.repoobject_columnlist.adoc[]"" as repo.RepoObject_ColumnList << V >> { -- } entity ""puml-link:dhw:sqldb:repo.repoobject_gross2.adoc[]"" as repo.RepoObject_gross2 << V >> { -- } entity ""puml-link:dhw:sqldb:repo.repoobject_sat2.adoc[]"" as repo.RepoObject_sat2 << V >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobject_sat2_t.adoc[]"" as repo.RepoObject_sat2_T << U >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobject_sqlcreatetable.adoc[]"" as repo.RepoObject_SqlCreateTable << V >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobjectcolumn_gross2.adoc[]"" as repo.RepoObjectColumn_gross2 << V >> { -- } entity ""puml-link:dhw:sqldb:repo.repoobjectcolumn_missingsource_typev.adoc[]"" as repo.RepoObjectColumn_MissingSource_TypeV << V >> { -- } entity ""puml-link:dhw:sqldb:repo.usp_index_inheritance.adoc[]"" as repo.usp_index_inheritance << P >> { -- } entity ""puml-link:dhw:sqldb:repo.usp_main.adoc[]"" as repo.usp_main << P >> { -- } entity ""puml-link:dhw:sqldb:repo.usp_persist_indexcolumn_referencedreferencing_hasfullcolumnsinreferencing_t.adoc[]"" as repo.usp_PERSIST_IndexColumn_ReferencedReferencing_HasFullColumnsInReferencing_T << P >> { -- } entity ""puml-link:dhw:sqldb:repo.usp_persist_repoobject_sat2_t.adoc[]"" as repo.usp_PERSIST_RepoObject_sat2_T << P >> { -- } entity ""puml-link:dhw:sqldb:sqlparse.ftv_sqlparse_identifierlist__testonly.adoc[]"" as sqlparse.ftv_sqlparse_IdentifierList__TestOnly << IF >> { -- } entity ""puml-link:dhw:sqldb:sqlparse.ftv_sqlparse_with_some_children.adoc[]"" as sqlparse.ftv_sqlparse_with_some_children << IF >> { -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_20_statement_children.adoc[]"" as sqlparse.RepoObject_SqlModules_20_statement_children << V >> { - **RepoObject_guid** : (uniqueidentifier) - **json_key** : (nvarchar(4000)) -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_21_statement_children_helper.adoc[]"" as sqlparse.RepoObject_SqlModules_21_statement_children_helper << V >> { -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_22_identifier_alias_as.adoc[]"" as sqlparse.RepoObject_SqlModules_22_identifier_alias_AS << V >> { - **RepoObject_guid** : (uniqueidentifier) - **json_key** : (nvarchar(4000)) **RowNumber** : (bigint) -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_23_normalized_wo_nolock.adoc[]"" as sqlparse.RepoObject_SqlModules_23_normalized_wo_nolock << V >> { -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_24_identifierlist_children.adoc[]"" as sqlparse.RepoObject_SqlModules_24_IdentifierList_children << V >> { - **RepoObject_guid** : (uniqueidentifier) - **json_key** : (nvarchar(4000)) - **T2_json_key** : (nvarchar(4000)) -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_25_identifierlist_children_identifiersplit.adoc[]"" as sqlparse.RepoObject_SqlModules_25_IdentifierList_children_IdentifierSplit << V >> { -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_26_identifierlist_children_identifiersplit_quotename.adoc[]"" as sqlparse.RepoObject_SqlModules_26_IdentifierList_children_IdentifierSplit_QuoteName << V >> { -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_29_1_object_is_union.adoc[]"" as sqlparse.RepoObject_SqlModules_29_1_object_is_union << V >> { -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_29_2_object_is_groupby.adoc[]"" as sqlparse.RepoObject_SqlModules_29_2_object_is_GroupBy << V >> { -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_31_object.adoc[]"" as sqlparse.RepoObject_SqlModules_31_object << V >> { -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_32_objectclass.adoc[]"" as sqlparse.RepoObject_SqlModules_32_ObjectClass << V >> { - **RepoObject_guid** : (uniqueidentifier) **class** : (nvarchar(500)) -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_33_objectnormalized.adoc[]"" as sqlparse.RepoObject_SqlModules_33_ObjectNormalized << V >> { - **RepoObject_guid** : (uniqueidentifier) **normalized** : (nvarchar(max)) -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_39_object.adoc[]"" as sqlparse.RepoObject_SqlModules_39_object << V >> { -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_41_from.adoc[]"" as sqlparse.RepoObject_SqlModules_41_from << V >> { -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_41_from_t.adoc[]"" as sqlparse.RepoObject_SqlModules_41_from_T << U >> { -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_42_from_identifier.adoc[]"" as sqlparse.RepoObject_SqlModules_42_from_Identifier << V >> { -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_43_from_identifier.adoc[]"" as sqlparse.RepoObject_SqlModules_43_from_Identifier << V >> { -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_44_from_identifier_quotename.adoc[]"" as sqlparse.RepoObject_SqlModules_44_from_Identifier_QuoteName << V >> { -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_51_identitfier.adoc[]"" as sqlparse.RepoObject_SqlModules_51_Identitfier << V >> { -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_52_identitfier_quotename.adoc[]"" as sqlparse.RepoObject_SqlModules_52_Identitfier_QuoteName << V >> { -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_61_selectidentifier_union.adoc[]"" as sqlparse.RepoObject_SqlModules_61_SelectIdentifier_Union << V >> { -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_61_selectidentifier_union_t.adoc[]"" as sqlparse.RepoObject_SqlModules_61_SelectIdentifier_Union_T << U >> { -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_71_reference_explicitetablealias.adoc[]"" as sqlparse.RepoObject_SqlModules_71_reference_ExpliciteTableAlias << V >> { -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_72_reference_notablealias.adoc[]"" as sqlparse.RepoObject_SqlModules_72_reference_NoTableAlias << V >> { -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_79_reference_union.adoc[]"" as sqlparse.RepoObject_SqlModules_79_reference_union << V >> { -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_identitfier.adoc[]"" as sqlparse.RepoObject_SqlModules_Identitfier << V >> { -- } entity ""puml-link:dhw:sqldb:sqlparse.usp_persist_repoobject_sqlmodules_41_from_t.adoc[]"" as sqlparse.usp_PERSIST_RepoObject_SqlModules_41_from_T << P >> { -- } entity ""puml-link:dhw:sqldb:sqlparse.usp_persist_repoobject_sqlmodules_61_selectidentifier_union_t.adoc[]"" as sqlparse.usp_PERSIST_RepoObject_SqlModules_61_SelectIdentifier_Union_T << P >> { -- } entity ""puml-link:dhw:sqldb:sqlparse.usp_sqlparse.adoc[]"" as sqlparse.usp_sqlparse << P >> { -- } entity ""puml-link:dhw:sqldb:uspgenerator.generatoruspstep_persistence_src.adoc[]"" as uspgenerator.GeneratorUspStep_Persistence_src << V >> { - **usp_id** : (int) -- } entity ""puml-link:dhw:sqldb:uspgenerator.usp_generatorusp_insert_update_persistence.adoc[]"" as uspgenerator.usp_GeneratorUsp_insert_update_persistence << P >> { -- } docs.ftv_RepoObject_Reference_PlantUml_EntityRefList <.. docs.RepoObject_Plantuml docs.ObjectRefCyclic_EntityList <.. docs.ObjectRefCyclic docs.RepoObject_Adoc <.. docs.RepoObject_Adoc_T docs.RepoObject_Adoc <.. docs.usp_PERSIST_RepoObject_Adoc_T docs.REpoObject_Adoc_T <.. docs.usp_PERSIST_RepoObject_Adoc_T docs.RepoObject_ColumnList <.. docs.usp_PERSIST_RepoObject_ColumnList_T docs.RepoObject_ColumnList <.. docs.RepoObject_ColumnList_T docs.RepoObject_ColumnList_T <.. docs.RepoObject_Adoc docs.RepoObject_ColumnList_T <.. docs.usp_PERSIST_RepoObject_ColumnList_T docs.RepoObject_ColumnList_T <.. docs.RepoObject_Plantuml_Entity docs.RepoObject_Plantuml <.. docs.RepoObject_Plantuml_T docs.RepoObject_Plantuml <.. docs.usp_PERSIST_RepoObject_Plantuml_T docs.RepoObject_Plantuml_ColRefList_1_1 <.. docs.RepoObject_Plantuml docs.RepoObject_Plantuml_Entity <.. docs.RepoObject_Plantuml_Entity_T docs.RepoObject_Plantuml_Entity <.. docs.usp_PERSIST_RepoObject_Plantuml_Entity_T docs.RepoObject_Plantuml_Entity_T <.. docs.RepoObject_Adoc docs.RepoObject_Plantuml_Entity_T <.. docs.ftv_RepoObject_Reference_PlantUml_EntityRefList docs.RepoObject_Plantuml_Entity_T <.. docs.usp_PERSIST_RepoObject_Plantuml_Entity_T docs.RepoObject_Plantuml_Entity_T <.. docs.Schema_EntityList docs.RepoObject_Plantuml_Entity_T <.. docs.ObjectRefCyclic_EntityList docs.RepoObject_Plantuml_Entity_T <.. docs.RepoObject_PlantUml_PumlEntityFkList docs.RepoObject_PlantUml_PumlEntityFkList <.. docs.RepoObject_Plantuml docs.RepoObject_Plantuml_T <.. docs.usp_PERSIST_RepoObject_Plantuml_T docs.RepoObject_Plantuml_T <.. docs.RepoObject_Adoc docs.Schema_EntityList <.. docs.Schema_puml docs.Schema_puml <.. docs.AntoraNavListPage_by_schema docs.usp_AntoraExport_ObjectPartialsContent <.. docs.usp_AntoraExport docs.usp_AntoraExport_ObjectPuml <.. docs.usp_AntoraExport docs.usp_PERSIST_RepoObject_Adoc_T <.. docs.usp_AntoraExport_ObjectPartialsContent docs.usp_PERSIST_RepoObject_ColumnList_T <.. docs.usp_AntoraExport_ObjectPartialsContent docs.usp_PERSIST_RepoObject_Plantuml_Entity_T <.. docs.usp_AntoraExport_ObjectPuml docs.usp_PERSIST_RepoObject_Plantuml_T <.. docs.usp_AntoraExport_ObjectPuml property.RepoObjectProperty_Collect_source_ROGross <.. property.usp_RepoObjectProperty_collect property.usp_RepoObject_Inheritance <.. repo.usp_main property.usp_RepoObjectProperty_collect <.. property.usp_RepoObject_Inheritance property.usp_RepoObjectProperty_collect <.. repo.usp_main reference.ftv_RepoObjectColumn_ReferenceTree <.. reference.RepoObjectColumn_ReferenceTree reference.RepoObjectColumn_reference <.. reference.RepoObjectColumn_reference_T reference.RepoObjectColumn_reference <.. reference.usp_PERSIST_RepoObjectColumn_reference_T reference.RepoObjectColumn_reference_SqlModules <.. reference.RepoObjectColumn_reference_union reference.RepoObjectColumn_reference_T <.. docs.RepoObject_Plantuml_ColRefList_1_1 reference.RepoObjectColumn_reference_T <.. reference.RepoObjectColumn_ReferencedReferencing reference.RepoObjectColumn_reference_T <.. reference.usp_PERSIST_RepoObjectColumn_reference_T reference.RepoObjectColumn_reference_T <.. repo.IndexColumn_ReferencedReferencing_HasFullColumnsInReferencing reference.RepoObjectColumn_reference_T <.. repo.RepoObjectColumn_MissingSource_TypeV reference.RepoObjectColumn_reference_T <.. reference.RepoObjectColumn_RelationScript reference.RepoObjectColumn_reference_union <.. reference.RepoObjectColumn_reference reference.RepoObjectColumn_ReferencedList <.. repo.RepoObjectColumn_gross2 reference.RepoObjectColumn_ReferencedReferencing <.. reference.RepoObjectColumn_ReferencingList reference.RepoObjectColumn_ReferencedReferencing <.. reference.ftv_RepoObject_DbmlColumnRelation reference.RepoObjectColumn_ReferencedReferencing <.. reference.RepoObjectColumn_ReferencedList reference.RepoObjectColumn_ReferencedReferencing <.. reference.ftv_RepoObjectColumn_ReferenceTree reference.RepoObjectColumn_ReferenceTree <.. reference.ftv_RepoObject_ColumReferenceRepoObject reference.RepoObjectColumn_ReferencingList <.. repo.RepoObjectColumn_gross2 reference.RepoObjectColumn_RelationScript <.. reference.ftv_RepoObject_ColumReferenceRepoObject reference.usp_PERSIST_RepoObjectColumn_reference_T <.. repo.usp_main repo.Index_referencing_IndexPatternColumnGuid <.. repo.IndexReferencedReferencing_HasFullColumnsInReferencing repo.IndexColumn_ReferencedReferencing_HasFullColumnsInReferencing <.. repo.IndexColumn_ReferencedReferencing_HasFullColumnsInReferencing_T repo.IndexColumn_ReferencedReferencing_HasFullColumnsInReferencing <.. repo.usp_PERSIST_IndexColumn_ReferencedReferencing_HasFullColumnsInReferencing_T repo.IndexColumn_ReferencedReferencing_HasFullColumnsInReferencing_T <.. repo.IndexColumn_virtual_referenced_setpoint repo.IndexColumn_ReferencedReferencing_HasFullColumnsInReferencing_T <.. repo.IndexReferencedReferencing_HasFullColumnsInReferencing repo.IndexColumn_ReferencedReferencing_HasFullColumnsInReferencing_T <.. repo.Index_referencing_IndexPatternColumnGuid repo.IndexColumn_ReferencedReferencing_HasFullColumnsInReferencing_T <.. repo.usp_PERSIST_IndexColumn_ReferencedReferencing_HasFullColumnsInReferencing_T repo.IndexColumn_ReferencedReferencing_HasFullColumnsInReferencing_T <.. repo.IndexColumn_ReferencedReferencing_HasFullColumnsInReferencing_check repo.IndexColumn_virtual_referenced_setpoint <.. repo.check_IndexColumn_virtual_referenced_setpoint repo.IndexColumn_virtual_referenced_setpoint <.. repo.usp_index_inheritance repo.IndexReferencedReferencing_HasFullColumnsInReferencing <.. repo.usp_index_inheritance repo.RepoObject_ColumnList <.. repo.RepoObject_gross2 repo.RepoObject_ColumnList <.. repo.RepoObject_sat2 repo.RepoObject_ColumnList <.. repo.RepoObject_SqlCreateTable repo.RepoObject_gross2 <.. uspgenerator.GeneratorUspStep_Persistence_src repo.RepoObject_sat2 <.. repo.usp_PERSIST_RepoObject_sat2_T repo.RepoObject_sat2 <.. repo.RepoObject_sat2_T repo.RepoObject_sat2_T <.. repo.usp_PERSIST_RepoObject_sat2_T repo.RepoObject_sat2_T <.. property.RepoObjectProperty_Collect_source_ROGross repo.RepoObject_sat2_T <.. docs.RepoObject_Adoc repo.RepoObject_SqlCreateTable <.. reference.ftv_RepoObject_ColumReferenceRepoObject repo.RepoObjectColumn_gross2 <.. repo.RepoObject_ColumnList repo.RepoObjectColumn_gross2 <.. uspgenerator.usp_GeneratorUsp_insert_update_persistence repo.RepoObjectColumn_gross2 <.. docs.RepoObject_ColumnList repo.usp_index_inheritance <.. repo.usp_main repo.usp_PERSIST_IndexColumn_ReferencedReferencing_HasFullColumnsInReferencing_T <.. repo.usp_index_inheritance repo.usp_PERSIST_RepoObject_sat2_T <.. repo.usp_main sqlparse.ftv_sqlparse_with_some_children <.. sqlparse.RepoObject_SqlModules_20_statement_children sqlparse.ftv_sqlparse_with_some_children <.. sqlparse.RepoObject_SqlModules_24_IdentifierList_children sqlparse.ftv_sqlparse_with_some_children <.. sqlparse.ftv_sqlparse_IdentifierList__TestOnly sqlparse.RepoObject_SqlModules_20_statement_children <.. sqlparse.RepoObject_SqlModules_Identitfier sqlparse.RepoObject_SqlModules_20_statement_children <.. sqlparse.RepoObject_SqlModules_51_Identitfier sqlparse.RepoObject_SqlModules_20_statement_children <.. sqlparse.RepoObject_SqlModules_41_from sqlparse.RepoObject_SqlModules_20_statement_children <.. sqlparse.RepoObject_SqlModules_24_IdentifierList_children sqlparse.RepoObject_SqlModules_20_statement_children <.. sqlparse.RepoObject_SqlModules_23_normalized_wo_nolock sqlparse.RepoObject_SqlModules_20_statement_children <.. sqlparse.RepoObject_SqlModules_22_identifier_alias_AS sqlparse.RepoObject_SqlModules_20_statement_children <.. sqlparse.RepoObject_SqlModules_33_ObjectNormalized sqlparse.RepoObject_SqlModules_20_statement_children <.. sqlparse.RepoObject_SqlModules_32_ObjectClass sqlparse.RepoObject_SqlModules_20_statement_children <.. sqlparse.RepoObject_SqlModules_29_2_object_is_GroupBy sqlparse.RepoObject_SqlModules_20_statement_children <.. sqlparse.RepoObject_SqlModules_29_1_object_is_union sqlparse.RepoObject_SqlModules_20_statement_children <.. sqlparse.RepoObject_SqlModules_21_statement_children_helper sqlparse.RepoObject_SqlModules_21_statement_children_helper <.. sqlparse.RepoObject_SqlModules_31_object sqlparse.RepoObject_SqlModules_22_identifier_alias_AS <.. sqlparse.RepoObject_SqlModules_41_from sqlparse.RepoObject_SqlModules_24_IdentifierList_children <.. sqlparse.RepoObject_SqlModules_25_IdentifierList_children_IdentifierSplit sqlparse.RepoObject_SqlModules_25_IdentifierList_children_IdentifierSplit <.. sqlparse.RepoObject_SqlModules_26_IdentifierList_children_IdentifierSplit_QuoteName sqlparse.RepoObject_SqlModules_26_IdentifierList_children_IdentifierSplit_QuoteName <.. sqlparse.RepoObject_SqlModules_61_SelectIdentifier_Union sqlparse.RepoObject_SqlModules_29_1_object_is_union <.. sqlparse.RepoObject_SqlModules_39_object sqlparse.RepoObject_SqlModules_29_1_object_is_union <.. sqlparse.RepoObject_SqlModules_42_from_Identifier sqlparse.RepoObject_SqlModules_29_2_object_is_GroupBy <.. sqlparse.RepoObject_SqlModules_39_object sqlparse.RepoObject_SqlModules_31_object <.. sqlparse.RepoObject_SqlModules_39_object sqlparse.RepoObject_SqlModules_32_ObjectClass <.. sqlparse.RepoObject_SqlModules_39_object sqlparse.RepoObject_SqlModules_33_ObjectNormalized <.. sqlparse.RepoObject_SqlModules_39_object sqlparse.RepoObject_SqlModules_39_object <.. sqlparse.RepoObject_SqlModules_41_from sqlparse.RepoObject_SqlModules_39_object <.. sqlparse.RepoObject_SqlModules_61_SelectIdentifier_Union sqlparse.RepoObject_SqlModules_41_from <.. sqlparse.usp_PERSIST_RepoObject_SqlModules_41_from_T sqlparse.RepoObject_SqlModules_41_from <.. sqlparse.RepoObject_SqlModules_41_from_T sqlparse.RepoObject_SqlModules_41_from_T <.. sqlparse.usp_PERSIST_RepoObject_SqlModules_41_from_T sqlparse.RepoObject_SqlModules_41_from_T <.. sqlparse.RepoObject_SqlModules_42_from_Identifier sqlparse.RepoObject_SqlModules_42_from_Identifier <.. sqlparse.RepoObject_SqlModules_43_from_Identifier sqlparse.RepoObject_SqlModules_43_from_Identifier <.. sqlparse.RepoObject_SqlModules_44_from_Identifier_QuoteName sqlparse.RepoObject_SqlModules_44_from_Identifier_QuoteName <.. sqlparse.RepoObject_SqlModules_71_reference_ExpliciteTableAlias sqlparse.RepoObject_SqlModules_44_from_Identifier_QuoteName <.. sqlparse.RepoObject_SqlModules_72_reference_NoTableAlias sqlparse.RepoObject_SqlModules_51_Identitfier <.. sqlparse.RepoObject_SqlModules_52_Identitfier_QuoteName sqlparse.RepoObject_SqlModules_52_Identitfier_QuoteName <.. sqlparse.RepoObject_SqlModules_61_SelectIdentifier_Union sqlparse.RepoObject_SqlModules_61_SelectIdentifier_Union <.. sqlparse.usp_PERSIST_RepoObject_SqlModules_61_SelectIdentifier_Union_T sqlparse.RepoObject_SqlModules_61_SelectIdentifier_Union <.. sqlparse.RepoObject_SqlModules_61_SelectIdentifier_Union_T sqlparse.RepoObject_SqlModules_61_SelectIdentifier_Union_T <.. sqlparse.RepoObject_SqlModules_71_reference_ExpliciteTableAlias sqlparse.RepoObject_SqlModules_61_SelectIdentifier_Union_T <.. sqlparse.usp_PERSIST_RepoObject_SqlModules_61_SelectIdentifier_Union_T sqlparse.RepoObject_SqlModules_61_SelectIdentifier_Union_T <.. sqlparse.RepoObject_SqlModules_72_reference_NoTableAlias sqlparse.RepoObject_SqlModules_71_reference_ExpliciteTableAlias <.. sqlparse.RepoObject_SqlModules_79_reference_union sqlparse.RepoObject_SqlModules_72_reference_NoTableAlias <.. sqlparse.RepoObject_SqlModules_79_reference_union sqlparse.RepoObject_SqlModules_79_reference_union <.. reference.RepoObjectColumn_reference_SqlModules sqlparse.usp_PERSIST_RepoObject_SqlModules_41_from_T <.. sqlparse.usp_sqlparse sqlparse.usp_PERSIST_RepoObject_SqlModules_61_SelectIdentifier_Union_T <.. sqlparse.usp_sqlparse uspgenerator.GeneratorUspStep_Persistence_src <.. uspgenerator.usp_GeneratorUsp_insert_update_persistence uspgenerator.usp_GeneratorUsp_insert_update_persistence <.. repo.usp_main footer The diagram is interactive and contains links. @enduml .... // end::puml_entity_0_30_objectref[] === PlantUML 1 1 ColumnRef // tag::puml_entity_1_1_colref[] [plantuml, entity_1_1_colref-{docname}, svg, subs=macros] .... @startuml left to right direction 'top to bottom direction hide circle 'avoide ""."" issues: set namespaceSeparator none skinparam class { BackgroundColor White BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<> LightGray BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<

> Aqua BackgroundColor<> Aqua BackgroundColor<> Yellow BackgroundColor<> SlateBlue BackgroundColor<> LightGray BackgroundColor<> Tomato BackgroundColor<> White BackgroundColor<> WhiteSmoke BackgroundColor<> Aqua BackgroundColor<> AliceBlue } entity ""puml-link:dhw:sqldb:sqlparse.ftv_sqlparse_identifierlist__testonly.adoc[]"" as sqlparse.ftv_sqlparse_IdentifierList__TestOnly << IF >> { Identifier_alias : (nvarchar(max)) Identifier_source : (nvarchar(max)) Identifier_source_children : (nvarchar(max)) Identifier_source_class : (nvarchar(500)) T2_class : (nvarchar(500)) -- } entity ""puml-link:dhw:sqldb:sqlparse.ftv_sqlparse_with_some_children.adoc[]"" as sqlparse.ftv_sqlparse_with_some_children << IF >> { child0_children : (nvarchar(max)) child0_class : (nvarchar(500)) child0_is_group : (bit) child0_is_keyword : (bit) child0_is_whitespace : (bit) child0_normalized : (nvarchar(max)) child1_children : (nvarchar(max)) child1_class : (nvarchar(500)) child1_is_group : (bit) child1_is_keyword : (bit) child1_is_whitespace : (bit) child1_normalized : (nvarchar(max)) child2_children : (nvarchar(max)) child2_class : (nvarchar(500)) child2_is_group : (bit) child2_is_keyword : (bit) child2_is_whitespace : (bit) child2_normalized : (nvarchar(max)) child3_children : (nvarchar(max)) child3_class : (nvarchar(500)) child3_is_group : (bit) child3_is_keyword : (bit) child3_is_whitespace : (bit) child3_normalized : (nvarchar(max)) child4_children : (nvarchar(max)) child4_class : (nvarchar(500)) child4_is_group : (bit) child4_is_keyword : (bit) child4_is_whitespace : (bit) child4_normalized : (nvarchar(max)) children : (nvarchar(max)) class : (nvarchar(500)) is_group : (bit) is_keyword : (bit) is_whitespace : (bit) - json_key : (nvarchar(4000)) normalized : (nvarchar(max)) -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_20_statement_children.adoc[]"" as sqlparse.RepoObject_SqlModules_20_statement_children << V >> { - **RepoObject_guid** : (uniqueidentifier) - **json_key** : (nvarchar(4000)) child0_children : (nvarchar(max)) child0_class : (nvarchar(500)) child0_is_group : (bit) child0_is_keyword : (bit) child0_is_whitespace : (bit) child0_normalized : (nvarchar(max)) child1_children : (nvarchar(max)) child1_class : (nvarchar(500)) child1_is_group : (bit) child1_is_keyword : (bit) child1_is_whitespace : (bit) child1_normalized : (nvarchar(max)) child2_children : (nvarchar(max)) child2_class : (nvarchar(500)) child2_is_group : (bit) child2_is_keyword : (bit) child2_is_whitespace : (bit) child2_normalized : (nvarchar(max)) child3_children : (nvarchar(max)) child3_class : (nvarchar(500)) child3_is_group : (bit) child3_is_keyword : (bit) child3_is_whitespace : (bit) child3_normalized : (nvarchar(max)) child4_children : (nvarchar(max)) child4_class : (nvarchar(500)) child4_is_group : (bit) child4_is_keyword : (bit) child4_is_whitespace : (bit) child4_normalized : (nvarchar(max)) children : (nvarchar(max)) class : (nvarchar(500)) is_group : (bit) is_keyword : (bit) is_whitespace : (bit) normalized : (nvarchar(max)) RowNumber_per_Object : (bigint) SysObject_fullname : (nvarchar(261)) -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_24_identifierlist_children.adoc[]"" as sqlparse.RepoObject_SqlModules_24_IdentifierList_children << V >> { - **RepoObject_guid** : (uniqueidentifier) - **json_key** : (nvarchar(4000)) - **T2_json_key** : (nvarchar(4000)) child0_children : (nvarchar(max)) child0_class : (nvarchar(500)) child0_is_group : (bit) child0_is_keyword : (bit) child0_is_whitespace : (bit) child0_normalized : (nvarchar(max)) child1_children : (nvarchar(max)) child1_class : (nvarchar(500)) child1_is_group : (bit) child1_is_keyword : (bit) child1_is_whitespace : (bit) child1_normalized : (nvarchar(max)) child2_children : (nvarchar(max)) child2_class : (nvarchar(500)) child2_is_group : (bit) child2_is_keyword : (bit) child2_is_whitespace : (bit) child2_normalized : (nvarchar(max)) child3_children : (nvarchar(max)) child3_class : (nvarchar(500)) child3_is_group : (bit) child3_is_keyword : (bit) child3_is_whitespace : (bit) child3_normalized : (nvarchar(max)) child4_children : (nvarchar(max)) child4_class : (nvarchar(500)) child4_is_group : (bit) child4_is_keyword : (bit) child4_is_whitespace : (bit) child4_normalized : (nvarchar(max)) children : (nvarchar(max)) class : (nvarchar(500)) Identifier_alias : (nvarchar(max)) Identifier_source : (nvarchar(max)) Identifier_source_children : (nvarchar(max)) Identifier_source_class : (nvarchar(500)) is_group : (bit) is_keyword : (bit) is_whitespace : (bit) normalized : (nvarchar(max)) RowNumber_per_Object : (bigint) SysObject_fullname : (nvarchar(261)) T2_class : (nvarchar(500)) -- } sqlparse.ftv_sqlparse_with_some_children <.. sqlparse.ftv_sqlparse_IdentifierList__TestOnly sqlparse.ftv_sqlparse_with_some_children <.. sqlparse.RepoObject_SqlModules_20_statement_children sqlparse.ftv_sqlparse_with_some_children <.. sqlparse.RepoObject_SqlModules_24_IdentifierList_children footer The diagram is interactive and contains links. @enduml .... // end::puml_entity_1_1_colref[] == sql_modules_definition // tag::sql_modules_definition[] [%collapsible] ======= [source,sql,numbered,indent=0] ---- CREATE Function [sqlparse].ftv_sqlparse_with_some_children ( @json_array NVarchar(Max) ) Returns Table As Return ( Select j1.[Key] As json_key , j2.* From OpenJson ( @json_array ) j1 Cross Apply OpenJson ( j1.Value ) With ( class NVarchar ( 500 ) N'$.class' , is_group Bit N'$.is_group' , is_keyword Bit N'$.is_keyword' , is_whitespace Bit N'$.is_whitespace' , normalized NVarchar ( Max ) N'$.normalized' , children NVarchar ( Max ) N'$.children' As Json --get values of some children --children[0] is the first children , child0_class NVarchar ( 500 ) N'$.children[0].class' , child0_is_group Bit N'$.children[0].is_group' , child0_is_keyword Bit N'$.children[0].is_keyword' , child0_is_whitespace Bit N'$.children[0].is_whitespace' , child0_normalized NVarchar ( Max ) N'$.children[0].normalized' , child0_children NVarchar ( Max ) N'$.children[0].children' As Json , child1_class NVarchar ( 500 ) N'$.children[1].class' , child1_is_group Bit N'$.children[1].is_group' , child1_is_keyword Bit N'$.children[1].is_keyword' , child1_is_whitespace Bit N'$.children[1].is_whitespace' , child1_normalized NVarchar ( Max ) N'$.children[1].normalized' , child1_children NVarchar ( Max ) N'$.children[1].children' As Json , child2_class NVarchar ( 500 ) N'$.children[2].class' , child2_is_group Bit N'$.children[2].is_group' , child2_is_keyword Bit N'$.children[2].is_keyword' , child2_is_whitespace Bit N'$.children[2].is_whitespace' , child2_normalized NVarchar ( Max ) N'$.children[2].normalized' , child2_children NVarchar ( Max ) N'$.children[2].children' As Json , child3_class NVarchar ( 500 ) N'$.children[3].class' , child3_is_group Bit N'$.children[3].is_group' , child3_is_keyword Bit N'$.children[3].is_keyword' , child3_is_whitespace Bit N'$.children[3].is_whitespace' , child3_normalized NVarchar ( Max ) N'$.children[3].normalized' , child3_children NVarchar ( Max ) N'$.children[3].children' As Json , child4_class NVarchar ( 500 ) N'$.children[4].class' , child4_is_group Bit N'$.children[4].is_group' , child4_is_keyword Bit N'$.children[4].is_keyword' , child4_is_whitespace Bit N'$.children[4].is_whitespace' , child4_normalized NVarchar ( Max ) N'$.children[4].normalized' , child4_children NVarchar ( Max ) N'$.children[4].children' As Json ) j2 ); ---- ======= // end::sql_modules_definition[] ",16251,True,3214.1603700086393,median "= v1.ImageStream {product-author} {product-version} :data-uri: :icons: :toc: macro :toc-title: :toclevels: 2 toc::[] == Description [%hardbreaks] ImageStream stores a mapping of tags to images, metadata overrides that are applied when images are tagged in a stream, and an optional reference to a Docker image repository on a registry. == Object Schema Expand or mouse-over a field for more information about it. ++++

apiVersion:
kind:
metadata:
annotations:
[string]:
clusterName:
creationTimestamp:
deletionGracePeriodSeconds:
deletionTimestamp:
finalizers:
- [string]:
generateName:
generation:
:
pending:
- name:
result:
apiVersion:
code:
details:
causes:
- field:
message:
reason:
group:
kind:
name:
retryAfterSeconds:
uid:
kind:
message:
metadata:
continue:
resourceVersion:
selfLink:
reason:
status:
labels:
[string]:
name:
namespace:
ownerReferences:
- apiVersion:
blockOwnerDeletion:
controller:
kind:
name:
uid:
resourceVersion:
selfLink:
uid:
spec:
dockerImageRepository:
lookupPolicy:
local:
tags:
- annotations:
- [string]:
from:
apiVersion:
fieldPath:
kind:
name:
namespace:
resourceVersion:
uid:
generation:
importPolicy:
insecure:
scheduled:
name:
reference:
referencePolicy:
type:
status:
dockerImageRepository:
publicDockerImageRepository:
tags:
- conditions:
- - generation:
lastTransitionTime:
message:
reason:
status:
type:
items:
- created:
dockerImageReference:
generation:
image:
tag:
++++ == Operations [[Post-apis-image.openshift.io-v1-imagestreams]] === Create a ImageStream Create an ImageStream ==== HTTP request ---- POST /apis/image.openshift.io/v1/imagestreams HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json' { ""kind"": ""ImageStream"", ""apiVersion"": ""image.openshift.io/v1"", ... } ---- ==== Curl request ---- $ curl -k \\ -X POST \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json' \\ https://$ENDPOINT/apis/image.openshift.io/v1/imagestreams <<'EOF' { ""kind"": ""ImageStream"", ""apiVersion"": ""image.openshift.io/v1"", ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1.ImageStream |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.ImageStream |201 Created|v1.ImageStream |202 Accepted|v1.ImageStream |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Post-apis-image.openshift.io-v1-namespaces-namespace-imagestreams]] === Create a ImageStream in a namespace Create an ImageStream ==== HTTP request ---- POST /apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json' { ""kind"": ""ImageStream"", ""apiVersion"": ""image.openshift.io/v1"", ... } ---- ==== Curl request ---- $ curl -k \\ -X POST \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json' \\ https://$ENDPOINT/apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams <<'EOF' { ""kind"": ""ImageStream"", ""apiVersion"": ""image.openshift.io/v1"", ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1.ImageStream |=== ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.ImageStream |201 Created|v1.ImageStream |202 Accepted|v1.ImageStream |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Get-apis-image.openshift.io-v1-namespaces-namespace-imagestreams-name]] === Get a ImageStream in a namespace Read the specified ImageStream ==== HTTP request ---- GET /apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the ImageStream |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |exact|Should the export be exact. Exact export maintains cluster-specific fields like 'Namespace'. |export|Should this value be exported. Export strips fields that a user can not specify. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.ImageStream |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Get-apis-image.openshift.io-v1-imagestreams]] === Get all ImageStreams List or watch objects of kind ImageStream ==== HTTP request ---- GET /apis/image.openshift.io/v1/imagestreams HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/image.openshift.io/v1/imagestreams ---- ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.ImageStreamList |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf * application/json;stream=watch * application/vnd.kubernetes.protobuf;stream=watch [[Get-apis-image.openshift.io-v1-namespaces-namespace-imagestreams]] === Get all ImageStreams in a namespace List or watch objects of kind ImageStream ==== HTTP request ---- GET /apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.ImageStreamList |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf * application/json;stream=watch * application/vnd.kubernetes.protobuf;stream=watch [[Get-apis-image.openshift.io-v1-watch-namespaces-namespace-imagestreams-name]] === Watch a ImageStream in a namespace Watch changes to an object of kind ImageStream ==== HTTP request ---- GET /apis/image.openshift.io/v1/watch/namespaces/$NAMESPACE/imagestreams/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/image.openshift.io/v1/watch/namespaces/$NAMESPACE/imagestreams/$NAME ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the ImageStream |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |pretty|If 'true', then the output is pretty printed. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.WatchEvent |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf * application/json;stream=watch * application/vnd.kubernetes.protobuf;stream=watch [[Get-apis-image.openshift.io-v1-watch-imagestreams]] === Watch all ImageStreams Watch individual changes to a list of ImageStream ==== HTTP request ---- GET /apis/image.openshift.io/v1/watch/imagestreams HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/image.openshift.io/v1/watch/imagestreams ---- ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |pretty|If 'true', then the output is pretty printed. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.WatchEvent |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf * application/json;stream=watch * application/vnd.kubernetes.protobuf;stream=watch [[Get-apis-image.openshift.io-v1-watch-namespaces-namespace-imagestreams]] === Watch all ImageStreams in a namespace Watch individual changes to a list of ImageStream ==== HTTP request ---- GET /apis/image.openshift.io/v1/watch/namespaces/$NAMESPACE/imagestreams HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/image.openshift.io/v1/watch/namespaces/$NAMESPACE/imagestreams ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |pretty|If 'true', then the output is pretty printed. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.WatchEvent |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf * application/json;stream=watch * application/vnd.kubernetes.protobuf;stream=watch [[Put-apis-image.openshift.io-v1-namespaces-namespace-imagestreams-name]] === Update a ImageStream in a namespace Replace the specified ImageStream ==== HTTP request ---- PUT /apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json' { ""kind"": ""ImageStream"", ""apiVersion"": ""image.openshift.io/v1"", ... } ---- ==== Curl request ---- $ curl -k \\ -X PUT \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json' \\ https://$ENDPOINT/apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME <<'EOF' { ""kind"": ""ImageStream"", ""apiVersion"": ""image.openshift.io/v1"", ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1.ImageStream |=== ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the ImageStream |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.ImageStream |201 Created|v1.ImageStream |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Patch-apis-image.openshift.io-v1-namespaces-namespace-imagestreams-name]] === Patch a ImageStream in a namespace Partially update the specified ImageStream ==== HTTP request ---- PATCH /apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json-patch+json' { ... } ---- ==== Curl request ---- $ curl -k \\ -X PATCH \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json-patch+json' \\ https://$ENDPOINT/apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME <<'EOF' { ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1.Patch |=== ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the ImageStream |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.ImageStream |401 Unauthorized| |=== ==== Consumes * application/json-patch+json * application/merge-patch+json * application/strategic-merge-patch+json ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Delete-apis-image.openshift.io-v1-namespaces-namespace-imagestreams-name]] === Delete a ImageStream in a namespace Delete an ImageStream ==== HTTP request ---- DELETE /apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json' { ... } ---- ==== Curl request ---- $ curl -k \\ -X DELETE \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json' \\ https://$ENDPOINT/apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME <<'EOF' { ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1.DeleteOptions |=== ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the ImageStream |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |gracePeriodSeconds|The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. |orphanDependents|Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the ""orphan"" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. |propagationPolicy|Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.Status |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Delete-apis-image.openshift.io-v1-namespaces-namespace-imagestreams]] === Delete all ImageStreams in a namespace Delete collection of ImageStream ==== HTTP request ---- DELETE /apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -X DELETE \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.Status |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Get-apis-image.openshift.io-v1-namespaces-namespace-imagestreams-name-secrets]] === Get secrets of a ImageStream in a namespace Read secrets of the specified ImageStream ==== HTTP request ---- GET /apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME/secrets HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME/secrets ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the SecretList |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |pretty|If 'true', then the output is pretty printed. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.SecretList |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Get-apis-image.openshift.io-v1-namespaces-namespace-imagestreams-name-status]] === Get status of a ImageStream in a namespace Read status of the specified ImageStream ==== HTTP request ---- GET /apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME/status HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME/status ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the ImageStream |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.ImageStream |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Put-apis-image.openshift.io-v1-namespaces-namespace-imagestreams-name-status]] === Update status of a ImageStream in a namespace Replace status of the specified ImageStream ==== HTTP request ---- PUT /apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME/status HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json' { ""kind"": ""ImageStream"", ""apiVersion"": ""image.openshift.io/v1"", ... } ---- ==== Curl request ---- $ curl -k \\ -X PUT \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json' \\ https://$ENDPOINT/apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME/status <<'EOF' { ""kind"": ""ImageStream"", ""apiVersion"": ""image.openshift.io/v1"", ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1.ImageStream |=== ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the ImageStream |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.ImageStream |201 Created|v1.ImageStream |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Patch-apis-image.openshift.io-v1-namespaces-namespace-imagestreams-name-status]] === Patch status of a ImageStream in a namespace Partially update status of the specified ImageStream ==== HTTP request ---- PATCH /apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME/status HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json-patch+json' { ... } ---- ==== Curl request ---- $ curl -k \\ -X PATCH \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json-patch+json' \\ https://$ENDPOINT/apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME/status <<'EOF' { ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1.Patch |=== ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the ImageStream |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.ImageStream |401 Unauthorized| |=== ==== Consumes * application/json-patch+json * application/merge-patch+json * application/strategic-merge-patch+json ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf ",16193,True,3031.84005636907,median "------------------------------------------------------------------------------ -- -- -- GNAT LIBRARY COMPONENTS -- -- -- -- G N A T . S P I T B O L . P A T T E R N S -- -- -- -- S p e c -- -- -- -- $Revision$ -- -- -- Copyright (C) 1997-1999 Ada Core Technologies, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 2, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNAT; see file COPYING. If not, write -- -- to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, -- -- MA 02111-1307, USA. -- -- -- -- As a special exception, if other files instantiate generics from this -- -- unit, or you link this unit with other files to produce an executable, -- -- this unit does not by itself cause the resulting executable to be -- -- covered by the GNU General Public License. This exception does not -- -- however invalidate any other reasons why the executable file might be -- -- covered by the GNU Public License. -- -- -- -- GNAT is maintained by Ada Core Technologies Inc (http://www.gnat.com). -- -- -- ------------------------------------------------------------------------------ -- SPITBOL-like pattern construction and matching -- This child package of GNAT.SPITBOL provides a complete implementation -- of the SPITBOL-like pattern construction and matching operations. This -- package is based on Macro-SPITBOL created by Robert Dewar. ------------------------------------------------------------ -- Summary of Pattern Matching Packages in GNAT Hierarchy -- ------------------------------------------------------------ -- There are three related packages that perform pattern maching functions. -- the following is an outline of these packages, to help you determine -- which is best for your needs. -- GNAT.Regexp (files g-regexp.ads/g-regexp.adb) -- This is a simple package providing Unix-style regular expression -- matching with the restriction that it matches entire strings. It -- is particularly useful for file name matching, and in particular -- it provides ""globbing patterns"" that are useful in implementing -- unix or DOS style wild card matching for file names. -- GNAT.Regpat (files g-regpat.ads/g-regpat.adb) -- This is a more complete implementation of Unix-style regular -- expressions, copied from the original V7 style regular expression -- library written in C by Henry Spencer. It is functionally the -- same as this library, and uses the same internal data structures -- stored in a binary compatible manner. -- GNAT.Spitbol.Patterns (files g-spipat.ads/g-spipat.adb) -- This is a completely general patterm matching package based on the -- pattern language of SNOBOL4, as implemented in SPITBOL. The pattern -- language is modeled on context free grammars, with context sensitive -- extensions that provide full (type 0) computational capabilities. with Ada.Finalization; use Ada.Finalization; with Ada.Strings.Maps; use Ada.Strings.Maps; with Ada.Text_IO; use Ada.Text_IO; package GNAT.Spitbol.Patterns is pragma Elaborate_Body (Patterns); ------------------------------- -- Pattern Matching Tutorial -- ------------------------------- -- A pattern matching operation (a call to one of the Match subprograms) -- takes a subject string and a pattern, and optionally a replacement -- string. The replacement string option is only allowed if the subject -- is a variable. -- The pattern is matched against the subject string, and either the -- match fails, or it succeeds matching a contiguous substring. If a -- replacement string is specified, then the subject string is modified -- by replacing the matched substring with the given replacement. -- Concatenation and Alternation -- ============================= -- A pattern consists of a series of pattern elements. The pattern is -- built up using either the concatenation operator: -- A & B -- which means match A followed immediately by matching B, or the -- alternation operator: -- A or B -- which means first attempt to match A, and then if that does not -- succeed, match B. -- There is full backtracking, which means that if a given pattern -- element fails to match, then previous alternatives are matched. -- For example if we have the pattern: -- (A or B) & (C or D) & (E or F) -- First we attempt to match A, if that succeeds, then we go on to try -- to match C, and if that succeeds, we go on to try to match E. If E -- fails, then we try F. If F fails, then we go back and try matching -- D instead of C. Let's make this explicit using a specific example, -- and introducing the simplest kind of pattern element, which is a -- literal string. The meaning of this pattern element is simply to -- match the characters that correspond to the string characters. Now -- let's rewrite the above pattern form with specific string literals -- as the pattern elements: -- (""ABC"" or ""AB"") & (""DEF"" or ""CDE"") & (""GH"" or ""IJ"") -- The following strings will be attempted in sequence: -- ABC . DEF . GH -- ABC . DEF . IJ -- ABC . CDE . GH -- ABC . CDE . IJ -- AB . DEF . GH -- AB . DEF . IJ -- AB . CDE . GH -- AB . CDE . IJ -- Here we use the dot simply to separate the pieces of the string -- matched by the three separate elements. -- Moving the Start Point -- ====================== -- A pattern is not required to match starting at the first character -- of the string, and is not required to match to the end of the string. -- The first attempt does indeed attempt to match starting at the first -- character of the string, trying all the possible alternatives. But -- if all alternatives fail, then the starting point of the match is -- moved one character, and all possible alternatives are attempted at -- the new anchor point. -- The entire match fails only when every possible starting point has -- been attempted. As an example, suppose that we had the subject -- string -- ""ABABCDEIJKL"" -- matched using the pattern in the previous example: -- (""ABC"" or ""AB"") & (""DEF"" or ""CDE"") & (""GH"" or ""IJ"") -- would succeed, afer two anchor point moves: -- ""ABABCDEIJKL"" -- ^^^^^^^ -- matched -- section -- This mode of pattern matching is called the unanchored mode. It is -- also possible to put the pattern matcher into anchored mode by -- setting the global variable Anchored_Mode to True. This will cause -- all subsequent matches to be performed in anchored mode, where the -- match is required to start at the first character. -- We will also see later how the effect of an anchored match can be -- obtained for a single specified anchor point if this is desired. -- Other Pattern Elements -- ====================== -- In addition to strings (or single characters), there are many special -- pattern elements that correspond to special predefined alternations: -- Arb Matches any string. First it matches the null string, and -- then on a subsequent failure, matches one character, and -- then two characters, and so on. It only fails if the -- entire remaining string is matched. -- Bal Matches a non-empty string that is parentheses balanced -- with respect to ordinary () characters. Examples of -- balanced strings are ""ABC"", ""A((B)C)"", and ""A(B)C(D)E"". -- Bal matches the shortest possible balanced string on the -- first attempt, and if there is a subsequent failure, -- attempts to extend the string. -- Cancel Immediately aborts the entire pattern match, signalling -- failure. This is a specialized pattern element, which is -- useful in conjunction with some of the special pattern -- elements that have side effects. -- Fail The null alternation. Matches no possible strings, so it -- always signals failure. This is a specialized pattern -- element, which is useful in conjunction with some of the -- special pattern elements that have side effects. -- Fence Matches the null string at first, and then if a failure -- causes alternatives to be sought, aborts the match (like -- a Cancel). Note that using Fence at the start of a pattern -- has the same effect as matching in anchored mode. -- Rest Matches from the current point to the last character in -- the string. This is a specialized pattern element, which -- is useful in conjunction with some of the special pattern -- elements that have side effects. -- Succeed Repeatedly matches the null string (it is equivalent to -- the alternation ("""" or """" or """" ....). This is a special -- pattern element, which is useful in conjunction with some -- of the special pattern elements that have side effects. -- Pattern Construction Functions -- ============================== -- The following functions construct additional pattern elements -- Any(S) Where S is a string, matches a single character that is -- any one of the characters in S. Fails if the current -- character is not one of the given set of characters. -- Arbno(P) Where P is any pattern, matches any number of instances -- of the pattern, starting with zero occurrences. It is -- thus equivalent to ("""" or (P & ("""" or (P & ("""" ....)))). -- The pattern P may contain any number of pattern elements -- including the use of alternatiion and concatenation. -- Break(S) Where S is a string, matches a string of zero or more -- characters up to but not including a break character -- that is one of the characters given in the string S. -- Can match the null string, but cannot match the last -- character in the string, since a break character is -- required to be present. -- BreakX(S) Where S is a string, behaves exactly like Break(S) when -- it first matches, but if a string is successfully matched, -- then a susequent failure causes an attempt to extend the -- matched string. -- Fence(P) Where P is a pattern, attempts to match the pattern P -- including trying all possible alternatives of P. If none -- of these alternatives succeeds, then the Fence pattern -- fails. If one alternative succeeds, then the pattern -- match proceeds, but on a subsequent failure, no attempt -- is made to search for alternative matches of P. The -- pattern P may contain any number of pattern elements -- including the use of alternatiion and concatenation. -- Len(N) Where N is a natural number, matches the given number of -- characters. For example, Len(10) matches any string that -- is exactly ten characters long. -- NotAny(S) Where S is a string, matches a single character that is -- not one of the characters of S. Fails if the current -- characer is one of the given set of characters. -- NSpan(S) Where S is a string, matches a string of zero or more -- characters that is among the characters given in the -- string. Always matches the longest possible such string. -- Always succeeds, since it can match the null string. -- Pos(N) Where N is a natural number, matches the null string -- if exactly N characters have been matched so far, and -- otherwise fails. -- Rpos(N) Where N is a natural number, matches the null string -- if exactly N characters remain to be matched, and -- otherwise fails. -- Rtab(N) Where N is a natural number, matches characters from -- the current position until exactly N characters remain -- to be matched in the string. Fails if fewer than N -- unmatched characters remain in the string. -- Tab(N) Where N is a natural number, matches characters from -- the current position until exactly N characters have -- been matched in all. Fails if more than N characters -- have already been matched. -- Span(S) Where S is a string, matches a string of one or more -- characters that is among the characters given in the -- string. Always matches the longest possible such string. -- Fails if the current character is not one of the given -- set of characters. -- Recursive Pattern Matching -- ========================== -- The plus operator (+P) where P is a pattern variable, creates -- a recursive pattern that will, at pattern matching time, follow -- the pointer to obtain the referenced pattern, and then match this -- pattern. This may be used to construct recursive patterns. Consider -- for example: -- P := (""A"" or (""B"" & (+P))) -- On the first attempt, this pattern attempts to match the string ""A"". -- If this fails, then the alternative matches a ""B"", followed by an -- attempt to match P again. This second attempt first attempts to -- match ""A"", and so on. The result is a pattern that will match a -- string of B's followed by a single A. -- This particular example could simply be written as NSpan('B') & 'A', -- but the use of recursive patterns in the general case can construct -- complex patterns which could not otherwise be built. -- Pattern Assignment Operations -- ============================= -- In addition to the overall result of a pattern match, which indicates -- success or failure, it is often useful to be able to keep track of -- the pieces of the subject string that are matched by individual -- pattern elements, or subsections of the pattern. -- The pattern assignment operators allow this capability. The first -- form is the immediate assignment: -- P * S -- Here P is an arbitrary pattern, and S is a variable of type VString -- that will be set to the substring matched by P. This assignment -- happens during pattern matching, so if P matches more than once, -- then the assignment happens more than once. -- The deferred assignment operation: -- P ** S -- avoids these multiple assignments by deferring the assignment to the -- end of the match. If the entire match is successful, and if the -- pattern P was part of the successful match, then at the end of the -- matching operation the assignment to S of the string matching P is -- performed. -- The cursor assignment operation: -- Setcur(N'Access) -- assigns the current cursor position to the natural variable N. The -- cursor position is defined as the count of characters that have been -- matched so far (including any start point moves). -- Finally the operations * and ** may be used with values of type -- Text_IO.File_Access. The effect is to do a Put_Line operation of -- the matched substring. These are particularly useful in debugging -- pattern matches. -- Deferred Matching -- ================= -- The pattern construction functions (such as Len and Any) all permit -- the use of pointers to natural or string values, or functions that -- return natural or string values. These forms cause the actual value -- to be obtained at pattern matching time. This allows interesting -- possibilities for constructing dynamic patterns as illustrated in -- the examples section. -- In addition the (+S) operator may be used where S is a pointer to -- string or function returning string, with a similar deferred effect. -- A special use of deferred matching is the construction of predicate -- functions. The element (+P) where P is an access to a function that -- returns a Boolean value, causes the function to be called at the -- time the element is matched. If the function returns True, then the -- null string is matched, if the function returns False, then failure -- is signalled and previous alternatives are sought. -- Deferred Replacement -- ==================== -- The simple model given for pattern replacement (where the matched -- substring is replaced by the string given as the third argument to -- Match) works fine in simple cases, but this approach does not work -- in the case where the expression used as the replacement string is -- dependent on values set by the match. -- For example, suppose we want to find an instance of a parenthesized -- character, and replace the parentheses with square brackets. At first -- glance it would seem that: -- Match (Subject, '(' & Len (1) * Char & ')', '[' & Char & ']'); -- would do the trick, but that does not work, because the third -- argument to Match gets evaluated too early, before the call to -- Match, and before the pattern match has had a chance to set Char. -- To solve this problem we provide the deferred replacement capability. -- With this approach, which of course is only needed if the pattern -- involved has side effects, is to do the match in two stages. The -- call to Match sets a pattern result in a variable of the private -- type Match_Result, and then a subsequent Replace operation uses -- this Match_Result object to perform the required replacement. -- Using this approach, we can now write the above operation properly -- in a manner that will work: -- M : Match_Result; -- ... -- Match (Subject, '(' & Len (1) * Char & ')', M); -- Replace (M, '[' & Char & ']'); -- As with other Match cases, there is a function and procedure form -- of this match call. A call to Replace after a failed match has no -- effect. Note that Subject should not be modified between the calls. -- Examples of Pattern Matching -- ============================ -- First a simple example of the use of pattern replacement to remove -- a line number from the start of a string. We assume that the line -- number has the form of a string of decimal digits followed by a -- period, followed by one or more spaces. -- Digs : constant Pattern := Span(""0123456789""); -- Lnum : constant Pattern := Pos(0) & Digs & '.' & Span(' '); -- Now to use this pattern we simply do a match with a replacement: -- Match (Line, Lnum, """"); -- which replaces the line number by the null string. Note that it is -- also possible to use an Ada.Strings.Maps.Character_Set value as an -- argument to Span and similar functions, and in particular all the -- useful constants 'in Ada.Strings.Maps.Constants are available. This -- means that we could define Digs as: -- Digs : constant Pattern := Span(Decimal_Digit_Set); -- The style we use here, of defining constant patterns and then using -- them is typical. It is possible to build up patterns dynamically, -- but it is usually more efficient to build them in pieces in advance -- using constant declarations. Note in particular that although it is -- possible to construct a pattern directly as an argument for the -- Match routine, it is much more efficient to preconstruct the pattern -- as we did in this example. -- Now let's look at the use of pattern assignment to break a -- string into sections. Suppose that the input string has two -- unsigned decimal integers, separated by spaces or a comma, -- with spaces allowed anywhere. Then we can isolate the two -- numbers with the following pattern: -- Num1, Num2 : aliased VString; -- B : constant Pattern := NSpan(' '); -- N : constant Pattern := Span(""0123456789""); -- T : constant Pattern := -- NSpan(' ') & N * Num1 & Span("" ,"") & N * Num2; -- The match operation Match ("" 124, 257 "", T) would assign the -- string 124 to Num1 and the string 257 to Num2. -- Now let's see how more complex elements can be built from the -- set of primitive elements. The following pattern matches strings -- that have the syntax of Ada 95 based literals: -- Digs : constant Pattern := Span(Decimal_Digit_Set); -- UDigs : constant Pattern := Digs & Arbno('_' & Digs); -- Edig : constant Pattern := Span(Hexadecimal_Digit_Set); -- UEdig : constant Pattern := Edig & Arbno('_' & Edig); -- Bnum : constant Pattern := Udigs & '#' & UEdig & '#'; -- A match against Bnum will now match the desired strings, e.g. -- it will match 16#123_abc#, but not a#b#. However, this pattern -- is not quite complete, since it does not allow colons to replace -- the pound signs. The following is more complete: -- Bchar : constant Pattern := Any(""#:""); -- Bnum : constant Pattern := Udigs & Bchar & UEdig & Bchar; -- but that is still not quite right, since it allows # and : to be -- mixed, and they are supposed to be used consistently. We solve -- this by using a deferred match. -- Temp : aliased VString; -- Bnum : constant Pattern := -- Udigs & Bchar * Temp & UEdig & (+Temp) -- Here the first instance of the base character is stored in Temp, and -- then later in the pattern we rematch the value that was assigned. -- For an example of a recursive pattern, let's define a pattern -- that is like the built in Bal, but the string matched is balanced -- with respect to square brackets or curly brackets. -- The language for such strings might be defined in extended BNF as -- ELEMENT ::= -- | '[' BALANCED_STRING ']' -- | '{' BALANCED_STRING '}' -- BALANCED_STRING ::= ELEMENT {ELEMENT} -- Here we use {} to indicate zero or more occurrences of a term, as -- is common practice in extended BNF. Now we can translate the above -- BNF into recursive patterns as follows: -- Element, Balanced_String : aliased Pattern; -- . -- . -- . -- Element := NotAny (""[]{}"") -- or -- ('[' & (+Balanced_String) & ']') -- or -- ('{' & (+Balanced_String) & '}'); -- Balanced_String := Element & Arbno (Element); -- Note the important use of + here to refer to a pattern not yet -- defined. Note also that we use assignments precisely because we -- cannot refer to as yet undeclared variables in initializations. -- Now that this pattern is constructed, we can use it as though it -- were a new primitive pattern element, and for example, the match: -- Match (""xy[ab{cd}]"", Balanced_String * Current_Output & Fail); -- will generate the output: -- x -- xy -- xy[ab{cd}] -- y -- y[ab{cd}] -- [ab{cd}] -- a -- ab -- ab{cd} -- b -- b{cd} -- {cd} -- c -- cd -- d -- Note that the function of the fail here is simply to force the -- pattern Balanced_String to match all possible alternatives. Studying -- the operation of this pattern in detail is highly instructive. -- Finally we give a rather elaborate example of the use of deferred -- matching. The following declarations build up a pattern which will -- find the longest string of decimal digits in the subject string. -- Max, Cur : VString; -- Loc : Natural; -- function GtS return Boolean is -- begin -- return Length (Cur) > Length (Max); -- end GtS; -- Digit : constant Character_Set := Decimal_Digit_Set; -- Digs : constant Pattern := Span(Digit); -- Find : constant Pattern := -- """" * Max & Fence & -- initialize Max to null -- BreakX (Digit) & -- scan looking for digits -- ((Span(Digit) * Cur & -- assign next string to Cur -- (+GtS'Unrestricted_Access) & -- check size(Cur) > Size(Max) -- Setcur(Loc'Access)) -- if so, save location -- * Max) & -- and assign to Max -- Fail; -- seek all alternatives -- As we see from the comments here, complex patterns like this take -- on aspects of sequential programs. In fact they are sequential -- programs with general backtracking. In this pattern, we first use -- a pattern assignment that matches null and assigns it to Max, so -- that it is initialized for the new match. Now BreakX scans to the -- next digit. Arb would do here, but BreakX will be more efficient. -- Once we have found a digit, we scan out the longest string of -- digits with Span, and assign it to Cur. The deferred call to GtS -- tests if the string we assigned to Cur is the longest so far. If -- not, then failure is signalled, and we seek alternatives (this -- means that BreakX will extend and look for the next digit string). -- If the call to GtS succeeds then the matched string is assigned -- as the largest string so far into Max and its location is saved -- in Loc. Finally Fail forces the match to fail and seek alternatives, -- so that the entire string is searched. -- If the pattern Find is matched against a string, the variable Max -- at the end of the pattern will have the longest string of digits, -- and Loc will be the starting character location of the string. For -- example, Match(""ab123cd4657ef23"", Find) will assign ""4657"" to Max -- and 11 to Loc (indicating that the string ends with the eleventh -- character of the string). -- Note: the use of Unrestricted_Access to reference GtS will not -- be needed if GtS is defined at the outer level, but definitely -- will be necessary if GtS is a nested function (in which case of -- course the scope of the pattern Find will be restricted to this -- nested scope, and this cannot be checked, i.e. use of the pattern -- outside this scope is erroneous). Generally it is a good idea to -- define patterns and the functions they call at the outer level -- where possible, to avoid such problems. -- Correspondence with Pattern Matching in SPITBOL -- =============================================== -- Generally the Ada syntax and names correspond closely to SPITBOL -- syntax for pattern matching construction. -- The basic pattern construction operators are renamed as follows: -- Spitbol Ada -- (space) & -- | or -- $ * -- . ** -- The Ada operators were chosen so that the relative precedences of -- these operators corresponds to that of the Spitbol operators, but -- as always, the use of parentheses is advisable to clarify. -- The pattern construction operators all have similar names except for -- Spitbol Ada -- Abort Cancel -- Rem Rest -- where we have clashes with Ada reserved names. -- Ada requires the use of 'Access to refer to functions used in the -- pattern match, and often the use of 'Unrestricted_Access may be -- necessary to get around the scope restrictions if the functions -- are not declared at the outer level. -- The actual pattern matching syntax is modified in Ada as follows: -- Spitbol Ada -- X Y Match (X, Y); -- X Y = Z Match (X, Y, Z); -- and pattern failure is indicated by returning a Boolean result from -- the Match function (True for success, False for failure). ----------------------- -- Type Declarations -- ----------------------- type Pattern is private; -- Type representing a pattern. This package provides a complete set of -- operations for constructing patterns that can be used in the pattern -- matching operations provided. type Boolean_Func is access function return Boolean; -- General Boolean function type. When this type is used as a formal -- parameter type in this package, it indicates a deferred predicate -- pattern. The function will be called when the pattern element is -- matched and failure signalled if False is returned. type Natural_Func is access function return Natural; -- General Natural function type. When this type is used as a formal -- parameter type in this package, it indicates a deferred pattern. -- The function will be called when the pattern element is matched -- to obtain the currently referenced Natural value. type VString_Func is access function return VString; -- General VString function type. When this type is used as a formal -- parameter type in this package, it indicates a deferred pattern. -- The function will be called when the pattern element is matched -- to obtain the currently referenced string value. subtype PString is String; -- This subtype is used in the remainder of the package to indicate a -- formal parameter that is converted to its corresponding pattern, -- i.e. a pattern that matches the characters of the string. subtype PChar is Character; -- Similarly, this subtype is used in the remainder of the package to -- indicate a formal parameter that is converted to its corresponding -- pattern, i.e. a pattern that matches this one character. subtype VString_Var is VString; subtype Pattern_Var is Pattern; -- These synonyms are used as formal parameter types to a function where, -- if the language allowed, we would use in out parameters, but we are -- not allowed to have in out parameters for functions. Instead we pass -- actuals which must be variables, and with a bit of trickery in the -- body, manage to interprete them properly as though they were indeed -- in out parameters. -------------------------------- -- Basic Pattern Construction -- -------------------------------- function ""&"" (L : Pattern; R : Pattern) return Pattern; function ""&"" (L : PString; R : Pattern) return Pattern; function ""&"" (L : Pattern; R : PString) return Pattern; function ""&"" (L : PChar; R : Pattern) return Pattern; function ""&"" (L : Pattern; R : PChar) return Pattern; -- Pattern concatenation. Matches L followed by R. function ""or"" (L : Pattern; R : Pattern) return Pattern; function ""or"" (L : PString; R : Pattern) return Pattern; function ""or"" (L : Pattern; R : PString) return Pattern; function ""or"" (L : PString; R : PString) return Pattern; function ""or"" (L : PChar; R : Pattern) return Pattern; function ""or"" (L : Pattern; R : PChar) return Pattern; function ""or"" (L : PChar; R : PChar) return Pattern; function ""or"" (L : PString; R : PChar) return Pattern; function ""or"" (L : PChar; R : PString) return Pattern; -- Pattern alternation. Creates a pattern that will first try to match -- L and then on a subsequent failure, attempts to match R instead. ---------------------------------- -- Pattern Assignment Functions -- ---------------------------------- function ""*"" (P : Pattern; Var : VString_Var) return Pattern; function ""*"" (P : PString; Var : VString_Var) return Pattern; function ""*"" (P : PChar; Var : VString_Var) return Pattern; -- Matches P, and if the match succeeds, assigns the matched substring -- to the given VString variable S. This assignment happens as soon as -- the substring is matched, and if the pattern P1 is matched more than -- once during the course of the match, then the assignment will occur -- more than once. function ""**"" (P : Pattern; Var : VString_Var) return Pattern; function ""**"" (P : PString; Var : VString_Var) return Pattern; function ""**"" (P : PChar; Var : VString_Var) return Pattern; -- Like ""*"" above, except that the assignment happens at most once -- after the entire match is completed successfully. If the match -- fails, then no assignment takes place. ---------------------------------- -- Deferred Matching Operations -- ---------------------------------- function ""+"" (Str : VString_Var) return Pattern; -- Here Str must be a VString variable. This function constructs a -- pattern which at pattern matching time will access the current -- value of this variable, and match against these characters. function ""+"" (Str : VString_Func) return Pattern; -- Constructs a pattern which at pattern matching time calls the given -- function, and then matches against the string or character value -- that is returned by the call. function ""+"" (P : Pattern_Var) return Pattern; -- Here P must be a Pattern variable. This function constructs a -- pattern which at pattern matching time will access the current -- value of this variable, and match against the pattern value. function ""+"" (P : Boolean_Func) return Pattern; -- Constructs a predicate pattern function that at pattern matching time -- calls the given function. If True is returned, then the pattern matches. -- If False is returned, then failure is signalled. -------------------------------- -- Pattern Building Functions -- -------------------------------- function Arb return Pattern; -- Constructs a pattern that will match any string. On the first attempt, -- the pattern matches a null string, then on each successive failure, it -- matches one more character, and only fails if matching the entire rest -- of the string. function Arbno (P : Pattern) return Pattern; function Arbno (P : PString) return Pattern; function Arbno (P : PChar) return Pattern; -- Pattern repetition. First matches null, then on a subsequent failure -- attempts to match an additional instance of the given pattern. -- Equivalent to (but more efficient than) P & ("""" or (P & ("""" or ... function Any (Str : String) return Pattern; function Any (Str : VString) return Pattern; function Any (Str : Character) return Pattern; function Any (Str : Character_Set) return Pattern; function Any (Str : access VString) return Pattern; function Any (Str : VString_Func) return Pattern; -- Constructs a pattern that matches a single character that is one of -- the characters in the given argument. The pattern fails if the current -- character is not in Str. function Bal return Pattern; -- Constructs a pattern that will match any non-empty string that is -- parentheses balanced with respect to the normal parentheses characters. -- Attempts to extend the string if a subsequent failure occurs. function Break (Str : String) return Pattern; function Break (Str : VString) return Pattern; function Break (Str : Character) return Pattern; function Break (Str : Character_Set) return Pattern; function Break (Str : access VString) return Pattern; function Break (Str : VString_Func) return Pattern; -- Constructs a pattern that matches a (possibly null) string which -- is immediately followed by a character in the given argument. This -- character is not part of the matched string. The pattern fails if -- the remaining characters to be matched do not include any of the -- characters in Str. function BreakX (Str : String) return Pattern; function BreakX (Str : VString) return Pattern; function BreakX (Str : Character) return Pattern; function BreakX (Str : Character_Set) return Pattern; function BreakX (Str : access VString) return Pattern; function BreakX (Str : VString_Func) return Pattern; -- Like Break, but the pattern attempts to extend on a failure to find -- the next occurrence of a character in Str, and only fails when the -- last such instance causes a failure. function Cancel return Pattern; -- Constructs a pattern that immediately aborts the entire match function Fail return Pattern; -- Constructs a pattern that always fails. function Fence return Pattern; -- Constructs a pattern that matches null on the first attempt, and then -- causes the entire match to be aborted if a subsequent failure occurs. function Fence (P : Pattern) return Pattern; -- Constructs a pattern that first matches P. if P fails, then the -- constructed pattern fails. If P succeeds, then the match proceeds, -- but if subsequent failure occurs, alternatives in P are not sought. -- The idea of Fence is that each time the pattern is matched, just -- one attempt is made to match P, without trying alternatives. function Len (Count : Natural) return Pattern; function Len (Count : access Natural) return Pattern; function Len (Count : Natural_Func) return Pattern; -- Constructs a pattern that matches exactly the given number of -- characters. The pattern fails if fewer than this number of characters -- remain to be matched in the string. function NotAny (Str : String) return Pattern; function NotAny (Str : VString) return Pattern; function NotAny (Str : Character) return Pattern; function NotAny (Str : Character_Set) return Pattern; function NotAny (Str : access VString) return Pattern; function NotAny (Str : VString_Func) return Pattern; -- Constructs a pattern that matches a single character that is not -- one of the characters in the given argument. The pattern Fails if -- the current character is in Str. function NSpan (Str : String) return Pattern; function NSpan (Str : VString) return Pattern; function NSpan (Str : Character) return Pattern; function NSpan (Str : Character_Set) return Pattern; function NSpan (Str : access VString) return Pattern; function NSpan (Str : VString_Func) return Pattern; -- Constructs a pattern that matches the longest possible string -- consisting entirely of characters from the given argument. The -- string may be empty, so this pattern always succeeds. function Pos (Count : Natural) return Pattern; function Pos (Count : access Natural) return Pattern; function Pos (Count : Natural_Func) return Pattern; -- Constructs a pattern that matches the null string if exactly Count -- characters have already been matched, and otherwise fails. function Rest return Pattern; -- Constructs a pattern that always succeeds, matching the remaining -- unmatched characters in the pattern. function Rpos (Count : Natural) return Pattern; function Rpos (Count : access Natural) return Pattern; function Rpos (Count : Natural_Func) return Pattern; -- Constructs a pattern that matches the null string if exactly Count -- characters remain to be matched in the string, and otherwise fails. function Rtab (Count : Natural) return Pattern; function Rtab (Count : access Natural) return Pattern; function Rtab (Count : Natural_Func) return Pattern; -- Constructs a pattern that matches from the current location until -- exactly Count characters remain to be matched in the string. The -- pattern fails if fewer than Count characters remain to be matched. function Setcur (Var : access Natural) return Pattern; -- Constructs a pattern that matches the null string, and assigns the -- current cursor position in the string. This value is the number of -- characters matched so far. So it is zero at the start of the match. function Span (Str : String) return Pattern; function Span (Str : VString) return Pattern; function Span (Str : Character) return Pattern; function Span (Str : Character_Set) return Pattern; function Span (Str : access VString) return Pattern; function Span (Str : VString_Func) return Pattern; -- Constructs a pattern that matches the longest possible string -- consisting entirely of characters from the given argument. The -- string cannot be empty , so the pattern fails if the current -- character is not one of the characters in Str. function Succeed return Pattern; -- Constructs a pattern that succeeds matching null, both on the first -- attempt, and on any rematch attempt, i.e. it is equivalent to an -- infinite alternation of null strings. function Tab (Count : Natural) return Pattern; function Tab (Count : access Natural) return Pattern; function Tab (Count : Natural_Func) return Pattern; -- Constructs a pattern that from the current location until Count -- characters have been matched. The pattern fails if more than Count -- characters have already been matched. --------------------------------- -- Pattern Matching Operations -- --------------------------------- -- The Match function performs an actual pattern matching operation. -- The versions with three parameters perform a match without modifying -- the subject string and return a Boolean result indicating if the -- match is successful or not. The Anchor parameter is set to True to -- obtain an anchored match in which the pattern is required to match -- the first character of the string. In an unanchored match, which is -- the default, successive attempts are made to match the given pattern -- at each character of the subject string until a match succeeds, or -- until all possibilities have failed. -- Note that pattern assignment functions in the pattern may generate -- side effects, so these functions are not necessarily pure. Anchored_Mode : Boolean := False; -- This global variable can be set True to cause all subsequent pattern -- matches to operate in anchored mode. In anchored mode, no attempt is -- made to move the anchor point, so that if the match succeeds it must -- succeed starting at the first character. Note that the effect of -- anchored mode may be achieved in individual pattern matches by using -- Fence or Pos(0) at the start of the pattern. Pattern_Stack_Overflow : exception; -- Exception raised if internal pattern matching stack overflows. This -- is typically the result of runaway pattern recursion. If there is a -- genuine case of stack overflow, then either the match must be broken -- down into simpler steps, or the stack limit must be reset. Stack_Size : constant Positive := 2000; -- Size used for internal pattern matching stack. Increase this size if -- complex patterns cause Pattern_Stack_Overflow to be raised. -- Simple match functions. The subject is matched against the pattern. -- Any immediate or deferred assignments or writes are executed, and -- the returned value indicates whether or not the match succeeded. function Match (Subject : VString; Pat : Pattern) return Boolean; function Match (Subject : VString; Pat : PString) return Boolean; function Match (Subject : String; Pat : Pattern) return Boolean; function Match (Subject : String; Pat : PString) return Boolean; -- Replacement functions. The subject is matched against the pattern. -- Any immediate or deferred assignments or writes are executed, and -- the returned value indicates whether or not the match succeeded. -- If the match succeeds, then the matched part of the subject string -- is replaced by the given Replace string. function Match (Subject : VString_Var; Pat : Pattern; Replace : VString) return Boolean; function Match (Subject : VString_Var; Pat : PString; Replace : VString) return Boolean; function Match (Subject : VString_Var; Pat : Pattern; Replace : String) return Boolean; function Match (Subject : VString_Var; Pat : PString; Replace : String) return Boolean; -- Simple match procedures. The subject is matched against the pattern. -- Any immediate or deferred assignments or writes are executed. No -- indication of success or failure is returned. procedure Match (Subject : VString; Pat : Pattern); procedure Match (Subject : VString; Pat : PString); procedure Match (Subject : String; Pat : Pattern); procedure Match (Subject : String; Pat : PString); -- Replacement procedures. The subject is matched against the pattern. -- Any immediate or deferred assignments or writes are executed. No -- indication of success or failure is returned. If the match succeeds, -- then the matched part of the subject string is replaced by the given -- Replace string. procedure Match (Subject : in out VString; Pat : Pattern; Replace : VString); procedure Match (Subject : in out VString; Pat : PString; Replace : VString); procedure Match (Subject : in out VString; Pat : Pattern; Replace : String); procedure Match (Subject : in out VString; Pat : PString; Replace : String); -- Deferred Replacement type Match_Result is private; -- Type used to record result of pattern match subtype Match_Result_Var is Match_Result; -- This synonyms is used as a formal parameter type to a function where, -- if the language allowed, we would use an in out parameter, but we are -- not allowed to have in out parameters for functions. Instead we pass -- actuals which must be variables, and with a bit of trickery in the -- body, manage to interprete them properly as though they were indeed -- in out parameters. function Match (Subject : VString_Var; Pat : Pattern; Result : Match_Result_Var) return Boolean; procedure Match (Subject : in out VString; Pat : Pattern; Result : out Match_Result); procedure Replace (Result : in out Match_Result; Replace : VString); -- Given a previous call to Match which set Result, performs a pattern -- replacement if the match was successful. Has no effect if the match -- failed. This call should immediately follow the Match call. ------------------------ -- Debugging Routines -- ------------------------ -- Debugging pattern matching operations can often be quite complex, -- since there is no obvious way to trace the progress of the match. -- The declarations in this section provide some debugging assistance. Debug_Mode : Boolean := False; -- This global variable can be set True to generate debugging on all -- subsequent calls to Match. The debugging output is a full trace of -- the actions of the pattern matcher, written to Standard_Output. The -- level of this information is intended to be comprehensible at the -- abstract level of this package declaration. However, note that the -- use of this switch often generates large amounts of output. function ""*"" (P : Pattern; Fil : File_Access) return Pattern; function ""*"" (P : PString; Fil : File_Access) return Pattern; function ""*"" (P : PChar; Fil : File_Access) return Pattern; function ""**"" (P : Pattern; Fil : File_Access) return Pattern; function ""**"" (P : PString; Fil : File_Access) return Pattern; function ""**"" (P : PChar; Fil : File_Access) return Pattern; -- These are similar to the corresponding pattern assignment operations -- except that instead of setting the value of a variable, the matched -- substring is written to the appropriate file. This can be useful in -- following the progress of a match without generating the full amount -- of information obtained by setting Debug_Mode to True. Terminal : constant File_Access := Standard_Error; Output : constant File_Access := Standard_Output; -- Two handy synonyms for use with the above pattern write operations. -- Finally we have some routines that are useful for determining what -- patterns are in use, particularly if they are constructed dynamically. function Image (P : Pattern) return String; function Image (P : Pattern) return VString; -- This procedures yield strings that corresponds to the syntax needed -- to create the given pattern using the functions in this package. The -- form of this string is such that it could actually be compiled and -- evaluated to yield the required pattern except for references to -- variables and functions, which are output using one of the following -- forms: -- -- access Natural NP(16#...#) -- access Pattern PP(16#...#) -- access VString VP(16#...#) -- -- Natural_Func NF(16#...#) -- VString_Func VF(16#...#) -- -- where 16#...# is the hex representation of the integer address that -- corresponds to the given access value procedure Dump (P : Pattern); -- This procedure writes information about the pattern to Standard_Out. -- The format of this information is keyed to the internal data structures -- used to implement patterns. The information provided by Dump is thus -- more precise than that yielded by Image, but is also a bit more obscure -- (i.e. it cannot be interpreted solely in terms of this spec, you have -- to know something about the data structures). ------------------ -- Private Part -- ------------------ private type PE; -- Pattern element, a pattern is a plex structure of PE's. This type -- is defined and sdescribed in the body of this package. type PE_Ptr is access all PE; -- Pattern reference. PE's use PE_Ptr values to reference other PE's type Pattern is new Controlled with record Stk : Natural; -- Maximum number of stack entries required for matching this -- pattern. See description of pattern history stack in body. P : PE_Ptr; -- Pointer to initial pattern element for pattern end record; pragma Finalize_Storage_Only (Pattern); procedure Adjust (Object : in out Pattern); -- Adjust routine used to copy pattern objects procedure Finalize (Object : in out Pattern); -- Finalization routine used to release storage allocated for a pattern. type VString_Ptr is access all VString; type Match_Result is record Var : VString_Ptr; -- Pointer to subject string. Set to null if match failed. Start : Natural; -- Starting index position (1's origin) of matched section of -- subject string. Only valid if Var is non-null. Stop : Natural; -- Ending index position (1's origin) of matched section of -- subject string. Only valid if Var is non-null. end record; pragma Volatile (Match_Result); -- This ensures that the Result parameter is passed by reference, so -- that we can play our games with the bogus Match_Result_Var parameter -- in the function case to treat it as though it were an in out parameter. end GNAT.Spitbol.Patterns; ",12386,False,2354.9385211908566,median " //// This file is generated! See _meta/fields.yml and scripts/generate_field_docs.py //// [[exported-fields]] = Exported fields [partintro] -- This document describes the fields that are exported by Journalbeat. They are grouped in the following categories: * <> * <> * <> * <> * <> * <> * <> * <> * <> -- [[exported-fields-beat]] == Beat fields Contains common beat fields available in all event types. *`agent.hostname`*:: + -- type: keyword Hostname of the agent. -- *`beat.timezone`*:: + -- type: alias alias to: event.timezone -- *`fields`*:: + -- type: object Contains user configurable fields. -- [float] == error fields Error fields containing additional info in case of errors. *`error.type`*:: + -- type: keyword Error type. -- *`beat.name`*:: + -- type: alias alias to: host.name -- *`beat.hostname`*:: + -- type: alias alias to: agent.hostname -- *`timeseries.instance`*:: + -- type: keyword Time series instance id -- [[exported-fields-cloud]] == Cloud provider metadata fields Metadata from cloud providers added by the add_cloud_metadata processor. *`cloud.project.id`*:: + -- example: project-x Name of the project in Google Cloud. -- *`meta.cloud.provider`*:: + -- type: alias alias to: cloud.provider -- *`meta.cloud.instance_id`*:: + -- type: alias alias to: cloud.instance.id -- *`meta.cloud.instance_name`*:: + -- type: alias alias to: cloud.instance.name -- *`meta.cloud.machine_type`*:: + -- type: alias alias to: cloud.machine.type -- *`meta.cloud.availability_zone`*:: + -- type: alias alias to: cloud.availability_zone -- *`meta.cloud.project_id`*:: + -- type: alias alias to: cloud.project.id -- *`meta.cloud.region`*:: + -- type: alias alias to: cloud.region -- [[exported-fields-common]] == Common Journalbeat fields Contains common fields available in all event types. [float] == coredump fields Fields used by systemd-coredump kernel helper. *`coredump.unit`*:: + -- type: keyword Annotations of messages containing coredumps from system units. -- *`coredump.user_unit`*:: + -- type: keyword Annotations of messages containing coredumps from user units. -- [float] == journald fields Fields provided by journald. [float] == object fields Fields to log on behalf of a different program. [float] == audit fields Audit fields of event. *`journald.object.audit.login_uid`*:: + -- type: long example: 1000 required: False The login UID of the object process. -- *`journald.object.audit.session`*:: + -- type: long example: 3 required: False The audit session of the object process. -- *`journald.object.cmd`*:: + -- type: keyword example: /lib/systemd/systemd --user required: False The command line of the process. -- *`journald.object.name`*:: + -- type: keyword example: /lib/systemd/systemd required: False Name of the executable. -- *`journald.object.executable`*:: + -- type: keyword example: /lib/systemd/systemd required: False Path to the the executable. -- *`journald.object.uid`*:: + -- type: long required: False UID of the object process. -- *`journald.object.gid`*:: + -- type: long required: False GID of the object process. -- *`journald.object.pid`*:: + -- type: long required: False PID of the object process. -- [float] == systemd fields Systemd fields of event. *`journald.object.systemd.owner_uid`*:: + -- type: long required: False The UID of the owner. -- *`journald.object.systemd.session`*:: + -- type: keyword required: False The ID of the systemd session. -- *`journald.object.systemd.unit`*:: + -- type: keyword required: False The name of the systemd unit. -- *`journald.object.systemd.user_unit`*:: + -- type: keyword required: False The name of the systemd user unit. -- [float] == kernel fields Fields to log on behalf of a different program. *`journald.kernel.device`*:: + -- type: keyword required: False The kernel device name. -- *`journald.kernel.subsystem`*:: + -- type: keyword required: False The kernel subsystem name. -- *`journald.kernel.device_symlinks`*:: + -- type: keyword required: False Additional symlink names pointing to the device node in /dev. -- *`journald.kernel.device_node_path`*:: + -- type: keyword required: False The device node path of this device in /dev. -- *`journald.kernel.device_name`*:: + -- type: keyword required: False The kernel device name as it shows up in the device tree below /sys. -- [float] == code fields Fields of the code generating the event. *`journald.code.file`*:: + -- type: keyword example: ../src/core/manager.c required: False The name of the source file where the log is generated. -- *`journald.code.function`*:: + -- type: keyword example: job_log_status_message required: False The name of the function which generated the log message. -- *`journald.code.line`*:: + -- type: long example: 123 required: False The line number of the code which generated the log message. -- [float] == process fields Fields to log on behalf of a different program. [float] == audit fields Audit fields of event. *`journald.process.audit.loginuid`*:: + -- type: long example: 1000 required: False The login UID of the source process. -- *`journald.process.audit.session`*:: + -- type: long example: 3 required: False The audit session of the source process. -- *`journald.process.cmd`*:: + -- type: keyword example: /lib/systemd/systemd --user required: False The command line of the process. -- *`journald.process.name`*:: + -- type: keyword example: /lib/systemd/systemd required: False Name of the executable. -- *`journald.process.executable`*:: + -- type: keyword example: /lib/systemd/systemd required: False Path to the the executable. -- *`journald.process.pid`*:: + -- type: long example: 1 required: False The ID of the process which logged the message. -- *`journald.process.gid`*:: + -- type: long example: 1 required: False The ID of the group which runs the process. -- *`journald.process.uid`*:: + -- type: long example: 1 required: False The ID of the user which runs the process. -- *`journald.process.capabilites`*:: + -- required: False The effective capabilites of the process. -- [float] == systemd fields Fields of systemd. *`systemd.invocation_id`*:: + -- type: keyword example: 8450f1672de646c88cd133aadd4f2d70 required: False The invocation ID for the runtime cycle of the unit the message was generated in. -- *`systemd.cgroup`*:: + -- type: keyword example: /user.slice/user-1234.slice/session-2.scope required: False The control group path in the systemd hierarchy. -- *`systemd.owner_uid`*:: + -- type: long required: False The owner UID of the systemd user unit or systemd session. -- *`systemd.session`*:: + -- type: keyword required: False The ID of the systemd session. -- *`systemd.slice`*:: + -- type: keyword example: user-1234.slice required: False The systemd slice unit. -- *`systemd.user_slice`*:: + -- type: keyword required: False The systemd user slice unit. -- *`systemd.unit`*:: + -- type: keyword example: nginx.service required: False The name of the systemd unit. -- *`systemd.user_unit`*:: + -- type: keyword example: user-1234.slice required: False The name of the systemd user unit. -- *`systemd.transport`*:: + -- type: keyword example: syslog required: True How the log message was received by journald. -- [float] == host fields Fields of the host. *`host.boot_id`*:: + -- type: keyword example: dd8c974asdf01dbe2ef26d7fasdf264c9 required: False The boot ID for the boot the log was generated in. -- [float] == syslog fields Fields of the code generating the event. *`syslog.priority`*:: + -- type: long example: 1 required: False The priority of the message. A syslog compatibility field. -- *`syslog.facility`*:: + -- type: long example: 1 required: False The facility of the message. A syslog compatibility field. -- *`syslog.identifier`*:: + -- type: keyword example: su required: False The identifier of the message. A syslog compatibility field. -- *`custom`*:: + -- type: nested required: False Arbitrary fields coming from processes. -- *`read_timestamp`*:: + -- type: alias alias to: event.created -- *`container.log.tag`*:: + -- type: keyword User defined tag of a container. -- [[exported-fields-docker-processor]] == Docker fields Docker stats collected from Docker. *`docker.container.id`*:: + -- type: alias alias to: container.id -- *`docker.container.image`*:: + -- type: alias alias to: container.image.name -- *`docker.container.name`*:: + -- type: alias alias to: container.name -- *`docker.container.labels`*:: + -- type: object Image labels. -- [[exported-fields-ecs]] == ECS fields ECS Fields. *`@timestamp`*:: + -- type: date example: 2016-05-23T08:05:34.853Z required: True Date/time when the event originated. This is the date/time extracted from the event, typically representing when the event was generated by the source. If the event source has no original timestamp, this value is typically populated by the first time the event was received by the pipeline. Required field for all events. -- *`labels`*:: + -- type: object example: {'application': 'foo-bar', 'env': 'production'} Custom key/value pairs. Can be used to add meta information to events. Should not contain nested objects. All values are stored as keyword. Example: `docker` and `k8s` labels. -- *`message`*:: + -- type: text example: Hello World For log events the message field contains the log message, optimized for viewing in a log viewer. For structured logs without an original message field, other fields can be concatenated to form a human-readable summary of the event. If multiple messages exist, they can be combined into one message. -- *`tags`*:: + -- type: keyword example: [""production"", ""env2""] List of keywords used to tag each event. -- [float] == agent fields The agent fields contain the data about the software entity, if any, that collects, detects, or observes events on a host, or takes measurements on a host. Examples include Beats. Agents may also run on observers. ECS agent.* fields shall be populated with details of the agent running on the host or observer where the event happened or the measurement was taken. *`agent.ephemeral_id`*:: + -- type: keyword example: 8a4f500f Ephemeral identifier of this agent (if one exists). This id normally changes across restarts, but `agent.id` does not. -- *`agent.id`*:: + -- type: keyword example: 8a4f500d Unique identifier of this agent (if one exists). Example: For Beats this would be beat.id. -- *`agent.name`*:: + -- type: keyword example: foo Custom name of the agent. This is a name that can be given to an agent. This can be helpful if for example two Filebeat instances are running on the same host but a human readable separation is needed on which Filebeat instance data is coming from. If no name is given, the name is often left empty. -- *`agent.type`*:: + -- type: keyword example: filebeat Type of the agent. The agent type stays always the same and should be given by the agent used. In case of Filebeat the agent would always be Filebeat also if two Filebeat instances are run on the same machine. -- *`agent.version`*:: + -- type: keyword example: 6.0.0-rc2 Version of the agent. -- [float] == client fields A client is defined as the initiator of a network connection for events regarding sessions, connections, or bidirectional flow records. For TCP events, the client is the initiator of the TCP connection that sends the SYN packet(s). For other protocols, the client is generally the initiator or requestor in the network transaction. Some systems use the term ""originator"" to refer the client in TCP connections. The client fields describe details about the system acting as the client in the network event. Client fields are usually populated in conjunction with server fields. Client fields are generally not populated for packet-level events. Client / server representations can add semantic context to an exchange, which is helpful to visualize the data in certain situations. If your context falls in that category, you should still ensure that source and destination are filled appropriately. *`client.address`*:: + -- type: keyword Some event client addresses are defined ambiguously. The event will sometimes list an IP, a domain or a unix socket. You should always store the raw address in the `.address` field. Then it should be duplicated to `.ip` or `.domain`, depending on which one it is. -- *`client.bytes`*:: + -- type: long example: 184 format: bytes Bytes sent from the client to the server. -- *`client.domain`*:: + -- type: keyword Client domain. -- *`client.geo.city_name`*:: + -- type: keyword example: Montreal City name. -- *`client.geo.continent_name`*:: + -- type: keyword example: North America Name of the continent. -- *`client.geo.country_iso_code`*:: + -- type: keyword example: CA Country ISO code. -- *`client.geo.country_name`*:: + -- type: keyword example: Canada Country name. -- *`client.geo.location`*:: + -- type: geo_point example: { ""lon"": -73.614830, ""lat"": 45.505918 } Longitude and latitude. -- *`client.geo.name`*:: + -- type: keyword example: boston-dc User-defined description of a location, at the level of granularity they care about. Could be the name of their data centers, the floor number, if this describes a local physical entity, city names. Not typically used in automated geolocation. -- *`client.geo.region_iso_code`*:: + -- type: keyword example: CA-QC Region ISO code. -- *`client.geo.region_name`*:: + -- type: keyword example: Quebec Region name. -- *`client.ip`*:: + -- type: ip IP address of the client. Can be one or multiple IPv4 or IPv6 addresses. -- *`client.mac`*:: + -- type: keyword MAC address of the client. -- *`client.packets`*:: + -- type: long example: 12 Packets sent from the client to the server. -- *`client.port`*:: + -- type: long Port of the client. -- *`client.user.email`*:: + -- type: keyword User email address. -- *`client.user.full_name`*:: + -- type: keyword example: Albert Einstein User's full name, if available. -- *`client.user.group.id`*:: + -- type: keyword Unique identifier for the group on the system/platform. -- *`client.user.group.name`*:: + -- type: keyword Name of the group. -- *`client.user.hash`*:: + -- type: keyword Unique user hash to correlate information for a user in anonymized form. Useful if `user.id` or `user.name` contain confidential information and cannot be used. -- *`client.user.id`*:: + -- type: keyword One or multiple unique identifiers of the user. -- *`client.user.name`*:: + -- type: keyword example: albert Short name or login of the user. -- [float] == cloud fields Fields related to the cloud or infrastructure the events are coming from. *`cloud.account.id`*:: + -- type: keyword example: 666777888999 The cloud account or organization id used to identify different entities in a multi-tenant environment. Examples: AWS account id, Google Cloud ORG Id, or other unique identifier. -- *`cloud.availability_zone`*:: + -- type: keyword example: us-east-1c Availability zone in which this host is running. -- *`cloud.instance.id`*:: + -- type: keyword example: i-1234567890abcdef0 Instance ID of the host machine. -- *`cloud.instance.name`*:: + -- type: keyword Instance name of the host machine. -- *`cloud.machine.type`*:: + -- type: keyword example: t2.medium Machine type of the host machine. -- *`cloud.provider`*:: + -- type: keyword example: aws Name of the cloud provider. Example values are aws, azure, gcp, or digitalocean. -- *`cloud.region`*:: + -- type: keyword example: us-east-1 Region in which this host is running. -- [float] == container fields Container fields are used for meta information about the specific container that is the source of information. These fields help correlate data based containers from any runtime. *`container.id`*:: + -- type: keyword Unique container id. -- *`container.image.name`*:: + -- type: keyword Name of the image the container was built on. -- *`container.image.tag`*:: + -- type: keyword Container image tag. -- *`container.labels`*:: + -- type: object Image labels. -- *`container.name`*:: + -- type: keyword Container name. -- *`container.runtime`*:: + -- type: keyword example: docker Runtime managing this container. -- [float] == destination fields Destination fields describe details about the destination of a packet/event. Destination fields are usually populated in conjunction with source fields. *`destination.address`*:: + -- type: keyword Some event destination addresses are defined ambiguously. The event will sometimes list an IP, a domain or a unix socket. You should always store the raw address in the `.address` field. Then it should be duplicated to `.ip` or `.domain`, depending on which one it is. -- *`destination.bytes`*:: + -- type: long example: 184 format: bytes Bytes sent from the destination to the source. -- *`destination.domain`*:: + -- type: keyword Destination domain. -- *`destination.geo.city_name`*:: + -- type: keyword example: Montreal City name. -- *`destination.geo.continent_name`*:: + -- type: keyword example: North America Name of the continent. -- *`destination.geo.country_iso_code`*:: + -- type: keyword example: CA Country ISO code. -- *`destination.geo.country_name`*:: + -- type: keyword example: Canada Country name. -- *`destination.geo.location`*:: + -- type: geo_point example: { ""lon"": -73.614830, ""lat"": 45.505918 } Longitude and latitude. -- *`destination.geo.name`*:: + -- type: keyword example: boston-dc User-defined description of a location, at the level of granularity they care about. Could be the name of their data centers, the floor number, if this describes a local physical entity, city names. Not typically used in automated geolocation. -- *`destination.geo.region_iso_code`*:: + -- type: keyword example: CA-QC Region ISO code. -- *`destination.geo.region_name`*:: + -- type: keyword example: Quebec Region name. -- *`destination.ip`*:: + -- type: ip IP address of the destination. Can be one or multiple IPv4 or IPv6 addresses. -- *`destination.mac`*:: + -- type: keyword MAC address of the destination. -- *`destination.packets`*:: + -- type: long example: 12 Packets sent from the destination to the source. -- *`destination.port`*:: + -- type: long Port of the destination. -- *`destination.user.email`*:: + -- type: keyword User email address. -- *`destination.user.full_name`*:: + -- type: keyword example: Albert Einstein User's full name, if available. -- *`destination.user.group.id`*:: + -- type: keyword Unique identifier for the group on the system/platform. -- *`destination.user.group.name`*:: + -- type: keyword Name of the group. -- *`destination.user.hash`*:: + -- type: keyword Unique user hash to correlate information for a user in anonymized form. Useful if `user.id` or `user.name` contain confidential information and cannot be used. -- *`destination.user.id`*:: + -- type: keyword One or multiple unique identifiers of the user. -- *`destination.user.name`*:: + -- type: keyword example: albert Short name or login of the user. -- [float] == ecs fields Meta-information specific to ECS. *`ecs.version`*:: + -- type: keyword example: 1.0.0 required: True ECS version this event conforms to. `ecs.version` is a required field and must exist in all events. When querying across multiple indices -- which may conform to slightly different ECS versions -- this field lets integrations adjust to the schema version of the events. -- [float] == error fields These fields can represent errors of any kind. Use them for errors that happen while fetching events or in cases where the event itself contains an error. *`error.code`*:: + -- type: keyword Error code describing the error. -- *`error.id`*:: + -- type: keyword Unique identifier for the error. -- *`error.message`*:: + -- type: text Error message. -- [float] == event fields The event fields are used for context information about the log or metric event itself. A log is defined as an event containing details of something that happened. Log events must include the time at which the thing happened. Examples of log events include a process starting on a host, a network packet being sent from a source to a destination, or a network connection between a client and a server being initiated or closed. A metric is defined as an event containing one or more numerical or categorical measurements and the time at which the measurement was taken. Examples of metric events include memory pressure measured on a host, or vulnerabilities measured on a scanned host. *`event.action`*:: + -- type: keyword example: user-password-change The action captured by the event. This describes the information in the event. It is more specific than `event.category`. Examples are `group-add`, `process-started`, `file-created`. The value is normally defined by the implementer. -- *`event.category`*:: + -- type: keyword example: user-management Event category. This contains high-level information about the contents of the event. It is more generic than `event.action`, in the sense that typically a category contains multiple actions. Warning: In future versions of ECS, we plan to provide a list of acceptable values for this field, please use with caution. -- *`event.created`*:: + -- type: date event.created contains the date/time when the event was first read by an agent, or by your pipeline. This field is distinct from @timestamp in that @timestamp typically contain the time extracted from the original event. In most situations, these two timestamps will be slightly different. The difference can be used to calculate the delay between your source generating an event, and the time when your agent first processed it. This can be used to monitor your agent's or pipeline's ability to keep up with your event source. In case the two timestamps are identical, @timestamp should be used. -- *`event.dataset`*:: + -- type: keyword example: stats Name of the dataset. The concept of a `dataset` (fileset / metricset) is used in Beats as a subset of modules. It contains the information which is currently stored in metricset.name and metricset.module or fileset.name. -- *`event.duration`*:: + -- type: long format: duration Duration of the event in nanoseconds. If event.start and event.end are known this value should be the difference between the end and start time. -- *`event.end`*:: + -- type: date event.end contains the date when the event ended or when the activity was last observed. -- *`event.hash`*:: + -- type: keyword example: 123456789012345678901234567890ABCD Hash (perhaps logstash fingerprint) of raw field to be able to demonstrate log integrity. -- *`event.id`*:: + -- type: keyword example: 8a4f500d Unique ID to describe the event. -- *`event.kind`*:: + -- type: keyword example: state The kind of the event. This gives information about what type of information the event contains, without being specific to the contents of the event. Examples are `event`, `state`, `alarm`. Warning: In future versions of ECS, we plan to provide a list of acceptable values for this field, please use with caution. -- *`event.module`*:: + -- type: keyword example: mysql Name of the module this data is coming from. This information is coming from the modules used in Beats or Logstash. -- *`event.original`*:: + -- type: keyword example: Sep 19 08:26:10 host CEF:0|Security| threatmanager|1.0|100| worm successfully stopped|10|src=10.0.0.1 dst=2.1.2.2spt=1232 Raw text message of entire event. Used to demonstrate log integrity. This field is not indexed and doc_values are disabled. It cannot be searched, but it can be retrieved from `_source`. -- *`event.outcome`*:: + -- type: keyword example: success The outcome of the event. If the event describes an action, this fields contains the outcome of that action. Examples outcomes are `success` and `failure`. Warning: In future versions of ECS, we plan to provide a list of acceptable values for this field, please use with caution. -- *`event.risk_score`*:: + -- type: float Risk score or priority of the event (e.g. security solutions). Use your system's original value here. -- *`event.risk_score_norm`*:: + -- type: float Normalized risk score or priority of the event, on a scale of 0 to 100. This is mainly useful if you use more than one system that assigns risk scores, and you want to see a normalized value across all systems. -- *`event.severity`*:: + -- type: long example: 7 Severity describes the original severity of the event. What the different severity values mean can very different between use cases. It's up to the implementer to make sure severities are consistent across events. -- *`event.start`*:: + -- type: date event.start contains the date when the event started or when the activity was first observed. -- *`event.timezone`*:: + -- type: keyword This field should be populated when the event's timestamp does not include timezone information already (e.g. default Syslog timestamps). It's optional otherwise. Acceptable timezone formats are: a canonical ID (e.g. ""Europe/Amsterdam""), abbreviated (e.g. ""EST"") or an HH:mm differential (e.g. ""-05:00""). -- *`event.type`*:: + -- type: keyword Reserved for future usage. Please avoid using this field for user data. -- [float] == file fields A file is defined as a set of information that has been created on, or has existed on a filesystem. File objects can be associated with host events, network events, and/or file events (e.g., those produced by File Integrity Monitoring [FIM] products or services). File fields provide details about the affected file associated with the event or metric. *`file.ctime`*:: + -- type: date Last time file metadata changed. -- *`file.device`*:: + -- type: keyword Device that is the source of the file. -- *`file.extension`*:: + -- type: keyword example: png File extension. This should allow easy filtering by file extensions. -- *`file.gid`*:: + -- type: keyword Primary group ID (GID) of the file. -- *`file.group`*:: + -- type: keyword Primary group name of the file. -- *`file.inode`*:: + -- type: keyword Inode representing the file in the filesystem. -- *`file.mode`*:: + -- type: keyword example: 416 Mode of the file in octal representation. -- *`file.mtime`*:: + -- type: date Last time file content was modified. -- *`file.owner`*:: + -- type: keyword File owner's username. -- *`file.path`*:: + -- type: keyword Path to the file. -- *`file.size`*:: + -- type: long File size in bytes (field is only added when `type` is `file`). -- *`file.target_path`*:: + -- type: keyword Target path for symlinks. -- *`file.type`*:: + -- type: keyword File type (file, dir, or symlink). -- *`file.uid`*:: + -- type: keyword The user ID (UID) or security identifier (SID) of the file owner. -- [float] == geo fields Geo fields can carry data about a specific location related to an event. This geolocation information can be derived from techniques such as Geo IP, or be user-supplied. *`geo.city_name`*:: + -- type: keyword example: Montreal City name. -- *`geo.continent_name`*:: + -- type: keyword example: North America Name of the continent. -- *`geo.country_iso_code`*:: + -- type: keyword example: CA Country ISO code. -- *`geo.country_name`*:: + -- type: keyword example: Canada Country name. -- *`geo.location`*:: + -- type: geo_point example: { ""lon"": -73.614830, ""lat"": 45.505918 } Longitude and latitude. -- *`geo.name`*:: + -- type: keyword example: boston-dc User-defined description of a location, at the level of granularity they care about. Could be the name of their data centers, the floor number, if this describes a local physical entity, city names. Not typically used in automated geolocation. -- *`geo.region_iso_code`*:: + -- type: keyword example: CA-QC Region ISO code. -- *`geo.region_name`*:: + -- type: keyword example: Quebec Region name. -- [float] == group fields The group fields are meant to represent groups that are relevant to the event. *`group.id`*:: + -- type: keyword Unique identifier for the group on the system/platform. -- *`group.name`*:: + -- type: keyword Name of the group. -- [float] == host fields A host is defined as a general computing instance. ECS host.* fields should be populated with details about the host on which the event happened, or from which the measurement was taken. Host types include hardware, virtual machines, Docker containers, and Kubernetes nodes. *`host.architecture`*:: + -- type: keyword example: x86_64 Operating system architecture. -- *`host.geo.city_name`*:: + -- type: keyword example: Montreal City name. -- *`host.geo.continent_name`*:: + -- type: keyword example: North America Name of the continent. -- *`host.geo.country_iso_code`*:: + -- type: keyword example: CA Country ISO code. -- *`host.geo.country_name`*:: + -- type: keyword example: Canada Country name. -- *`host.geo.location`*:: + -- type: geo_point example: { ""lon"": -73.614830, ""lat"": 45.505918 } Longitude and latitude. -- *`host.geo.name`*:: + -- type: keyword example: boston-dc User-defined description of a location, at the level of granularity they care about. Could be the name of their data centers, the floor number, if this describes a local physical entity, city names. Not typically used in automated geolocation. -- *`host.geo.region_iso_code`*:: + -- type: keyword example: CA-QC Region ISO code. -- *`host.geo.region_name`*:: + -- type: keyword example: Quebec Region name. -- *`host.hostname`*:: + -- type: keyword Hostname of the host. It normally contains what the `hostname` command returns on the host machine. -- *`host.id`*:: + -- type: keyword Unique host id. As hostname is not always unique, use values that are meaningful in your environment. Example: The current usage of `beat.name`. -- *`host.ip`*:: + -- type: ip Host ip address. -- *`host.mac`*:: + -- type: keyword Host mac address. -- *`host.name`*:: + -- type: keyword Name of the host. It can contain what `hostname` returns on Unix systems, the fully qualified domain name, or a name specified by the user. The sender decides which value to use. -- *`host.os.family`*:: + -- type: keyword example: debian OS family (such as redhat, debian, freebsd, windows). -- *`host.os.full`*:: + -- type: keyword example: Mac OS Mojave Operating system name, including the version or code name. -- *`host.os.kernel`*:: + -- type: keyword example: 4.4.0-112-generic Operating system kernel version as a raw string. -- *`host.os.name`*:: + -- type: keyword example: Mac OS X Operating system name, without the version. -- *`host.os.platform`*:: + -- type: keyword example: darwin Operating system platform (such centos, ubuntu, windows). -- *`host.os.version`*:: + -- type: keyword example: 10.14.1 Operating system version as a raw string. -- *`host.type`*:: + -- type: keyword Type of host. For Cloud providers this can be the machine type like `t2.medium`. If vm, this could be the container, for example, or other information meaningful in your environment. -- *`host.user.email`*:: + -- type: keyword User email address. -- *`host.user.full_name`*:: + -- type: keyword example: Albert Einstein User's full name, if available. -- *`host.user.group.id`*:: + -- type: keyword Unique identifier for the group on the system/platform. -- *`host.user.group.name`*:: + -- type: keyword Name of the group. -- *`host.user.hash`*:: + -- type: keyword Unique user hash to correlate information for a user in anonymized form. Useful if `user.id` or `user.name` contain confidential information and cannot be used. -- *`host.user.id`*:: + -- type: keyword One or multiple unique identifiers of the user. -- *`host.user.name`*:: + -- type: keyword example: albert Short name or login of the user. -- [float] == http fields Fields related to HTTP activity. Use the `url` field set to store the url of the request. *`http.request.body.bytes`*:: + -- type: long example: 887 format: bytes Size in bytes of the request body. -- *`http.request.body.content`*:: + -- type: keyword example: Hello world The full HTTP request body. -- *`http.request.bytes`*:: + -- type: long example: 1437 format: bytes Total size in bytes of the request (body and headers). -- *`http.request.method`*:: + -- type: keyword example: get, post, put HTTP request method. The field value must be normalized to lowercase for querying. See the documentation section ""Implementing ECS"". -- *`http.request.referrer`*:: + -- type: keyword example: https://blog.example.com/ Referrer for this HTTP request. -- *`http.response.body.bytes`*:: + -- type: long example: 887 format: bytes Size in bytes of the response body. -- *`http.response.body.content`*:: + -- type: keyword example: Hello world The full HTTP response body. -- *`http.response.bytes`*:: + -- type: long example: 1437 format: bytes Total size in bytes of the response (body and headers). -- *`http.response.status_code`*:: + -- type: long example: 404 HTTP response status code. -- *`http.version`*:: + -- type: keyword example: 1.1 HTTP version. -- [float] == log fields Fields which are specific to log events. *`log.level`*:: + -- type: keyword example: err Original log level of the log event. Some examples are `warn`, `error`, `i`. -- *`log.original`*:: + -- type: keyword example: Sep 19 08:26:10 localhost My log This is the original log message and contains the full log message before splitting it up in multiple parts. In contrast to the `message` field which can contain an extracted part of the log message, this field contains the original, full log message. It can have already some modifications applied like encoding or new lines removed to clean up the log message. This field is not indexed and doc_values are disabled so it can't be queried but the value can be retrieved from `_source`. -- [float] == network fields The network is defined as the communication path over which a host or network event happens. The network.* fields should be populated with details about the network activity associated with an event. *`network.application`*:: + -- type: keyword example: aim A name given to an application level protocol. This can be arbitrarily assigned for things like microservices, but also apply to things like skype, icq, facebook, twitter. This would be used in situations where the vendor or service can be decoded such as from the source/dest IP owners, ports, or wire format. The field value must be normalized to lowercase for querying. See the documentation section ""Implementing ECS"". -- *`network.bytes`*:: + -- type: long example: 368 format: bytes Total bytes transferred in both directions. If `source.bytes` and `destination.bytes` are known, `network.bytes` is their sum. -- *`network.community_id`*:: + -- type: keyword example: 1:hO+sN4H+MG5MY/8hIrXPqc4ZQz0= A hash of source and destination IPs and ports, as well as the protocol used in a communication. This is a tool-agnostic standard to identify flows. Learn more at https://github.com/corelight/community-id-spec. -- *`network.direction`*:: + -- type: keyword example: inbound Direction of the network traffic. Recommended values are: * inbound * outbound * internal * external * unknown When mapping events from a host-based monitoring context, populate this field from the host's point of view. When mapping events from a network or perimeter-based monitoring context, populate this field from the point of view of your network perimeter. -- *`network.forwarded_ip`*:: + -- type: ip example: 192.1.1.2 Host IP address when the source IP address is the proxy. -- *`network.iana_number`*:: + -- type: keyword example: 6 IANA Protocol Number (https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml). Standardized list of protocols. This aligns well with NetFlow and sFlow related logs which use the IANA Protocol Number. -- *`network.name`*:: + -- type: keyword example: Guest Wifi Name given by operators to sections of their network. -- *`network.packets`*:: + -- type: long example: 24 Total packets transferred in both directions. If `source.packets` and `destination.packets` are known, `network.packets` is their sum. -- *`network.protocol`*:: + -- type: keyword example: http L7 Network protocol name. ex. http, lumberjack, transport protocol. The field value must be normalized to lowercase for querying. See the documentation section ""Implementing ECS"". -- *`network.transport`*:: + -- type: keyword example: tcp Same as network.iana_number, but instead using the Keyword name of the transport layer (udp, tcp, ipv6-icmp, etc.) The field value must be normalized to lowercase for querying. See the documentation section ""Implementing ECS"". -- *`network.type`*:: + -- type: keyword example: ipv4 In the OSI Model this would be the Network Layer. ipv4, ipv6, ipsec, pim, etc The field value must be normalized to lowercase for querying. See the documentation section ""Implementing ECS"". -- [float] == observer fields An observer is defined as a special network, security, or application device used to detect, observe, or create network, security, or application-related events and metrics. This could be a custom hardware appliance or a server that has been configured to run special network, security, or application software. Examples include firewalls, intrusion detection/prevention systems, network monitoring sensors, web application firewalls, data loss prevention systems, and APM servers. The observer.* fields shall be populated with details of the system, if any, that detects, observes and/or creates a network, security, or application event or metric. Message queues and ETL components used in processing events or metrics are not considered observers in ECS. *`observer.geo.city_name`*:: + -- type: keyword example: Montreal City name. -- *`observer.geo.continent_name`*:: + -- type: keyword example: North America Name of the continent. -- *`observer.geo.country_iso_code`*:: + -- type: keyword example: CA Country ISO code. -- *`observer.geo.country_name`*:: + -- type: keyword example: Canada Country name. -- *`observer.geo.location`*:: + -- type: geo_point example: { ""lon"": -73.614830, ""lat"": 45.505918 } Longitude and latitude. -- *`observer.geo.name`*:: + -- type: keyword example: boston-dc User-defined description of a location, at the level of granularity they care about. Could be the name of their data centers, the floor number, if this describes a local physical entity, city names. Not typically used in automated geolocation. -- *`observer.geo.region_iso_code`*:: + -- type: keyword example: CA-QC Region ISO code. -- *`observer.geo.region_name`*:: + -- type: keyword example: Quebec Region name. -- *`observer.hostname`*:: + -- type: keyword Hostname of the observer. -- *`observer.ip`*:: + -- type: ip IP address of the observer. -- *`observer.mac`*:: + -- type: keyword MAC address of the observer -- *`observer.os.family`*:: + -- type: keyword example: debian OS family (such as redhat, debian, freebsd, windows). -- *`observer.os.full`*:: + -- type: keyword example: Mac OS Mojave Operating system name, including the version or code name. -- *`observer.os.kernel`*:: + -- type: keyword example: 4.4.0-112-generic Operating system kernel version as a raw string. -- *`observer.os.name`*:: + -- type: keyword example: Mac OS X Operating system name, without the version. -- *`observer.os.platform`*:: + -- type: keyword example: darwin Operating system platform (such centos, ubuntu, windows). -- *`observer.os.version`*:: + -- type: keyword example: 10.14.1 Operating system version as a raw string. -- *`observer.serial_number`*:: + -- type: keyword Observer serial number. -- *`observer.type`*:: + -- type: keyword example: firewall The type of the observer the data is coming from. There is no predefined list of observer types. Some examples are `forwarder`, `firewall`, `ids`, `ips`, `proxy`, `poller`, `sensor`, `APM server`. -- *`observer.vendor`*:: + -- type: keyword observer vendor information. -- *`observer.version`*:: + -- type: keyword Observer version. -- [float] == organization fields The organization fields enrich data with information about the company or entity the data is associated with. These fields help you arrange or filter data stored in an index by one or multiple organizations. *`organization.id`*:: + -- type: keyword Unique identifier for the organization. -- *`organization.name`*:: + -- type: keyword Organization name. -- [float] == os fields The OS fields contain information about the operating system. *`os.family`*:: + -- type: keyword example: debian OS family (such as redhat, debian, freebsd, windows). -- *`os.full`*:: + -- type: keyword example: Mac OS Mojave Operating system name, including the version or code name. -- *`os.kernel`*:: + -- type: keyword example: 4.4.0-112-generic Operating system kernel version as a raw string. -- *`os.name`*:: + -- type: keyword example: Mac OS X Operating system name, without the version. -- *`os.platform`*:: + -- type: keyword example: darwin Operating system platform (such centos, ubuntu, windows). -- *`os.version`*:: + -- type: keyword example: 10.14.1 Operating system version as a raw string. -- [float] == process fields These fields contain information about a process. These fields can help you correlate metrics information with a process id/name from a log message. The `process.pid` often stays in the metric itself and is copied to the global field for correlation. *`process.args`*:: + -- type: keyword example: ['ssh', '-l', 'user', '10.0.0.16'] Array of process arguments. May be filtered to protect sensitive information. -- *`process.executable`*:: + -- type: keyword example: /usr/bin/ssh Absolute path to the process executable. -- *`process.name`*:: + -- type: keyword example: ssh Process name. Sometimes called program name or similar. -- *`process.pid`*:: + -- type: long Process id. -- *`process.ppid`*:: + -- type: long Process parent id. -- *`process.start`*:: + -- type: date example: 2016-05-23T08:05:34.853Z The time the process started. -- *`process.thread.id`*:: + -- type: long example: 4242 Thread ID. -- *`process.title`*:: + -- type: keyword Process title. The proctitle, some times the same as process name. Can also be different: for example a browser setting its title to the web page currently opened. -- *`process.working_directory`*:: + -- type: keyword example: /home/alice The working directory of the process. -- [float] == related fields This field set is meant to facilitate pivoting around a piece of data. Some pieces of information can be seen in many places in an ECS event. To facilitate searching for them, store an array of all seen values to their corresponding field in `related.`. A concrete example is IP addresses, which can be under host, observer, source, destination, client, server, and network.forwarded_ip. If you append all IPs to `related.ip`, you can then search for a given IP trivially, no matter where it appeared, by querying `related.ip:a.b.c.d`. *`related.ip`*:: + -- type: ip All of the IPs seen on your event. -- [float] == server fields A Server is defined as the responder in a network connection for events regarding sessions, connections, or bidirectional flow records. For TCP events, the server is the receiver of the initial SYN packet(s) of the TCP connection. For other protocols, the server is generally the responder in the network transaction. Some systems actually use the term ""responder"" to refer the server in TCP connections. The server fields describe details about the system acting as the server in the network event. Server fields are usually populated in conjunction with client fields. Server fields are generally not populated for packet-level events. Client / server representations can add semantic context to an exchange, which is helpful to visualize the data in certain situations. If your context falls in that category, you should still ensure that source and destination are filled appropriately. *`server.address`*:: + -- type: keyword Some event server addresses are defined ambiguously. The event will sometimes list an IP, a domain or a unix socket. You should always store the raw address in the `.address` field. Then it should be duplicated to `.ip` or `.domain`, depending on which one it is. -- *`server.bytes`*:: + -- type: long example: 184 format: bytes Bytes sent from the server to the client. -- *`server.domain`*:: + -- type: keyword Server domain. -- *`server.geo.city_name`*:: + -- type: keyword example: Montreal City name. -- *`server.geo.continent_name`*:: + -- type: keyword example: North America Name of the continent. -- *`server.geo.country_iso_code`*:: + -- type: keyword example: CA Country ISO code. -- *`server.geo.country_name`*:: + -- type: keyword example: Canada Country name. -- *`server.geo.location`*:: + -- type: geo_point example: { ""lon"": -73.614830, ""lat"": 45.505918 } Longitude and latitude. -- *`server.geo.name`*:: + -- type: keyword example: boston-dc User-defined description of a location, at the level of granularity they care about. Could be the name of their data centers, the floor number, if this describes a local physical entity, city names. Not typically used in automated geolocation. -- *`server.geo.region_iso_code`*:: + -- type: keyword example: CA-QC Region ISO code. -- *`server.geo.region_name`*:: + -- type: keyword example: Quebec Region name. -- *`server.ip`*:: + -- type: ip IP address of the server. Can be one or multiple IPv4 or IPv6 addresses. -- *`server.mac`*:: + -- type: keyword MAC address of the server. -- *`server.packets`*:: + -- type: long example: 12 Packets sent from the server to the client. -- *`server.port`*:: + -- type: long Port of the server. -- *`server.user.email`*:: + -- type: keyword User email address. -- *`server.user.full_name`*:: + -- type: keyword example: Albert Einstein User's full name, if available. -- *`server.user.group.id`*:: + -- type: keyword Unique identifier for the group on the system/platform. -- *`server.user.group.name`*:: + -- type: keyword Name of the group. -- *`server.user.hash`*:: + -- type: keyword Unique user hash to correlate information for a user in anonymized form. Useful if `user.id` or `user.name` contain confidential information and cannot be used. -- *`server.user.id`*:: + -- type: keyword One or multiple unique identifiers of the user. -- *`server.user.name`*:: + -- type: keyword example: albert Short name or login of the user. -- [float] == service fields The service fields describe the service for or from which the data was collected. These fields help you find and correlate logs for a specific service and version. *`service.ephemeral_id`*:: + -- type: keyword example: 8a4f500f Ephemeral identifier of this service (if one exists). This id normally changes across restarts, but `service.id` does not. -- *`service.id`*:: + -- type: keyword example: d37e5ebfe0ae6c4972dbe9f0174a1637bb8247f6 Unique identifier of the running service. This id should uniquely identify this service. This makes it possible to correlate logs and metrics for one specific service. Example: If you are experiencing issues with one redis instance, you can filter on that id to see metrics and logs for that single instance. -- *`service.name`*:: + -- type: keyword example: elasticsearch-metrics Name of the service data is collected from. The name of the service is normally user given. This allows if two instances of the same service are running on the same machine they can be differentiated by the `service.name`. Also it allows for distributed services that run on multiple hosts to correlate the related instances based on the name. In the case of Elasticsearch the service.name could contain the cluster name. For Beats the service.name is by default a copy of the `service.type` field if no name is specified. -- *`service.state`*:: + -- type: keyword Current state of the service. -- *`service.type`*:: + -- type: keyword example: elasticsearch The type of the service data is collected from. The type can be used to group and correlate logs and metrics from one service type. Example: If logs or metrics are collected from Elasticsearch, `service.type` would be `elasticsearch`. -- *`service.version`*:: + -- type: keyword example: 3.2.4 Version of the service the data was collected from. This allows to look at a data set only for a specific version of a service. -- [float] == source fields Source fields describe details about the source of a packet/event. Source fields are usually populated in conjunction with destination fields. *`source.address`*:: + -- type: keyword Some event source addresses are defined ambiguously. The event will sometimes list an IP, a domain or a unix socket. You should always store the raw address in the `.address` field. Then it should be duplicated to `.ip` or `.domain`, depending on which one it is. -- *`source.bytes`*:: + -- type: long example: 184 format: bytes Bytes sent from the source to the destination. -- *`source.domain`*:: + -- type: keyword Source domain. -- *`source.geo.city_name`*:: + -- type: keyword example: Montreal City name. -- *`source.geo.continent_name`*:: + -- type: keyword example: North America Name of the continent. -- *`source.geo.country_iso_code`*:: + -- type: keyword example: CA Country ISO code. -- *`source.geo.country_name`*:: + -- type: keyword example: Canada Country name. -- *`source.geo.location`*:: + -- type: geo_point example: { ""lon"": -73.614830, ""lat"": 45.505918 } Longitude and latitude. -- *`source.geo.name`*:: + -- type: keyword example: boston-dc User-defined description of a location, at the level of granularity they care about. Could be the name of their data centers, the floor number, if this describes a local physical entity, city names. Not typically used in automated geolocation. -- *`source.geo.region_iso_code`*:: + -- type: keyword example: CA-QC Region ISO code. -- *`source.geo.region_name`*:: + -- type: keyword example: Quebec Region name. -- *`source.ip`*:: + -- type: ip IP address of the source. Can be one or multiple IPv4 or IPv6 addresses. -- *`source.mac`*:: + -- type: keyword MAC address of the source. -- *`source.packets`*:: + -- type: long example: 12 Packets sent from the source to the destination. -- *`source.port`*:: + -- type: long Port of the source. -- *`source.user.email`*:: + -- type: keyword User email address. -- *`source.user.full_name`*:: + -- type: keyword example: Albert Einstein User's full name, if available. -- *`source.user.group.id`*:: + -- type: keyword Unique identifier for the group on the system/platform. -- *`source.user.group.name`*:: + -- type: keyword Name of the group. -- *`source.user.hash`*:: + -- type: keyword Unique user hash to correlate information for a user in anonymized form. Useful if `user.id` or `user.name` contain confidential information and cannot be used. -- *`source.user.id`*:: + -- type: keyword One or multiple unique identifiers of the user. -- *`source.user.name`*:: + -- type: keyword example: albert Short name or login of the user. -- [float] == url fields URL fields provide support for complete or partial URLs, and supports the breaking down into scheme, domain, path, and so on. *`url.domain`*:: + -- type: keyword example: www.elastic.co Domain of the url, such as ""www.elastic.co"". In some cases a URL may refer to an IP and/or port directly, without a domain name. In this case, the IP address would go to the `domain` field. -- *`url.fragment`*:: + -- type: keyword Portion of the url after the `#`, such as ""top"". The `#` is not part of the fragment. -- *`url.full`*:: + -- type: keyword example: https://www.elastic.co:443/search?q=elasticsearch#top If full URLs are important to your use case, they should be stored in `url.full`, whether this field is reconstructed or present in the event source. -- *`url.original`*:: + -- type: keyword example: https://www.elastic.co:443/search?q=elasticsearch#top or /search?q=elasticsearch Unmodified original url as seen in the event source. Note that in network monitoring, the observed URL may be a full URL, whereas in access logs, the URL is often just represented as a path. This field is meant to represent the URL as it was observed, complete or not. -- *`url.password`*:: + -- type: keyword Password of the request. -- *`url.path`*:: + -- type: keyword Path of the request, such as ""/search"". -- *`url.port`*:: + -- type: long example: 443 Port of the request, such as 443. -- *`url.query`*:: + -- type: keyword The query field describes the query string of the request, such as ""q=elasticsearch"". The `?` is excluded from the query string. If a URL contains no `?`, there is no query field. If there is a `?` but no query, the query field exists with an empty string. The `exists` query can be used to differentiate between the two cases. -- *`url.scheme`*:: + -- type: keyword example: https Scheme of the request, such as ""https"". Note: The `:` is not part of the scheme. -- *`url.username`*:: + -- type: keyword Username of the request. -- [float] == user fields The user fields describe information about the user that is relevant to the event. Fields can have one entry or multiple entries. If a user has more than one id, provide an array that includes all of them. *`user.email`*:: + -- type: keyword User email address. -- *`user.full_name`*:: + -- type: keyword example: Albert Einstein User's full name, if available. -- *`user.group.id`*:: + -- type: keyword Unique identifier for the group on the system/platform. -- *`user.group.name`*:: + -- type: keyword Name of the group. -- *`user.hash`*:: + -- type: keyword Unique user hash to correlate information for a user in anonymized form. Useful if `user.id` or `user.name` contain confidential information and cannot be used. -- *`user.id`*:: + -- type: keyword One or multiple unique identifiers of the user. -- *`user.name`*:: + -- type: keyword example: albert Short name or login of the user. -- [float] == user_agent fields The user_agent fields normally come from a browser request. They often show up in web service logs coming from the parsed user agent string. *`user_agent.device.name`*:: + -- type: keyword example: iPhone Name of the device. -- *`user_agent.name`*:: + -- type: keyword example: Safari Name of the user agent. -- *`user_agent.original`*:: + -- type: keyword example: Mozilla/5.0 (iPhone; CPU iPhone OS 12_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Mobile/15E148 Safari/604.1 Unparsed version of the user_agent. -- *`user_agent.os.family`*:: + -- type: keyword example: debian OS family (such as redhat, debian, freebsd, windows). -- *`user_agent.os.full`*:: + -- type: keyword example: Mac OS Mojave Operating system name, including the version or code name. -- *`user_agent.os.kernel`*:: + -- type: keyword example: 4.4.0-112-generic Operating system kernel version as a raw string. -- *`user_agent.os.name`*:: + -- type: keyword example: Mac OS X Operating system name, without the version. -- *`user_agent.os.platform`*:: + -- type: keyword example: darwin Operating system platform (such centos, ubuntu, windows). -- *`user_agent.os.version`*:: + -- type: keyword example: 10.14.1 Operating system version as a raw string. -- *`user_agent.version`*:: + -- type: keyword example: 12.0 Version of the user agent. -- [[exported-fields-host-processor]] == Host fields Info collected for the host machine. *`host.containerized`*:: + -- type: boolean If the host is a container. -- *`host.os.build`*:: + -- type: keyword example: 18D109 OS build information. -- [[exported-fields-jolokia-autodiscover]] == Jolokia Discovery autodiscover provider fields Metadata from Jolokia Discovery added by the jolokia provider. *`jolokia.agent.version`*:: + -- type: keyword Version number of jolokia agent. -- *`jolokia.agent.id`*:: + -- type: keyword Each agent has a unique id which can be either provided during startup of the agent in form of a configuration parameter or being autodetected. If autodected, the id has several parts: The IP, the process id, hashcode of the agent and its type. -- *`jolokia.server.product`*:: + -- type: keyword The container product if detected. -- *`jolokia.server.version`*:: + -- type: keyword The container's version (if detected). -- *`jolokia.server.vendor`*:: + -- type: keyword The vendor of the container the agent is running in. -- *`jolokia.url`*:: + -- type: keyword The URL how this agent can be contacted. -- *`jolokia.secured`*:: + -- type: boolean Whether the agent was configured for authentication or not. -- [[exported-fields-kubernetes-processor]] == Kubernetes fields Kubernetes metadata added by the kubernetes processor *`kubernetes.pod.name`*:: + -- type: keyword Kubernetes pod name -- *`kubernetes.pod.uid`*:: + -- type: keyword Kubernetes Pod UID -- *`kubernetes.namespace`*:: + -- type: keyword Kubernetes namespace -- *`kubernetes.node.name`*:: + -- type: keyword Kubernetes node name -- *`kubernetes.labels`*:: + -- type: object Kubernetes labels map -- *`kubernetes.annotations`*:: + -- type: object Kubernetes annotations map -- *`kubernetes.replicaset.name`*:: + -- type: keyword Kubernetes replicaset name -- *`kubernetes.deployment.name`*:: + -- type: keyword Kubernetes deployment name -- *`kubernetes.statefulset.name`*:: + -- type: keyword Kubernetes statefulset name -- *`kubernetes.container.name`*:: + -- type: keyword Kubernetes container name -- *`kubernetes.container.image`*:: + -- type: keyword Kubernetes container image -- [[exported-fields-process]] == Process fields Process metadata fields *`process.exe`*:: + -- type: alias alias to: process.executable -- ",16308,True,3997.1320135648343,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. */ //// [[schema]] = HBase and Schema Design :doctype: book :numbered: :toc: left :icons: font :experimental: A good introduction on the strength and weaknesses modelling on the various non-rdbms datastores is to be found in Ian Varley's Master thesis, link:http://ianvarley.com/UT/MR/Varley_MastersReport_Full_2009-08-07.pdf[No Relation: The Mixed Blessings of Non-Relational Databases]. It is a little dated now but a good background read if you have a moment on how HBase schema modeling differs from how it is done in an RDBMS. Also, read <> for how HBase stores data internally, and the section on <>. The documentation on the Cloud Bigtable website, link:https://cloud.google.com/bigtable/docs/schema-design[Designing Your Schema], is pertinent and nicely done and lessons learned there equally apply here in HBase land; just divide any quoted values by ~10 to get what works for HBase: e.g. where it says individual values can be ~10MBs in size, HBase can do similar -- perhaps best to go smaller if you can -- and where it says a maximum of 100 column families in Cloud Bigtable, think ~10 when modeling on HBase. See also Robert Yokota's link:https://blogs.apache.org/hbase/entry/hbase-application-archetypes-redux[HBase Application Archetypes] (an update on work done by other HBasers), for a helpful categorization of use cases that do well on top of the HBase model. [[schema.creation]] == Schema Creation HBase schemas can be created or updated using the <> or by using link:https://hbase.apache.org/apidocs/org/apache/hadoop/hbase/client/Admin.html[Admin] in the Java API. Tables must be disabled when making ColumnFamily modifications, for example: [source,java] ---- Configuration config = HBaseConfiguration.create(); Admin admin = new Admin(conf); TableName table = TableName.valueOf(""myTable""); admin.disableTable(table); HColumnDescriptor cf1 = ...; admin.addColumn(table, cf1); // adding new ColumnFamily HColumnDescriptor cf2 = ...; admin.modifyColumn(table, cf2); // modifying existing ColumnFamily admin.enableTable(table); ---- See <> for more information about configuring client connections. NOTE: online schema changes are supported in the 0.92.x codebase, but the 0.90.x codebase requires the table to be disabled. [[schema.updates]] === Schema Updates When changes are made to either Tables or ColumnFamilies (e.g. region size, block size), these changes take effect the next time there is a major compaction and the StoreFiles get re-written. See <> for more information on StoreFiles. [[table_schema_rules_of_thumb]] == Table Schema Rules Of Thumb There are many different data sets, with different access patterns and service-level expectations. Therefore, these rules of thumb are only an overview. Read the rest of this chapter to get more details after you have gone through this list. * Aim to have regions sized between 10 and 50 GB. * Aim to have cells no larger than 10 MB, or 50 MB if you use <>. Otherwise, consider storing your cell data in HDFS and store a pointer to the data in HBase. * A typical schema has between 1 and 3 column families per table. HBase tables should not be designed to mimic RDBMS tables. * Around 50-100 regions is a good number for a table with 1 or 2 column families. Remember that a region is a contiguous segment of a column family. * Keep your column family names as short as possible. The column family names are stored for every value (ignoring prefix encoding). They should not be self-documenting and descriptive like in a typical RDBMS. * If you are storing time-based machine data or logging information, and the row key is based on device ID or service ID plus time, you can end up with a pattern where older data regions never have additional writes beyond a certain age. In this type of situation, you end up with a small number of active regions and a large number of older regions which have no new writes. For these situations, you can tolerate a larger number of regions because your resource consumption is driven by the active regions only. * If only one column family is busy with writes, only that column family accomulates memory. Be aware of write patterns when allocating resources. [[regionserver_sizing_rules_of_thumb]] = RegionServer Sizing Rules of Thumb Lars Hofhansl wrote a great link:http://hadoop-hbase.blogspot.com/2013/01/hbase-region-server-memory-sizing.html[blog post] about RegionServer memory sizing. The upshot is that you probably need more memory than you think you need. He goes into the impact of region size, memstore size, HDFS replication factor, and other things to check. [quote, Lars Hofhansl, http://hadoop-hbase.blogspot.com/2013/01/hbase-region-server-memory-sizing.html] ____ Personally I would place the maximum disk space per machine that can be served exclusively with HBase around 6T, unless you have a very read-heavy workload. In that case the Java heap should be 32GB (20G regions, 128M memstores, the rest defaults). ____ [[number.of.cfs]] == On the number of column families HBase currently does not do well with anything above two or three column families so keep the number of column families in your schema low. Currently, flushing is done on a per Region basis so if one column family is carrying the bulk of the data bringing on flushes, the adjacent families will also be flushed even though the amount of data they carry is small. When many column families exist the flushing interaction can make for a bunch of needless i/o (To be addressed by changing flushing to work on a per column family basis). In addition, compactions triggered at table/region level will happen per store too. Try to make do with one column family if you can in your schemas. Only introduce a second and third column family in the case where data access is usually column scoped; i.e. you query one column family or the other but usually not both at the one time. [[number.of.cfs.card]] === Cardinality of ColumnFamilies Where multiple ColumnFamilies exist in a single table, be aware of the cardinality (i.e., number of rows). If ColumnFamilyA has 1 million rows and ColumnFamilyB has 1 billion rows, ColumnFamilyA's data will likely be spread across many, many regions (and RegionServers). This makes mass scans for ColumnFamilyA less efficient. [[rowkey.design]] == Rowkey Design === Hotspotting Rows in HBase are sorted lexicographically by row key. This design optimizes for scans, allowing you to store related rows, or rows that will be read together, near each other. However, poorly designed row keys are a common source of [firstterm]_hotspotting_. Hotspotting occurs when a large amount of client traffic is directed at one node, or only a few nodes, of a cluster. This traffic may represent reads, writes, or other operations. The traffic overwhelms the single machine responsible for hosting that region, causing performance degradation and potentially leading to region unavailability. This can also have adverse effects on other regions hosted by the same region server as that host is unable to service the requested load. It is important to design data access patterns such that the cluster is fully and evenly utilized. To prevent hotspotting on writes, design your row keys such that rows that truly do need to be in the same region are, but in the bigger picture, data is being written to multiple regions across the cluster, rather than one at a time. Some common techniques for avoiding hotspotting are described below, along with some of their advantages and drawbacks. .Salting Salting in this sense has nothing to do with cryptography, but refers to adding random data to the start of a row key. In this case, salting refers to adding a randomly-assigned prefix to the row key to cause it to sort differently than it otherwise would. The number of possible prefixes correspond to the number of regions you want to spread the data across. Salting can be helpful if you have a few ""hot"" row key patterns which come up over and over amongst other more evenly-distributed rows. Consider the following example, which shows that salting can spread write load across multiple RegionServers, and illustrates some of the negative implications for reads. .Salting Example ==== Suppose you have the following list of row keys, and your table is split such that there is one region for each letter of the alphabet. Prefix 'a' is one region, prefix 'b' is another. In this table, all rows starting with 'f' are in the same region. This example focuses on rows with keys like the following: ---- foo0001 foo0002 foo0003 foo0004 ---- Now, imagine that you would like to spread these across four different regions. You decide to use four different salts: `a`, `b`, `c`, and `d`. In this scenario, each of these letter prefixes will be on a different region. After applying the salts, you have the following rowkeys instead. Since you can now write to four separate regions, you theoretically have four times the throughput when writing that you would have if all the writes were going to the same region. ---- a-foo0003 b-foo0001 c-foo0004 d-foo0002 ---- Then, if you add another row, it will randomly be assigned one of the four possible salt values and end up near one of the existing rows. ---- a-foo0003 b-foo0001 c-foo0003 c-foo0004 d-foo0002 ---- Since this assignment will be random, you will need to do more work if you want to retrieve the rows in lexicographic order. In this way, salting attempts to increase throughput on writes, but has a cost during reads. ==== .Hashing Instead of a random assignment, you could use a one-way [firstterm]_hash_ that would cause a given row to always be ""salted"" with the same prefix, in a way that would spread the load across the RegionServers, but allow for predictability during reads. Using a deterministic hash allows the client to reconstruct the complete rowkey and use a Get operation to retrieve that row as normal. .Hashing Example [example] Given the same situation in the salting example above, you could instead apply a one-way hash that would cause the row with key `foo0003` to always, and predictably, receive the `a` prefix. Then, to retrieve that row, you would already know the key. You could also optimize things so that certain pairs of keys were always in the same region, for instance. .Reversing the Key A third common trick for preventing hotspotting is to reverse a fixed-width or numeric row key so that the part that changes the most often (the least significant digit) is first. This effectively randomizes row keys, but sacrifices row ordering properties. See https://communities.intel.com/community/itpeernetwork/datastack/blog/2013/11/10/discussion-on-designing-hbase-tables, and link:https://phoenix.apache.org/salted.html[article on Salted Tables] from the Phoenix project, and the discussion in the comments of link:https://issues.apache.org/jira/browse/HBASE-11682[HBASE-11682] for more information about avoiding hotspotting. [[timeseries]] === Monotonically Increasing Row Keys/Timeseries Data In the HBase chapter of Tom White's book link:http://oreilly.com/catalog/9780596521981[Hadoop: The Definitive Guide] (O'Reilly) there is a an optimization note on watching out for a phenomenon where an import process walks in lock-step with all clients in concert pounding one of the table's regions (and thus, a single node), then moving onto the next region, etc. With monotonically increasing row-keys (i.e., using a timestamp), this will happen. See this comic by IKai Lan on why monotonically increasing row keys are problematic in BigTable-like datastores: link:http://ikaisays.com/2011/01/25/app-engine-datastore-tip-monotonically-increasing-values-are-bad/[monotonically increasing values are bad]. The pile-up on a single region brought on by monotonically increasing keys can be mitigated by randomizing the input records to not be in sorted order, but in general it's best to avoid using a timestamp or a sequence (e.g. 1, 2, 3) as the row-key. If you do need to upload time series data into HBase, you should study link:http://opentsdb.net/[OpenTSDB] as a successful example. It has a page describing the link:http://opentsdb.net/schema.html[schema] it uses in HBase. The key format in OpenTSDB is effectively [metric_type][event_timestamp], which would appear at first glance to contradict the previous advice about not using a timestamp as the key. However, the difference is that the timestamp is not in the _lead_ position of the key, and the design assumption is that there are dozens or hundreds (or more) of different metric types. Thus, even with a continual stream of input data with a mix of metric types, the Puts are distributed across various points of regions in the table. See <> for some rowkey design examples. [[keysize]] === Try to minimize row and column sizes In HBase, values are always freighted with their coordinates; as a cell value passes through the system, it'll be accompanied by its row, column name, and timestamp - always. If your rows and column names are large, especially compared to the size of the cell value, then you may run up against some interesting scenarios. One such is the case described by Marc Limotte at the tail of link:https://issues.apache.org/jira/browse/HBASE-3551?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=13005272#comment-13005272[HBASE-3551] (recommended!). Therein, the indices that are kept on HBase storefiles (<>) to facilitate random access may end up occupying large chunks of the HBase allotted RAM because the cell value coordinates are large. Mark in the above cited comment suggests upping the block size so entries in the store file index happen at a larger interval or modify the table schema so it makes for smaller rows and column names. Compression will also make for larger indices. See the thread link:https://lists.apache.org/thread.html/b158eae5d8888d3530be378298bca90c17f80982fdcdfa01d0844c3d%401306240189%40%3Cuser.hbase.apache.org%3E[a question storefileIndexSize] up on the user mailing list. Most of the time small inefficiencies don't matter all that much. Unfortunately, this is a case where they do. Whatever patterns are selected for ColumnFamilies, attributes, and rowkeys they could be repeated several billion times in your data. See <> for more information on HBase stores data internally to see why this is important. [[keysize.cf]] ==== Column Families Try to keep the ColumnFamily names as small as possible, preferably one character (e.g. ""d"" for data/default). See <> for more information on HBase stores data internally to see why this is important. [[keysize.attributes]] ==== Attributes Although verbose attribute names (e.g., ""myVeryImportantAttribute"") are easier to read, prefer shorter attribute names (e.g., ""via"") to store in HBase. See <> for more information on HBase stores data internally to see why this is important. [[keysize.row]] ==== Rowkey Length Keep them as short as is reasonable such that they can still be useful for required data access (e.g. Get vs. Scan). A short key that is useless for data access is not better than a longer key with better get/scan properties. Expect tradeoffs when designing rowkeys. [[keysize.patterns]] ==== Byte Patterns A long is 8 bytes. You can store an unsigned number up to 18,446,744,073,709,551,615 in those eight bytes. If you stored this number as a String -- presuming a byte per character -- you need nearly 3x the bytes. Not convinced? Below is some sample code that you can run on your own. [source,java] ---- // long // long l = 1234567890L; byte[] lb = Bytes.toBytes(l); System.out.println(""long bytes length: "" + lb.length); // returns 8 String s = String.valueOf(l); byte[] sb = Bytes.toBytes(s); System.out.println(""long as string length: "" + sb.length); // returns 10 // hash // MessageDigest md = MessageDigest.getInstance(""MD5""); byte[] digest = md.digest(Bytes.toBytes(s)); System.out.println(""md5 digest bytes length: "" + digest.length); // returns 16 String sDigest = new String(digest); byte[] sbDigest = Bytes.toBytes(sDigest); System.out.println(""md5 digest as string length: "" + sbDigest.length); // returns 26 ---- Unfortunately, using a binary representation of a type will make your data harder to read outside of your code. For example, this is what you will see in the shell when you increment a value: [source] ---- hbase(main):001:0> incr 't', 'r', 'f:q', 1 COUNTER VALUE = 1 hbase(main):002:0> get 't', 'r' COLUMN CELL f:q timestamp=1369163040570, value=\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01 1 row(s) in 0.0310 seconds ---- The shell makes a best effort to print a string, and it this case it decided to just print the hex. The same will happen to your row keys inside the region names. It can be okay if you know what's being stored, but it might also be unreadable if arbitrary data can be put in the same cells. This is the main trade-off. [[reverse.timestamp]] === Reverse Timestamps .Reverse Scan API [NOTE] ==== link:https://issues.apache.org/jira/browse/HBASE-4811[HBASE-4811] implements an API to scan a table or a range within a table in reverse, reducing the need to optimize your schema for forward or reverse scanning. This feature is available in HBase 0.98 and later. See link:https://hbase.apache.org/apidocs/org/apache/hadoop/hbase/client/Scan.html#setReversed-boolean-[Scan.setReversed()] for more information. ==== A common problem in database processing is quickly finding the most recent version of a value. A technique using reverse timestamps as a part of the key can help greatly with a special case of this problem. Also found in the HBase chapter of Tom White's book Hadoop: The Definitive Guide (O'Reilly), the technique involves appending (`Long.MAX_VALUE - timestamp`) to the end of any key, e.g. [key][reverse_timestamp]. The most recent value for [key] in a table can be found by performing a Scan for [key] and obtaining the first record. Since HBase keys are in sorted order, this key sorts before any older row-keys for [key] and thus is first. This technique would be used instead of using <> where the intent is to hold onto all versions ""forever"" (or a very long time) and at the same time quickly obtain access to any other version by using the same Scan technique. [[rowkey.scope]] === Rowkeys and ColumnFamilies Rowkeys are scoped to ColumnFamilies. Thus, the same rowkey could exist in each ColumnFamily that exists in a table without collision. [[changing.rowkeys]] === Immutability of Rowkeys Rowkeys cannot be changed. The only way they can be ""changed"" in a table is if the row is deleted and then re-inserted. This is a fairly common question on the HBase dist-list so it pays to get the rowkeys right the first time (and/or before you've inserted a lot of data). [[rowkey.regionsplits]] === Relationship Between RowKeys and Region Splits If you pre-split your table, it is _critical_ to understand how your rowkey will be distributed across the region boundaries. As an example of why this is important, consider the example of using displayable hex characters as the lead position of the key (e.g., ""0000000000000000"" to ""ffffffffffffffff""). Running those key ranges through `Bytes.split` (which is the split strategy used when creating regions in `Admin.createTable(byte[] startKey, byte[] endKey, numRegions)` for 10 regions will generate the following splits... ---- 48 48 48 48 48 48 48 48 48 48 48 48 48 48 48 48 // 0 54 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 // 6 61 -67 -67 -67 -67 -67 -67 -67 -67 -67 -67 -67 -67 -67 -67 -68 // = 68 -124 -124 -124 -124 -124 -124 -124 -124 -124 -124 -124 -124 -124 -124 -126 // D 75 75 75 75 75 75 75 75 75 75 75 75 75 75 75 72 // K 82 18 18 18 18 18 18 18 18 18 18 18 18 18 18 14 // R 88 -40 -40 -40 -40 -40 -40 -40 -40 -40 -40 -40 -40 -40 -40 -44 // X 95 -97 -97 -97 -97 -97 -97 -97 -97 -97 -97 -97 -97 -97 -97 -102 // _ 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 // f ---- (note: the lead byte is listed to the right as a comment.) Given that the first split is a '0' and the last split is an 'f', everything is great, right? Not so fast. The problem is that all the data is going to pile up in the first 2 regions and the last region thus creating a ""lumpy"" (and possibly ""hot"") region problem. To understand why, refer to an link:http://www.asciitable.com[ASCII Table]. '0' is byte 48, and 'f' is byte 102, but there is a huge gap in byte values (bytes 58 to 96) that will _never appear in this keyspace_ because the only values are [0-9] and [a-f]. Thus, the middle regions will never be used. To make pre-splitting work with this example keyspace, a custom definition of splits (i.e., and not relying on the built-in split method) is required. Lesson #1: Pre-splitting tables is generally a best practice, but you need to pre-split them in such a way that all the regions are accessible in the keyspace. While this example demonstrated the problem with a hex-key keyspace, the same problem can happen with _any_ keyspace. Know your data. Lesson #2: While generally not advisable, using hex-keys (and more generally, displayable data) can still work with pre-split tables as long as all the created regions are accessible in the keyspace. To conclude this example, the following is an example of how appropriate splits can be pre-created for hex-keys:. [source,java] ---- public static boolean createTable(Admin admin, HTableDescriptor table, byte[][] splits) throws IOException { try { admin.createTable( table, splits ); return true; } catch (TableExistsException e) { logger.info(""table "" + table.getNameAsString() + "" already exists""); // the table already exists... return false; } } public static byte[][] getHexSplits(String startKey, String endKey, int numRegions) { byte[][] splits = new byte[numRegions-1][]; BigInteger lowestKey = new BigInteger(startKey, 16); BigInteger highestKey = new BigInteger(endKey, 16); BigInteger range = highestKey.subtract(lowestKey); BigInteger regionIncrement = range.divide(BigInteger.valueOf(numRegions)); lowestKey = lowestKey.add(regionIncrement); for(int i=0; i < numRegions-1;i++) { BigInteger key = lowestKey.add(regionIncrement.multiply(BigInteger.valueOf(i))); byte[] b = String.format(""%016x"", key).getBytes(); splits[i] = b; } return splits; } ---- [[schema.versions]] == Number of Versions [[schema.versions.max]] === Maximum Number of Versions The maximum number of row versions to store is configured per column family via link:https://hbase.apache.org/apidocs/org/apache/hadoop/hbase/HColumnDescriptor.html[HColumnDescriptor]. The default for max versions is 1. This is an important parameter because as described in <> section HBase does _not_ overwrite row values, but rather stores different values per row by time (and qualifier). Excess versions are removed during major compactions. The number of max versions may need to be increased or decreased depending on application needs. It is not recommended setting the number of max versions to an exceedingly high level (e.g., hundreds or more) unless those old values are very dear to you because this will greatly increase StoreFile size. [[schema.minversions]] === Minimum Number of Versions Like maximum number of row versions, the minimum number of row versions to keep is configured per column family via link:https://hbase.apache.org/apidocs/org/apache/hadoop/hbase/HColumnDescriptor.html[HColumnDescriptor]. The default for min versions is 0, which means the feature is disabled. The minimum number of row versions parameter is used together with the time-to-live parameter and can be combined with the number of row versions parameter to allow configurations such as ""keep the last T minutes worth of data, at most N versions, _but keep at least M versions around_"" (where M is the value for minimum number of row versions, M>, and that includes versioning. Take that into consideration when making your design, as well as block size for the ColumnFamily. === Counters One supported datatype that deserves special mention are ""counters"" (i.e., the ability to do atomic increments of numbers). See link:https://hbase.apache.org/apidocs/org/apache/hadoop/hbase/client/Table.html#increment%28org.apache.hadoop.hbase.client.Increment%29[Increment] in `Table`. Synchronization on counters are done on the RegionServer, not in the client. [[schema.joins]] == Joins If you have multiple tables, don't forget to factor in the potential for <> into the schema design. [[ttl]] == Time To Live (TTL) ColumnFamilies can set a TTL length in seconds, and HBase will automatically delete rows once the expiration time is reached. This applies to _all_ versions of a row - even the current one. The TTL time encoded in the HBase for the row is specified in UTC. Store files which contains only expired rows are deleted on minor compaction. Setting `hbase.store.delete.expired.storefile` to `false` disables this feature. Setting minimum number of versions to other than 0 also disables this. See link:https://hbase.apache.org/apidocs/org/apache/hadoop/hbase/HColumnDescriptor.html[HColumnDescriptor] for more information. Recent versions of HBase also support setting time to live on a per cell basis. See link:https://issues.apache.org/jira/browse/HBASE-10560[HBASE-10560] for more information. Cell TTLs are submitted as an attribute on mutation requests (Appends, Increments, Puts, etc.) using Mutation#setTTL. If the TTL attribute is set, it will be applied to all cells updated on the server by the operation. There are two notable differences between cell TTL handling and ColumnFamily TTLs: * Cell TTLs are expressed in units of milliseconds instead of seconds. * A cell TTLs cannot extend the effective lifetime of a cell beyond a ColumnFamily level TTL setting. [[cf.keep.deleted]] == Keeping Deleted Cells By default, delete markers extend back to the beginning of time. Therefore, link:https://hbase.apache.org/apidocs/org/apache/hadoop/hbase/client/Get.html[Get] or link:https://hbase.apache.org/apidocs/org/apache/hadoop/hbase/client/Scan.html[Scan] operations will not see a deleted cell (row or column), even when the Get or Scan operation indicates a time range before the delete marker was placed. ColumnFamilies can optionally keep deleted cells. In this case, deleted cells can still be retrieved, as long as these operations specify a time range that ends before the timestamp of any delete that would affect the cells. This allows for point-in-time queries even in the presence of deletes. Deleted cells are still subject to TTL and there will never be more than ""maximum number of versions"" deleted cells. A new ""raw"" scan options returns all deleted rows and the delete markers. .Change the Value of `KEEP_DELETED_CELLS` Using HBase Shell ---- hbase> hbase> alter ‘t1′, NAME => ‘f1′, KEEP_DELETED_CELLS => true ---- .Change the Value of `KEEP_DELETED_CELLS` Using the API ==== [source,java] ---- ... HColumnDescriptor.setKeepDeletedCells(true); ... ---- ==== Let us illustrate the basic effect of setting the `KEEP_DELETED_CELLS` attribute on a table. First, without: [source] ---- create 'test', {NAME=>'e', VERSIONS=>2147483647} put 'test', 'r1', 'e:c1', 'value', 10 put 'test', 'r1', 'e:c1', 'value', 12 put 'test', 'r1', 'e:c1', 'value', 14 delete 'test', 'r1', 'e:c1', 11 hbase(main):017:0> scan 'test', {RAW=>true, VERSIONS=>1000} ROW COLUMN+CELL r1 column=e:c1, timestamp=14, value=value r1 column=e:c1, timestamp=12, value=value r1 column=e:c1, timestamp=11, type=DeleteColumn r1 column=e:c1, timestamp=10, value=value 1 row(s) in 0.0120 seconds hbase(main):018:0> flush 'test' 0 row(s) in 0.0350 seconds hbase(main):019:0> scan 'test', {RAW=>true, VERSIONS=>1000} ROW COLUMN+CELL r1 column=e:c1, timestamp=14, value=value r1 column=e:c1, timestamp=12, value=value r1 column=e:c1, timestamp=11, type=DeleteColumn 1 row(s) in 0.0120 seconds hbase(main):020:0> major_compact 'test' 0 row(s) in 0.0260 seconds hbase(main):021:0> scan 'test', {RAW=>true, VERSIONS=>1000} ROW COLUMN+CELL r1 column=e:c1, timestamp=14, value=value r1 column=e:c1, timestamp=12, value=value 1 row(s) in 0.0120 seconds ---- Notice how delete cells are let go. Now let's run the same test only with `KEEP_DELETED_CELLS` set on the table (you can do table or per-column-family): [source] ---- hbase(main):005:0> create 'test', {NAME=>'e', VERSIONS=>2147483647, KEEP_DELETED_CELLS => true} 0 row(s) in 0.2160 seconds => Hbase::Table - test hbase(main):006:0> put 'test', 'r1', 'e:c1', 'value', 10 0 row(s) in 0.1070 seconds hbase(main):007:0> put 'test', 'r1', 'e:c1', 'value', 12 0 row(s) in 0.0140 seconds hbase(main):008:0> put 'test', 'r1', 'e:c1', 'value', 14 0 row(s) in 0.0160 seconds hbase(main):009:0> delete 'test', 'r1', 'e:c1', 11 0 row(s) in 0.0290 seconds hbase(main):010:0> scan 'test', {RAW=>true, VERSIONS=>1000} ROW COLUMN+CELL r1 column=e:c1, timestamp=14, value=value r1 column=e:c1, timestamp=12, value=value r1 column=e:c1, timestamp=11, type=DeleteColumn r1 column=e:c1, timestamp=10, value=value 1 row(s) in 0.0550 seconds hbase(main):011:0> flush 'test' 0 row(s) in 0.2780 seconds hbase(main):012:0> scan 'test', {RAW=>true, VERSIONS=>1000} ROW COLUMN+CELL r1 column=e:c1, timestamp=14, value=value r1 column=e:c1, timestamp=12, value=value r1 column=e:c1, timestamp=11, type=DeleteColumn r1 column=e:c1, timestamp=10, value=value 1 row(s) in 0.0620 seconds hbase(main):013:0> major_compact 'test' 0 row(s) in 0.0530 seconds hbase(main):014:0> scan 'test', {RAW=>true, VERSIONS=>1000} ROW COLUMN+CELL r1 column=e:c1, timestamp=14, value=value r1 column=e:c1, timestamp=12, value=value r1 column=e:c1, timestamp=11, type=DeleteColumn r1 column=e:c1, timestamp=10, value=value 1 row(s) in 0.0650 seconds ---- KEEP_DELETED_CELLS is to avoid removing Cells from HBase when the _only_ reason to remove them is the delete marker. So with KEEP_DELETED_CELLS enabled deleted cells would get removed if either you write more versions than the configured max, or you have a TTL and Cells are in excess of the configured timeout, etc. [[secondary.indexes]] == Secondary Indexes and Alternate Query Paths This section could also be titled ""what if my table rowkey looks like _this_ but I also want to query my table like _that_."" A common example on the dist-list is where a row-key is of the format ""user-timestamp"" but there are reporting requirements on activity across users for certain time ranges. Thus, selecting by user is easy because it is in the lead position of the key, but time is not. There is no single answer on the best way to handle this because it depends on... * Number of users * Data size and data arrival rate * Flexibility of reporting requirements (e.g., completely ad-hoc date selection vs. pre-configured ranges) * Desired execution speed of query (e.g., 90 seconds may be reasonable to some for an ad-hoc report, whereas it may be too long for others) and solutions are also influenced by the size of the cluster and how much processing power you have to throw at the solution. Common techniques are in sub-sections below. This is a comprehensive, but not exhaustive, list of approaches. It should not be a surprise that secondary indexes require additional cluster space and processing. This is precisely what happens in an RDBMS because the act of creating an alternate index requires both space and processing cycles to update. RDBMS products are more advanced in this regard to handle alternative index management out of the box. However, HBase scales better at larger data volumes, so this is a feature trade-off. Pay attention to <> when implementing any of these approaches. Additionally, see the David Butler response in this dist-list thread link:https://lists.apache.org/thread.html/b0ca33407f010d5b1be67a20d1708e8d8bb1e147770f2cb7182a2e37%401300972712%40%3Cuser.hbase.apache.org%3E[HBase, mail # user - Stargate+hbase] [[secondary.indexes.filter]] === Filter Query Depending on the case, it may be appropriate to use <>. In this case, no secondary index is created. However, don't try a full-scan on a large table like this from an application (i.e., single-threaded client). [[secondary.indexes.periodic]] === Periodic-Update Secondary Index A secondary index could be created in another table which is periodically updated via a MapReduce job. The job could be executed intra-day, but depending on load-strategy it could still potentially be out of sync with the main data table. See <> for more information. [[secondary.indexes.dualwrite]] === Dual-Write Secondary Index Another strategy is to build the secondary index while publishing data to the cluster (e.g., write to data table, write to index table). If this is approach is taken after a data table already exists, then bootstrapping will be needed for the secondary index with a MapReduce job (see <>). [[secondary.indexes.summary]] === Summary Tables Where time-ranges are very wide (e.g., year-long report) and where the data is voluminous, summary tables are a common approach. These would be generated with MapReduce jobs into another table. See <> for more information. [[secondary.indexes.coproc]] === Coprocessor Secondary Index Coprocessors act like RDBMS triggers. These were added in 0.92. For more information, see <> == Constraints HBase currently supports 'constraints' in traditional (SQL) database parlance. The advised usage for Constraints is in enforcing business rules for attributes in the table (e.g. make sure values are in the range 1-10). Constraints could also be used to enforce referential integrity, but this is strongly discouraged as it will dramatically decrease the write throughput of the tables where integrity checking is enabled. Extensive documentation on using Constraints can be found at link:https://hbase.apache.org/devapidocs/org/apache/hadoop/hbase/constraint/Constraint.html[Constraint] since version 0.94. [[schema.casestudies]] == Schema Design Case Studies The following will describe some typical data ingestion use-cases with HBase, and how the rowkey design and construction can be approached. Note: this is just an illustration of potential approaches, not an exhaustive list. Know your data, and know your processing requirements. It is highly recommended that you read the rest of the <> first, before reading these case studies. The following case studies are described: * Log Data / Timeseries Data * Log Data / Timeseries on Steroids * Customer/Order * Tall/Wide/Middle Schema Design * List Data [[schema.casestudies.log_timeseries]] === Case Study - Log Data and Timeseries Data Assume that the following data elements are being collected. * Hostname * Timestamp * Log event * Value/message We can store them in an HBase table called LOG_DATA, but what will the rowkey be? From these attributes the rowkey will be some combination of hostname, timestamp, and log-event - but what specifically? [[schema.casestudies.log_timeseries.tslead]] ==== Timestamp In The Rowkey Lead Position The rowkey `[timestamp][hostname][log-event]` suffers from the monotonically increasing rowkey problem described in <>. There is another pattern frequently mentioned in the dist-lists about ""bucketing"" timestamps, by performing a mod operation on the timestamp. If time-oriented scans are important, this could be a useful approach. Attention must be paid to the number of buckets, because this will require the same number of scans to return results. [source,java] ---- long bucket = timestamp % numBuckets; ---- to construct: [source] ---- [bucket][timestamp][hostname][log-event] ---- As stated above, to select data for a particular timerange, a Scan will need to be performed for each bucket. 100 buckets, for example, will provide a wide distribution in the keyspace but it will require 100 Scans to obtain data for a single timestamp, so there are trade-offs. [[schema.casestudies.log_timeseries.hostlead]] ==== Host In The Rowkey Lead Position The rowkey `[hostname][log-event][timestamp]` is a candidate if there is a large-ish number of hosts to spread the writes and reads across the keyspace. This approach would be useful if scanning by hostname was a priority. [[schema.casestudies.log_timeseries.revts]] ==== Timestamp, or Reverse Timestamp? If the most important access path is to pull most recent events, then storing the timestamps as reverse-timestamps (e.g., `timestamp = Long.MAX_VALUE – timestamp`) will create the property of being able to do a Scan on `[hostname][log-event]` to obtain the most recently captured events. Neither approach is wrong, it just depends on what is most appropriate for the situation. .Reverse Scan API [NOTE] ==== link:https://issues.apache.org/jira/browse/HBASE-4811[HBASE-4811] implements an API to scan a table or a range within a table in reverse, reducing the need to optimize your schema for forward or reverse scanning. This feature is available in HBase 0.98 and later. See link:https://hbase.apache.org/apidocs/org/apache/hadoop/hbase/client/Scan.html#setReversed-boolean-[Scan.setReversed()] for more information. ==== [[schema.casestudies.log_timeseries.varkeys]] ==== Variable Length or Fixed Length Rowkeys? It is critical to remember that rowkeys are stamped on every column in HBase. If the hostname is `a` and the event type is `e1` then the resulting rowkey would be quite small. However, what if the ingested hostname is `myserver1.mycompany.com` and the event type is `com.package1.subpackage2.subsubpackage3.ImportantService`? It might make sense to use some substitution in the rowkey. There are at least two approaches: hashed and numeric. In the Hostname In The Rowkey Lead Position example, it might look like this: Composite Rowkey With Hashes: * [MD5 hash of hostname] = 16 bytes * [MD5 hash of event-type] = 16 bytes * [timestamp] = 8 bytes Composite Rowkey With Numeric Substitution: For this approach another lookup table would be needed in addition to LOG_DATA, called LOG_TYPES. The rowkey of LOG_TYPES would be: * `[type]` (e.g., byte indicating hostname vs. event-type) * `[bytes]` variable length bytes for raw hostname or event-type. A column for this rowkey could be a long with an assigned number, which could be obtained by using an link:https://hbase.apache.org/apidocs/org/apache/hadoop/hbase/client/Table.html#incrementColumnValue-byte:A-byte:A-byte:A-long-[HBase counter] So the resulting composite rowkey would be: * [substituted long for hostname] = 8 bytes * [substituted long for event type] = 8 bytes * [timestamp] = 8 bytes In either the Hash or Numeric substitution approach, the raw values for hostname and event-type can be stored as columns. [[schema.casestudies.log_steroids]] === Case Study - Log Data and Timeseries Data on Steroids This effectively is the OpenTSDB approach. What OpenTSDB does is re-write data and pack rows into columns for certain time-periods. For a detailed explanation, see: http://opentsdb.net/schema.html, and link:https://www.slideshare.net/cloudera/4-opentsdb-hbasecon[Lessons Learned from OpenTSDB] from HBaseCon2012. But this is how the general concept works: data is ingested, for example, in this manner... ---- [hostname][log-event][timestamp1] [hostname][log-event][timestamp2] [hostname][log-event][timestamp3] ---- with separate rowkeys for each detailed event, but is re-written like this... ---- [hostname][log-event][timerange] ---- and each of the above events are converted into columns stored with a time-offset relative to the beginning timerange (e.g., every 5 minutes). This is obviously a very advanced processing technique, but HBase makes this possible. [[schema.casestudies.custorder]] === Case Study - Customer/Order Assume that HBase is used to store customer and order information. There are two core record-types being ingested: a Customer record type, and Order record type. The Customer record type would include all the things that you'd typically expect: * Customer number * Customer name * Address (e.g., city, state, zip) * Phone numbers, etc. The Order record type would include things like: * Customer number * Order number * Sales date * A series of nested objects for shipping locations and line-items (see <> for details) Assuming that the combination of customer number and sales order uniquely identify an order, these two attributes will compose the rowkey, and specifically a composite key such as: ---- [customer number][order number] ---- for an ORDER table. However, there are more design decisions to make: are the _raw_ values the best choices for rowkeys? The same design questions in the Log Data use-case confront us here. What is the keyspace of the customer number, and what is the format (e.g., numeric? alphanumeric?) As it is advantageous to use fixed-length keys in HBase, as well as keys that can support a reasonable spread in the keyspace, similar options appear: Composite Rowkey With Hashes: * [MD5 of customer number] = 16 bytes * [MD5 of order number] = 16 bytes Composite Numeric/Hash Combo Rowkey: * [substituted long for customer number] = 8 bytes * [MD5 of order number] = 16 bytes [[schema.casestudies.custorder.tables]] ==== Single Table? Multiple Tables? A traditional design approach would have separate tables for CUSTOMER and SALES. Another option is to pack multiple record types into a single table (e.g., CUSTOMER++). Customer Record Type Rowkey: * [customer-id] * [type] = type indicating `1' for customer record type Order Record Type Rowkey: * [customer-id] * [type] = type indicating `2' for order record type * [order] The advantage of this particular CUSTOMER++ approach is that organizes many different record-types by customer-id (e.g., a single scan could get you everything about that customer). The disadvantage is that it's not as easy to scan for a particular record-type. [[schema.casestudies.custorder.obj]] ==== Order Object Design Now we need to address how to model the Order object. Assume that the class structure is as follows: Order:: (an Order can have multiple ShippingLocations LineItem:: (a ShippingLocation can have multiple LineItems there are multiple options on storing this data. [[schema.casestudies.custorder.obj.norm]] ===== Completely Normalized With this approach, there would be separate tables for ORDER, SHIPPING_LOCATION, and LINE_ITEM. The ORDER table's rowkey was described above: <> The SHIPPING_LOCATION's composite rowkey would be something like this: * `[order-rowkey]` * `[shipping location number]` (e.g., 1st location, 2nd, etc.) The LINE_ITEM table's composite rowkey would be something like this: * `[order-rowkey]` * `[shipping location number]` (e.g., 1st location, 2nd, etc.) * `[line item number]` (e.g., 1st lineitem, 2nd, etc.) Such a normalized model is likely to be the approach with an RDBMS, but that's not your only option with HBase. The cons of such an approach is that to retrieve information about any Order, you will need: * Get on the ORDER table for the Order * Scan on the SHIPPING_LOCATION table for that order to get the ShippingLocation instances * Scan on the LINE_ITEM for each ShippingLocation granted, this is what an RDBMS would do under the covers anyway, but since there are no joins in HBase you're just more aware of this fact. [[schema.casestudies.custorder.obj.rectype]] ===== Single Table With Record Types With this approach, there would exist a single table ORDER that would contain The Order rowkey was described above: <> * `[order-rowkey]` * `[ORDER record type]` The ShippingLocation composite rowkey would be something like this: * `[order-rowkey]` * `[SHIPPING record type]` * `[shipping location number]` (e.g., 1st location, 2nd, etc.) The LineItem composite rowkey would be something like this: * `[order-rowkey]` * `[LINE record type]` * `[shipping location number]` (e.g., 1st location, 2nd, etc.) * `[line item number]` (e.g., 1st lineitem, 2nd, etc.) [[schema.casestudies.custorder.obj.denorm]] ===== Denormalized A variant of the Single Table With Record Types approach is to denormalize and flatten some of the object hierarchy, such as collapsing the ShippingLocation attributes onto each LineItem instance. The LineItem composite rowkey would be something like this: * `[order-rowkey]` * `[LINE record type]` * `[line item number]` (e.g., 1st lineitem, 2nd, etc., care must be taken that there are unique across the entire order) and the LineItem columns would be something like this: * itemNumber * quantity * price * shipToLine1 (denormalized from ShippingLocation) * shipToLine2 (denormalized from ShippingLocation) * shipToCity (denormalized from ShippingLocation) * shipToState (denormalized from ShippingLocation) * shipToZip (denormalized from ShippingLocation) The pros of this approach include a less complex object hierarchy, but one of the cons is that updating gets more complicated in case any of this information changes. [[schema.casestudies.custorder.obj.singleobj]] ===== Object BLOB With this approach, the entire Order object graph is treated, in one way or another, as a BLOB. For example, the ORDER table's rowkey was described above: <>, and a single column called ""order"" would contain an object that could be deserialized that contained a container Order, ShippingLocations, and LineItems. There are many options here: JSON, XML, Java Serialization, Avro, Hadoop Writables, etc. All of them are variants of the same approach: encode the object graph to a byte-array. Care should be taken with this approach to ensure backward compatibility in case the object model changes such that older persisted structures can still be read back out of HBase. Pros are being able to manage complex object graphs with minimal I/O (e.g., a single HBase Get per Order in this example), but the cons include the aforementioned warning about backward compatibility of serialization, language dependencies of serialization (e.g., Java Serialization only works with Java clients), the fact that you have to deserialize the entire object to get any piece of information inside the BLOB, and the difficulty in getting frameworks like Hive to work with custom objects like this. [[schema.smackdown]] === Case Study - ""Tall/Wide/Middle"" Schema Design Smackdown This section will describe additional schema design questions that appear on the dist-list, specifically about tall and wide tables. These are general guidelines and not laws - each application must consider its own needs. [[schema.smackdown.rowsversions]] ==== Rows vs. Versions A common question is whether one should prefer rows or HBase's built-in-versioning. The context is typically where there are ""a lot"" of versions of a row to be retained (e.g., where it is significantly above the HBase default of 1 max versions). The rows-approach would require storing a timestamp in some portion of the rowkey so that they would not overwrite with each successive update. Preference: Rows (generally speaking). [[schema.smackdown.rowscols]] ==== Rows vs. Columns Another common question is whether one should prefer rows or columns. The context is typically in extreme cases of wide tables, such as having 1 row with 1 million attributes, or 1 million rows with 1 columns apiece. Preference: Rows (generally speaking). To be clear, this guideline is in the context is in extremely wide cases, not in the standard use-case where one needs to store a few dozen or hundred columns. But there is also a middle path between these two options, and that is ""Rows as Columns."" [[schema.smackdown.rowsascols]] ==== Rows as Columns The middle path between Rows vs. Columns is packing data that would be a separate row into columns, for certain rows. OpenTSDB is the best example of this case where a single row represents a defined time-range, and then discrete events are treated as columns. This approach is often more complex, and may require the additional complexity of re-writing your data, but has the advantage of being I/O efficient. For an overview of this approach, see <>. [[casestudies.schema.listdata]] === Case Study - List Data The following is an exchange from the user dist-list regarding a fairly common question: how to handle per-user list data in Apache HBase. *** QUESTION *** We're looking at how to store a large amount of (per-user) list data in HBase, and we were trying to figure out what kind of access pattern made the most sense. One option is store the majority of the data in a key, so we could have something like: [source] ---- :"""" (no value) :"""" (no value) :"""" (no value) ---- The other option we had was to do this entirely using: [source,xml] ---- :... :... ---- where each row would contain multiple values. So in one case reading the first thirty values would be: [source,java] ---- scan { STARTROW => 'FixedWidthUsername' LIMIT => 30} ---- And in the second case it would be [source] ---- get 'FixedWidthUserName\\x00\\x00\\x00\\x00' ---- The general usage pattern would be to read only the first 30 values of these lists, with infrequent access reading deeper into the lists. Some users would have <= 30 total values in these lists, and some users would have millions (i.e. power-law distribution) The single-value format seems like it would take up more space on HBase, but would offer some improved retrieval / pagination flexibility. Would there be any significant performance advantages to be able to paginate via gets vs paginating with scans? My initial understanding was that doing a scan should be faster if our paging size is unknown (and caching is set appropriately), but that gets should be faster if we'll always need the same page size. I've ended up hearing different people tell me opposite things about performance. I assume the page sizes would be relatively consistent, so for most use cases we could guarantee that we only wanted one page of data in the fixed-page-length case. I would also assume that we would have infrequent updates, but may have inserts into the middle of these lists (meaning we'd need to update all subsequent rows). Thanks for help / suggestions / follow-up questions. *** ANSWER *** If I understand you correctly, you're ultimately trying to store triples in the form ""user, valueid, value"", right? E.g., something like: [source] ---- ""user123, firstname, Paul"", ""user234, lastname, Smith"" ---- (But the usernames are fixed width, and the valueids are fixed width). And, your access pattern is along the lines of: ""for user X, list the next 30 values, starting with valueid Y"". Is that right? And these values should be returned sorted by valueid? The tl;dr version is that you should probably go with one row per user+value, and not build a complicated intra-row pagination scheme on your own unless you're really sure it is needed. Your two options mirror a common question people have when designing HBase schemas: should I go ""tall"" or ""wide""? Your first schema is ""tall"": each row represents one value for one user, and so there are many rows in the table for each user; the row key is user + valueid, and there would be (presumably) a single column qualifier that means ""the value"". This is great if you want to scan over rows in sorted order by row key (thus my question above, about whether these ids are sorted correctly). You can start a scan at any user+valueid, read the next 30, and be done. What you're giving up is the ability to have transactional guarantees around all the rows for one user, but it doesn't sound like you need that. Doing it this way is generally recommended (see here https://hbase.apache.org/book.html#schema.smackdown). Your second option is ""wide"": you store a bunch of values in one row, using different qualifiers (where the qualifier is the valueid). The simple way to do that would be to just store ALL values for one user in a single row. I'm guessing you jumped to the ""paginated"" version because you're assuming that storing millions of columns in a single row would be bad for performance, which may or may not be true; as long as you're not trying to do too much in a single request, or do things like scanning over and returning all of the cells in the row, it shouldn't be fundamentally worse. The client has methods that allow you to get specific slices of columns. Note that neither case fundamentally uses more disk space than the other; you're just ""shifting"" part of the identifying information for a value either to the left (into the row key, in option one) or to the right (into the column qualifiers in option 2). Under the covers, every key/value still stores the whole row key, and column family name. (If this is a bit confusing, take an hour and watch Lars George's excellent video about understanding HBase schema design: http://www.youtube.com/watch?v=_HLoH_PgrLk). A manually paginated version has lots more complexities, as you note, like having to keep track of how many things are in each page, re-shuffling if new values are inserted, etc. That seems significantly more complex. It might have some slight speed advantages (or disadvantages!) at extremely high throughput, and the only way to really know that would be to try it out. If you don't have time to build it both ways and compare, my advice would be to start with the simplest option (one row per user+value). Start simple and iterate! :) [[schema.ops]] == Operational and Performance Configuration Options === Tune HBase Server RPC Handling * Set `hbase.regionserver.handler.count` (in `hbase-site.xml`) to cores x spindles for concurrency. * Optionally, split the call queues into separate read and write queues for differentiated service. The parameter `hbase.ipc.server.callqueue.handler.factor` specifies the number of call queues: - `0` means a single shared queue - `1` means one queue for each handler. - A value between `0` and `1` allocates the number of queues proportionally to the number of handlers. For instance, a value of `.5` shares one queue between each two handlers. * Use `hbase.ipc.server.callqueue.read.ratio` (`hbase.ipc.server.callqueue.read.share` in 0.98) to split the call queues into read and write queues: - `0.5` means there will be the same number of read and write queues - `< 0.5` for more read than write - `> 0.5` for more write than read * Set `hbase.ipc.server.callqueue.scan.ratio` (HBase 1.0+) to split read call queues into small-read and long-read queues: - 0.5 means that there will be the same number of short-read and long-read queues - `< 0.5` for more short-read - `> 0.5` for more long-read === Disable Nagle for RPC Disable Nagle’s algorithm. Delayed ACKs can add up to ~200ms to RPC round trip time. Set the following parameters: * In Hadoop’s `core-site.xml`: - `ipc.server.tcpnodelay = true` - `ipc.client.tcpnodelay = true` * In HBase’s `hbase-site.xml`: - `hbase.ipc.client.tcpnodelay = true` - `hbase.ipc.server.tcpnodelay = true` === Limit Server Failure Impact Detect regionserver failure as fast as reasonable. Set the following parameters: * In `hbase-site.xml`, set `zookeeper.session.timeout` to 30 seconds or less to bound failure detection (20-30 seconds is a good start). - Note: Zookeeper clients negotiate a session timeout with the server during client init. Server enforces this timeout to be in the range [`minSessionTimeout`, `maxSessionTimeout`] and both these timeouts (measured in milliseconds) are configurable in Zookeeper service configuration. If not configured, these default to 2 * `tickTime` and 20 * `tickTime` respectively (`tickTime` is the basic time unit used by ZooKeeper, as measured in milliseconds. It is used to regulate heartbeats, timeouts etc.). Refer to Zookeeper documentation for additional details. * Detect and avoid unhealthy or failed HDFS DataNodes: in `hdfs-site.xml` and `hbase-site.xml`, set the following parameters: - `dfs.namenode.avoid.read.stale.datanode = true` - `dfs.namenode.avoid.write.stale.datanode = true` [[shortcircuit.reads]] === Optimize on the Server Side for Low Latency Skip the network for local blocks when the RegionServer goes to read from HDFS by exploiting HDFS's link:https://hadoop.apache.org/docs/stable/hadoop-project-dist/hadoop-hdfs/ShortCircuitLocalReads.html[Short-Circuit Local Reads] facility. Note how setup must be done both at the datanode and on the dfsclient ends of the conneciton -- i.e. at the RegionServer and how both ends need to have loaded the hadoop native `.so` library. After configuring your hadoop setting _dfs.client.read.shortcircuit_ to _true_ and configuring the _dfs.domain.socket.path_ path for the datanode and dfsclient to share and restarting, next configure the regionserver/dfsclient side. * In `hbase-site.xml`, set the following parameters: - `dfs.client.read.shortcircuit = true` - `dfs.client.read.shortcircuit.skip.checksum = true` so we don't double checksum (HBase does its own checksumming to save on i/os. See <> for more on this. - `dfs.domain.socket.path` to match what was set for the datanodes. - `dfs.client.read.shortcircuit.buffer.size = 131072` Important to avoid OOME -- hbase has a default it uses if unset, see `hbase.dfs.client.read.shortcircuit.buffer.size`; its default is 131072. * Ensure data locality. In `hbase-site.xml`, set `hbase.hstore.min.locality.to.skip.major.compact = 0.7` (Meaning that 0.7 \\<= n \\<= 1) * Make sure DataNodes have enough handlers for block transfers. In `hdfs-site.xml`, set the following parameters: - `dfs.datanode.max.xcievers >= 8192` - `dfs.datanode.handler.count =` number of spindles Check the RegionServer logs after restart. You should only see complaint if misconfiguration. Otherwise, shortcircuit read operates quietly in background. It does not provide metrics so no optics on how effective it is but read latencies should show a marked improvement, especially if good data locality, lots of random reads, and dataset is larger than available cache. Other advanced configurations that you might play with, especially if shortcircuit functionality is complaining in the logs, include `dfs.client.read.shortcircuit.streams.cache.size` and `dfs.client.socketcache.capacity`. Documentation is sparse on these options. You'll have to read source code. RegionServer metric system exposes HDFS short circuit read metrics `shortCircuitBytesRead`. Other HDFS read metrics, including `totalBytesRead` (The total number of bytes read from HDFS), `localBytesRead` (The number of bytes read from the local HDFS DataNode), `zeroCopyBytesRead` (The number of bytes read through HDFS zero copy) are available and can be used to troubleshoot short-circuit read issues. For more on short-circuit reads, see Colin's old blog on rollout, link:http://blog.cloudera.com/blog/2013/08/how-improved-short-circuit-local-reads-bring-better-performance-and-security-to-hadoop/[How Improved Short-Circuit Local Reads Bring Better Performance and Security to Hadoop]. The link:https://issues.apache.org/jira/browse/HDFS-347[HDFS-347] issue also makes for an interesting read showing the HDFS community at its best (caveat a few comments). === JVM Tuning ==== Tune JVM GC for low collection latencies * Use the CMS collector: `-XX:+UseConcMarkSweepGC` * Keep eden space as small as possible to minimize average collection time. Example: -XX:CMSInitiatingOccupancyFraction=70 * Optimize for low collection latency rather than throughput: `-Xmn512m` * Collect eden in parallel: `-XX:+UseParNewGC` * Avoid collection under pressure: `-XX:+UseCMSInitiatingOccupancyOnly` * Limit per request scanner result sizing so everything fits into survivor space but doesn’t tenure. In `hbase-site.xml`, set `hbase.client.scanner.max.result.size` to 1/8th of eden space (with -`Xmn512m` this is ~51MB ) * Set `max.result.size` x `handler.count` less than survivor space ==== OS-Level Tuning * Turn transparent huge pages (THP) off: echo never > /sys/kernel/mm/transparent_hugepage/enabled echo never > /sys/kernel/mm/transparent_hugepage/defrag * Set `vm.swappiness = 0` * Set `vm.min_free_kbytes` to at least 1GB (8GB on larger memory systems) * Disable NUMA zone reclaim with `vm.zone_reclaim_mode = 0` == Special Cases === For applications where failing quickly is better than waiting * In `hbase-site.xml` on the client side, set the following parameters: - Set `hbase.client.pause = 1000` - Set `hbase.client.retries.number = 3` - If you want to ride over splits and region moves, increase `hbase.client.retries.number` substantially (>= 20) - Set the RecoverableZookeeper retry count: `zookeeper.recovery.retry = 1` (no retry) * In `hbase-site.xml` on the server side, set the Zookeeper session timeout for detecting server failures: `zookeeper.session.timeout` <= 30 seconds (20-30 is good). === For applications that can tolerate slightly out of date information **HBase timeline consistency (HBASE-10070) ** With read replicas enabled, read-only copies of regions (replicas) are distributed over the cluster. One RegionServer services the default or primary replica, which is the only replica that can service writes. Other RegionServers serve the secondary replicas, follow the primary RegionServer, and only see committed updates. The secondary replicas are read-only, but can serve reads immediately while the primary is failing over, cutting read availability blips from seconds to milliseconds. Phoenix supports timeline consistency as of 4.4.0 Tips: * Deploy HBase 1.0.0 or later. * Enable timeline consistent replicas on the server side. * Use one of the following methods to set timeline consistency: - Use `ALTER SESSION SET CONSISTENCY = 'TIMELINE’` - Set the connection property `Consistency` to `timeline` in the JDBC connect string === More Information See the Performance section <> for more information about operational and performance schema design options, such as Bloom Filters, Table-configured regionsizes, compression, and blocksizes. ",16156,True,2596.7096749639063,median "------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- C H E C K S -- -- -- -- S p e c -- -- -- -- Copyright (C) 1992-2020, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNAT; see file COPYING3. If not, go to -- -- http://www.gnu.org/licenses for a complete copy of the license. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ -- Package containing routines used to deal with run-time checks. These -- routines are used both by the semantics and by the expander. In some -- cases, checks are enabled simply by setting a flag for the back end, -- and in other cases the code for the check is expanded. -- The approach used for range and length checks, in regards to suppressed -- checks, is to attempt to detect at compilation time that a constraint -- error will occur. If this is detected a warning or error is issued and the -- offending expression or statement replaced with a constraint error node. -- This always occurs whether checks are suppressed or not. Dynamic range -- checks are, of course, not inserted if checks are suppressed. with Errout; use Errout; with Namet; use Namet; with Table; with Types; use Types; with Uintp; use Uintp; with Urealp; use Urealp; package Checks is procedure Initialize; -- Called for each new main source program, to initialize internal -- variables used in the package body of the Checks unit. function Access_Checks_Suppressed (E : Entity_Id) return Boolean; function Accessibility_Checks_Suppressed (E : Entity_Id) return Boolean; function Alignment_Checks_Suppressed (E : Entity_Id) return Boolean; function Allocation_Checks_Suppressed (E : Entity_Id) return Boolean; function Atomic_Synchronization_Disabled (E : Entity_Id) return Boolean; function Discriminant_Checks_Suppressed (E : Entity_Id) return Boolean; function Division_Checks_Suppressed (E : Entity_Id) return Boolean; function Duplicated_Tag_Checks_Suppressed (E : Entity_Id) return Boolean; function Elaboration_Checks_Suppressed (E : Entity_Id) return Boolean; function Index_Checks_Suppressed (E : Entity_Id) return Boolean; function Length_Checks_Suppressed (E : Entity_Id) return Boolean; function Overflow_Checks_Suppressed (E : Entity_Id) return Boolean; function Predicate_Checks_Suppressed (E : Entity_Id) return Boolean; function Range_Checks_Suppressed (E : Entity_Id) return Boolean; function Storage_Checks_Suppressed (E : Entity_Id) return Boolean; function Tag_Checks_Suppressed (E : Entity_Id) return Boolean; function Validity_Checks_Suppressed (E : Entity_Id) return Boolean; -- These functions check to see if the named check is suppressed, either -- by an active scope suppress setting, or because the check has been -- specifically suppressed for the given entity. If no entity is relevant -- for the current check, then Empty is used as an argument. Note: the -- reason we insist on specifying Empty is to force the caller to think -- about whether there is any relevant entity that should be checked. function Is_Check_Suppressed (E : Entity_Id; C : Check_Id) return Boolean; -- This function is called if Checks_May_Be_Suppressed (E) is True to -- determine whether check C is suppressed either on the entity E or -- as the result of a scope suppress pragma. If Checks_May_Be_Suppressed -- is False, then the status of the check can be determined simply by -- examining Scope_Suppress, so this routine is not called in that case. function Overflow_Check_Mode return Overflow_Mode_Type; -- Returns current overflow checking mode, taking into account whether -- we are inside an assertion expression and the assertion policy. ----------------------------------------- -- Control of Alignment Check Warnings -- ----------------------------------------- -- When we have address clauses, there is an issue of whether the address -- specified is appropriate to the alignment. In the general case where the -- address is dynamic, we generate a check and a possible warning (this -- warning occurs for example if we have a restricted runtime with the -- restriction No_Exception_Propagation). We also issue this warning in -- the case where the address is static, but we don't know the alignment -- at the time we process the address clause. In such a case, we issue the -- warning, but we may be able to find out later (after the back end has -- annotated the actual alignment chosen) that the warning was not needed. -- To deal with deleting these potentially annoying warnings, we save the -- warning information in a table, and then delete the warnings in the -- post compilation validation stage if we can tell that the check would -- never fail (in general the back end will also optimize away the check -- in such cases). -- Table used to record information type Alignment_Warnings_Record is record E : Entity_Id; -- Entity whose alignment possibly warrants a warning A : Uint; -- Compile time known value of address clause for which the alignment -- is to be checked once we know the alignment. P : Node_Id; -- Prefix of address clause when it is of the form X'Address W : Error_Msg_Id; -- Id of warning message we might delete end record; package Alignment_Warnings is new Table.Table ( Table_Component_Type => Alignment_Warnings_Record, Table_Index_Type => Int, Table_Low_Bound => 0, Table_Initial => 10, Table_Increment => 200, Table_Name => ""Alignment_Warnings""); procedure Validate_Alignment_Check_Warnings; -- This routine is called after back annotation of type data to delete any -- alignment warnings that turn out to be false alarms, based on knowing -- the actual alignment, and a compile-time known alignment value. ------------------------------------------- -- Procedures to Activate Checking Flags -- ------------------------------------------- procedure Activate_Division_Check (N : Node_Id); pragma Inline (Activate_Division_Check); -- Sets Do_Division_Check flag in node N, and handles possible local raise. -- Always call this routine rather than calling Set_Do_Division_Check to -- set an explicit value of True, to ensure handling the local raise case. procedure Activate_Overflow_Check (N : Node_Id); pragma Inline (Activate_Overflow_Check); -- Sets Do_Overflow_Check flag in node N, and handles possible local raise. -- Always call this routine rather than calling Set_Do_Overflow_Check to -- set an explicit value of True, to ensure handling the local raise case. -- Note that for discrete types, this call has no effect for MOD, REM, and -- unary ""+"" for which overflow is never possible in any case. -- -- Note: for the discrete-type case, it is legitimate to call this routine -- on an unanalyzed node where the Etype field is not set. However, for the -- floating-point case, Etype must be set (to a floating-point type). -- -- For floating-point, we set the flag if we have automatic overflow checks -- on the target, or if Check_Float_Overflow mode is set. For the floating- -- point case, we ignore all the unary operators (""+"", ""-"", and abs) since -- none of these can result in overflow. If there are no overflow checks on -- the target, and Check_Float_Overflow mode is not set, then the call has -- no effect, since in such cases we want to generate NaN's and infinities. procedure Activate_Range_Check (N : Node_Id); pragma Inline (Activate_Range_Check); -- Sets Do_Range_Check flag in node N, and handles possible local raise. -- Always call this routine rather than calling Set_Do_Range_Check to -- set an explicit value of True, to ensure handling the local raise case. -------------------------------- -- Procedures to Apply Checks -- -------------------------------- -- General note on following checks. These checks are always active if -- Expander_Active and not Inside_A_Generic. They are inactive and have -- no effect Inside_A_Generic. In the case where not Expander_Active -- and not Inside_A_Generic, most of them are inactive, but some of them -- operate anyway since they may generate useful compile time warnings. procedure Apply_Access_Check (N : Node_Id); -- Determines whether an expression node requires a run-time access -- check and if so inserts the appropriate run-time check. procedure Apply_Accessibility_Check (N : Node_Id; Typ : Entity_Id; Insert_Node : Node_Id); -- Given a name N denoting an access parameter, emits a run-time -- accessibility check (if necessary), checking that the level of -- the object denoted by the access parameter is not deeper than the -- level of the type Typ. Program_Error is raised if the check fails. -- Insert_Node indicates the node where the check should be inserted. procedure Apply_Address_Clause_Check (E : Entity_Id; N : Node_Id); -- E is the entity for an object which has an address clause. If checks -- are enabled, then this procedure generates a check that the specified -- address has an alignment consistent with the alignment of the object, -- raising PE if this is not the case. The resulting check (if one is -- generated) is prepended to the Actions list of N_Freeze_Entity node N. -- Note that the check references E'Alignment, so it cannot be emitted -- before N (its freeze node), otherwise this would cause an illegal -- access before elaboration error in gigi. For the case of a clear overlay -- situation, we also check that the size of the overlaying object is not -- larger than the overlaid object. procedure Apply_Arithmetic_Overflow_Check (N : Node_Id); -- Handle overflow checking for an arithmetic operator. Also handles the -- cases of ELIMINATED and MINIMIZED overflow checking mode. If the mode -- is one of the latter two, then this routine can also be called with -- an if or case expression node to make sure that we properly handle -- overflow checking for dependent expressions. This routine handles -- front end vs back end overflow checks (in the front end case it expands -- the necessary check). Note that divide is handled separately using -- Apply_Divide_Checks. Node N may or may not have Do_Overflow_Check. -- In STRICT mode, there is nothing to do if this flag is off, but in -- MINIMIZED/ELIMINATED mode we still have to deal with possible use -- of doing operations in Long_Long_Integer or Bignum mode. procedure Apply_Constraint_Check (N : Node_Id; Typ : Entity_Id; No_Sliding : Boolean := False); -- Top-level procedure, calls all the others depending on the class of -- Typ. Checks that expression N satisfies the constraint of type Typ. -- No_Sliding is only relevant for constrained array types, if set to -- True, it checks that indexes are in range. procedure Apply_Discriminant_Check (N : Node_Id; Typ : Entity_Id; Lhs : Node_Id := Empty); -- Given an expression N of a discriminated type, or of an access type -- whose designated type is a discriminanted type, generates a check to -- ensure that the expression can be converted to the subtype given as -- the second parameter. Lhs is empty except in the case of assignments, -- where the target object may be needed to determine the subtype to -- check against (such as the cases of unconstrained formal parameters -- and unconstrained aliased objects). For the case of unconstrained -- formals, the check is performed only if the corresponding actual is -- constrained, i.e., whether Lhs'Constrained is True. procedure Apply_Divide_Checks (N : Node_Id); -- The node kind is N_Op_Divide, N_Op_Mod, or N_Op_Rem if either of the -- flags Do_Division_Check or Do_Overflow_Check is set, then this routine -- ensures that the appropriate checks are made. Note that overflow can -- occur in the signed case for the case of the largest negative number -- divided by minus one. This procedure only applies to Integer types. procedure Apply_Parameter_Aliasing_Checks (Call : Node_Id; Subp : Entity_Id); -- Given a subprogram call Call, add a check to verify that none of the -- actuals overlap. Subp denotes the subprogram being called. procedure Apply_Parameter_Validity_Checks (Subp : Entity_Id); -- Given a subprogram Subp, add both a pre and post condition pragmas that -- verify the proper initialization of scalars in parameters and function -- results. procedure Apply_Predicate_Check (N : Node_Id; Typ : Entity_Id; Fun : Entity_Id := Empty); -- N is an expression to which a predicate check may need to be applied for -- Typ, if Typ has a predicate function. When N is an actual in a call, Fun -- is the function being called, which is used to generate a better warning -- if the call leads to an infinite recursion. procedure Apply_Type_Conversion_Checks (N : Node_Id); -- N is an N_Type_Conversion node. A type conversion actually involves -- two sorts of checks. The first check is the checks that ensures that -- the operand in the type conversion fits onto the base type of the -- subtype it is being converted to (see RM 4.6 (28)-(50)). The second -- check is there to ensure that once the operand has been converted to -- a value of the target type, this converted value meets the -- constraints imposed by the target subtype (see RM 4.6 (51)). procedure Apply_Universal_Integer_Attribute_Checks (N : Node_Id); -- The argument N is an attribute reference node intended for processing -- by gigi. The attribute is one that returns a universal integer, but -- the attribute reference node is currently typed with the expected -- result type. This routine deals with range and overflow checks needed -- to make sure that the universal result is in range. function Build_Discriminant_Checks (N : Node_Id; T_Typ : Entity_Id) return Node_Id; -- Subsidiary routine for Apply_Discriminant_Check. Builds the expression -- that compares discriminants of the expression with discriminants of the -- type. Also used directly for membership tests (see Exp_Ch4.Expand_N_In). function Convert_From_Bignum (N : Node_Id) return Node_Id; -- Returns result of converting node N from Bignum. The returned value is -- not analyzed, the caller takes responsibility for this. Node N must be -- a subexpression node of type Bignum. The result is Long_Long_Integer. function Convert_To_Bignum (N : Node_Id) return Node_Id; -- Returns result of converting node N to Bignum. The returned value is not -- analyzed, the caller takes responsibility for this. Node N must be a -- subexpression node of a signed integer type or Bignum type (if it is -- already a Bignum, the returned value is Relocate_Node (N)). procedure Determine_Range (N : Node_Id; OK : out Boolean; Lo : out Uint; Hi : out Uint; Assume_Valid : Boolean := False); -- N is a node for a subexpression. If N is of a discrete type with no -- error indications, and no other peculiarities (e.g. missing Etype), -- then OK is True on return, and Lo and Hi are set to a conservative -- estimate of the possible range of values of N. Thus if OK is True on -- return, the value of the subexpression N is known to lie in the range -- Lo .. Hi (inclusive). For enumeration and character literals the values -- returned are the Pos value in the relevant enumeration type. If the -- expression is not of a discrete type, or some kind of error condition -- is detected, then OK is False on exit, and Lo/Hi are set to No_Uint. -- Thus the significance of OK being False on return is that no useful -- information is available on the range of the expression. Assume_Valid -- determines whether the processing is allowed to assume that values are -- in range of their subtypes. If it is set to True, then this assumption -- is valid, if False, then processing is done using base types to allow -- invalid values. procedure Determine_Range_R (N : Node_Id; OK : out Boolean; Lo : out Ureal; Hi : out Ureal; Assume_Valid : Boolean := False); -- Similar to Determine_Range, but for a node N of floating-point type. OK -- is True on return only for IEEE floating-point types and only if we do -- not have to worry about extended precision (i.e. on the x86, we must be -- using -msse2 -mfpmath=sse). At the current time, this is used only in -- GNATprove, though we could consider using it more generally in future. -- For that to happen, the possibility of arguments of infinite or NaN -- value should be taken into account, which is not the case currently. procedure Install_Null_Excluding_Check (N : Node_Id); -- Determines whether an access node requires a run-time access check and -- if so inserts the appropriate run-time check. procedure Install_Primitive_Elaboration_Check (Subp_Body : Node_Id); -- Insert a check which ensures that subprogram body Subp_Body has been -- properly elaborated. The check is installed only when Subp_Body is the -- body of a nonabstract library-level primitive of a tagged type. Further -- restrictions may apply, see the body for details. function Make_Bignum_Block (Loc : Source_Ptr) return Node_Id; -- This function is used by top level overflow checking routines to do a -- mark/release operation on the secondary stack around bignum operations. -- The block created looks like: -- -- declare -- M : Mark_Id := SS_Mark; -- begin -- SS_Release (M); -- end; -- -- The idea is that the caller will insert any needed extra declarations -- after the declaration of M, and any needed statements (in particular -- the bignum operations) before the call to SS_Release, and then do an -- Insert_Action of the whole block (it is returned unanalyzed). The Loc -- parameter is used to supply Sloc values for the constructed tree. procedure Minimize_Eliminate_Overflows (N : Node_Id; Lo : out Uint; Hi : out Uint; Top_Level : Boolean); -- This is the main routine for handling MINIMIZED and ELIMINATED overflow -- processing. On entry N is a node whose result is a signed integer -- subtype. The Do_Overflow_Check flag may or may not be set on N. If the -- node is an arithmetic operation, then a range analysis is carried out, -- and there are three possibilities: -- -- The node is left unchanged (apart from expansion of an exponentiation -- operation). This happens if the routine can determine that the result -- is definitely in range. The Do_Overflow_Check flag is turned off in -- this case. -- -- The node is transformed into an arithmetic operation with a result -- type of Long_Long_Integer. -- -- The node is transformed into a function call that calls an appropriate -- function in the System.Bignums package to compute a Bignum result. -- -- In the first two cases, Lo and Hi are set to the bounds of the possible -- range of results, computed as accurately as possible. In the third case -- Lo and Hi are set to No_Uint (there are some cases where we could get an -- advantage from keeping result ranges for Bignum values, but it could use -- a lot of space and is very unlikely to be valuable). -- -- If the node is not an arithmetic operation, then it is unchanged but -- Lo and Hi are still set (to the bounds of the result subtype if nothing -- better can be determined). -- -- Note: this function is recursive, if called with an arithmetic operator, -- recursive calls are made to process the operands using this procedure. -- So we end up doing things top down. Nothing happens to an arithmetic -- expression until this procedure is called on the top level node and -- then the recursive calls process all the children. We have to do it -- this way. If we try to do it bottom up in natural expansion order, then -- there are two problems. First, where do we stash the bounds, and more -- importantly, semantic processing will be messed up. Consider A+B+C where -- A,B,C are all of type integer, if we processed A+B before doing semantic -- analysis of the addition of this result to C, that addition could end up -- with a Long_Long_Integer left operand and an Integer right operand, and -- we would get a semantic error. -- -- The routine is called in three situations if we are operating in either -- MINIMIZED or ELIMINATED modes. -- -- Overflow processing applied to the top node of an expression tree when -- that node is an arithmetic operator. In this case the result is -- converted to the appropriate result type (there is special processing -- when the parent is a conversion, see body for details). -- -- Overflow processing applied to the operands of a comparison operation. -- In this case, the comparison is done on the result Long_Long_Integer -- or Bignum values, without raising any exceptions. -- -- Overflow processing applied to the left operand of a membership test. -- In this case no exception is raised if a Long_Long_Integer or Bignum -- result is outside the range of the type of that left operand (it is -- just that the result of IN is false in that case). -- -- Note that if Bignum values appear, the caller must take care of doing -- the appropriate mark/release operations on the secondary stack. -- -- Top_Level is used to avoid inefficient unnecessary transitions into the -- Bignum domain. If Top_Level is True, it means that the caller will have -- to convert any Bignum value back to Long_Long_Integer, possibly checking -- that the value is in range. This is the normal case for a top level -- operator in a subexpression. There is no point in going into Bignum mode -- to avoid an overflow just so we can check for overflow the next moment. -- For calls from comparisons and membership tests, and for all recursive -- calls, we do want to transition into the Bignum domain if necessary. -- Note that this setting is only relevant in ELIMINATED mode. ------------------------------------------------------- -- Control and Optimization of Range/Overflow Checks -- ------------------------------------------------------- -- Range checks are controlled by the Do_Range_Check flag. The front end -- is responsible for setting this flag in relevant nodes. Originally the -- back end generated all the corresponding range checks, but later on we -- decided to generate all the range checks in the front end and this is -- the current situation. -- Overflow checks are similarly controlled by the Do_Overflow_Check flag. -- The difference here is that if back end overflow checks are inactive -- (Backend_Overflow_Checks_On_Target set False), then the actual overflow -- checks are generated by the front end, but if back end overflow checks -- are active (Backend_Overflow_Checks_On_Target set True), then the back -- end does generate the checks. -- The following two routines are used to set these flags, they allow -- for the possibility of eliminating checks. Checks can be eliminated -- if an identical check has already been performed. procedure Enable_Overflow_Check (N : Node_Id); -- First this routine determines if an overflow check is needed by doing -- an appropriate range check. If a check is not needed, then the call -- has no effect. If a check is needed then this routine sets the flag -- Do_Overflow_Check in node N to True, unless it can be determined that -- the check is not needed. The only condition under which this is the -- case is if there was an identical check earlier on. procedure Enable_Range_Check (N : Node_Id); -- Set Do_Range_Check flag in node N True, unless it can be determined -- that the check is not needed. The only condition under which this is -- the case is if there was an identical check earlier on. This routine -- is not responsible for doing range analysis to determine whether or -- not such a check is needed -- the caller is expected to do this. The -- one other case in which the request to set the flag is ignored is -- when Kill_Range_Check is set in an N_Unchecked_Conversion node. -- The following routines are used to keep track of processing sequences -- of statements (e.g. the THEN statements of an IF statement). A check -- that appears within such a sequence can eliminate an identical check -- within this sequence of statements. However, after the end of the -- sequence of statements, such a check is no longer of interest, since -- it may not have been executed. procedure Conditional_Statements_Begin; -- This call marks the start of processing of a sequence of statements. -- Every call to this procedure must be followed by a matching call to -- Conditional_Statements_End. procedure Conditional_Statements_End; -- This call removes from consideration all saved checks since the -- corresponding call to Conditional_Statements_Begin. These two -- procedures operate in a stack like manner. -- The mechanism for optimizing checks works by remembering checks -- that have already been made, but certain conditions, for example -- an assignment to a variable involved in a check, may mean that the -- remembered check is no longer valid, in the sense that if the same -- expression appears again, another check is required because the -- value may have changed. -- The following routines are used to note conditions which may render -- some or all of the stored and remembered checks to be invalidated. procedure Kill_Checks (V : Entity_Id); -- This procedure records an assignment or other condition that causes -- the value of the variable to be changed, invalidating any stored -- checks that reference the value. Note that all such checks must -- be discarded, even if they are not in the current statement range. procedure Kill_All_Checks; -- This procedure kills all remembered checks ----------------------------- -- Length and Range Checks -- ----------------------------- -- In the following procedures, there are three arguments which have -- a common meaning as follows: -- Expr The expression to be checked. If a check is required, -- the appropriate flag will be placed on this node. Whether -- this node is further examined depends on the setting of -- the parameter Source_Typ, as described below. -- Target_Typ The target type on which the check is to be based. For -- example, if we have a scalar range check, then the check -- is that we are in range of this type. -- Source_Typ Normally Empty, but can be set to a type, in which case -- this type is used for the check, see below. -- The checks operate in one of two modes: -- If Source_Typ is Empty, then the node Expr is examined, at the very -- least to get the source subtype. In addition for some of the checks, -- the actual form of the node may be examined. For example, a node of -- type Integer whose actual form is an Integer conversion from a type -- with range 0 .. 3 can be determined to have a value in range 0 .. 3. -- If Source_Typ is given, then nothing can be assumed about the Expr, -- and indeed its contents are not examined. In this case the check is -- based on the assumption that Expr can be an arbitrary value of the -- given Source_Typ. -- Currently, the only case in which a Source_Typ is explicitly supplied -- is for the case of Out and In_Out parameters, where, for the conversion -- on return (the Out direction), the types must be reversed. This is -- handled by the caller. procedure Apply_Length_Check (Expr : Node_Id; Target_Typ : Entity_Id; Source_Typ : Entity_Id := Empty); -- This procedure builds a sequence of declarations to do a length check -- that checks if the lengths of the two arrays Target_Typ and source type -- are the same. The resulting actions are inserted at Node using a call -- to Insert_Actions. -- -- For access types, the Directly_Designated_Type is retrieved and -- processing continues as enumerated above, with a guard against null -- values. -- -- Note: calls to Apply_Length_Check currently never supply an explicit -- Source_Typ parameter, but Apply_Length_Check takes this parameter and -- processes it as described above for consistency with the other routines -- in this section. procedure Apply_Length_Check_On_Assignment (Expr : Node_Id; Target_Typ : Entity_Id; Target : Node_Id; Source_Typ : Entity_Id := Empty); -- Similar to Apply_Length_Check, but takes the target of an assignment for -- which the check is to be done. Used to filter out specific cases where -- the check is superfluous. procedure Apply_Static_Length_Check (Expr : Node_Id; Target_Typ : Entity_Id; Source_Typ : Entity_Id := Empty); -- Tries to determine statically whether the two array types source type -- and Target_Typ have the same length. If it can be determined at compile -- time that they do not, then an N_Raise_Constraint_Error node replaces -- Expr, and a warning message is issued. procedure Apply_Range_Check (Expr : Node_Id; Target_Typ : Entity_Id; Source_Typ : Entity_Id := Empty; Insert_Node : Node_Id := Empty); -- For a Node of kind N_Range, constructs a range check action that tests -- first that the range is not null and then that the range is contained in -- the Target_Typ range. -- -- For scalar types, constructs a range check action that first tests that -- the expression is contained in the Target_Typ range. The difference -- between this and Apply_Scalar_Range_Check is that the latter generates -- the actual checking code against the Etype of the expression. -- -- For constrained array types, construct series of range check actions -- to check that each Expr range is properly contained in the range of -- Target_Typ. -- -- For a type conversion to an unconstrained array type, constructs a range -- check action to check that the bounds of the source type are within the -- constraints imposed by the Target_Typ. -- -- For access types, the Directly_Designated_Type is retrieved and -- processing continues as enumerated above, with a guard against null -- values. -- -- The source type is used by type conversions to unconstrained array -- types to retrieve the corresponding bounds. -- Insert_Node indicates the node where the check should be inserted. -- If it is empty, then the check is inserted directly at Expr instead. procedure Apply_Scalar_Range_Check (Expr : Node_Id; Target_Typ : Entity_Id; Source_Typ : Entity_Id := Empty; Fixed_Int : Boolean := False); -- For scalar types, determines whether an expression node should be -- flagged as needing a run-time range check. If the node requires such a -- check, the Do_Range_Check flag is turned on. The Fixed_Int flag if set -- causes any fixed-point values to be treated as though they were discrete -- values (i.e. the underlying integer value is used). type Check_Result is private; -- Type used to return result of Get_Range_Checks call, for later use in -- call to Insert_Range_Checks procedure. function Get_Range_Checks (Expr : Node_Id; Target_Typ : Entity_Id; Source_Typ : Entity_Id := Empty; Warn_Node : Node_Id := Empty) return Check_Result; -- Like Apply_Range_Check, except it does not modify anything. Instead -- it returns an encapsulated result of the check operations for later -- use in a call to Insert_Range_Checks. If Warn_Node is non-empty, its -- Sloc is used, in the static case, for the generated warning or error. -- Additionally, it is used rather than Expr (or Low/High_Bound of Expr) -- in constructing the check. procedure Append_Range_Checks (Checks : Check_Result; Stmts : List_Id; Suppress_Typ : Entity_Id; Static_Sloc : Source_Ptr); -- Called to append range checks as returned by a call to Get_Range_Checks. -- Stmts is a list to which either the dynamic check is appended or the -- raise Constraint_Error statement is appended (for static checks). -- Suppress_Typ is the type to check to determine if checks are suppressed. -- Static_Sloc is the Sloc at which the raise CE node points. procedure Insert_Range_Checks (Checks : Check_Result; Node : Node_Id; Suppress_Typ : Entity_Id; Static_Sloc : Source_Ptr; Do_Before : Boolean := False); -- Called to insert range checks as returned by a call to Get_Range_Checks. -- Node is the node after which either the dynamic check is inserted or -- the raise Constraint_Error statement is inserted (for static checks). -- Suppress_Typ is the type to check to determine if checks are suppressed. -- Static_Sloc is the Sloc at which the raise CE node points. Normally the -- checks are inserted after Node; if Do_Before is True, they are before. ----------------------- -- Expander Routines -- ----------------------- -- In most cases, the processing for range checks done by semantic analysis -- only results in setting the Do_Range_Check flag, rather than actually -- generating checks. The following routines must be called later on in the -- expansion process upon seeing the Do_Range_Check flag; they generate the -- actual checks and reset the flag. The remaining cases where range checks -- are still directly generated during semantic analysis occur as part of -- the processing of constraints in (sub)type and object declarations. procedure Generate_Range_Check (N : Node_Id; Target_Type : Entity_Id; Reason : RT_Exception_Code); -- This procedure is called to actually generate and insert a range check. -- A check is generated to ensure that the value of N lies within the range -- of the target type. Note that the base type of N may be different from -- the base type of the target type. This happens in the conversion case. -- The Reason parameter is the exception code to be used for the exception -- if raised. -- -- Note: if the expander is not active, or if we are in GNATprove mode, -- then we do not generate explicit range checks. Instead we just turn the -- Do_Range_Check flag on, since in these cases that's what we want to see -- in the tree (GNATprove in particular depends on this flag being set). If -- we generate the actual range checks, then we make sure the flag is off -- afterward, since the code we generate takes complete care of the checks. -- -- Historical note: We used to just pass on the Do_Range_Check flag to the -- back end to generate the check, but now in code-generation mode we never -- have this flag set, since the front end takes care of the check. The -- normal processing flow now is that the analyzer typically turns on the -- Do_Range_Check flag, and if it is set, this routine is called, which -- turns the flag off in code-generation mode. procedure Generate_Index_Checks (N : Node_Id); -- This procedure is called to generate index checks on the subscripts for -- the indexed component node N. Each subscript expression is examined, and -- if the Do_Range_Check flag is set, an appropriate index check is -- generated and the flag is reset. -- Similarly, we set the flag Do_Discriminant_Check in the semantic -- analysis to indicate that a discriminant check is required for selected -- component of a discriminated type. The following routine is called from -- the expander to actually generate the call. procedure Generate_Discriminant_Check (N : Node_Id); -- N is a selected component for which a discriminant check is required to -- make sure that the discriminants have appropriate values for the -- selection. This is done by calling the appropriate discriminant checking -- routine for the selector. ----------------------- -- Validity Checking -- ----------------------- -- In (RM 13.9.1(9-11)) we have the following rules on invalid values -- If the representation of a scalar object does not represent value of -- the object's subtype (perhaps because the object was not initialized), -- the object is said to have an invalid representation. It is a bounded -- error to evaluate the value of such an object. If the error is -- detected, either Constraint_Error or Program_Error is raised. -- Otherwise, execution continues using the invalid representation. The -- rules of the language outside this subclause assume that all objects -- have valid representations. The semantics of operations on invalid -- representations are as follows: -- -- 10 If the representation of the object represents a value of the -- object's type, the value of the type is used. -- -- 11 If the representation of the object does not represent a value -- of the object's type, the semantics of operations on such -- representations is implementation-defined, but does not by -- itself lead to erroneous or unpredictable execution, or to -- other objects becoming abnormal. -- We quote the rules in full here since they are quite delicate. Most -- of the time, we can just compute away with wrong values, and get a -- possibly wrong result, which is well within the range of allowed -- implementation defined behavior. The two tricky cases are subscripted -- array assignments, where we don't want to do wild stores, and case -- statements where we don't want to do wild jumps. -- In GNAT, we control validity checking with a switch -gnatV that can take -- three parameters, n/d/f for None/Default/Full. These modes have the -- following meanings: -- None (no validity checking) -- In this mode, there is no specific checking for invalid values -- and the code generator assumes that all stored values are always -- within the bounds of the object subtype. The consequences are as -- follows: -- For case statements, an out of range invalid value will cause -- Constraint_Error to be raised, or an arbitrary one of the case -- alternatives will be executed. Wild jumps cannot result even -- in this mode, since we always do a range check -- For subscripted array assignments, wild stores will result in -- the expected manner when addresses are calculated using values -- of subscripts that are out of range. -- It could perhaps be argued that this mode is still conformant with -- the letter of the RM, since implementation defined is a rather -- broad category, but certainly it is not in the spirit of the -- RM requirement, since wild stores certainly seem to be a case of -- erroneous behavior. -- Default (default standard RM-compatible validity checking) -- In this mode, which is the default, minimal validity checking is -- performed to ensure no erroneous behavior as follows: -- For case statements, an out of range invalid value will cause -- Constraint_Error to be raised. -- For subscripted array assignments, invalid out of range -- subscript values will cause Constraint_Error to be raised. -- Full (Full validity checking) -- In this mode, the protections guaranteed by the standard mode are -- in place, and the following additional checks are made: -- For every assignment, the right side is checked for validity -- For every call, IN and IN OUT parameters are checked for validity -- For every subscripted array reference, both for stores and loads, -- all subscripts are checked for validity. -- These checks are not required by the RM, but will in practice -- improve the detection of uninitialized variables, particularly -- if used in conjunction with pragma Normalize_Scalars. -- In the above description, we talk about performing validity checks, -- but we don't actually generate a check in a case where the compiler -- can be sure that the value is valid. Note that this assurance must -- be achieved without assuming that any uninitialized value lies within -- the range of its type. The following are cases in which values are -- known to be valid. The flag Is_Known_Valid is used to keep track of -- some of these cases. -- If all possible stored values are valid, then any uninitialized -- value must be valid. -- Literals, including enumeration literals, are clearly always valid -- Constants are always assumed valid, with a validity check being -- performed on the initializing value where necessary to ensure that -- this is the case. -- For variables, the status is set to known valid if there is an -- initializing expression. Again a check is made on the initializing -- value if necessary to ensure that this assumption is valid. The -- status can change as a result of local assignments to a variable. -- If a known valid value is unconditionally assigned, then we mark -- the left side as known valid. If a value is assigned that is not -- known to be valid, then we mark the left side as invalid. This -- kind of processing does NOT apply to non-local variables since we -- are not following the flow graph (more properly the flow of actual -- processing only corresponds to the flow graph for local assignments). -- For non-local variables, we preserve the current setting, i.e. a -- validity check is performed when assigning to a knonwn valid global. -- Note: no validity checking is required if range checks are suppressed -- regardless of the setting of the validity checking mode. -- The following procedures are used in handling validity checking procedure Apply_Subscript_Validity_Checks (Expr : Node_Id); -- Expr is the node for an indexed component. If validity checking and -- range checking are enabled, all subscripts for this indexed component -- are checked for validity. procedure Check_Valid_Lvalue_Subscripts (Expr : Node_Id); -- Expr is a lvalue, i.e. an expression representing the target of an -- assignment. This procedure checks for this expression involving an -- assignment to an array value. We have to be sure that all the subscripts -- in such a case are valid, since according to the rules in (RM -- 13.9.1(9-11)) such assignments are not permitted to result in erroneous -- behavior in the case of invalid subscript values. procedure Ensure_Valid (Expr : Node_Id; Holes_OK : Boolean := False; Related_Id : Entity_Id := Empty; Is_Low_Bound : Boolean := False; Is_High_Bound : Boolean := False); -- Ensure that Expr represents a valid value of its type. If this type -- is not a scalar type, then the call has no effect, since validity -- is only an issue for scalar types. The effect of this call is to -- check if the value is known valid, if so, nothing needs to be done. -- If this is not known, then either Expr is set to be range checked, -- or specific checking code is inserted so that an exception is raised -- if the value is not valid. -- -- The optional argument Holes_OK indicates whether it is necessary to -- worry about enumeration types with non-standard representations leading -- to ""holes"" in the range of possible representations. If Holes_OK is -- True, then such values are assumed valid (this is used when the caller -- will make a separate check for this case anyway). If Holes_OK is False, -- then this case is checked, and code is inserted to ensure that Expr is -- valid, raising Constraint_Error if the value is not valid. -- -- Related_Id denotes the entity of the context where Expr appears. Flags -- Is_Low_Bound and Is_High_Bound specify whether the expression to check -- is the low or the high bound of a range. These three optional arguments -- signal Remove_Side_Effects to create an external symbol of the form -- Chars (Related_Id)_FIRST/_LAST. For suggested use of these parameters -- see the warning in the body of Sem_Ch3.Process_Range_Expr_In_Decl. function Expr_Known_Valid (Expr : Node_Id) return Boolean; -- This function tests it the value of Expr is known to be valid in the -- sense of RM 13.9.1(9-11). In the case of GNAT, it is only discrete types -- which are a concern, since for non-discrete types we simply continue -- computation with invalid values, which does not lead to erroneous -- behavior. Thus Expr_Known_Valid always returns True if the type of Expr -- is non-discrete. For discrete types the value returned is True only if -- it can be determined that the value is Valid. Otherwise False is -- returned. procedure Insert_Valid_Check (Expr : Node_Id; Related_Id : Entity_Id := Empty; Is_Low_Bound : Boolean := False; Is_High_Bound : Boolean := False); -- Inserts code that will check for the value of Expr being valid, in the -- sense of the 'Valid attribute returning True. Constraint_Error will be -- raised if the value is not valid. -- -- Related_Id denotes the entity of the context where Expr appears. Flags -- Is_Low_Bound and Is_High_Bound specify whether the expression to check -- is the low or the high bound of a range. These three optional arguments -- signal Remove_Side_Effects to create an external symbol of the form -- Chars (Related_Id)_FIRST/_LAST. For suggested use of these parameters -- see the warning in the body of Sem_Ch3.Process_Range_Expr_In_Decl. procedure Null_Exclusion_Static_Checks (N : Node_Id; Comp : Node_Id := Empty; Array_Comp : Boolean := False); -- Ada 2005 (AI-231): Test for and warn on null-excluding objects or -- components that will raise an exception due to initialization by null. -- -- When a value for Comp is supplied (as in the case of an uninitialized -- null-excluding component within a composite object), a reported warning -- will indicate the offending component instead of the object itself. -- Array_Comp being True indicates an array object with null-excluding -- components, and any reported warning will indicate that. procedure Remove_Checks (Expr : Node_Id); -- Remove all checks from Expr except those that are only executed -- conditionally (on the right side of And Then/Or Else. This call -- removes only embedded checks (Do_Range_Check, Do_Overflow_Check). procedure Validity_Check_Range (N : Node_Id; Related_Id : Entity_Id := Empty); -- If N is an N_Range node, then Ensure_Valid is called on its bounds, if -- validity checking of operands is enabled. Related_Id denotes the entity -- of the context where N appears. ----------------------------- -- Handling of Check Names -- ----------------------------- -- The following table contains Name_Id's for recognized checks. The first -- entries (corresponding to the values of the subtype Predefined_Check_Id) -- contain the Name_Id values for the checks that are predefined, including -- All_Checks (see Types). Remaining entries are those that are introduced -- by pragma Check_Names. package Check_Names is new Table.Table ( Table_Component_Type => Name_Id, Table_Index_Type => Check_Id, Table_Low_Bound => 1, Table_Initial => 30, Table_Increment => 200, Table_Name => ""Name_Check_Names""); function Get_Check_Id (N : Name_Id) return Check_Id; -- Function to search above table for matching name. If found returns the -- corresponding Check_Id value in the range 1 .. Check_Name.Last. If not -- found returns No_Check_Id. private type Check_Result is array (Positive range 1 .. 2) of Node_Id; -- There are two cases for the result returned by Range_Check: -- -- For the static case the result is one or two nodes that should cause -- a Constraint_Error. Typically these will include Expr itself or the -- direct descendants of Expr, such as Low/High_Bound (Expr)). It is the -- responsibility of the caller to rewrite and substitute the nodes with -- N_Raise_Constraint_Error nodes. -- -- For the non-static case a single N_Raise_Constraint_Error node with a -- non-empty Condition field is returned. -- -- Unused entries in Check_Result, if any, are simply set to Empty For -- external clients, the required processing on this result is achieved -- using the Insert_Range_Checks routine. pragma Inline (Apply_Length_Check); pragma Inline (Apply_Range_Check); pragma Inline (Apply_Static_Length_Check); end Checks; ",12078,False,2424.3218289710394,median ":sectnums: == NEORV32 Central Processing Unit (CPU) image::riscv_logo.png[width=350,align=center] **Key Features** * 32-bit multi-cycle in-order `rv32` RISC-V CPU * Optional RISC-V extensions: ** `A` - atomic memory access operations ** `B` - bit-manipulation instructions ** `C` - 16-bit compressed instructions ** `I` - integer base ISA (always enabled) ** `E` - embedded CPU version (reduced register file size) ** `M` - integer multiplication and division hardware ** `U` - less-privileged _user_ mode ** `Zfinx` - single-precision floating-point unit ** `Zicsr` - control and status register access (privileged architecture) ** `Zicntr` - CPU base counters ** `Zihpm` - hardware performance monitors ** `Zifencei` - instruction stream synchronization ** `Zmmul` - integer multiplication hardware ** `PMP` - physical memory protection ** `Debug` - debug mode * Compatible to the RISC-V user specifications and a subset of the RISC-V privileged architecture specifications - passes the official RISC-V Architecture Tests (v2+) * Official RISC-V open-source architecture ID * Standard RISC-V interrupts (_external_, _timer_, _software_) plus 16 _fast_ interrupts * Supports _all_ of the machine-level traps from the RISC-V specifications (including bus access exceptions and all unimplemented/illegal/malformed instructions) ** This is a special aspect on _execution safety_ by <<_full_virtualization>> * Optional physical memory configuration (PMP), compatible to the RISC-V specifications * Optional hardware performance monitors (HPM) for application benchmarking * Separated interfaces for instruction fetch and data access (merged into a single processor bus)) * little-endian byte order * Configurable hardware reset * No hardware support of unaligned data/instruction accesses - they will trigger an exception. [NOTE] It is recommended to use the **NEORV32 Processor** as default top instance even if you only want to use the actual CPU. Simply disable all the processor-internal modules via the generics and you will get a ""CPU wrapper"" that provides a minimal CPU environment and an external bus interface (like AXI4). This setup also allows to further use the default bootloader and software framework. From this base you can start building your own SoC. Of course you can also use the CPU in it’s true stand-alone mode. [NOTE] This documentation assumes the reader is familiar with the official RISC-V ""User"" and ""Privileged Architecture"" specifications. <<< // #################################################################################################################### :sectnums: === Architecture The NEORV32 CPU was designed from scratch based only on the official ISA / privileged architecture specifications. The following figure shows the simplified architecture of the CPU. image::neorv32_cpu.png[align=center] The CPU implements a _multi-cycle_ architecture. Hence, each instruction is executed as a series of consecutive micro-operations. In order to increase performance, the CPU's **front-end** (instruction fetch) and **back-end** (instruction execution) are de-couples via a FIFO (the ""instruction prefetch buffer""). Therefore, the front-end can already fetch new instructions while the back-end is still processing previously-fetched instructions. The front-end is responsible for fetching 32-bit chunks of instruction words (one aligned 32-bit instruction, two 16-bit instructions or a mixture if 32-bit instructions are not aligned to 32-bit boundaries). The instruction data is stored to a FIFO queue - the instruction prefetch buffer. The back-end is responsible for the actual execution of the instruction. It includes an ""issue engine"", which takes data from the instruction prefetch buffer and assembles 32-bit instruction words (plain 32-bit instruction or decompressed 16-bit instructions) for execution. Front-end and back-end operate in parallel and with overlapping operations. Hence, the optimal CPI (cycles per instructions) is 2, but it can be significantly higher: for instance when executing loads/stores (accessing memory-mapped devices with high latency), executing multi-cycle ALU operations (like divisions) or when the CPU front-end has to reload the prefetch buffer due to a taken branch. Basically, the NEORV32 CPU is somewhere between a classical pipelined architecture, where each stage requires exactly one processing cycle (if not stalled) and a classical multi-cycle architecture, which executes every single instruction (_including_ fetch) in a series of consecutive micro-operations. The combination of these two classical design paradigms allows an increased instruction execution in contrast to a pure multi-cycle approach (due to overlapping operation of fetch and execute) at a reduced hardware footprint (due to the multi-cycle concept). As a Von-Neumann machine, the CPU provides independent interfaces for instruction fetch and data access. These two bus interfaces are merged into a single processor-internal bus via a prioritizing bus switch (data accesses have higher priority). Hence, ALL memory locations including peripheral devices are mapped to a single unified 32-bit address space. // #################################################################################################################### :sectnums: === Full Virtualization Just like the RISC-V ISA the NEORV32 aims to provide _maximum virtualization_ capabilities on CPU _and_ SoC level to allow a high standard of **execution safety**. The CPU supports **all** traps specified by the official RISC-V specifications. footnote:[If the `Zicsr` CPU extension is enabled (implementing the full set of the privileged architecture).] Thus, the CPU provides defined hardware fall-backs via traps for any expected and unexpected situation (e.g. executing an malformed instruction word or accessing a not-allocated memory address). For any kind of trap the core is always in a defined and fully synchronized state throughout the whole architecture (i.e. there are no out-of-order operations that might have to reverted). This allows predictable execution behavior at any time improving overall _execution safety_. **Execution Safety - NEORV32 Virtualization Features** * Due to the acknowledged memory accesses the CPU is _always_ sync with the memory system (i.e. there is no speculative execution / no out-of-order states). * The CPU supports _all_ RISC-V compatible bus exceptions including access exceptions, which are triggered if an accessed address does not respond or encounters an internal error during access. * Accessed memory addresses (plain memory, but also memory-mapped devices) need to respond within a fixed time window. Otherwise a bus access exception is raised. * The RISC-V specs. state that executing an malformed instruction results in unpredictable behavior. As an additional execution safety feature the NEORV32 CPU ensures that _all_ unimplemented/malformed/illegal instructions do raise an illegal instruction exceptions and do not commit any state-changing operation (like writing registers or triggering memory operations). * To be continued... // #################################################################################################################### :sectnums: === RISC-V Compatibility The NEORV32 CPU passes the rv32_m/I, rv32_m/M, rv32_m/C, rv32_m/privilege, and rv32_m/Zifencei tests of the official RISC-V Architecture Tests (GitHub). The port files for the NEORV32 processor are located in the repository's `sw/isa-test` folder. [NOTE] See section https://stnolting.github.io/neorv32/ug/#_risc_v_architecture_test_framework[User Guide: RISC-V Architecture Test Framework] for information how to run the tests on the NEORV32. .**RISC-V `rv32_m/C` Tests** ................................... Check cadd-01 ... OK Check caddi-01 ... OK Check caddi16sp-01 ... OK Check caddi4spn-01 ... OK Check cand-01 ... OK Check candi-01 ... OK Check cbeqz-01 ... OK Check cbnez-01 ... OK Check cebreak-01 ... OK Check cj-01 ... OK Check cjal-01 ... OK Check cjalr-01 ... OK Check cjr-01 ... OK Check cli-01 ... OK Check clui-01 ... OK Check clw-01 ... OK Check clwsp-01 ... OK Check cmv-01 ... OK Check cnop-01 ... OK Check cor-01 ... OK Check cslli-01 ... OK Check csrai-01 ... OK Check csrli-01 ... OK Check csub-01 ... OK Check csw-01 ... OK Check cswsp-01 ... OK Check cxor-01 ... OK -------------------------------- OK: 27/27 RISCV_TARGET=neorv32 RISCV_DEVICE=C XLEN=32 ................................... .**RISC-V `rv32_m/I` Tests** ................................... Check add-01 ... OK Check addi-01 ... OK Check and-01 ... OK Check andi-01 ... OK Check auipc-01 ... OK Check beq-01 ... OK Check bge-01 ... OK Check bgeu-01 ... OK Check blt-01 ... OK Check bltu-01 ... OK Check bne-01 ... OK Check fence-01 ... OK Check jal-01 ... OK Check jalr-01 ... OK Check lb-align-01 ... OK Check lbu-align-01 ... OK Check lh-align-01 ... OK Check lhu-align-01 ... OK Check lui-01 ... OK Check lw-align-01 ... OK Check or-01 ... OK Check ori-01 ... OK Check sb-align-01 ... OK Check sh-align-01 ... OK Check sll-01 ... OK Check slli-01 ... OK Check slt-01 ... OK Check slti-01 ... OK Check sltiu-01 ... OK Check sltu-01 ... OK Check sra-01 ... OK Check srai-01 ... OK Check srl-01 ... OK Check srli-01 ... OK Check sub-01 ... OK Check sw-align-01 ... OK Check xor-01 ... OK Check xori-01 ... OK Check fence-01 ... OK -------------------------------- OK: 39/39 RISCV_TARGET=neorv32 RISCV_DEVICE=I XLEN=32 ................................... .**RISC-V `rv32_m/M` Tests** ................................... Check div-01 ... OK Check divu-01 ... OK Check mul-01 ... OK Check mulh-01 ... OK Check mulhsu-01 ... OK Check mulhu-01 ... OK Check rem-01 ... OK Check remu-01 ... OK -------------------------------- OK: 8/8 RISCV_TARGET=neorv32 RISCV_DEVICE=M XLEN=32 ................................... .**RISC-V `rv32_m/privilege` Tests** ................................... Check ebreak ... OK Check ecall ... OK Check misalign-beq-01 ... OK Check misalign-bge-01 ... OK Check misalign-bgeu-01 ... OK Check misalign-blt-01 ... OK Check misalign-bltu-01 ... OK Check misalign-bne-01 ... OK Check misalign-jal-01 ... OK Check misalign-lh-01 ... OK Check misalign-lhu-01 ... OK Check misalign-lw-01 ... OK Check misalign-sh-01 ... OK Check misalign-sw-01 ... OK Check misalign1-jalr-01 ... OK Check misalign2-jalr-01 ... OK -------------------------------- OK: 16/16 RISCV_TARGET=neorv32 RISCV_DEVICE=privilege XLEN=32 ................................... .**RISC-V `rv32_m/Zifencei` Tests** ................................... Check Fencei ... OK -------------------------------- OK: 1/1 RISCV_TARGET=neorv32 RISCV_DEVICE=Zifencei XLEN=32 ................................... <<< :sectnums: ==== RISC-V Incompatibility Issues and Limitations This list shows the currently identified issues regarding full RISC-V-compatibility. More specific information can be found in section <<_instruction_sets_and_extensions>>. .Read-Only ""Read-Write"" CSRs [IMPORTANT] The `misa` and `mtval` CSRs in the NEORV32 are _read-only_. Any machine-mode write access to them is ignored and will _not_ cause any exceptions or side-effects to maintain RISC-V compatibility. .Physical Memory Protection [IMPORTANT] The physical memory protection (see section <<_machine_physical_memory_protection_csrs>>) only supports the modes _OFF_ and _NAPOT_ yet and a minimal granularity of 8 bytes per region. .Atomic Memory Operations [IMPORTANT] The `A` CPU extension only implements the `lr.w` and `sc.w` instructions yet. However, these instructions are sufficient to emulate all further atomic memory operations. .Bit-Manipulation ISA Extension [IMPORTANT] The NEORV32 `B` extension only implements the _basic bit-manipulation instructions_ (`Zbb`) subset and the _address generation instructions_ (`Zba`) subset yet. <<< // #################################################################################################################### :sectnums: === CPU Top Entity - Signals The following table shows all interface signals of the CPU top entity `rtl/core/neorv32_cpu.vhd`. The type of all signals is _std_ulogic_ or _std_ulogic_vector_, respectively. The ""Dir."" column shows the signal direction seen from the CPU. .NEORV32 CPU top entity signals [cols=""<2,^1,^1,<6""] [options=""header"", grid=""rows""] |======================= | Signal | Width | Dir. | Function 4+^| **Global Signals** | `clk_i` | 1 | in | global clock line, all registers triggering on rising edge | `rstn_i` | 1 | in | global reset, low-active | `sleep_o` | 1 | out | CPU is in sleep mode when set | `debug_o` | 1 | out | CPU is in debug mode when set 4+^| **Instruction Bus Interface (<<_bus_interface>>)** | `i_bus_addr_o` | 32 | out | destination address | `i_bus_rdata_i` | 32 | in | read data | `i_bus_wdata_o` | 32 | out | write data (always zero) | `i_bus_ben_o` | 4 | out | byte enable | `i_bus_we_o` | 1 | out | write transaction (always zero) | `i_bus_re_o` | 1 | out | read transaction | `i_bus_lock_o` | 1 | out | exclusive access request (always zero) | `i_bus_ack_i` | 1 | in | bus transfer acknowledge from accessed peripheral | `i_bus_err_i` | 1 | in | bus transfer terminate from accessed peripheral | `i_bus_fence_o` | 1 | out | indicates an executed _fence.i_ instruction | `i_bus_priv_o` | 2 | out | current CPU privilege level 4+^| **Data Bus Interface (<<_bus_interface>>)** | `d_bus_addr_o` | 32 | out | destination address | `d_bus_rdata_i` | 32 | in | read data | `d_bus_wdata_o` | 32 | out | write data | `d_bus_ben_o` | 4 | out | byte enable | `d_bus_we_o` | 1 | out | write transaction | `d_bus_re_o` | 1 | out | read transaction | `d_bus_lock_o` | 1 | out | exclusive access request | `d_bus_ack_i` | 1 | in | bus transfer acknowledge from accessed peripheral | `d_bus_err_i` | 1 | in | bus transfer terminate from accessed peripheral | `d_bus_fence_o` | 1 | out | indicates an executed _fence_ instruction | `d_bus_priv_o` | 2 | out | current CPU privilege level 4+^| **System Time (see <<_timeh>> CSR)** | `time_i` | 64 | in | system time input (from MTIME) 4+^| **Interrupts, RISC-V-compatible (<<_traps_exceptions_and_interrupts>>)** | `msw_irq_i` | 1 | in | RISC-V machine software interrupt | `mext_irq_i` | 1 | in | RISC-V machine external interrupt | `mtime_irq_i` | 1 | in | RISC-V machine timer interrupt 4+^| **Fast Interrupts, NEORV32-specific (<<_traps_exceptions_and_interrupts>>)** | `firq_i` | 16 | in | fast interrupt request signals 4+^| **Enter Debug Mode Request (<<_on_chip_debugger_ocd>>)** | `db_halt_req_i` | 1 | in | request CPU to halt and enter debug mode |======================= <<< // #################################################################################################################### :sectnums: === CPU Top Entity - Generics Most of the CPU configuration generics are a subset of the actual Processor configuration generics (see section <<_processor_top_entity_generics>>). and are not listed here. However, the CPU provides some _specific_ generics that are used to configure the CPU for the NEORV32 processor setup. These generics are assigned by the processor setup only and are not available for user defined configuration. The _specific_ generics are listed below. [cols=""4,4,2""] [frame=""all"",grid=""none""] |====== | **CPU_BOOT_ADDR** | _std_ulogic_vector(31 downto 0)_ | 0x00000000 3+| This address defines the reset address at which the CPU starts fetching instructions after reset. In terms of the NEORV32 processor, this generic is configured with the base address of the bootloader ROM (default) or with the base address of the processor-internal instruction memory (IMEM) if the bootloader is disabled (_INT_BOOTLOADER_EN_ = _false_). See section <<_address_space>> for more information. |====== [cols=""4,4,2""] [frame=""all"",grid=""none""] |====== | **CPU_DEBUG_ADDR** | _std_ulogic_vector(31 downto 0)_ | 0x00000000 3+| This address defines the entry address for the ""execution based"" on-chip debugger. By default, this generic is configured with the base address of the debugger memory. See section <<_on_chip_debugger_ocd>> for more information. |====== [cols=""4,4,2""] [frame=""all"",grid=""none""] |====== | **CPU_EXTENSION_RISCV_DEBUG** | _boolean_ | false 3+| Implement RISC-V-compatible ""debug"" CPU operation mode. See section <<_cpu_debug_mode>> for more information. |====== <<< // #################################################################################################################### :sectnums: === Instruction Sets and Extensions The basic NEORV32 is a RISC-V `rv32i` architecture that provides several _optional_ RISC-V CPU and ISA (instruction set architecture) extensions. For more information regarding the RISC-V ISA extensions please see the the _RISC-V Instruction Set Manual - Volume I: Unprivileged ISA_ and _The RISC-V Instruction Set Manual Volume II: Privileged Architecture_, which are available in the projects `docs/references` folder. [TIP] The CPU can discover available ISA extensions via the <<_misa>> CSR and the `CPU` <<_system_configuration_information_memory_sysinfo, SYSINFO>> register or by executing an instruction and checking for an _illegal instruction exception_. [NOTE] Executing an instruction from an extension that is not supported yet or that is currently not enabled (via the according top entity generic) will raise an _illegal instruction_ exception. ==== **`A`** - Atomic Memory Access Atomic memory access instructions allow more sophisticated memory operations like implementing semaphores and mutexes. The RICS-C specs. defines a specific _atomic_ extension that provides instructions for atomic memory accesses. The `A` ISA extension is enabled if the `CPU_EXTENSION_RISCV_A` configuration generic is _true_. In this case the following additional instructions are available: * `lr.w`: load-reservate * `sc.w`: store-conditional [NOTE] Even though only `lr.w` and `sc.w` instructions are implemented yet, all further atomic operations (load-modify-write instruction) can be emulated using these two instruction. Furthermore, the instruction's ordering flags (`aq` and `lr`) are ignored by the CPU hardware. Using any other (not yet implemented) AMO (atomic memory operation) will raise an illegal instruction exception. The *load-reservate* instruction behaves as a ""normal"" load-word instruction (`lw`) but will also set a CPU-internal _data memory access lock_. Executing a *store-conditional* behaves as ""normal"" store-word instruction (`sw`) that will only conduct an actual memory write operations if the lock is still intact. Additionally, the store-conditional instruction will also return the lock state (returns zero if the lock is still intact or non-zero if the lock has been broken). After the execution of the `sc` instruction, the lock is automatically removed. The lock is broken if at least one of the following conditions occur: . executing any data memory access instruction other than `lr.w` . raising _any_ t (for example an interrupt or a memory access exception) [NOTE] The atomic instructions have special requirements for memory system / bus interconnect. More information can be found in sections <<_bus_interface>> and <<_processor_external_memory_interface_wishbone_axi4_lite>>, respectively. ==== **`B`** - Bit-Manipulation Operations The `B` ISA extension adds instructions for bit-manipulation operations. This extension is enabled if the `CPU_EXTENSION_RISCV_B` configuration generic is _true_. The official RISC-V specifications can be found here: https://github.com/riscv/riscv-bitmanip [IMPORTANT] The NEORV32 `B` extension only implements the _basic bit-manipulation instructions_ (`Zbb`) subset and the _address generation instructions_ (`Zba`) subset yet. The `Zbb` sub-extension adds the following instruction: * `andn`, `orn`, `xnor` * `clz`, `ctz`, `cpop` * `max`, `maxu`, `min`, `minu` * `sext.b`, `sext.h`, `zext.h` * `rol`, `ror`, `rori` * `orc.b`, `rev8` The `Zba` sub-extension adds the following instruction: * `sh1add`, `sh2add`, `sh3add` [TIP] By default, the bit-manipulation unit uses an _iterative_ approach to compute shift-related operations like `clz` and `rol`. To increase performance (at the cost of additional hardware resources) the <<_fast_shift_en>> generic can be enabled to implement full-parallel logic (like barrel shifters) for all shift-related `B` instructions. [WARNING] The `B` extension is frozen but not officially ratified yet. There is no software support for this extension in the upstream GCC RISC-V port yet. However, an intrinsic library is provided to utilize the provided `B` extension features from C-language code (see `sw/example/bitmanip_test`). ==== **`C`** - Compressed Instructions The _compressed_ ISA extension provides 16-bit encodings of commonly used instructions to reduce code space size. The `C` extension is available when the `CPU_EXTENSION_RISCV_C` configuration generic is _true_. In this case the following instructions are available: * `c.addi4spn`, `c.lw`, `c.sw`, `c.nop`, `c.addi`, `c.jal`, `c.li`, `c.addi16sp`, `c.lui`, `c.srli`, `c.srai` `c.andi`, `c.sub`, `c.xor`, `c.or`, `c.and`, `c.j`, `c.beqz`, `c.bnez`, `c.slli`, `c.lwsp`, `c.jr`, `c.mv`, `c.ebreak`, `c.jalr`, `c.add`, `c.swsp` [NOTE] When the compressed instructions extension is enabled, branches to an _unaligned_ and _uncompressed_ instruction require an additional instruction fetch to load the according second half-word of that instruction. The performance can be increased again by forcing a 32-bit alignment of branch target addresses. By default, this is enforced via the GCC `-falign-functions=4`, `-falign-labels=4`, `-falign-loops=4` and `-falign-jumps=4` compile flags (via the makefile). ==== **`E`** - Embedded CPU The embedded CPU extensions reduces the size of the general purpose register file from 32 entries to 16 entries to decrease physical hardware requirements (for example block RAM). This extensions is enabled when the `CPU_EXTENSION_RISCV_E` configuration generic is _true_. Accesses to registers beyond `x15` will raise and _illegal instruction exception_. This extension does not add any additional instructions or features. [IMPORTANT] Due to the reduced register file size an alternate toolchain ABI (**`ilp32e`**) is required. ==== **`I`** - Base Integer ISA The CPU always supports the complete `rv32i` base integer instruction set. This base set is always enabled regardless of the setting of the remaining exceptions. The base instruction set includes the following instructions: * immediate: `lui`, `auipc` * jumps: `jal`, `jalr` * branches: `beq`, `bne`, `blt`, `bge`, `bltu`, `bgeu` * memory: `lb`, `lh`, `lw`, `lbu`, `lhu`, `sb`, `sh`, `sw` * alu: `addi`, `slti`, `sltiu`, `xori`, `ori`, `andi`, `slli`, `srli`, `srai`, `add`, `sub`, `sll`, `slt`, `sltu`, `xor`, `srl`, `sra`, `or`, `and` * environment: `ecall`, `ebreak`, `fence` [NOTE] In order to keep the hardware footprint low, the CPU's shift unit uses a bit-serial serial approach. Hence, shift operations take up to 32 cycles (plus overhead) depending on the actual shift amount. Alternatively, the shift operations can be processed completely in parallels by a fast (but large) barrel shifter when the `FAST_SHIFT_EN` generic is _true_. In that case, shift operations complete within 2 cycles (plus overhead) regardless of the actual shift amount. [NOTE] Internally, the `fence` instruction does not perform any operation inside the CPU. It only sets the top’s `d_bus_fence_o` signal high for one cycle to inform the memory system a `fence` instruction has been executed. Any flags within the `fence` instruction word are ignore by the hardware. ==== **`M`** - Integer Multiplication and Division Hardware-accelerated integer multiplication and division operations are available when the `CPU_EXTENSION_RISCV_M` configuration generic is _true_. In this case the following instructions are available: * multiplication: `mul`, `mulh`, `mulhsu`, `mulhu` * division: `div`, `divu`, `rem`, `remu` [NOTE] By default, multiplication and division operations are executed in a bit-serial approach. Alternatively, the multiplier core can be implemented using DSP blocks if the `FAST_MUL_EN` generic is _true_ allowing faster execution. Multiplications and divisions always require a fixed amount of cycles to complete - regardless of the input operands. ==== **`Zmmul`** - Integer Multiplication This is a _sub-extension_ of the `M` ISA extension. It implements the multiplication-only operations of the `M` extensions and is intended for size-constrained setups that require hardware-based integer multiplications but not hardware-based divisions, which will be computed entirely in software. This extension requires only ~50% of the hardware utilization of the ""full"" `M` extension. * multiplication: `mul`, `mulh`, `mulhsu`, `mulhu` If `Zmmul` is enabled, executing any division instruction from the `M` ISA extension (`div`, `divu`, `rem`, `remu`) will raise an _illegal instruction exception_. Note that `M` and `Zmmul` extensions _cannot_ be enabled at the same time. [TIP] If your RISC-V GCC toolchain does not (yet) support the `_Zmmul` ISA extensions, it can be ""emulated"" using a `rv32im` machine architecture and setting the `-mno-div` compiler flag (example `$ make MARCH=rv32im USER_FLAGS+=-mno-div clean_all exe`). ==== **`U`** - Less-Privileged User Mode In addition to the basic (and highest-privileged) machine-mode, the _user-mode_ ISA extensions adds a second less-privileged operation mode. It is implemented if the `CPU_EXTENSION_RISCV_U` configuration generic is _true_. Code executed in user-mode cannot access machine-mode CSRs. Furthermore, user-mode access to the address space (like peripheral/IO devices) can be constrained via the physical memory protection (_PMP_). Any kind of privilege rights violation will raise an exception to allow full virtualization. ==== **`X`** - NEORV32-Specific (Custom) Extensions The NEORV32-specific extensions are always enabled and are indicated by the set `X` bit in the `misa` CSR. The most important points of the NEORV32-specific extensions are: * The CPU provides 16 _fast interrupt_ interrupts (`FIRQ)`, which are controlled via custom bits in the `mie` and `mip` CSR. This extension is mapped to CSR bits, that are available for custom use (according to the RISC-V specs). Also, custom trap codes for `mcause` are implemented. * All undefined/unimplemented/malformed/illegal instructions do raise an illegal instruction exception (see <<_full_virtualization>>). ==== **`Zfinx`** Single-Precision Floating-Point Operations The `Zfinx` floating-point extension is an _alternative_ of the standard `F` floating-point ISA extension. The `Zfinx` extensions also uses the integer register file `x` to store and operate on floating-point data instead of a dedicated floating-point register file (hence, `F-in-x`). Thus, the `Zfinx` extension requires less hardware resources and features faster context changes. This also implies that there are NO dedicated `f` register file-related load/store or move instructions. The official RISC-V specifications can be found here: https://github.com/riscv/riscv-zfinx [TIP] The NEORV32 floating-point unit used by the `Zfinx` extension is compatible to the _IEEE-754_ specifications. The `Zfinx` extensions only supports single-precision (`.s` instruction suffix), so it is a direct alternative to the `F` extension. The `Zfinx` extension is implemented when the `CPU_EXTENSION_RISCV_Zfinx` configuration generic is _true_. In this case the following instructions and CSRs are available: * conversion: `fcvt.s.w`, `fcvt.s.wu`, `fcvt.w.s`, `fcvt.wu.s` * comparison: `fmin.s`, `fmax.s`, `feq.s`, `flt.s`, `fle.s` * computational: `fadd.s`, `fsub.s`, `fmul.s` * sign-injection: `fsgnj.s`, `fsgnjn.s`, `fsgnjx.s` * number classification: `fclass.s` * additional CSRs: `fcsr`, `frm`, `fflags` [WARNING] Fused multiply-add instructions `f[n]m[add/sub].s` are not supported! Division `fdiv.s` and square root `fsqrt.s` instructions are not supported yet! [WARNING] Subnormal numbers (""de-normalized"" numbers) are not supported by the NEORV32 FPU. Subnormal numbers (exponent = 0) are _flushed to zero_ setting them to +/- 0 before entering the FPU's processing core. If a computational instruction (like `fmul.s`) generates a subnormal result, the result is also flushed to zero during normalization. [WARNING] The `Zfinx` extension is not yet officially ratified, but is expected to stay unchanged. There is no software support for the `Zfinx` extension in the upstream GCC RISC-V port yet. However, an intrinsic library is provided to utilize the provided `Zfinx` floating-point extension from C-language code (see `sw/example/floating_point_test`). ==== **`Zicsr`** Control and Status Register Access / Privileged Architecture The CSR access instructions as well as the exception and interrupt system (= the privileged architecture) is implemented when the `CPU_EXTENSION_RISCV_Zicsr` configuration generic is _true_. [IMPORTANT] If the `Zicsr` extension is disabled the CPU does not provide any _privileged architecture_ features at all! In order to provide the full set of privileged functions that are required to run more complex tasks like operating system and to allow a secure execution environment the `Zicsr` extension should always be enabled. In this case the following instructions are available: * CSR access: `csrrw`, `csrrs`, `csrrc`, `csrrwi`, `csrrsi`, `csrrci` * environment: `mret`, `wfi` [NOTE] If `rd=x0` for the `csrrw[i]` instructions there will be no actual read access to the according CSR. However, access privileges are still enforced so these instruction variants _do_ cause side-effects (the RISC-V spec. state that these combinations ""_shall_ not cause any side-effects""). [NOTE] The ""wait for interrupt instruction"" `wfi` acts like a sleep command. When executed, the CPU is halted until a valid interrupt request occurs. To wake up again, the according interrupt source has to be enabled via the `mie` CSR and the global interrupt enable flag in `mstatus` has to be set. The `wfi` instruction may also be executed in user-mode without causing an exception as <<_mstatus>> bit `TW` (timeout wait) is _hardwired_ to zero. ==== **`Zicntr`** CPU Base Counters The `Zicntr` ISA extension adds the basic cycle `[m]cycle[h]`), instruction-retired (`[m]instret[h]`) and time (`time[h]`) counters. This extensions is stated is _mandatory_ by the RISC-V spec. However, size-constrained setups may remove support for these counters. Section <<_machine_counter_and_timer_csrs>> shows a list of all `Zicntr`-related CSRs. These are available if the `Zicntr` ISA extensions is enabled via the <<_cpu_extension_riscv_zicntr>> generic. [NOTE] Disabling the `Zicntr` extension does not remove the `time[h]`-driving MTIME unit. If `Zicntr` is disabled, all accesses to the according counter CSRs will raise an illegal instruction exception. ==== **`Zihpm`** Hardware Performance Monitors In additions to the base cycle, instructions-retired and time counters the NEORV32 CPU provides up to 29 hardware performance monitors (HPM 3..31), which can be used to benchmark applications. Each HPM consists of an N-bit wide counter (split in a high-word 32-bit CSR and a low-word 32-bit CSR), where N is defined via the top's `HPM_CNT_WIDTH` generic (0..64-bit) and a corresponding event configuration CSR. The event configuration CSR defines the architectural events that lead to an increment of the associated HPM counter. The HPM counters are available if the `Zihpm` ISA extensions is enabled via the <<_cpu_extension_riscv_zihpm>> generic. Depending on the configuration the following additional CSR are available: * counters: `mhpmcounter*[h]` (3..31, depending on `HPM_NUM_CNTS`) * event configuration: `mhpmevent*` (3..31, depending on `HPM_NUM_CNTS`) [IMPORTANT] The HPM counter CSR can only be accessed in machine-mode. Hence, the according `mcounteren` CSR bits are always zero and read-only. Any access from less-privileged modes will raise an illegal instruction exception. [TIP] Auto-increment of the HPMs can be individually deactivated via the `mcountinhibit` CSR. [TIP] For a list of all HPM-related CSRs and all provided event configurations see section <<_hardware_performance_monitors_hpm>>. ==== **`Zifencei`** Instruction Stream Synchronization The `Zifencei` CPU extension is implemented if the `CPU_EXTENSION_RISCV_Zifencei` configuration generic is _true_. It allows manual synchronization of the instruction stream via the following instruction: * `fence.i` The `fence.i` instruction resets the CPU's front-end (instruction fetch) and flushes the prefetch buffer. This allows a clean re-fetch of modified instructions from memory. Also, the top's `i_bus_fencei_o` signal is set high for one cycle to inform the memory system (like the i-cache to perform a flush/reload. Any additional flags within the `fence.i` instruction word are ignore by the hardware. ==== **`PMP`** Physical Memory Protection The NEORV32 physical memory protection (PMP) is compatible to the RISC-V PMP specifications. It can be used to constrain memory read/write/execute rights for each available privilege level. The NEORV32 PMP only supports _NAPOT_ mode yet and a minimal region size (granularity) of 8 bytes. Larger minimal sizes can be configured via the top `PMP_MIN_GRANULARITY` generic to reduce hardware requirements. The physical memory protection system is implemented when the `PMP_NUM_REGIONS` configuration generic is >0. In this case the following additional CSRs are available: * `pmpcfg*` (0..15, depending on configuration): PMP configuration registers * `pmpaddr*` (0..63, depending on configuration): PMP address registers [TIP] See section <<_machine_physical_memory_protection_csrs>> for more information regarding the PMP CSRs. The actual number of regions and the minimal region granularity are defined via the top entity `PMP_MIN_GRANULARITY` and `PMP_NUM_REGIONS` generics. `PMP_MIN_GRANULARITY` defines the minimal available granularity of each region in bytes. `PMP_NUM_REGIONS` defines the total number of implemented regions and thus, the number of available `pmpcfg*` and `pmpaddr*` CSRs. When implementing more PMP regions that a _certain critical limit_ *an additional register stage is automatically inserted* into the CPU's memory interfaces to reduce critical path length. Unfortunately, this will also increase the latency of instruction fetches and data access by +1 cycle. The critical limit can be adapted for custom use by a constant from the main VHDL package file (`rtl/core/neorv32_package.vhd`). The default value is 8: [source,vhdl] ---- -- ""critical"" number of PMP regions -- constant pmp_num_regions_critical_c : natural := 8; ---- **Operation** Any CPU memory access address (from the instruction fetch or data access interface) is tested if it is accessing _any_ of the specified PMP regions(configured via `pmpaddr*` and enabled via `pmpcfg*`). If an address matches one of these regions, the configured access rights (attributes in `pmpcfg*`) are enforced: * a write access (store) will fail if no write attribute is set * a read access (load) will fail if no read attribute is set * an instruction fetch access will fail if no execute attribute is set If an access to a protected region does not have the according access rights it will raise the according instruction/load/store _access fault_ exception. By default, all PMP checks are enforced for user-level programs only. If you wish to enforce the physical memory protection also for machine-level programs you need to set the _locked bit_ in the according `pmpcfg*` configuration CSR. [IMPORTANT] After updating the address configuration registers `pmpaddr*` the system requires up to 33 cycles for internal (iterative) computations before the configuration becomes valid. [NOTE] For more information regarding RISC-V physical memory protection see the official _The RISC-V Instruction Set Manual - Volume II: Privileged Architecture_ specifications. <<< // #################################################################################################################### :sectnums: === Instruction Timing The instruction timing listed in the table below shows the required clock cycles for executing a certain instruction. These instruction cycles assume a bus access without additional wait states and a filled pipeline. Average CPI (cycles per instructions) values for ""real applications"" like for executing the CoreMark benchmark for different CPU configurations are presented in <<_cpu_performance>>. .Clock cycles per instruction [cols=""<2,^1,^4,<3""] [options=""header"", grid=""rows""] |======================= | Class | ISA | Instruction(s) | Execution cycles | ALU | `I/E` | `addi` `slti` `sltiu` `xori` `ori` `andi` `add` `sub` `slt` `sltu` `xor` `or` `and` `lui` `auipc` | 2 | ALU | `C` | `c.addi4spn` `c.nop` `c.addi` `c.li` `c.addi16sp` `c.lui` `c.andi` `c.sub` `c.xor` `c.or` `c.and` `c.add` `c.mv` | 2 | ALU | `I/E` | `slli` `srli` `srai` `sll` `srl` `sra` | 3 + SAfootnote:[Shift amount.]/4 + SA%4; FAST_SHIFTfootnote:[Barrel shift when `FAST_SHIFT_EN` is enabled.]: 4; TINY_SHIFTfootnote:[Serial shift when `TINY_SHIFT_EN` is enabled.]: 2..32 | ALU | `C` | `c.srli` `c.srai` `c.slli` | 3 + SAfootnote:[Shift amount (0..31).]; FAST_SHIFTfootnote:[Barrel shifter when `FAST_SHIFT_EN` is enabled.]: | Branches | `I/E` | `beq` `bne` `blt` `bge` `bltu` `bgeu` | Taken: 5 + MLfootnote:[Memory latency.]; Not taken: 3 | Branches | `C` | `c.beqz` `c.bnez` | Taken: 5 + MLfootnote:[Memory latency.]; Not taken: 3 | Jumps / Calls | `I/E` | `jal` `jalr` | 4 + ML | Jumps / Calls | `C` | `c.jal` `c.j` `c.jr` `c.jalr` | 4 + ML | Memory access | `I/E` | `lb` `lh` `lw` `lbu` `lhu` `sb` `sh` `sw` | 4 + ML | Memory access | `C` | `c.lw` `c.sw` `c.lwsp` `c.swsp` | 4 + ML | Memory access | `A` | `lr.w` `sc.w` | 4 + ML | Multiplication | `M` | `mul` `mulh` `mulhsu` `mulhu` | 2+32+2; FAST_MULfootnote:[DSP-based multiplication; enabled via `FAST_MUL_EN`.]: 4 | Division | `M` | `div` `divu` `rem` `remu` | 2+32+2 | CSR access | `Zicsr` | `csrrw` `csrrs` `csrrc` `csrrwi` `csrrsi` `csrrci` | 4 | System | `I/E`+`Zicsr` | `ecall` `ebreak` | 4 | System | `I/E` | `fence` | 3 | System | `C`+`Zicsr` | `c.break` | 4 | System | `Zicsr` | `mret` `wfi` | 5 | System | `Zifencei` | `fence.i` | 3 + ML | Floating-point - artihmetic | `Zfinx` | `fadd.s` | 110 | Floating-point - artihmetic | `Zfinx` | `fsub.s` | 112 | Floating-point - artihmetic | `Zfinx` | `fmul.s` | 22 | Floating-point - compare | `Zfinx` | `fmin.s` `fmax.s` `feq.s` `flt.s` `fle.s` | 13 | Floating-point - misc | `Zfinx` | `fsgnj.s` `fsgnjn.s` `fsgnjx.s` `fclass.s` | 12 | Floating-point - conversion | `Zfinx` | `fcvt.w.s` `fcvt.wu.s` | 47 | Floating-point - conversion | `Zfinx` | `fcvt.s.w` `fcvt.s.wu` | 48 | Bit-manipulation - arithmetic/logic | `B(Zbb)` | `sext.b` `sext.h` `min` `minu` `max` `maxu` `andn` `orn` `xnor` `zext`(pack) `rev8`(grevi) `orc.b`(gorci) | 3 | Bit-manipulation - arithmetic/logic | `B(Zba)` | `sh1add` `sh2add` `sh3add` | 3 | Bit-manipulation - shifts | `B(Zbb)` | `clz` `ctz` | 3 + 0..32 | Bit-manipulation - shifts | `B(Zbb)` | `cpop` | 3 + 32 | Bit-manipulation - shifts | `B(Zbb)` | `rol` `ror` `rori` | 3 + SA | Bit-manipulation - single-bit | `B(Zbs)` | `sbset[i]` `sbclr[i]` `sbinv[i]` `sbext[i]` | 3 | Bit-manipulation - shifted-add | `B(Zba)` | `sh1add` `sh2add` `sh3add` | 3 |======================= [NOTE] The presented values of the *floating-point execution cycles* are average values - obtained from 4096 instruction executions using pseudo-random input values. The execution time for emulating the instructions (using pure-software libraries) is ~17..140 times higher. <<< // #################################################################################################################### include::cpu_csr.adoc[] <<< // #################################################################################################################### :sectnums: ==== Traps, Exceptions and Interrupts In this document the following nomenclature regarding traps is used: * _interrupts_ = asynchronous exceptions * _exceptions_ = synchronous exceptions * _traps_ = exceptions + interrupts (synchronous or asynchronous exceptions) Whenever an exception or interrupt is triggered, the CPU transfers control to the address stored in `mtvec` CSR. The cause of the according interrupt or exception can be determined via the content of `mcause` CSR. The address that reflects the current program counter when a trap was taken is stored to `mepc` CSR. Additional information regarding the cause of the trap can be retrieved from `mtval` CSR. The traps are prioritized. If several _exceptions_ occur at once only the one with highest priority is triggered while all remaining exceptions are ignored. If several _interrupts_ trigger at once, the one with highest priority is serviced first while the remaining ones stay _pending_. After completing the interrupt handler the interrupt with the second highest priority will get serviced and so on until no further interrupt are pending. .Interrupt Signal Requirements - Standard RISC-V Interrupts [IMPORTANT] All standard RISC-V interrupts request signals are **high-active**. A request has to stay at high-level (=asserted) until it is explicitly acknowledged by the CPU software (for example by writing to a specific memory-mapped register). .Interrupt Signal Requirements - Fast Interrupt Requests [IMPORTANT] The NEORV32-specific FIRQ request lines are triggered by a rising edge. Each request is buffered in the CPU control unit until the channel is either disabled (by clearing the according `mie` CSR bit) or the request is explicitly cleared (by setting the according `mip` CSR bit). .Instruction Atomicity [NOTE] All instructions execute as atomic operations - interrupts can only trigger between two instructions. So if there is a permanent interrupt request, exactly one instruction from the interrupt program will be executed before a new interrupt handler can start. :sectnums: ==== Memory Access Exceptions** If a load operation causes any exception, the instruction's destination register is _not written_ at all. Load exceptions caused by a misalignment or a physical memory protection fault do not trigger a bus read-operation at all. Exceptions caused by a store address misalignment or a store physical memory protection fault do not trigger a bus write-operation at all. :sectnums: ==== Custom Fast Interrupt Request Lines As a custom extension, the NEORV32 CPU features 16 fast interrupt request (FIRQ) lines via the `firq_i` CPU top entity signals. These interrupts have custom configuration and status flags in the `mie` and `mip` CSRs and also provide custom trap codes in `mcause`. These FIRQs are reserved for NEORV32 processor-internal usage only. <<< // #################################################################################################################### :sectnums: ==== NEORV32 Trap Listing The following table shows all traps that are currently supported by the NEORV32 CPU. It also shows the prioritization and the CSR side-effects. A more detailed description of the actual trap triggering events is provided in a further table. [NOTE] _Asynchronous exceptions_ (= interrupts) set the MSB of `mcause` while _synchronous exception_ (= ""software exception"") clear the MSB. **Table Annotations** The ""Prio."" column shows the priority of each trap. The highest priority is 1. The ""`mcause`"" column shows the cause ID of the according trap that is written to `mcause` CSR. The ""[RISC-V]"" columns show the interrupt/exception code value from the official RISC-V privileged architecture manual. The ""[C]"" names are defined by the NEORV32 core library (`sw/lib/include/neorv32.h`) and can be used in plain C code. The ""`mepc`"" and ""`mtval`"" columns show the value written to `mepc` and `mtval` CSRs when a trap is triggered: * _I-PC_ - address of interrupted instruction (instruction has not been execute/completed yet) * _B-ADR_- bad memory access address that cause the trap * _PC_ - address of instruction that caused the trap * _0_ - zero * _Inst_ - the faulting instruction itself .NEORV32 Trap Listing [cols=""3,6,5,14,11,4,4""] [options=""header"",grid=""rows""] |======================= | Prio. | `mcause` | [RISC-V] | ID [C] | Cause | `mepc` | `mtval` | 1 | `0x00000000` | 0.0 | _TRAP_CODE_I_MISALIGNED_ | instruction address misaligned | _B-ADR_ | _PC_ | 2 | `0x00000001` | 0.1 | _TRAP_CODE_I_ACCESS_ | instruction access fault | _B-ADR_ | _PC_ | 3 | `0x00000002` | 0.2 | _TRAP_CODE_I_ILLEGAL_ | illegal instruction | _PC_ | _Inst_ | 4 | `0x0000000B` | 0.11 | _TRAP_CODE_MENV_CALL_ | environment call from M-mode (`ecall` in machine-mode) | _PC_ | _PC_ | 5 | `0x00000008` | 0.8 | _TRAP_CODE_UENV_CALL_ | environment call from U-mode (`ecall` in user-mode) | _PC_ | _PC_ | 6 | `0x00000003` | 0.3 | _TRAP_CODE_BREAKPOINT_ | breakpoint (`ebreak`) | _PC_ | _PC_ | 7 | `0x00000006` | 0.6 | _TRAP_CODE_S_MISALIGNED_ | store address misaligned | _B-ADR_ | _B-ADR_ | 8 | `0x00000004` | 0.4 | _TRAP_CODE_L_MISALIGNED_ | load address misaligned | _B-ADR_ | _B-ADR_ | 9 | `0x00000007` | 0.7 | _TRAP_CODE_S_ACCESS_ | store access fault | _B-ADR_ | _B-ADR_ | 10 | `0x00000005` | 0.5 | _TRAP_CODE_L_ACCESS_ | load access fault | _B-ADR_ | _B-ADR_ | 11 | `0x80000010` | 1.16 | _TRAP_CODE_FIRQ_0_ | fast interrupt request channel 0 | _I-PC_ | _0_ | 12 | `0x80000011` | 1.17 | _TRAP_CODE_FIRQ_1_ | fast interrupt request channel 1 | _I-PC_ | _0_ | 13 | `0x80000012` | 1.18 | _TRAP_CODE_FIRQ_2_ | fast interrupt request channel 2 | _I-PC_ | _0_ | 14 | `0x80000013` | 1.19 | _TRAP_CODE_FIRQ_3_ | fast interrupt request channel 3 | _I-PC_ | _0_ | 15 | `0x80000014` | 1.20 | _TRAP_CODE_FIRQ_4_ | fast interrupt request channel 4 | _I-PC_ | _0_ | 16 | `0x80000015` | 1.21 | _TRAP_CODE_FIRQ_5_ | fast interrupt request channel 5 | _I-PC_ | _0_ | 17 | `0x80000016` | 1.22 | _TRAP_CODE_FIRQ_6_ | fast interrupt request channel 6 | _I-PC_ | _0_ | 18 | `0x80000017` | 1.23 | _TRAP_CODE_FIRQ_7_ | fast interrupt request channel 7 | _I-PC_ | _0_ | 19 | `0x80000018` | 1.24 | _TRAP_CODE_FIRQ_8_ | fast interrupt request channel 8 | _I-PC_ | _0_ | 20 | `0x80000019` | 1.25 | _TRAP_CODE_FIRQ_9_ | fast interrupt request channel 9 | _I-PC_ | _0_ | 21 | `0x8000001a` | 1.26 | _TRAP_CODE_FIRQ_10_ | fast interrupt request channel 10 | _I-PC_ | _0_ | 22 | `0x8000001b` | 1.27 | _TRAP_CODE_FIRQ_11_ | fast interrupt request channel 11 | _I-PC_ | _0_ | 23 | `0x8000001c` | 1.28 | _TRAP_CODE_FIRQ_12_ | fast interrupt request channel 12 | _I-PC_ | _0_ | 24 | `0x8000001d` | 1.29 | _TRAP_CODE_FIRQ_13_ | fast interrupt request channel 13 | _I-PC_ | _0_ | 25 | `0x8000001e` | 1.30 | _TRAP_CODE_FIRQ_14_ | fast interrupt request channel 14 | _I-PC_ | _0_ | 26 | `0x8000001f` | 1.31 | _TRAP_CODE_FIRQ_15_ | fast interrupt request channel 15 | _I-PC_ | _0_ | 27 | `0x8000000B` | 1.11 | _TRAP_CODE_MEI_ | machine external interrupt | _I-PC_ | _0_ | 28 | `0x80000003` | 1.3 | _TRAP_CODE_MSI_ | machine software interrupt | _I-PC_ | _0_ | 29 | `0x80000007` | 1.7 | _TRAP_CODE_MTI_ | machine timer interrupt | _I-PC_ | _0_ |======================= The following table provides a summarized description of the actual events for triggering a specific trap. .NEORV32 Trap Description [cols=""<3,<7""] [options=""header"",grid=""rows""] |======================= | Trap ID | Triggered when ... | _TRAP_CODE_I_MISALIGNED_ | fetching an 32-bit instruction word that is not 32-bit-aligned (_see note below!_) | _TRAP_CODE_I_ACCESS_ | bus timeout or bus error during instruction word fetch | _TRAP_CODE_I_ILLEGAL_ | trying to execute an invalid instruction word (malformed or not supported) or on a privilege violation | _TRAP_CODE_MENV_CALL_ | executing `ecall` instruction in machine-mode | _TRAP_CODE_UENV_CALL_ | executing `ecall` instruction in user-mode | _TRAP_CODE_BREAKPOINT_ | executing `ebreak` instruction (or triggered by on-chip debugger) | _TRAP_CODE_S_MISALIGNED_ | storing data to an address that is not naturally aligned to the data size (byte, half, word) being stored | _TRAP_CODE_L_MISALIGNED_ | loading data from an address that is not naturally aligned to the data size (byte, half, word) being loaded | _TRAP_CODE_S_ACCESS_ | bus timeout or bus error during load data operation | _TRAP_CODE_L_ACCESS_ | bus timeout or bus error during store data operation | _TRAP_CODE_FIRQ_0_ ... _TRAP_CODE_FIRQ_15_| caused by interrupt-condition of processor-internal modules, see <<_neorv32_specific_fast_interrupt_requests>> | _TRAP_CODE_MEI_ | user-defined processor-external source (via dedicated top-entity signal) | _TRAP_CODE_MSI_ | user-defined processor-external source (via dedicated top-entity signal) | _TRAP_CODE_MTI_ | processor-internal machine timer overflow OR user-defined processor-external source (via dedicated top-entity signal) |======================= .Instruction Address Misaligned Exception [NOTE] For 32-bit-only instructions (= no `C` extension) the misaligned instruction exception is raised if bit 1 of the fetch address is set (i.e. not on a 32-bit boundary). If the `C` extension is implemented there will never be a misaligned instruction exception _at all_. In both cases bit 0 of the program counter (and all related registers) is hardwired to zero. <<< // #################################################################################################################### :sectnums: ==== Bus Interface The CPU provides two independent bus interfaces: One for fetching instructions (`i_bus_*`) and one for accessing data (`d_bus_*`) via load and store operations. Both interfaces use the same interface protocol. :sectnums: ===== Address Space The CPU is a 32-bit architecture with separated instruction and data interfaces making it a Harvard Architecture. Each of this interfaces can access an address space of up to 2^32^ bytes (4GB). The memory system is based on 32-bit words with a minimal granularity of 1 byte. Please note, that the NEORV32 CPU does not support unaligned memory accesses _in hardware_ - however, a software-based handling can be implemented as any unaligned memory access will trigger an according exception. :sectnums: ===== Interface Signals The following table shows the signals of the data and instruction interfaces seen from the CPU (`*_o` signals are driven by the CPU / outputs, `*_i` signals are read by the CPU / inputs). .CPU bus interface [cols=""<2,^1,<7""] [options=""header"",grid=""rows""] |======================= | Signal | Size | Function | `bus_addr_o` | 32 | access address | `bus_rdata_i` | 32 | data input for read operations | `bus_wdata_o` | 32 | data output for write operations | `bus_ben_o` | 4 | byte enable signal for write operations | `bus_we_o` | 1 | bus write access | `bus_re_o` | 1 | bus read access | `bus_lock_o` | 1 | exclusive access request | `bus_ack_i` | 1 | accessed peripheral indicates a successful completion of the bus transaction | `bus_err_i` | 1 | accessed peripheral indicates an error during the bus transaction | `bus_fence_o` | 1 | this signal is set for one cycle when the CPU executes a data/instruction fence operation | `bus_priv_o` | 2 | current CPU privilege level |======================= [NOTE] Currently, there a no pipelined or overlapping operations implemented within the same bus interface. So only a single transfer request can be ""on the fly"". :sectnums: ===== Protocol A bus request is triggered either by the `bus_re_o` signal (for reading data) or by the `bus_we_o` signal (for writing data). These signals are active for exactly one cycle and initiate either a read or a write transaction. The transaction is completed when the accessed peripheral either sets the `bus_ack_i` signal (-> successful completion) or the `bus_err_i` signal is set (-> failed completion). All these control signals are only active (= high) for one single cycle. An error indicated via the `bus_err_i` signal during a transfer will trigger the according instruction bus access fault or load/store bus access fault exception. [NOTE] The transfer can be completed directly in the same cycle as it was initiated (via the `bus_re_o` or `bus_we_o` signal) if the peripheral sets `bus_ack_i` or `bus_err_i` high for one cycle. However, in order to shorten the critical path such ""asynchronous"" completion should be avoided. The default processor-internal module provide exactly **one cycle delay** between initiation and completion of transfers. .Bus Keeper: Processor-internal memories and memory-mapped devices with variable / high latency [IMPORTANT] Processor-internal peripherals or memories do not have to respond within one cycle after the transfer initiation (= latency > 1 cycle). However, the bus transaction has to be completed (= acknowledged) within a certain **response time window**. This time window is defined by the global `max_proc_int_response_time_c` constant (default = 15 cycles) from the processor's VHDL package file (`rtl/neorv32_package.vhd`). It defines the maximum number of cycles after which an _unacknowledged_ processor-internal bus transfer will timeout and raise a **bus fault exception**. The _BUSKEEPER_ hardware module (see section <<_internal_bus_monitor_buskeeper>>) keeps track of all _internal_ bus transactions. If any bus operations times out (for example when accessing ""address space holes"") this unit will issue a bus error to the CPU that will raise the according instruction fetch or data access bus exception. Note that **the bus keeper does not track external accesses via the external memory bus interface**. However, the external memory bus interface also provides an _optional_ bus timeout (see section <<_processor_external_memory_interface_wishbone_axi4_lite>>). **Exemplary Bus Accesses** .Example bus accesses: see read/write access description below [cols=""^2,^2""] [grid=""none""] |======================= a| image::cpu_interface_read_long.png[read,300,150] a| image::cpu_interface_write_long.png[write,300,150] | Read access | Write access |======================= **Write Access** For a write access, the accessed address (`bus_addr_o`), the data to be written (`bus_wdata_o`) and the byte enable signals (`bus_ben_o`) are set when bus_we_o goes high. These three signals are kept stable until the transaction is completed. In the example the accessed peripheral cannot answer directly in the next cycle after issuing. Here, the transaction is successful and the peripheral sets the `bus_ack_i` signal several cycles after issuing. **Read Access** For a read access, the accessed address (`bus_addr_o`) is set when `bus_re_o` goes high. The address is kept stable until the transaction is completed. In the example the accessed peripheral cannot answer directly in the next cycle after issuing. The peripheral hast to apply the read data right in the same cycle as the bus transaction is completed (here, the transaction is successful and the peripheral sets the `bus_ack_i` signal). **Access Boundaries** The instruction interface will always access memory on word (= 32-bit) boundaries even if fetching compressed (16-bit) instructions. The data interface can access memory on byte (= 8-bit), half-word (= 16- bit) and word (= 32-bit) boundaries. **Exclusive (Atomic) Access** The CPU can access memory in an exclusive manner by generating a load-reservate and store-conditional combination. Normally, these combinations should target the same memory address. The CPU starts an exclusive access to memory via the _load-reservate instruction_ (`lr.w`). This instruction will set the CPU-internal _exclusive access lock_, which directly drives the `d_bus_lock_o`. It is the task of the memory system to manage this exclusive access reservation by storing the according access address and the source of the access itself (for example via the CPU ID in a multi-core system). When the CPU executes a _store-conditional instruction_ (`sc.w`) the _CPU-internal exclusive access lock_ is evaluated to check if the exclusive access was successful. If the lock is still OK, the instruction will write-back zero and will allow the according store operation to the memory system. If the lock is broken, the instruction will write-back non-zero and will not generate an actual memory store operation. The CPU-internal exclusive access lock is broken if at least one of the situations appear. * when executing any other memory-access operation than `lr.w` * when any trap (sync. or async.) is triggered (for example to force a context switch) * when the memory system signals a bus error (via the `bus_err_i` signal) [TIP] For more information regarding the SoC-level behavior and requirements of atomic operations see section <<_processor_external_memory_interface_wishbone_axi4_lite>>. **Memory Barriers** Whenever the CPU executes a fence instruction, the according interface signal is set high for one cycle (`d_bus_fence_o` for a _fence_ instruction; `i_bus_fence_o` for a _fencei_ instruction). It is the task of the memory system to perform the necessary operations (like a cache flush and refill). <<< // #################################################################################################################### :sectnums: ==== CPU Hardware Reset In order to reduce routing constraints (and by this the actual hardware requirements), most uncritical registers of the NEORV32 CPU as well as most register of the whole NEORV32 Processor do not use **a dedicated hardware reset**. ""Uncritical registers"" in this context means that the initial value of these registers after power-up is not relevant for a defined CPU boot process. **Rational** A good example to illustrate the concept of uncritical registers is a pipelined processing engine. Each stage of the engine features an N-bit _data register_ and a 1-bit _status register_. The status register is set when the data in the according data register is valid. At the end of the pipeline the status register might trigger a write-back of the processing result to some kind of memory. The initial status of the data registers after power-up is irrelevant as long as the status registers are all reset to a defined value that indicates there is no valid data in the pipeline’s data register. Therefore, the pipeline data register do no require a dedicated reset as they do not control the actual operation (in contrast to the status register). This makes the pipeline data registers from this example ""uncritical registers"". **NEORV32 CPU Reset** In terms of the NEORV32 CPU, there are several pipeline registers, state machine registers and even status and control registers (CSRs) that do not require a defined initial state to ensure a correct boot process. The pipeline register will get initialized by the CPU’s internal state machines, which are initialized from the main control engine that actually features a defined reset. The initialization of most of the CPU's core CSRs (like interrupt control) is done by the software (to be more specific, this is done by the `crt0.S` start-up code). During the very early boot process (where `crt0.S` is running) there is no chance for undefined behavior due to the lack of dedicated hardware resets of certain CSRs. For example the machine interrupt-enable CSR (`mie`) does not provide a dedicated reset. The value after reset of this register is uncritical as interrupts cannot fire because the global interrupt enabled flag in the status register (`mstatsus(mie)`) provides a dedicated hardware reset setting it to low (globally disabling interrupts). **Reset Configuration** Most CPU-internal register do feature an asynchronous reset in the VHDL code, but the ""don't care"" value (VHDL `'-'`) is used for initialization of the uncritical register, effectively generating a flip-flop without a reset. However, certain applications or situations (like advanced gate-level / timing simulations) might require a more deterministic reset state. For this case, a defined reset level (reset-to-low) of all registers can be enabled via a constant in the main VHDL package file (`rtl/core/neorv32_package.vhd`): [source,vhdl] ---- -- ""critical"" number of PMP regions -- constant dedicated_reset_c : boolean := false; -- use dedicated hardware reset value for UNCRITICAL registers (FALSE=reset value is irrelevant (might simplify HW), default; TRUE=defined LOW reset value) ---- ",16295,True,2730.8358191858883,median "------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- S E M _ A U X -- -- -- -- B o d y -- -- -- -- Copyright (C) 1992-2020, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNAT; see file COPYING3. If not, go to -- -- http://www.gnu.org/licenses for a complete copy of the license. -- -- -- -- As a special exception, if other files instantiate generics from this -- -- unit, or you link this unit with other files to produce an executable, -- -- this unit does not by itself cause the resulting executable to be -- -- covered by the GNU General Public License. This exception does not -- -- however invalidate any other reasons why the executable file might be -- -- covered by the GNU Public License. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ with Atree; use Atree; with Einfo; use Einfo; with Nlists; use Nlists; with Snames; use Snames; with Stand; use Stand; with Uintp; use Uintp; package body Sem_Aux is ---------------------- -- Ancestor_Subtype -- ---------------------- function Ancestor_Subtype (Typ : Entity_Id) return Entity_Id is begin -- If this is first subtype, or is a base type, then there is no -- ancestor subtype, so we return Empty to indicate this fact. if Is_First_Subtype (Typ) or else Is_Base_Type (Typ) then return Empty; end if; declare D : constant Node_Id := Declaration_Node (Typ); begin -- If we have a subtype declaration, get the ancestor subtype if Nkind (D) = N_Subtype_Declaration then if Nkind (Subtype_Indication (D)) = N_Subtype_Indication then return Entity (Subtype_Mark (Subtype_Indication (D))); else return Entity (Subtype_Indication (D)); end if; -- If not, then no subtype indication is available else return Empty; end if; end; end Ancestor_Subtype; -------------------- -- Available_View -- -------------------- function Available_View (Ent : Entity_Id) return Entity_Id is begin -- Obtain the non-limited view (if available) if Has_Non_Limited_View (Ent) then return Get_Full_View (Non_Limited_View (Ent)); -- In all other cases, return entity unchanged else return Ent; end if; end Available_View; -------------------- -- Constant_Value -- -------------------- function Constant_Value (Ent : Entity_Id) return Node_Id is D : constant Node_Id := Declaration_Node (Ent); Full_D : Node_Id; begin -- If we have no declaration node, then return no constant value. Not -- clear how this can happen, but it does sometimes and this is the -- safest approach. if No (D) then return Empty; -- Normal case where a declaration node is present elsif Nkind (D) = N_Object_Renaming_Declaration then return Renamed_Object (Ent); -- If this is a component declaration whose entity is a constant, it is -- a prival within a protected function (and so has no constant value). elsif Nkind (D) = N_Component_Declaration then return Empty; -- If there is an expression, return it elsif Present (Expression (D)) then return Expression (D); -- For a constant, see if we have a full view elsif Ekind (Ent) = E_Constant and then Present (Full_View (Ent)) then Full_D := Parent (Full_View (Ent)); -- The full view may have been rewritten as an object renaming if Nkind (Full_D) = N_Object_Renaming_Declaration then return Name (Full_D); else return Expression (Full_D); end if; -- Otherwise we have no expression to return else return Empty; end if; end Constant_Value; --------------------------------- -- Corresponding_Unsigned_Type -- --------------------------------- function Corresponding_Unsigned_Type (Typ : Entity_Id) return Entity_Id is pragma Assert (Is_Signed_Integer_Type (Typ)); Siz : constant Uint := Esize (Base_Type (Typ)); begin if Siz = Esize (Standard_Short_Short_Integer) then return Standard_Short_Short_Unsigned; elsif Siz = Esize (Standard_Short_Integer) then return Standard_Short_Unsigned; elsif Siz = Esize (Standard_Unsigned) then return Standard_Unsigned; elsif Siz = Esize (Standard_Long_Integer) then return Standard_Long_Unsigned; elsif Siz = Esize (Standard_Long_Long_Integer) then return Standard_Long_Long_Unsigned; else raise Program_Error; end if; end Corresponding_Unsigned_Type; ----------------------------- -- Enclosing_Dynamic_Scope -- ----------------------------- function Enclosing_Dynamic_Scope (Ent : Entity_Id) return Entity_Id is S : Entity_Id; begin -- The following test is an error defense against some syntax errors -- that can leave scopes very messed up. if Ent = Standard_Standard then return Ent; end if; -- Normal case, search enclosing scopes -- Note: the test for Present (S) should not be required, it defends -- against an ill-formed tree. S := Scope (Ent); loop -- If we somehow got an empty value for Scope, the tree must be -- malformed. Rather than blow up we return Standard in this case. if No (S) then return Standard_Standard; -- Quit if we get to standard or a dynamic scope. We must also -- handle enclosing scopes that have a full view; required to -- locate enclosing scopes that are synchronized private types -- whose full view is a task type. elsif S = Standard_Standard or else Is_Dynamic_Scope (S) or else (Is_Private_Type (S) and then Present (Full_View (S)) and then Is_Dynamic_Scope (Full_View (S))) then return S; -- Otherwise keep climbing else S := Scope (S); end if; end loop; end Enclosing_Dynamic_Scope; ------------------------ -- First_Discriminant -- ------------------------ function First_Discriminant (Typ : Entity_Id) return Entity_Id is Ent : Entity_Id; begin pragma Assert (Has_Discriminants (Typ) or else Has_Unknown_Discriminants (Typ)); Ent := First_Entity (Typ); -- The discriminants are not necessarily contiguous, because access -- discriminants will generate itypes. They are not the first entities -- either because the tag must be ahead of them. if Chars (Ent) = Name_uTag then Next_Entity (Ent); end if; -- Skip all hidden stored discriminants if any while Present (Ent) loop exit when Ekind (Ent) = E_Discriminant and then not Is_Completely_Hidden (Ent); Next_Entity (Ent); end loop; -- Call may be on a private type with unknown discriminants, in which -- case Ent is Empty, and as per the spec, we return Empty in this case. -- Historical note: The assertion in previous versions that Ent is a -- discriminant was overly cautious and prevented convenient application -- of this function in the gnatprove context. return Ent; end First_Discriminant; ------------------------------- -- First_Stored_Discriminant -- ------------------------------- function First_Stored_Discriminant (Typ : Entity_Id) return Entity_Id is Ent : Entity_Id; function Has_Completely_Hidden_Discriminant (Typ : Entity_Id) return Boolean; -- Scans the Discriminants to see whether any are Completely_Hidden -- (the mechanism for describing non-specified stored discriminants) -- Note that the entity list for the type may contain anonymous access -- types created by expressions that constrain access discriminants. ---------------------------------------- -- Has_Completely_Hidden_Discriminant -- ---------------------------------------- function Has_Completely_Hidden_Discriminant (Typ : Entity_Id) return Boolean is Ent : Entity_Id; begin pragma Assert (Ekind (Typ) = E_Discriminant); Ent := Typ; while Present (Ent) loop -- Skip anonymous types that may be created by expressions -- used as discriminant constraints on inherited discriminants. if Is_Itype (Ent) then null; elsif Ekind (Ent) = E_Discriminant and then Is_Completely_Hidden (Ent) then return True; end if; Next_Entity (Ent); end loop; return False; end Has_Completely_Hidden_Discriminant; -- Start of processing for First_Stored_Discriminant begin pragma Assert (Has_Discriminants (Typ) or else Has_Unknown_Discriminants (Typ)); Ent := First_Entity (Typ); if Chars (Ent) = Name_uTag then Next_Entity (Ent); end if; if Has_Completely_Hidden_Discriminant (Ent) then while Present (Ent) loop exit when Ekind (Ent) = E_Discriminant and then Is_Completely_Hidden (Ent); Next_Entity (Ent); end loop; end if; pragma Assert (Ekind (Ent) = E_Discriminant); return Ent; end First_Stored_Discriminant; ------------------- -- First_Subtype -- ------------------- function First_Subtype (Typ : Entity_Id) return Entity_Id is B : constant Entity_Id := Base_Type (Typ); F : constant Node_Id := Freeze_Node (B); Ent : Entity_Id; begin -- If the base type has no freeze node, it is a type in Standard, and -- always acts as its own first subtype, except where it is one of the -- predefined integer types. If the type is formal, it is also a first -- subtype, and its base type has no freeze node. On the other hand, a -- subtype of a generic formal is not its own first subtype. Its base -- type, if anonymous, is attached to the formal type declaration from -- which the first subtype is obtained. if No (F) then if B = Base_Type (Standard_Integer) then return Standard_Integer; elsif B = Base_Type (Standard_Long_Integer) then return Standard_Long_Integer; elsif B = Base_Type (Standard_Short_Short_Integer) then return Standard_Short_Short_Integer; elsif B = Base_Type (Standard_Short_Integer) then return Standard_Short_Integer; elsif B = Base_Type (Standard_Long_Long_Integer) then return Standard_Long_Long_Integer; elsif Is_Generic_Type (Typ) then if Present (Parent (B)) then return Defining_Identifier (Parent (B)); else return Defining_Identifier (Associated_Node_For_Itype (B)); end if; else return B; end if; -- Otherwise we check the freeze node, if it has a First_Subtype_Link -- then we use that link, otherwise (happens with some Itypes), we use -- the base type itself. else Ent := First_Subtype_Link (F); if Present (Ent) then return Ent; else return B; end if; end if; end First_Subtype; ------------------------- -- First_Tag_Component -- ------------------------- function First_Tag_Component (Typ : Entity_Id) return Entity_Id is Comp : Entity_Id; Ctyp : Entity_Id; begin Ctyp := Typ; pragma Assert (Is_Tagged_Type (Ctyp)); if Is_Class_Wide_Type (Ctyp) then Ctyp := Root_Type (Ctyp); end if; if Is_Private_Type (Ctyp) then Ctyp := Underlying_Type (Ctyp); -- If the underlying type is missing then the source program has -- errors and there is nothing else to do (the full-type declaration -- associated with the private type declaration is missing). if No (Ctyp) then return Empty; end if; end if; Comp := First_Entity (Ctyp); while Present (Comp) loop if Is_Tag (Comp) then return Comp; end if; Next_Entity (Comp); end loop; -- No tag component found return Empty; end First_Tag_Component; --------------------- -- Get_Binary_Nkind -- --------------------- function Get_Binary_Nkind (Op : Entity_Id) return Node_Kind is begin case Chars (Op) is when Name_Op_Add => return N_Op_Add; when Name_Op_Concat => return N_Op_Concat; when Name_Op_Expon => return N_Op_Expon; when Name_Op_Subtract => return N_Op_Subtract; when Name_Op_Mod => return N_Op_Mod; when Name_Op_Multiply => return N_Op_Multiply; when Name_Op_Divide => return N_Op_Divide; when Name_Op_Rem => return N_Op_Rem; when Name_Op_And => return N_Op_And; when Name_Op_Eq => return N_Op_Eq; when Name_Op_Ge => return N_Op_Ge; when Name_Op_Gt => return N_Op_Gt; when Name_Op_Le => return N_Op_Le; when Name_Op_Lt => return N_Op_Lt; when Name_Op_Ne => return N_Op_Ne; when Name_Op_Or => return N_Op_Or; when Name_Op_Xor => return N_Op_Xor; when others => raise Program_Error; end case; end Get_Binary_Nkind; ----------------------- -- Get_Called_Entity -- ----------------------- function Get_Called_Entity (Call : Node_Id) return Entity_Id is Nam : constant Node_Id := Name (Call); Id : Entity_Id; begin if Nkind (Nam) = N_Explicit_Dereference then Id := Etype (Nam); pragma Assert (Ekind (Id) = E_Subprogram_Type); elsif Nkind (Nam) = N_Selected_Component then Id := Entity (Selector_Name (Nam)); elsif Nkind (Nam) = N_Indexed_Component then Id := Entity (Selector_Name (Prefix (Nam))); else Id := Entity (Nam); end if; return Id; end Get_Called_Entity; ------------------ -- Get_Rep_Item -- ------------------ function Get_Rep_Item (E : Entity_Id; Nam : Name_Id; Check_Parents : Boolean := True) return Node_Id is N : Node_Id; begin N := First_Rep_Item (E); while Present (N) loop -- Only one of Priority / Interrupt_Priority can be specified, so -- return whichever one is present to catch illegal duplication. if Nkind (N) = N_Pragma and then (Pragma_Name_Unmapped (N) = Nam or else (Nam = Name_Priority and then Pragma_Name (N) = Name_Interrupt_Priority) or else (Nam = Name_Interrupt_Priority and then Pragma_Name (N) = Name_Priority)) then if Check_Parents then return N; -- If Check_Parents is False, return N if the pragma doesn't -- appear in the Rep_Item chain of the parent. else declare Par : constant Entity_Id := Nearest_Ancestor (E); -- This node represents the parent type of type E (if any) begin if No (Par) then return N; elsif not Present_In_Rep_Item (Par, N) then return N; end if; end; end if; elsif Nkind (N) = N_Attribute_Definition_Clause and then (Chars (N) = Nam or else (Nam = Name_Priority and then Chars (N) = Name_Interrupt_Priority)) then if Check_Parents or else Entity (N) = E then return N; end if; elsif Nkind (N) = N_Aspect_Specification and then (Chars (Identifier (N)) = Nam or else (Nam = Name_Priority and then Chars (Identifier (N)) = Name_Interrupt_Priority)) then if Check_Parents then return N; elsif Entity (N) = E then return N; end if; -- A Ghost-related aspect, if disabled, may have been replaced by a -- null statement. elsif Nkind (N) = N_Null_Statement then N := Original_Node (N); end if; Next_Rep_Item (N); end loop; return Empty; end Get_Rep_Item; function Get_Rep_Item (E : Entity_Id; Nam1 : Name_Id; Nam2 : Name_Id; Check_Parents : Boolean := True) return Node_Id is Nam1_Item : constant Node_Id := Get_Rep_Item (E, Nam1, Check_Parents); Nam2_Item : constant Node_Id := Get_Rep_Item (E, Nam2, Check_Parents); N : Node_Id; begin -- Check both Nam1_Item and Nam2_Item are present if No (Nam1_Item) then return Nam2_Item; elsif No (Nam2_Item) then return Nam1_Item; end if; -- Return the first node encountered in the list N := First_Rep_Item (E); while Present (N) loop if N = Nam1_Item or else N = Nam2_Item then return N; end if; Next_Rep_Item (N); end loop; return Empty; end Get_Rep_Item; -------------------- -- Get_Rep_Pragma -- -------------------- function Get_Rep_Pragma (E : Entity_Id; Nam : Name_Id; Check_Parents : Boolean := True) return Node_Id is N : constant Node_Id := Get_Rep_Item (E, Nam, Check_Parents); begin if Present (N) and then Nkind (N) = N_Pragma then return N; end if; return Empty; end Get_Rep_Pragma; function Get_Rep_Pragma (E : Entity_Id; Nam1 : Name_Id; Nam2 : Name_Id; Check_Parents : Boolean := True) return Node_Id is Nam1_Item : constant Node_Id := Get_Rep_Pragma (E, Nam1, Check_Parents); Nam2_Item : constant Node_Id := Get_Rep_Pragma (E, Nam2, Check_Parents); N : Node_Id; begin -- Check both Nam1_Item and Nam2_Item are present if No (Nam1_Item) then return Nam2_Item; elsif No (Nam2_Item) then return Nam1_Item; end if; -- Return the first node encountered in the list N := First_Rep_Item (E); while Present (N) loop if N = Nam1_Item or else N = Nam2_Item then return N; end if; Next_Rep_Item (N); end loop; return Empty; end Get_Rep_Pragma; --------------------- -- Get_Unary_Nkind -- --------------------- function Get_Unary_Nkind (Op : Entity_Id) return Node_Kind is begin case Chars (Op) is when Name_Op_Abs => return N_Op_Abs; when Name_Op_Subtract => return N_Op_Minus; when Name_Op_Not => return N_Op_Not; when Name_Op_Add => return N_Op_Plus; when others => raise Program_Error; end case; end Get_Unary_Nkind; --------------------------------- -- Has_External_Tag_Rep_Clause -- --------------------------------- function Has_External_Tag_Rep_Clause (T : Entity_Id) return Boolean is begin pragma Assert (Is_Tagged_Type (T)); return Has_Rep_Item (T, Name_External_Tag, Check_Parents => False); end Has_External_Tag_Rep_Clause; ------------------ -- Has_Rep_Item -- ------------------ function Has_Rep_Item (E : Entity_Id; Nam : Name_Id; Check_Parents : Boolean := True) return Boolean is begin return Present (Get_Rep_Item (E, Nam, Check_Parents)); end Has_Rep_Item; function Has_Rep_Item (E : Entity_Id; Nam1 : Name_Id; Nam2 : Name_Id; Check_Parents : Boolean := True) return Boolean is begin return Present (Get_Rep_Item (E, Nam1, Nam2, Check_Parents)); end Has_Rep_Item; function Has_Rep_Item (E : Entity_Id; N : Node_Id) return Boolean is Item : Node_Id; begin pragma Assert (Nkind (N) in N_Aspect_Specification | N_Attribute_Definition_Clause | N_Enumeration_Representation_Clause | N_Pragma | N_Record_Representation_Clause); Item := First_Rep_Item (E); while Present (Item) loop if Item = N then return True; end if; Next_Rep_Item (Item); end loop; return False; end Has_Rep_Item; -------------------- -- Has_Rep_Pragma -- -------------------- function Has_Rep_Pragma (E : Entity_Id; Nam : Name_Id; Check_Parents : Boolean := True) return Boolean is begin return Present (Get_Rep_Pragma (E, Nam, Check_Parents)); end Has_Rep_Pragma; function Has_Rep_Pragma (E : Entity_Id; Nam1 : Name_Id; Nam2 : Name_Id; Check_Parents : Boolean := True) return Boolean is begin return Present (Get_Rep_Pragma (E, Nam1, Nam2, Check_Parents)); end Has_Rep_Pragma; -------------------------------- -- Has_Unconstrained_Elements -- -------------------------------- function Has_Unconstrained_Elements (T : Entity_Id) return Boolean is U_T : constant Entity_Id := Underlying_Type (T); begin if No (U_T) then return False; elsif Is_Record_Type (U_T) then return Has_Discriminants (U_T) and then not Is_Constrained (U_T); elsif Is_Array_Type (U_T) then return Has_Unconstrained_Elements (Component_Type (U_T)); else return False; end if; end Has_Unconstrained_Elements; ---------------------- -- Has_Variant_Part -- ---------------------- function Has_Variant_Part (Typ : Entity_Id) return Boolean is FSTyp : Entity_Id; Decl : Node_Id; TDef : Node_Id; CList : Node_Id; begin if not Is_Type (Typ) then return False; end if; FSTyp := First_Subtype (Typ); if not Has_Discriminants (FSTyp) then return False; end if; -- Proceed with cautious checks here, return False if tree is not -- as expected (may be caused by prior errors). Decl := Declaration_Node (FSTyp); if Nkind (Decl) /= N_Full_Type_Declaration then return False; end if; TDef := Type_Definition (Decl); if Nkind (TDef) /= N_Record_Definition then return False; end if; CList := Component_List (TDef); if Nkind (CList) /= N_Component_List then return False; else return Present (Variant_Part (CList)); end if; end Has_Variant_Part; --------------------- -- In_Generic_Body -- --------------------- function In_Generic_Body (Id : Entity_Id) return Boolean is S : Entity_Id; begin -- Climb scopes looking for generic body S := Id; while Present (S) and then S /= Standard_Standard loop -- Generic package body if Ekind (S) = E_Generic_Package and then In_Package_Body (S) then return True; -- Generic subprogram body elsif Is_Subprogram (S) and then Nkind (Unit_Declaration_Node (S)) = N_Generic_Subprogram_Declaration then return True; end if; S := Scope (S); end loop; -- False if top of scope stack without finding a generic body return False; end In_Generic_Body; ------------------------------- -- Initialization_Suppressed -- ------------------------------- function Initialization_Suppressed (Typ : Entity_Id) return Boolean is begin return Suppress_Initialization (Typ) or else Suppress_Initialization (Base_Type (Typ)); end Initialization_Suppressed; ---------------- -- Initialize -- ---------------- procedure Initialize is begin Obsolescent_Warnings.Init; end Initialize; ------------- -- Is_Body -- ------------- function Is_Body (N : Node_Id) return Boolean is begin return Nkind (N) in N_Body_Stub | N_Entry_Body | N_Package_Body | N_Protected_Body | N_Subprogram_Body | N_Task_Body; end Is_Body; --------------------- -- Is_By_Copy_Type -- --------------------- function Is_By_Copy_Type (Ent : Entity_Id) return Boolean is begin -- If Id is a private type whose full declaration has not been seen, -- we assume for now that it is not a By_Copy type. Clearly this -- attribute should not be used before the type is frozen, but it is -- needed to build the associated record of a protected type. Another -- place where some lookahead for a full view is needed ??? return Is_Elementary_Type (Ent) or else (Is_Private_Type (Ent) and then Present (Underlying_Type (Ent)) and then Is_Elementary_Type (Underlying_Type (Ent))); end Is_By_Copy_Type; -------------------------- -- Is_By_Reference_Type -- -------------------------- function Is_By_Reference_Type (Ent : Entity_Id) return Boolean is Btype : constant Entity_Id := Base_Type (Ent); begin if Error_Posted (Ent) or else Error_Posted (Btype) then return False; elsif Is_Private_Type (Btype) then declare Utyp : constant Entity_Id := Underlying_Type (Btype); begin if No (Utyp) then return False; else return Is_By_Reference_Type (Utyp); end if; end; elsif Is_Incomplete_Type (Btype) then declare Ftyp : constant Entity_Id := Full_View (Btype); begin -- Return true for a tagged incomplete type built as a shadow -- entity in Build_Limited_Views. It can appear in the profile -- of a thunk and the back end needs to know how it is passed. if No (Ftyp) then return Is_Tagged_Type (Btype); else return Is_By_Reference_Type (Ftyp); end if; end; elsif Is_Concurrent_Type (Btype) then return True; elsif Is_Record_Type (Btype) then if Is_Limited_Record (Btype) or else Is_Tagged_Type (Btype) or else Is_Volatile (Btype) then return True; else declare C : Entity_Id; begin C := First_Component (Btype); while Present (C) loop -- For each component, test if its type is a by reference -- type and if its type is volatile. Also test the component -- itself for being volatile. This happens for example when -- a Volatile aspect is added to a component. if Is_By_Reference_Type (Etype (C)) or else Is_Volatile (Etype (C)) or else Is_Volatile (C) then return True; end if; Next_Component (C); end loop; end; return False; end if; elsif Is_Array_Type (Btype) then return Is_Volatile (Btype) or else Is_By_Reference_Type (Component_Type (Btype)) or else Is_Volatile (Component_Type (Btype)) or else Has_Volatile_Components (Btype); else return False; end if; end Is_By_Reference_Type; ------------------------- -- Is_Definite_Subtype -- ------------------------- function Is_Definite_Subtype (T : Entity_Id) return Boolean is pragma Assert (Is_Type (T)); K : constant Entity_Kind := Ekind (T); begin if Is_Constrained (T) then return True; elsif K in Array_Kind or else K in Class_Wide_Kind or else Has_Unknown_Discriminants (T) then return False; -- Known discriminants: definite if there are default values. Note that -- if any discriminant has a default, they all do. elsif Has_Discriminants (T) then return Present (Discriminant_Default_Value (First_Discriminant (T))); else return True; end if; end Is_Definite_Subtype; --------------------- -- Is_Derived_Type -- --------------------- function Is_Derived_Type (Ent : E) return B is Par : Node_Id; begin if Is_Type (Ent) and then Base_Type (Ent) /= Root_Type (Ent) and then not Is_Class_Wide_Type (Ent) -- An access_to_subprogram whose result type is a limited view can -- appear in a return statement, without the full view of the result -- type being available. Do not interpret this as a derived type. and then Ekind (Ent) /= E_Subprogram_Type then if not Is_Numeric_Type (Root_Type (Ent)) then return True; else Par := Parent (First_Subtype (Ent)); return Present (Par) and then Nkind (Par) = N_Full_Type_Declaration and then Nkind (Type_Definition (Par)) = N_Derived_Type_Definition; end if; else return False; end if; end Is_Derived_Type; ----------------------- -- Is_Generic_Formal -- ----------------------- function Is_Generic_Formal (E : Entity_Id) return Boolean is Kind : Node_Kind; begin if No (E) then return False; else -- Formal derived types are rewritten as private extensions, so -- examine original node. Kind := Nkind (Original_Node (Parent (E))); return Kind in N_Formal_Object_Declaration | N_Formal_Type_Declaration or else Is_Formal_Subprogram (E) or else (Ekind (E) = E_Package and then Nkind (Original_Node (Unit_Declaration_Node (E))) = N_Formal_Package_Declaration); end if; end Is_Generic_Formal; ------------------------------- -- Is_Immutably_Limited_Type -- ------------------------------- function Is_Immutably_Limited_Type (Ent : Entity_Id) return Boolean is Btype : constant Entity_Id := Available_View (Base_Type (Ent)); begin if Is_Limited_Record (Btype) then return True; elsif Ekind (Btype) = E_Limited_Private_Type and then Nkind (Parent (Btype)) = N_Formal_Type_Declaration then return not In_Package_Body (Scope ((Btype))); elsif Is_Private_Type (Btype) then -- AI05-0063: A type derived from a limited private formal type is -- not immutably limited in a generic body. if Is_Derived_Type (Btype) and then Is_Generic_Type (Etype (Btype)) then if not Is_Limited_Type (Etype (Btype)) then return False; -- A descendant of a limited formal type is not immutably limited -- in the generic body, or in the body of a generic child. elsif Ekind (Scope (Etype (Btype))) = E_Generic_Package then return not In_Package_Body (Scope (Btype)); else return False; end if; else declare Utyp : constant Entity_Id := Underlying_Type (Btype); begin if No (Utyp) then return False; else return Is_Immutably_Limited_Type (Utyp); end if; end; end if; elsif Is_Concurrent_Type (Btype) then return True; else return False; end if; end Is_Immutably_Limited_Type; --------------------- -- Is_Limited_Type -- --------------------- function Is_Limited_Type (Ent : Entity_Id) return Boolean is Btype : constant E := Base_Type (Ent); Rtype : constant E := Root_Type (Btype); begin if not Is_Type (Ent) then return False; elsif Ekind (Btype) = E_Limited_Private_Type or else Is_Limited_Composite (Btype) then return True; elsif Is_Concurrent_Type (Btype) then return True; -- The Is_Limited_Record flag normally indicates that the type is -- limited. The exception is that a type does not inherit limitedness -- from its interface ancestor. So the type may be derived from a -- limited interface, but is not limited. elsif Is_Limited_Record (Ent) and then not Is_Interface (Ent) then return True; -- Otherwise we will look around to see if there is some other reason -- for it to be limited, except that if an error was posted on the -- entity, then just assume it is non-limited, because it can cause -- trouble to recurse into a murky entity resulting from other errors. elsif Error_Posted (Ent) then return False; elsif Is_Record_Type (Btype) then if Is_Limited_Interface (Ent) then return True; -- AI-419: limitedness is not inherited from a limited interface elsif Is_Limited_Record (Rtype) then return not Is_Interface (Rtype) or else Is_Protected_Interface (Rtype) or else Is_Synchronized_Interface (Rtype) or else Is_Task_Interface (Rtype); elsif Is_Class_Wide_Type (Btype) then return Is_Limited_Type (Rtype); else declare C : E; begin C := First_Component (Btype); while Present (C) loop if Is_Limited_Type (Etype (C)) then return True; end if; Next_Component (C); end loop; end; return False; end if; elsif Is_Array_Type (Btype) then return Is_Limited_Type (Component_Type (Btype)); else return False; end if; end Is_Limited_Type; --------------------- -- Is_Limited_View -- --------------------- function Is_Limited_View (Ent : Entity_Id) return Boolean is Btype : constant Entity_Id := Available_View (Base_Type (Ent)); begin if Is_Limited_Record (Btype) then return True; elsif Ekind (Btype) = E_Limited_Private_Type and then Nkind (Parent (Btype)) = N_Formal_Type_Declaration then return not In_Package_Body (Scope ((Btype))); elsif Is_Private_Type (Btype) then -- AI05-0063: A type derived from a limited private formal type is -- not immutably limited in a generic body. if Is_Derived_Type (Btype) and then Is_Generic_Type (Etype (Btype)) then if not Is_Limited_Type (Etype (Btype)) then return False; -- A descendant of a limited formal type is not immutably limited -- in the generic body, or in the body of a generic child. elsif Ekind (Scope (Etype (Btype))) = E_Generic_Package then return not In_Package_Body (Scope (Btype)); else return False; end if; else declare Utyp : constant Entity_Id := Underlying_Type (Btype); begin if No (Utyp) then return False; else return Is_Limited_View (Utyp); end if; end; end if; elsif Is_Concurrent_Type (Btype) then return True; elsif Is_Record_Type (Btype) then -- Note that we return True for all limited interfaces, even though -- (unsynchronized) limited interfaces can have descendants that are -- nonlimited, because this is a predicate on the type itself, and -- things like functions with limited interface results need to be -- handled as build in place even though they might return objects -- of a type that is not inherently limited. if Is_Class_Wide_Type (Btype) then return Is_Limited_View (Root_Type (Btype)); else declare C : Entity_Id; begin C := First_Component (Btype); while Present (C) loop -- Don't consider components with interface types (which can -- only occur in the case of a _parent component anyway). -- They don't have any components, plus it would cause this -- function to return true for nonlimited types derived from -- limited interfaces. if not Is_Interface (Etype (C)) and then Is_Limited_View (Etype (C)) then return True; end if; Next_Component (C); end loop; end; return False; end if; elsif Is_Array_Type (Btype) then return Is_Limited_View (Component_Type (Btype)); else return False; end if; end Is_Limited_View; ---------------------------- -- Is_Protected_Operation -- ---------------------------- function Is_Protected_Operation (E : Entity_Id) return Boolean is begin return Is_Entry (E) or else (Is_Subprogram (E) and then Nkind (Parent (Unit_Declaration_Node (E))) = N_Protected_Definition); end Is_Protected_Operation; ------------------------------- -- Is_Record_Or_Limited_Type -- ------------------------------- function Is_Record_Or_Limited_Type (Typ : Entity_Id) return Boolean is begin return Is_Record_Type (Typ) or else Is_Limited_Type (Typ); end Is_Record_Or_Limited_Type; ---------------------- -- Nearest_Ancestor -- ---------------------- function Nearest_Ancestor (Typ : Entity_Id) return Entity_Id is D : constant Node_Id := Original_Node (Declaration_Node (Typ)); -- We use the original node of the declaration, because derived -- types from record subtypes are rewritten as record declarations, -- and it is the original declaration that carries the ancestor. begin -- If we have a subtype declaration, get the ancestor subtype if Nkind (D) = N_Subtype_Declaration then if Nkind (Subtype_Indication (D)) = N_Subtype_Indication then return Entity (Subtype_Mark (Subtype_Indication (D))); else return Entity (Subtype_Indication (D)); end if; -- If derived type declaration, find who we are derived from elsif Nkind (D) = N_Full_Type_Declaration and then Nkind (Type_Definition (D)) = N_Derived_Type_Definition then declare DTD : constant Entity_Id := Type_Definition (D); SI : constant Entity_Id := Subtype_Indication (DTD); begin if Is_Entity_Name (SI) then return Entity (SI); else return Entity (Subtype_Mark (SI)); end if; end; -- If this is a concurrent declaration with a nonempty interface list, -- get the first progenitor. Account for case of a record type created -- for a concurrent type (which is the only case that seems to occur -- in practice). elsif Nkind (D) = N_Full_Type_Declaration and then (Is_Concurrent_Type (Defining_Identifier (D)) or else Is_Concurrent_Record_Type (Defining_Identifier (D))) and then Is_Non_Empty_List (Interface_List (Type_Definition (D))) then return Entity (First (Interface_List (Type_Definition (D)))); -- If derived type and private type, get the full view to find who we -- are derived from. elsif Is_Derived_Type (Typ) and then Is_Private_Type (Typ) and then Present (Full_View (Typ)) then return Nearest_Ancestor (Full_View (Typ)); -- Otherwise, nothing useful to return, return Empty else return Empty; end if; end Nearest_Ancestor; --------------------------- -- Nearest_Dynamic_Scope -- --------------------------- function Nearest_Dynamic_Scope (Ent : Entity_Id) return Entity_Id is begin if Is_Dynamic_Scope (Ent) then return Ent; else return Enclosing_Dynamic_Scope (Ent); end if; end Nearest_Dynamic_Scope; ------------------------ -- Next_Tag_Component -- ------------------------ function Next_Tag_Component (Tag : Entity_Id) return Entity_Id is Comp : Entity_Id; begin pragma Assert (Is_Tag (Tag)); -- Loop to look for next tag component Comp := Next_Entity (Tag); while Present (Comp) loop if Is_Tag (Comp) then pragma Assert (Chars (Comp) /= Name_uTag); return Comp; end if; Next_Entity (Comp); end loop; -- No tag component found return Empty; end Next_Tag_Component; ----------------------- -- Number_Components -- ----------------------- function Number_Components (Typ : Entity_Id) return Nat is N : Nat := 0; Comp : Entity_Id; begin -- We do not call Einfo.First_Component_Or_Discriminant, as this -- function does not skip completely hidden discriminants, which we -- want to skip here. if Has_Discriminants (Typ) then Comp := First_Discriminant (Typ); else Comp := First_Component (Typ); end if; while Present (Comp) loop N := N + 1; Next_Component_Or_Discriminant (Comp); end loop; return N; end Number_Components; -------------------------- -- Number_Discriminants -- -------------------------- function Number_Discriminants (Typ : Entity_Id) return Pos is N : Nat := 0; Discr : Entity_Id := First_Discriminant (Typ); begin while Present (Discr) loop N := N + 1; Next_Discriminant (Discr); end loop; return N; end Number_Discriminants; ---------------------------------------------- -- Object_Type_Has_Constrained_Partial_View -- ---------------------------------------------- function Object_Type_Has_Constrained_Partial_View (Typ : Entity_Id; Scop : Entity_Id) return Boolean is begin return Has_Constrained_Partial_View (Typ) or else (In_Generic_Body (Scop) and then Is_Generic_Type (Base_Type (Typ)) and then (Is_Private_Type (Base_Type (Typ)) or else Is_Derived_Type (Base_Type (Typ))) and then not Is_Tagged_Type (Typ) and then not (Is_Array_Type (Typ) and then not Is_Constrained (Typ)) and then Has_Discriminants (Typ)); end Object_Type_Has_Constrained_Partial_View; ------------------ -- Package_Body -- ------------------ function Package_Body (E : Entity_Id) return Node_Id is N : Node_Id; begin if Ekind (E) = E_Package_Body then N := Parent (E); if Nkind (N) = N_Defining_Program_Unit_Name then N := Parent (N); end if; else N := Package_Spec (E); if Present (Corresponding_Body (N)) then N := Parent (Corresponding_Body (N)); if Nkind (N) = N_Defining_Program_Unit_Name then N := Parent (N); end if; else N := Empty; end if; end if; return N; end Package_Body; ------------------ -- Package_Spec -- ------------------ function Package_Spec (E : Entity_Id) return Node_Id is begin return Parent (Package_Specification (E)); end Package_Spec; --------------------------- -- Package_Specification -- --------------------------- function Package_Specification (E : Entity_Id) return Node_Id is N : Node_Id; begin N := Parent (E); if Nkind (N) = N_Defining_Program_Unit_Name then N := Parent (N); end if; return N; end Package_Specification; --------------------- -- Subprogram_Body -- --------------------- function Subprogram_Body (E : Entity_Id) return Node_Id is Body_E : constant Entity_Id := Subprogram_Body_Entity (E); begin if No (Body_E) then return Empty; else return Parent (Subprogram_Specification (Body_E)); end if; end Subprogram_Body; ---------------------------- -- Subprogram_Body_Entity -- ---------------------------- function Subprogram_Body_Entity (E : Entity_Id) return Entity_Id is N : constant Node_Id := Parent (Subprogram_Specification (E)); -- Declaration for E begin -- If this declaration is not a subprogram body, then it must be a -- subprogram declaration or body stub, from which we can retrieve the -- entity for the corresponding subprogram body if any, or an abstract -- subprogram declaration, for which we return Empty. case Nkind (N) is when N_Subprogram_Body => return E; when N_Subprogram_Body_Stub | N_Subprogram_Declaration => return Corresponding_Body (N); when others => return Empty; end case; end Subprogram_Body_Entity; --------------------- -- Subprogram_Spec -- --------------------- function Subprogram_Spec (E : Entity_Id) return Node_Id is N : constant Node_Id := Parent (Subprogram_Specification (E)); -- Declaration for E begin -- This declaration is either subprogram declaration or a subprogram -- body, in which case return Empty. if Nkind (N) = N_Subprogram_Declaration then return N; else return Empty; end if; end Subprogram_Spec; ------------------------------ -- Subprogram_Specification -- ------------------------------ function Subprogram_Specification (E : Entity_Id) return Node_Id is N : Node_Id; begin N := Parent (E); if Nkind (N) = N_Defining_Program_Unit_Name then N := Parent (N); end if; -- If the Parent pointer of E is not a subprogram specification node -- (going through an intermediate N_Defining_Program_Unit_Name node -- for subprogram units), then E is an inherited operation. Its parent -- points to the type derivation that produces the inheritance: that's -- the node that generates the subprogram specification. Its alias -- is the parent subprogram, and that one points to a subprogram -- declaration, or to another type declaration if this is a hierarchy -- of derivations. if Nkind (N) not in N_Subprogram_Specification then pragma Assert (Present (Alias (E))); N := Subprogram_Specification (Alias (E)); end if; return N; end Subprogram_Specification; -------------------- -- Ultimate_Alias -- -------------------- function Ultimate_Alias (Prim : Entity_Id) return Entity_Id is E : Entity_Id := Prim; begin while Present (Alias (E)) loop pragma Assert (Alias (E) /= E); E := Alias (E); end loop; return E; end Ultimate_Alias; -------------------------- -- Unit_Declaration_Node -- -------------------------- function Unit_Declaration_Node (Unit_Id : Entity_Id) return Node_Id is N : Node_Id := Parent (Unit_Id); begin -- Predefined operators do not have a full function declaration if Ekind (Unit_Id) = E_Operator then return N; end if; -- Isn't there some better way to express the following ??? while Nkind (N) /= N_Abstract_Subprogram_Declaration and then Nkind (N) /= N_Entry_Body and then Nkind (N) /= N_Entry_Declaration and then Nkind (N) /= N_Formal_Package_Declaration and then Nkind (N) /= N_Function_Instantiation and then Nkind (N) /= N_Generic_Package_Declaration and then Nkind (N) /= N_Generic_Subprogram_Declaration and then Nkind (N) /= N_Package_Declaration and then Nkind (N) /= N_Package_Body and then Nkind (N) /= N_Package_Instantiation and then Nkind (N) /= N_Package_Renaming_Declaration and then Nkind (N) /= N_Procedure_Instantiation and then Nkind (N) /= N_Protected_Body and then Nkind (N) /= N_Protected_Type_Declaration and then Nkind (N) /= N_Subprogram_Declaration and then Nkind (N) /= N_Subprogram_Body and then Nkind (N) /= N_Subprogram_Body_Stub and then Nkind (N) /= N_Subprogram_Renaming_Declaration and then Nkind (N) /= N_Task_Body and then Nkind (N) /= N_Task_Type_Declaration and then Nkind (N) not in N_Formal_Subprogram_Declaration and then Nkind (N) not in N_Generic_Renaming_Declaration loop N := Parent (N); -- We don't use Assert here, because that causes an infinite loop -- when assertions are turned off. Better to crash. if No (N) then raise Program_Error; end if; end loop; return N; end Unit_Declaration_Node; end Sem_Aux; ",12092,False,2449.237726084229,median "CLASS zcl_excel_common DEFINITION PUBLIC FINAL CREATE PUBLIC . *""* public components of class ZCL_EXCEL_COMMON *""* do not include other source files here!!! PUBLIC SECTION. CONSTANTS c_excel_baseline_date TYPE d VALUE '19000101'. ""#EC NOTEXT CLASS-DATA c_excel_numfmt_offset TYPE int1 VALUE 164. ""#EC NOTEXT . . . . . . . . . . . . . . . . "" . CONSTANTS c_excel_sheet_max_col TYPE int4 VALUE 16384. ""#EC NOTEXT CONSTANTS c_excel_sheet_min_col TYPE int4 VALUE 1. ""#EC NOTEXT CONSTANTS c_excel_sheet_max_row TYPE int4 VALUE 1048576. ""#EC NOTEXT CONSTANTS c_excel_sheet_min_row TYPE int4 VALUE 1. ""#EC NOTEXT CLASS-DATA c_spras_en TYPE spras VALUE 'E'. ""#EC NOTEXT . . . . . . . . . . . . . . . . "" . CLASS-DATA o_conv TYPE REF TO cl_abap_conv_out_ce . CONSTANTS c_excel_1900_leap_year TYPE d VALUE '19000228'. ""#EC NOTEXT CLASS-DATA c_xlsx_file_filter TYPE string VALUE 'Excel Workbook (*.xlsx)|*.xlsx|'. ""#EC NOTEXT . . . . . . . "" . CLASS-METHODS class_constructor . CLASS-METHODS describe_structure IMPORTING !io_struct TYPE REF TO cl_abap_structdescr RETURNING VALUE(rt_dfies) TYPE ddfields . CLASS-METHODS convert_column2alpha IMPORTING !ip_column TYPE simple RETURNING VALUE(ep_column) TYPE zexcel_cell_column_alpha RAISING zcx_excel . CLASS-METHODS convert_column2int IMPORTING !ip_column TYPE simple RETURNING VALUE(ep_column) TYPE zexcel_cell_column RAISING zcx_excel . CLASS-METHODS convert_columnrow2column_a_row IMPORTING !i_columnrow TYPE clike EXPORTING !e_column TYPE zexcel_cell_column_alpha !e_row TYPE zexcel_cell_row . CLASS-METHODS convert_range2column_a_row IMPORTING !i_range TYPE clike !i_allow_1dim_range TYPE abap_bool DEFAULT abap_false EXPORTING !e_column_start TYPE zexcel_cell_column_alpha !e_column_end TYPE zexcel_cell_column_alpha !e_row_start TYPE zexcel_cell_row !e_row_end TYPE zexcel_cell_row !e_sheet TYPE clike RAISING zcx_excel . CLASS-METHODS convert_columnrow2column_o_row IMPORTING !i_columnrow TYPE clike EXPORTING !e_column TYPE zexcel_cell_column_alpha !e_row TYPE zexcel_cell_row . CLASS-METHODS date_to_excel_string IMPORTING !ip_value TYPE d RETURNING VALUE(ep_value) TYPE zexcel_cell_value . CLASS-METHODS encrypt_password IMPORTING !i_pwd TYPE zexcel_aes_password RETURNING VALUE(r_encrypted_pwd) TYPE zexcel_aes_password . CLASS-METHODS escape_string IMPORTING !ip_value TYPE clike RETURNING VALUE(ep_escaped_value) TYPE string . CLASS-METHODS unescape_string IMPORTING !iv_escaped TYPE clike RETURNING VALUE(ev_unescaped_string) TYPE string RAISING zcx_excel . CLASS-METHODS excel_string_to_date IMPORTING !ip_value TYPE zexcel_cell_value RETURNING VALUE(ep_value) TYPE d RAISING zcx_excel . CLASS-METHODS excel_string_to_time IMPORTING !ip_value TYPE zexcel_cell_value RETURNING VALUE(ep_value) TYPE t RAISING zcx_excel . CLASS-METHODS excel_string_to_number IMPORTING !ip_value TYPE zexcel_cell_value RETURNING VALUE(ep_value) TYPE f RAISING zcx_excel . CLASS-METHODS get_fieldcatalog IMPORTING !ip_table TYPE STANDARD TABLE !iv_hide_mandt TYPE abap_bool DEFAULT abap_true RETURNING VALUE(ep_fieldcatalog) TYPE zexcel_t_fieldcatalog . CLASS-METHODS number_to_excel_string IMPORTING VALUE(ip_value) TYPE numeric RETURNING VALUE(ep_value) TYPE zexcel_cell_value . CLASS-METHODS recursive_class_to_struct IMPORTING !i_source TYPE any CHANGING !e_target TYPE data !e_targetx TYPE data . CLASS-METHODS recursive_struct_to_class IMPORTING !i_source TYPE data !i_sourcex TYPE data CHANGING !e_target TYPE any . CLASS-METHODS time_to_excel_string IMPORTING !ip_value TYPE t RETURNING VALUE(ep_value) TYPE zexcel_cell_value . TYPE-POOLS abap . TYPES: t_char10 TYPE c LENGTH 10. TYPES: t_char255 TYPE c LENGTH 255. CLASS-METHODS split_file IMPORTING !ip_file TYPE t_char255 EXPORTING !ep_file TYPE t_char255 !ep_extension TYPE t_char10 !ep_dotextension TYPE t_char10 . CLASS-METHODS calculate_cell_distance IMPORTING !iv_reference_cell TYPE clike !iv_current_cell TYPE clike EXPORTING !ev_row_difference TYPE i !ev_col_difference TYPE i RAISING zcx_excel . CLASS-METHODS determine_resulting_formula IMPORTING !iv_reference_cell TYPE clike !iv_reference_formula TYPE clike !iv_current_cell TYPE clike RETURNING VALUE(ev_resulting_formula) TYPE string RAISING zcx_excel . CLASS-METHODS shift_formula IMPORTING !iv_reference_formula TYPE clike VALUE(iv_shift_cols) TYPE i VALUE(iv_shift_rows) TYPE i RETURNING VALUE(ev_resulting_formula) TYPE string RAISING zcx_excel . CLASS-METHODS is_cell_in_range IMPORTING !ip_column TYPE simple !ip_row TYPE zexcel_cell_row !ip_range TYPE clike RETURNING VALUE(rp_in_range) TYPE abap_bool RAISING zcx_excel . *""* protected components of class ZCL_EXCEL_COMMON *""* do not include other source files here!!! *""* protected components of class ZCL_EXCEL_COMMON *""* do not include other source files here!!! PROTECTED SECTION. PRIVATE SECTION. CLASS-DATA c_excel_col_module TYPE int2 VALUE 64. ""#EC NOTEXT . . . . . . . . . . . . . . . "" . CLASS-DATA sv_prev_in1 TYPE zexcel_cell_column. CLASS-DATA sv_prev_out1 TYPE zexcel_cell_column_alpha. CLASS-DATA sv_prev_in2 TYPE c LENGTH 10. CLASS-DATA sv_prev_out2 TYPE zexcel_cell_column. CLASS-METHODS structure_case IMPORTING !is_component TYPE abap_componentdescr CHANGING !xt_components TYPE abap_component_tab . CLASS-METHODS structure_recursive IMPORTING !is_component TYPE abap_componentdescr RETURNING VALUE(rt_components) TYPE abap_component_tab . TYPES ty_char1 TYPE c LENGTH 1. CLASS-METHODS char2hex IMPORTING !i_char TYPE ty_char1 RETURNING VALUE(r_hex) TYPE zexcel_pwd_hash . CLASS-METHODS shl01 IMPORTING !i_pwd_hash TYPE zexcel_pwd_hash RETURNING VALUE(r_pwd_hash) TYPE zexcel_pwd_hash . CLASS-METHODS shr14 IMPORTING !i_pwd_hash TYPE zexcel_pwd_hash RETURNING VALUE(r_pwd_hash) TYPE zexcel_pwd_hash . ENDCLASS. CLASS zcl_excel_common IMPLEMENTATION. METHOD calculate_cell_distance. DATA: lv_reference_row TYPE i, lv_reference_col_alpha TYPE zexcel_cell_column_alpha, lv_reference_col TYPE i, lv_current_row TYPE i, lv_current_col_alpha TYPE zexcel_cell_column_alpha, lv_current_col TYPE i. *--------------------------------------------------------------------* * Split reference cell into numerical row/column representation *--------------------------------------------------------------------* convert_columnrow2column_a_row( EXPORTING i_columnrow = iv_reference_cell IMPORTING e_column = lv_reference_col_alpha e_row = lv_reference_row ). lv_reference_col = convert_column2int( lv_reference_col_alpha ). *--------------------------------------------------------------------* * Split current cell into numerical row/column representation *--------------------------------------------------------------------* convert_columnrow2column_a_row( EXPORTING i_columnrow = iv_current_cell IMPORTING e_column = lv_current_col_alpha e_row = lv_current_row ). lv_current_col = convert_column2int( lv_current_col_alpha ). *--------------------------------------------------------------------* * Calculate row and column difference * Positive: Current cell below reference cell * or Current cell right of reference cell * Negative: Current cell above reference cell * or Current cell left of reference cell *--------------------------------------------------------------------* ev_row_difference = lv_current_row - lv_reference_row. ev_col_difference = lv_current_col - lv_reference_col. ENDMETHOD. METHOD char2hex. IF o_conv IS NOT BOUND. o_conv = cl_abap_conv_out_ce=>create( endian = 'L' ignore_cerr = abap_true replacement = '#' ). ENDIF. CALL METHOD o_conv->reset( ). CALL METHOD o_conv->write( data = i_char ). r_hex+1 = o_conv->get_buffer( ). "" x'65' must be x'0065' ENDMETHOD. METHOD class_constructor. c_xlsx_file_filter = 'Excel Workbook (*.xlsx)|*.xlsx|'(005). ENDMETHOD. METHOD convert_column2alpha. DATA: lv_uccpi TYPE i, lv_text TYPE c LENGTH 2, lv_module TYPE int4, lv_column TYPE zexcel_cell_column. * Propagate zcx_excel if error occurs "" issue #155 - less restrictive typing for ip_column lv_column = convert_column2int( ip_column ). "" issue #155 - less restrictive typing for ip_column *--------------------------------------------------------------------* * Check whether column is in allowed range for EXCEL to handle ( 1-16384 ) *--------------------------------------------------------------------* IF lv_column > 16384 OR lv_column < 1. zcx_excel=>raise_text( 'Index out of bounds' ). ENDIF. *--------------------------------------------------------------------* * Look up for previous succesfull cached result *--------------------------------------------------------------------* IF lv_column = sv_prev_in1 AND sv_prev_out1 IS NOT INITIAL. ep_column = sv_prev_out1. RETURN. ELSE. CLEAR sv_prev_out1. sv_prev_in1 = lv_column. ENDIF. *--------------------------------------------------------------------* * Build alpha representation of column *--------------------------------------------------------------------* WHILE lv_column GT 0. lv_module = ( lv_column - 1 ) MOD 26. lv_uccpi = 65 + lv_module. lv_column = ( lv_column - lv_module ) / 26. lv_text = cl_abap_conv_in_ce=>uccpi( lv_uccpi ). CONCATENATE lv_text ep_column INTO ep_column. ENDWHILE. *--------------------------------------------------------------------* * Save succesfull output into cache *--------------------------------------------------------------------* sv_prev_out1 = ep_column. ENDMETHOD. METHOD convert_column2int. *--------------------------------------------------------------------* * issue #230 - Pimp my Code * - Stefan Schmoecker, (done) 2012-12-29 * - ... * changes: renaming variables to naming conventions * removing unused variables * removing commented out code that is inactive for more then half a year * message made to support multilinguality * adding comments to explain what we are trying to achieve *--------------------------------------------------------------------* * issue#246 - error converting lower case column names * - Stefan Schmoecker, 2012-12-29 * changes: translating the correct variable to upper dase * adding missing exception if input is a number * that is out of bounds * adding missing exception if input contains * illegal characters like german umlauts *--------------------------------------------------------------------* DATA: lv_column TYPE zexcel_cell_column_alpha, lv_column_c TYPE c LENGTH 10, lv_column_s TYPE string, lv_errormessage TYPE string, "" Can't pass '...'(abc) to exception-class lv_modulo TYPE i. *--------------------------------------------------------------------* * This module tries to identify which column a user wants to access * Numbers as input are just passed back, anything else will be converted * using EXCEL nomenclatura A = 1, AA = 27, ..., XFD = 16384 *--------------------------------------------------------------------* *--------------------------------------------------------------------* * Normalize input ( upper case , no gaps ) *--------------------------------------------------------------------* lv_column_c = ip_column. * TRANSLATE lv_column TO UPPER CASE. "" Fix #246 TRANSLATE lv_column_c TO UPPER CASE. "" Fix #246 CONDENSE lv_column_c NO-GAPS. IF lv_column_c EQ ''. * lv_errormessage = 'Unable to interpret input as column'(003). MESSAGE e800(zabap2xlsx) INTO lv_errormessage. zcx_excel=>raise_symsg( ). ENDIF. *--------------------------------------------------------------------* * Look up for previous succesfull cached result *--------------------------------------------------------------------* IF lv_column_c = sv_prev_in2 AND sv_prev_out2 IS NOT INITIAL. ep_column = sv_prev_out2. RETURN. ELSE. CLEAR sv_prev_out2. sv_prev_in2 = lv_column_c. ENDIF. *--------------------------------------------------------------------* * If a number gets passed, just convert it to an integer and return * the converted value *--------------------------------------------------------------------* TRY. IF lv_column_c CO '1234567890 '. "" Fix #164 ep_column = lv_column_c. "" Fix #164 *--------------------------------------------------------------------* * Maximum column for EXCEL: XFD = 16384 "" if anyone has a reference for this information - please add here instead of this comment *--------------------------------------------------------------------* IF ep_column > 16384 OR ep_column < 1. lv_errormessage = 'Index out of bounds'(004). zcx_excel=>raise_text( lv_errormessage ). ENDIF. RETURN. ENDIF. CATCH cx_sy_conversion_no_number. ""#EC NO_HANDLER "" Try the character-approach if approach via number has failed ENDTRY. *--------------------------------------------------------------------* * Raise error if unexpected characters turns up *--------------------------------------------------------------------* lv_column_s = lv_column_c. IF lv_column_s CN sy-abcde. * lv_errormessage = 'Unable to interpret input as column'(003). MESSAGE e800(zabap2xlsx) INTO lv_errormessage. zcx_excel=>raise_symsg( ). ENDIF. DO 1 TIMES. ""Because of using CHECK *--------------------------------------------------------------------* * Interpret input as number to base 26 with A=1, ... Z=26 * Raise error if unexpected character turns up *--------------------------------------------------------------------* * 1st character *--------------------------------------------------------------------* lv_column = lv_column_c. lv_modulo = cl_abap_conv_out_ce=>uccpi( lv_column+0(1) ) MOD zcl_excel_common=>c_excel_col_module. IF lv_modulo < 1 OR lv_modulo > 26. * lv_errormessage = 'Unable to interpret input as column'(003). MESSAGE e800(zabap2xlsx) INTO lv_errormessage. zcx_excel=>raise_symsg( ). ENDIF. ep_column = lv_modulo. "" Leftmost digit *--------------------------------------------------------------------* * 2nd character if present *--------------------------------------------------------------------* CHECK lv_column+1(1) IS NOT INITIAL. "" No need to continue if string ended lv_modulo = cl_abap_conv_out_ce=>uccpi( lv_column+1(1) ) MOD zcl_excel_common=>c_excel_col_module. IF lv_modulo < 1 OR lv_modulo > 26. * lv_errormessage = 'Unable to interpret input as column'(003). MESSAGE e800(zabap2xlsx) INTO lv_errormessage. zcx_excel=>raise_symsg( ). ENDIF. ep_column = 26 * ep_column + lv_modulo. "" if second digit is present first digit is for 26^1 *--------------------------------------------------------------------* * 3rd character if present *--------------------------------------------------------------------* CHECK lv_column+2(1) IS NOT INITIAL. "" No need to continue if string ended lv_modulo = cl_abap_conv_out_ce=>uccpi( lv_column+2(1) ) MOD zcl_excel_common=>c_excel_col_module. IF lv_modulo < 1 OR lv_modulo > 26. * lv_errormessage = 'Unable to interpret input as column'(003). MESSAGE e800(zabap2xlsx) INTO lv_errormessage. zcx_excel=>raise_symsg( ). ENDIF. ep_column = 26 * ep_column + lv_modulo. "" if third digit is present first digit is for 26^2 and second digit for 26^1 ENDDO. *--------------------------------------------------------------------* * Maximum column for EXCEL: XFD = 16384 "" if anyone has a reference for this information - please add here instead of this comment *--------------------------------------------------------------------* IF ep_column > 16384 OR ep_column < 1. lv_errormessage = 'Index out of bounds'(004). zcx_excel=>raise_text( lv_errormessage ). ENDIF. *--------------------------------------------------------------------* * Save succesfull output into cache *--------------------------------------------------------------------* sv_prev_out2 = ep_column. ENDMETHOD. METHOD convert_columnrow2column_a_row. *--------------------------------------------------------------------* ""issue #256 - replacing char processing with regex *--------------------------------------------------------------------* * Stefan Schmoecker, 2013-08-11 * Allow input to be CLIKE instead of STRING *--------------------------------------------------------------------* DATA: pane_cell_row_a TYPE string, lv_columnrow TYPE string. lv_columnrow = i_columnrow. "" Get rid of trailing blanks FIND REGEX '^(\\D+)(\\d+)$' IN lv_columnrow SUBMATCHES e_column pane_cell_row_a. e_row = pane_cell_row_a. ENDMETHOD. METHOD convert_range2column_a_row. *--------------------------------------------------------------------* * issue #230 - Pimp my Code * - Stefan Schmoecker, (done) 2012-12-07 * - ... * changes: renaming variables to naming conventions * aligning code * added exceptionclass * added errorhandling for invalid range * adding comments to explain what we are trying to achieve *--------------------------------------------------------------------* * issue#241 - error when sheetname contains ""!"" * - sheetname should be returned unescaped * - Stefan Schmoecker, 2012-12-07 * changes: changed coding to support sheetnames with ""!"" * unescaping sheetname *--------------------------------------------------------------------* * issue#155 - lessening restrictions of input parameters * - Stefan Schmoecker, 2012-12-07 * changes: i_range changed to clike * e_sheet changed to clike *--------------------------------------------------------------------* DATA: lv_sheet TYPE string, lv_range TYPE string, lv_columnrow_start TYPE string, lv_columnrow_end TYPE string, lv_position TYPE i, lv_errormessage TYPE string. "" Can't pass '...'(abc) to exception-class *--------------------------------------------------------------------* * Split input range into sheetname and Area * 4 cases - a) input empty --> nothing to do * - b) sheetname existing - starts with ' example 'Sheet 1'!$B$6:$D$13 * - c) sheetname existing - does not start with ' example Sheet1!$B$6:$D$13 * - d) no sheetname - just area example $B$6:$D$13 *--------------------------------------------------------------------* * Initialize output parameters CLEAR: e_column_start, e_column_end, e_row_start, e_row_end, e_sheet. IF i_range IS INITIAL. "" a) input empty --> nothing to do RETURN. ELSEIF i_range(1) = `'`. "" b) sheetname existing - starts with ' FIND REGEX '\\![^\\!]*$' IN i_range MATCH OFFSET lv_position. "" Find last ! IF sy-subrc = 0. lv_sheet = i_range(lv_position). ADD 1 TO lv_position. lv_range = i_range. SHIFT lv_range LEFT BY lv_position PLACES. ELSE. lv_errormessage = 'Invalid range'(001). zcx_excel=>raise_text( lv_errormessage ). ENDIF. ELSEIF i_range CS '!'. "" c) sheetname existing - does not start with ' SPLIT i_range AT '!' INTO lv_sheet lv_range. "" begin Dennis Schaaf IF lv_range CP '*#REF*'. lv_errormessage = 'Invalid range'(001). zcx_excel=>raise_text( lv_errormessage ). ENDIF. "" end Dennis Schaaf ELSE. "" d) no sheetname - just area lv_range = i_range. ENDIF. REPLACE ALL OCCURRENCES OF '$' IN lv_range WITH ''. SPLIT lv_range AT ':' INTO lv_columnrow_start lv_columnrow_end. IF i_allow_1dim_range = abap_true. convert_columnrow2column_o_row( EXPORTING i_columnrow = lv_columnrow_start IMPORTING e_column = e_column_start e_row = e_row_start ). convert_columnrow2column_o_row( EXPORTING i_columnrow = lv_columnrow_end IMPORTING e_column = e_column_end e_row = e_row_end ). ELSE. convert_columnrow2column_a_row( EXPORTING i_columnrow = lv_columnrow_start IMPORTING e_column = e_column_start e_row = e_row_start ). convert_columnrow2column_a_row( EXPORTING i_columnrow = lv_columnrow_end IMPORTING e_column = e_column_end e_row = e_row_end ). ENDIF. e_sheet = unescape_string( lv_sheet ). "" Return in unescaped form ENDMETHOD. METHOD convert_columnrow2column_o_row. DATA: row TYPE string. DATA: columnrow TYPE string. CLEAR e_column. columnrow = i_columnrow. FIND REGEX '^(\\D*)(\\d*)$' IN columnrow SUBMATCHES e_column row. e_row = row. ENDMETHOD. METHOD date_to_excel_string. DATA: lv_date_diff TYPE i. CHECK ip_value IS NOT INITIAL AND ip_value <> space. "" Needed hack caused by the problem that: "" Excel 2000 incorrectly assumes that the year 1900 is a leap year "" http://support.microsoft.com/kb/214326/en-us IF ip_value > c_excel_1900_leap_year. lv_date_diff = ip_value - c_excel_baseline_date + 2. ELSE. lv_date_diff = ip_value - c_excel_baseline_date + 1. ENDIF. ep_value = zcl_excel_common=>number_to_excel_string( ip_value = lv_date_diff ). ENDMETHOD. METHOD describe_structure. DATA: lt_components TYPE abap_component_tab, lt_comps TYPE abap_component_tab, ls_component TYPE abap_componentdescr, lo_elemdescr TYPE REF TO cl_abap_elemdescr, ls_dfies TYPE dfies, l_position TYPE tabfdpos. ""for DDIC structure get the info directly IF io_struct->is_ddic_type( ) = abap_true. rt_dfies = io_struct->get_ddic_field_list( ). ELSE. lt_components = io_struct->get_components( ). LOOP AT lt_components INTO ls_component. structure_case( EXPORTING is_component = ls_component CHANGING xt_components = lt_comps ) . ENDLOOP. LOOP AT lt_comps INTO ls_component. CLEAR ls_dfies. IF ls_component-type->kind = cl_abap_typedescr=>kind_elem. ""E Elementary Type ADD 1 TO l_position. lo_elemdescr ?= ls_component-type. IF lo_elemdescr->is_ddic_type( ) = abap_true. ls_dfies = lo_elemdescr->get_ddic_field( ). ls_dfies-fieldname = ls_component-name. ls_dfies-position = l_position. ELSE. ls_dfies-fieldname = ls_component-name. ls_dfies-position = l_position. ls_dfies-inttype = lo_elemdescr->type_kind. ls_dfies-leng = lo_elemdescr->length. ls_dfies-outputlen = lo_elemdescr->length. ls_dfies-decimals = lo_elemdescr->decimals. ls_dfies-fieldtext = ls_component-name. ls_dfies-reptext = ls_component-name. ls_dfies-scrtext_s = ls_component-name. ls_dfies-scrtext_m = ls_component-name. ls_dfies-scrtext_l = ls_component-name. ls_dfies-dynpfld = abap_true. ENDIF. INSERT ls_dfies INTO TABLE rt_dfies. ENDIF. ENDLOOP. ENDIF. ENDMETHOD. METHOD determine_resulting_formula. DATA: lv_row_difference TYPE i, lv_col_difference TYPE i. *--------------------------------------------------------------------* * Calculate distance of reference and current cell *--------------------------------------------------------------------* calculate_cell_distance( EXPORTING iv_reference_cell = iv_reference_cell iv_current_cell = iv_current_cell IMPORTING ev_row_difference = lv_row_difference ev_col_difference = lv_col_difference ). *--------------------------------------------------------------------* * and shift formula by using the row- and columndistance *--------------------------------------------------------------------* ev_resulting_formula = shift_formula( iv_reference_formula = iv_reference_formula iv_shift_rows = lv_row_difference iv_shift_cols = lv_col_difference ). ENDMETHOD. ""determine_resulting_formula METHOD encrypt_password. DATA lv_curr_offset TYPE i. DATA lv_curr_char TYPE c LENGTH 1. DATA lv_curr_hex TYPE zexcel_pwd_hash. DATA lv_pwd_len TYPE zexcel_pwd_hash. DATA lv_pwd_hash TYPE zexcel_pwd_hash. CONSTANTS: lv_0x7fff TYPE zexcel_pwd_hash VALUE '7FFF', lv_0x0001 TYPE zexcel_pwd_hash VALUE '0001', lv_0xce4b TYPE zexcel_pwd_hash VALUE 'CE4B'. DATA lv_pwd TYPE zexcel_aes_password. lv_pwd = i_pwd. lv_pwd_len = strlen( lv_pwd ). lv_curr_offset = lv_pwd_len - 1. WHILE lv_curr_offset GE 0. lv_curr_char = lv_pwd+lv_curr_offset(1). lv_curr_hex = char2hex( lv_curr_char ). lv_pwd_hash = ( shr14( lv_pwd_hash ) BIT-AND lv_0x0001 ) BIT-OR ( shl01( lv_pwd_hash ) BIT-AND lv_0x7fff ). lv_pwd_hash = lv_pwd_hash BIT-XOR lv_curr_hex. SUBTRACT 1 FROM lv_curr_offset. ENDWHILE. lv_pwd_hash = ( shr14( lv_pwd_hash ) BIT-AND lv_0x0001 ) BIT-OR ( shl01( lv_pwd_hash ) BIT-AND lv_0x7fff ). lv_pwd_hash = lv_pwd_hash BIT-XOR lv_0xce4b. lv_pwd_hash = lv_pwd_hash BIT-XOR lv_pwd_len. WRITE lv_pwd_hash TO r_encrypted_pwd. ENDMETHOD. METHOD escape_string. *--------------------------------------------------------------------* * issue #230 - Pimp my Code * - Stefan Schmoecker, (done) 2012-12-08 * - ... * changes: aligning code * adding comments to explain what we are trying to achieve *--------------------------------------------------------------------* * issue#242 - Support escaping for white-spaces * - Escaping also necessary when ' encountered in input * - Stefan Schmoecker, 2012-12-08 * changes: switched check if escaping is necessary to regular expression * and moved the ""REPLACE"" *--------------------------------------------------------------------* * issue#155 - lessening restrictions of input parameters * - Stefan Schmoecker, 2012-12-08 * changes: ip_value changed to clike *--------------------------------------------------------------------* DATA: lv_value TYPE string. *--------------------------------------------------------------------* * There exist various situations when a space will be used to separate * different parts of a string. When we have a string consisting spaces * that will cause errors unless we ""escape"" the string by putting ' at * the beginning and at the end of the string. *--------------------------------------------------------------------* *--------------------------------------------------------------------* * When allowing clike-input parameters we might encounter trailing * ""real"" blanks . These are automatically eliminated when moving * the input parameter to a string. * Now any remaining spaces ( white-spaces or normal spaces ) should * trigger the escaping as well as any ' *--------------------------------------------------------------------* lv_value = ip_value. FIND REGEX `\\s|'` IN lv_value. "" \\s finds regular and white spaces IF sy-subrc = 0. REPLACE ALL OCCURRENCES OF `'` IN lv_value WITH `''`. CONCATENATE `'` lv_value `'` INTO lv_value . ENDIF. ep_escaped_value = lv_value. ENDMETHOD. METHOD excel_string_to_date. DATA: lv_date_int TYPE i. CHECK ip_value IS NOT INITIAL AND ip_value CN ' 0'. TRY. lv_date_int = ip_value. IF lv_date_int NOT BETWEEN 1 AND 2958465. zcx_excel=>raise_text( 'Unable to interpret date' ). ENDIF. ep_value = lv_date_int + c_excel_baseline_date - 2. "" Needed hack caused by the problem that: "" Excel 2000 incorrectly assumes that the year 1900 is a leap year "" http://support.microsoft.com/kb/214326/en-us IF ep_value < c_excel_1900_leap_year. ep_value = ep_value + 1. ENDIF. CATCH cx_sy_conversion_error. zcx_excel=>raise_text( 'Index out of bounds' ). ENDTRY. ENDMETHOD. METHOD excel_string_to_number. * If we encounter anything more complicated in EXCEL we might have to extend this * But currently this works fine - even for numbers in scientific notation ep_value = ip_value. ENDMETHOD. METHOD excel_string_to_time. DATA: lv_seconds_in_day TYPE i, lv_day_fraction TYPE f, lc_seconds_in_day TYPE i VALUE 86400. TRY. lv_day_fraction = ip_value. lv_seconds_in_day = lv_day_fraction * lc_seconds_in_day. ep_value = lv_seconds_in_day. CATCH cx_sy_conversion_error. zcx_excel=>raise_text( 'Unable to interpret time' ). ENDTRY. ENDMETHOD. METHOD get_fieldcatalog. DATA: lr_dref_tab TYPE REF TO data, lo_salv_table TYPE REF TO cl_salv_table, lo_salv_columns_table TYPE REF TO cl_salv_columns_table, lt_salv_t_column_ref TYPE salv_t_column_ref, ls_salv_t_column_ref LIKE LINE OF lt_salv_t_column_ref, lo_salv_column_table TYPE REF TO cl_salv_column_table. FIELD-SYMBOLS: TYPE STANDARD TABLE. FIELD-SYMBOLS: LIKE LINE OF ep_fieldcatalog. * Get copy of IP_TABLE-structure <-- must be changeable to create salv CREATE DATA lr_dref_tab LIKE ip_table. ASSIGN lr_dref_tab->* TO . * Create salv --> implicitly create fieldcat TRY. cl_salv_table=>factory( IMPORTING r_salv_table = lo_salv_table CHANGING t_table = ). lo_salv_columns_table = lo_salv_table->get_columns( ). lt_salv_t_column_ref = lo_salv_columns_table->get( ). CATCH cx_root. * maybe some errorhandling here - just haven't made up my mind yet ENDTRY. * Loop through columns and set relevant fields ( fieldname, texts ) LOOP AT lt_salv_t_column_ref INTO ls_salv_t_column_ref. lo_salv_column_table ?= ls_salv_t_column_ref-r_column. APPEND INITIAL LINE TO ep_fieldcatalog ASSIGNING . -position = sy-tabix. -fieldname = ls_salv_t_column_ref-columnname. -scrtext_s = ls_salv_t_column_ref-r_column->get_short_text( ). -scrtext_m = ls_salv_t_column_ref-r_column->get_medium_text( ). -scrtext_l = ls_salv_t_column_ref-r_column->get_long_text( ). -abap_type = lo_salv_column_table->get_ddic_inttype( ). -dynpfld = 'X'. "" What in the world would we exclude here? "" except for the MANDT-field of most tables ( 1st column that is ) IF -position = 1 AND lo_salv_column_table->get_ddic_datatype( ) = 'CLNT' AND iv_hide_mandt = abap_true. CLEAR -dynpfld. ENDIF. * For fields that don't a description ( i.e. defined by ""field type i,"" ) * just use the fieldname as description - that is better than nothing IF -scrtext_s IS INITIAL AND -scrtext_m IS INITIAL AND -scrtext_l IS INITIAL. CONCATENATE 'Col:' -fieldname INTO -scrtext_l SEPARATED BY space. -scrtext_m = -scrtext_l. -scrtext_s = -scrtext_l. ENDIF. ENDLOOP. ENDMETHOD. METHOD is_cell_in_range. DATA lv_column_start TYPE zexcel_cell_column_alpha. DATA lv_column_end TYPE zexcel_cell_column_alpha. DATA lv_row_start TYPE zexcel_cell_row. DATA lv_row_end TYPE zexcel_cell_row. DATA lv_column_start_i TYPE zexcel_cell_column. DATA lv_column_end_i TYPE zexcel_cell_column. DATA lv_column_i TYPE zexcel_cell_column. * Split range and convert columns convert_range2column_a_row( EXPORTING i_range = ip_range IMPORTING e_column_start = lv_column_start e_column_end = lv_column_end e_row_start = lv_row_start e_row_end = lv_row_end ). lv_column_start_i = convert_column2int( ip_column = lv_column_start ). lv_column_end_i = convert_column2int( ip_column = lv_column_end ). lv_column_i = convert_column2int( ip_column = ip_column ). * Check if cell is in range IF lv_column_i >= lv_column_start_i AND lv_column_i <= lv_column_end_i AND ip_row >= lv_row_start AND ip_row <= lv_row_end. rp_in_range = abap_true. ENDIF. ENDMETHOD. METHOD number_to_excel_string. DATA: lv_value_c TYPE c LENGTH 100. WRITE ip_value TO lv_value_c EXPONENT 0 NO-GROUPING NO-SIGN. REPLACE ALL OCCURRENCES OF ',' IN lv_value_c WITH '.'. ep_value = lv_value_c. CONDENSE ep_value. IF ip_value < 0. CONCATENATE '-' ep_value INTO ep_value. ELSEIF ip_value EQ 0. ep_value = '0'. ENDIF. ENDMETHOD. METHOD recursive_class_to_struct. "" # issue 139 * is working for me - but after looking through this coding I guess * I'll rewrite this to a version w/o recursion * This is private an no one using it so far except me, so no need to hurry DATA: descr TYPE REF TO cl_abap_structdescr, wa_component LIKE LINE OF descr->components, attribute_name LIKE wa_component-name, flag_class TYPE abap_bool. FIELD-SYMBOLS: TYPE any, TYPE any, TYPE any. descr ?= cl_abap_structdescr=>describe_by_data( e_target ). LOOP AT descr->components INTO wa_component. * Assign structure and X-structure ASSIGN COMPONENT wa_component-name OF STRUCTURE e_target TO . ASSIGN COMPONENT wa_component-name OF STRUCTURE e_targetx TO . * At least one field in the structure should be marked - otherwise continue with next field CLEAR flag_class. * maybe source is just a structure - try assign component... ASSIGN COMPONENT wa_component-name OF STRUCTURE i_source TO . IF sy-subrc <> 0. * not - then it is an attribute of the class - use different assign then CONCATENATE 'i_source->' wa_component-name INTO attribute_name. ASSIGN (attribute_name) TO . IF sy-subrc <> 0. EXIT. ENDIF. "" Should not happen if structure is built properly - otherwise just exit to create no dumps flag_class = abap_true. ENDIF. CASE wa_component-type_kind. WHEN cl_abap_structdescr=>typekind_struct1 OR cl_abap_structdescr=>typekind_struct2. "" Structure --> use recursio * IF flag_class = abap_true. ** Only borders will be passed as unbound references. But since we want to set a value we have to create an instance * ENDIF. zcl_excel_common=>recursive_class_to_struct( EXPORTING i_source = CHANGING e_target = e_targetx = ). WHEN OTHERS. = . = abap_true. ENDCASE. ENDLOOP. ENDMETHOD. METHOD recursive_struct_to_class. "" # issue 139 * is working for me - but after looking through this coding I guess * I'll rewrite this to a version w/o recursion * This is private an no one using it so far except me, so no need to hurry DATA: descr TYPE REF TO cl_abap_structdescr, wa_component LIKE LINE OF descr->components, attribute_name LIKE wa_component-name, flag_class TYPE abap_bool, o_border TYPE REF TO zcl_excel_style_border. FIELD-SYMBOLS: TYPE any, TYPE any, TYPE any. descr ?= cl_abap_structdescr=>describe_by_data( i_source ). LOOP AT descr->components INTO wa_component. * Assign structure and X-structure ASSIGN COMPONENT wa_component-name OF STRUCTURE i_source TO . ASSIGN COMPONENT wa_component-name OF STRUCTURE i_sourcex TO . * At least one field in the structure should be marked - otherwise continue with next field CHECK CA abap_true. CLEAR flag_class. * maybe target is just a structure - try assign component... ASSIGN COMPONENT wa_component-name OF STRUCTURE e_target TO . IF sy-subrc <> 0. * not - then it is an attribute of the class - use different assign then CONCATENATE 'E_TARGET->' wa_component-name INTO attribute_name. ASSIGN (attribute_name) TO . IF sy-subrc <> 0.EXIT.ENDIF. "" Should not happen if structure is built properly - otherwise just exit to create no dumps flag_class = abap_true. ENDIF. CASE wa_component-type_kind. WHEN cl_abap_structdescr=>typekind_struct1 OR cl_abap_structdescr=>typekind_struct2. "" Structure --> use recursion "" To avoid dump with attribute GRADTYPE of class ZCL_EXCEL_STYLE_FILL "" quick and really dirty fix -> check the attribute name "" Border has to be initialized somewhere else IF wa_component-name EQ 'GRADTYPE'. flag_class = abap_false. ENDIF. IF flag_class = abap_true AND IS INITIAL. * Only borders will be passed as unbound references. But since we want to set a value we have to create an instance CREATE OBJECT o_border. = o_border. ENDIF. zcl_excel_common=>recursive_struct_to_class( EXPORTING i_source = i_sourcex = CHANGING e_target = ). * WHEN cl_abap_structdescr=>typekind_struct2. "" String * CHECK = abap_true. "" Marked for change * = . WHEN OTHERS. CHECK = abap_true. "" Marked for change = . ENDCASE. ENDLOOP. ENDMETHOD. METHOD shift_formula. CONSTANTS: lcv_operators TYPE string VALUE '+-/*^%=<>&, !', lcv_letters TYPE string VALUE 'ABCDEFGHIJKLMNOPQRSTUVWXYZ$', lcv_digits TYPE string VALUE '0123456789', lcv_cell_reference_error TYPE string VALUE '#REF!'. DATA: lv_tcnt TYPE i, "" Counter variable lv_tlen TYPE i, "" Temp variable length lv_cnt TYPE i, "" Counter variable lv_cnt2 TYPE i, "" Counter variable lv_offset1 TYPE i, "" Character offset lv_numchars TYPE i, "" Number of characters counter lv_tchar(1) TYPE c, "" Temp character lv_tchar2(1) TYPE c, "" Temp character lv_cur_form TYPE string, "" Formula for current cell lv_ref_cell_addr TYPE string, "" Reference cell address lv_tcol1 TYPE string, "" Temp column letter lv_tcol2 TYPE string, "" Temp column letter lv_tcoln TYPE i, "" Temp column number lv_trow1 TYPE string, "" Temp row number lv_trow2 TYPE string, "" Temp row number lv_flen TYPE i, "" Length of reference formula lv_tlen2 TYPE i, "" Temp variable length lv_substr1 TYPE string, "" Substring variable lv_abscol TYPE string, "" Absolute column symbol lv_absrow TYPE string, "" Absolute row symbol lv_ref_formula TYPE string, lv_compare_1 TYPE string, lv_compare_2 TYPE string, lv_level TYPE i, "" Level of groups [..[..]..] or {..} lv_errormessage TYPE string. *--------------------------------------------------------------------* * When copying a cell in EXCEL to another cell any inherent formulas * are copied as well. Cell-references in the formula are being adjusted * by the distance of the new cell to the original one *--------------------------------------------------------------------* * §1 Parse reference formula character by character * §2 Identify Cell-references * §3 Shift cell-reference * §4 Build resulting formula *--------------------------------------------------------------------* lv_ref_formula = iv_reference_formula. *--------------------------------------------------------------------* * No distance --> Reference = resulting cell/formula *--------------------------------------------------------------------* IF iv_shift_cols = 0 AND iv_shift_rows = 0. ev_resulting_formula = lv_ref_formula. RETURN. "" done ENDIF. lv_flen = strlen( lv_ref_formula ). lv_numchars = 1. *--------------------------------------------------------------------* * §1 Parse reference formula character by character *--------------------------------------------------------------------* DO lv_flen TIMES. CLEAR: lv_tchar, lv_substr1, lv_ref_cell_addr. lv_cnt2 = lv_cnt + 1. IF lv_cnt2 > lv_flen. EXIT. "" Done ENDIF. *--------------------------------------------------------------------* * Here we have the current character in the formula *--------------------------------------------------------------------* lv_tchar = lv_ref_formula+lv_cnt(1). *--------------------------------------------------------------------* * Operators or opening parenthesis will separate possible cellreferences *--------------------------------------------------------------------* IF ( lv_tchar CA lcv_operators OR lv_tchar CA '(' ) AND lv_cnt2 = 1. lv_substr1 = lv_ref_formula+lv_offset1(1). CONCATENATE lv_cur_form lv_substr1 INTO lv_cur_form. lv_cnt = lv_cnt + 1. lv_offset1 = lv_cnt. lv_numchars = 1. CONTINUE. "" --> next character in formula can be analyzed ENDIF. *--------------------------------------------------------------------* * Quoted literal text holds no cell reference --> advance to end of text *--------------------------------------------------------------------* IF lv_tchar EQ '""'. lv_cnt = lv_cnt + 1. lv_numchars = lv_numchars + 1. lv_tchar = lv_ref_formula+lv_cnt(1). WHILE lv_tchar NE '""'. lv_cnt = lv_cnt + 1. lv_numchars = lv_numchars + 1. lv_tchar = lv_ref_formula+lv_cnt(1). ENDWHILE. lv_cnt2 = lv_cnt + 1. lv_substr1 = lv_ref_formula+lv_offset1(lv_numchars). CONCATENATE lv_cur_form lv_substr1 INTO lv_cur_form. lv_cnt = lv_cnt + 1. IF lv_cnt = lv_flen. EXIT. ENDIF. lv_offset1 = lv_cnt. lv_numchars = 1. lv_tchar = lv_ref_formula+lv_cnt(1). lv_cnt2 = lv_cnt + 1. CONTINUE. "" --> next character in formula can be analyzed ENDIF. *--------------------------------------------------------------------* * Groups - Ignore values inside blocks [..[..]..] and {..} * R1C1-Style Cell Reference: R[1]C[1] * Cell References: 'C:\\[Source.xlsx]Sheet1'!$A$1 * Array constants: {1,3.5,TRUE,""Hello""} * ""Intra table reference"": Flights[[#This Row],[Air fare]] *--------------------------------------------------------------------* IF lv_tchar CA '[]{}' OR lv_level > 0. IF lv_tchar CA '[{'. lv_level = lv_level + 1. ELSEIF lv_tchar CA ']}'. lv_level = lv_level - 1. ENDIF. IF lv_cnt2 = lv_flen. lv_substr1 = iv_reference_formula+lv_offset1(lv_numchars). CONCATENATE lv_cur_form lv_substr1 INTO lv_cur_form. EXIT. ENDIF. lv_numchars = lv_numchars + 1. lv_cnt = lv_cnt + 1. lv_cnt2 = lv_cnt + 1. CONTINUE. ENDIF. *--------------------------------------------------------------------* * Operators or parenthesis or last character in formula will separate possible cellreferences *--------------------------------------------------------------------* IF lv_tchar CA lcv_operators OR lv_tchar CA '():' OR lv_cnt2 = lv_flen. IF lv_cnt > 0. lv_substr1 = lv_ref_formula+lv_offset1(lv_numchars). *--------------------------------------------------------------------* * Check for text concatenation and functions *--------------------------------------------------------------------* IF ( lv_tchar CA lcv_operators AND lv_tchar EQ lv_substr1 ) OR lv_tchar EQ '('. CONCATENATE lv_cur_form lv_substr1 INTO lv_cur_form. lv_cnt = lv_cnt + 1. lv_offset1 = lv_cnt. lv_cnt2 = lv_cnt + 1. lv_numchars = 1. CONTINUE. "" --> next character in formula can be analyzed ENDIF. lv_tlen = lv_cnt2 - lv_offset1. *--------------------------------------------------------------------* * Exclude mathematical operators and closing parentheses *--------------------------------------------------------------------* IF lv_tchar CA lcv_operators OR lv_tchar CA ':)'. IF lv_cnt2 = lv_flen AND lv_numchars = 1. CONCATENATE lv_cur_form lv_substr1 INTO lv_cur_form. lv_cnt = lv_cnt + 1. lv_offset1 = lv_cnt. lv_cnt2 = lv_cnt + 1. lv_numchars = 1. CONTINUE. "" --> next character in formula can be analyzed ELSE. lv_tlen = lv_tlen - 1. ENDIF. ENDIF. *--------------------------------------------------------------------* * Capture reference cell address *--------------------------------------------------------------------* TRY. MOVE: lv_ref_formula+lv_offset1(lv_tlen) TO lv_ref_cell_addr. ""Ref cell address CATCH cx_root. lv_errormessage = 'Internal error in Class ZCL_EXCEL_COMMON Method SHIFT_FORMULA Spot 1 '. "" Change to messageclass if possible zcx_excel=>raise_text( lv_errormessage ). ENDTRY. *--------------------------------------------------------------------* * Split cell address into characters and numbers *--------------------------------------------------------------------* CLEAR: lv_tlen, lv_tcnt, lv_tcol1, lv_trow1. lv_tlen = strlen( lv_ref_cell_addr ). IF lv_tlen <> 0. CLEAR: lv_tcnt. DO lv_tlen TIMES. CLEAR: lv_tchar2. lv_tchar2 = lv_ref_cell_addr+lv_tcnt(1). IF lv_tchar2 CA lcv_letters. CONCATENATE lv_tcol1 lv_tchar2 INTO lv_tcol1. ELSEIF lv_tchar2 CA lcv_digits. CONCATENATE lv_trow1 lv_tchar2 INTO lv_trow1. ENDIF. lv_tcnt = lv_tcnt + 1. ENDDO. ENDIF. "" Is valid column & row ? IF lv_tcol1 IS NOT INITIAL AND lv_trow1 IS NOT INITIAL. "" COLUMN + ROW CONCATENATE lv_tcol1 lv_trow1 INTO lv_compare_1. "" Original condensed string lv_compare_2 = lv_ref_cell_addr. CONDENSE lv_compare_2. IF lv_compare_1 <> lv_compare_2. CLEAR: lv_trow1, lv_tchar2. ENDIF. ENDIF. *--------------------------------------------------------------------* * Check for invalid cell address *--------------------------------------------------------------------* IF lv_tcol1 IS INITIAL OR lv_trow1 IS INITIAL. CONCATENATE lv_cur_form lv_substr1 INTO lv_cur_form. lv_cnt = lv_cnt + 1. lv_offset1 = lv_cnt. lv_cnt2 = lv_cnt + 1. lv_numchars = 1. CONTINUE. ENDIF. *--------------------------------------------------------------------* * Check for range names *--------------------------------------------------------------------* CLEAR: lv_tlen. lv_tlen = strlen( lv_tcol1 ). IF lv_tlen GT 3. CONCATENATE lv_cur_form lv_substr1 INTO lv_cur_form. lv_cnt = lv_cnt + 1. lv_offset1 = lv_cnt. lv_cnt2 = lv_cnt + 1. lv_numchars = 1. CONTINUE. ENDIF. *--------------------------------------------------------------------* * Check for valid row *--------------------------------------------------------------------* IF lv_trow1 GT 1048576. CONCATENATE lv_cur_form lv_substr1 INTO lv_cur_form. lv_cnt = lv_cnt + 1. lv_offset1 = lv_cnt. lv_cnt2 = lv_cnt + 1. lv_numchars = 1. CONTINUE. ENDIF. *--------------------------------------------------------------------* * Check for absolute column or row reference *--------------------------------------------------------------------* CLEAR: lv_tcol2, lv_trow2, lv_abscol, lv_absrow. lv_tlen2 = strlen( lv_tcol1 ) - 1. IF lv_tcol1 IS NOT INITIAL. lv_abscol = lv_tcol1(1). ENDIF. IF lv_tlen2 GE 0. lv_absrow = lv_tcol1+lv_tlen2(1). ENDIF. IF lv_abscol EQ '$' AND lv_absrow EQ '$'. lv_tlen2 = lv_tlen2 - 1. IF lv_tlen2 > 0. lv_tcol1 = lv_tcol1+1(lv_tlen2). ENDIF. lv_tlen2 = lv_tlen2 + 1. ELSEIF lv_abscol EQ '$'. lv_tcol1 = lv_tcol1+1(lv_tlen2). ELSEIF lv_absrow EQ '$'. lv_tcol1 = lv_tcol1(lv_tlen2). ENDIF. *--------------------------------------------------------------------* * Check for valid column *--------------------------------------------------------------------* TRY. lv_tcoln = zcl_excel_common=>convert_column2int( lv_tcol1 ) + iv_shift_cols. CATCH zcx_excel. CONCATENATE lv_cur_form lv_substr1 INTO lv_cur_form. lv_cnt = lv_cnt + 1. lv_offset1 = lv_cnt. lv_cnt2 = lv_cnt + 1. lv_numchars = 1. CONTINUE. ENDTRY. *--------------------------------------------------------------------* * Check whether there is a referencing problem *--------------------------------------------------------------------* lv_trow2 = lv_trow1 + iv_shift_rows. "" Remove the space used for the sign CONDENSE lv_trow2. IF ( lv_tcoln < 1 AND lv_abscol <> '$' ) "" Maybe we should add here max-column and max row-tests as well. OR ( lv_trow2 < 1 AND lv_absrow <> '$' ). "" Check how EXCEL behaves in this case *--------------------------------------------------------------------* * Referencing problem encountered --> set error *--------------------------------------------------------------------* CONCATENATE lv_cur_form lcv_cell_reference_error INTO lv_cur_form. ELSE. *--------------------------------------------------------------------* * No referencing problems --> adjust row and column *--------------------------------------------------------------------* *--------------------------------------------------------------------* * Adjust column *--------------------------------------------------------------------* IF lv_abscol EQ '$'. CONCATENATE lv_cur_form lv_abscol lv_tcol1 INTO lv_cur_form. ELSEIF iv_shift_cols EQ 0. CONCATENATE lv_cur_form lv_tcol1 INTO lv_cur_form. ELSE. TRY. lv_tcol2 = zcl_excel_common=>convert_column2alpha( lv_tcoln ). CONCATENATE lv_cur_form lv_tcol2 INTO lv_cur_form. CATCH zcx_excel. CONCATENATE lv_cur_form lv_substr1 INTO lv_cur_form. lv_cnt = lv_cnt + 1. lv_offset1 = lv_cnt. lv_cnt2 = lv_cnt + 1. lv_numchars = 1. CONTINUE. ENDTRY. ENDIF. *--------------------------------------------------------------------* * Adjust row *--------------------------------------------------------------------* IF lv_absrow EQ '$'. CONCATENATE lv_cur_form lv_absrow lv_trow1 INTO lv_cur_form. ELSEIF iv_shift_rows = 0. CONCATENATE lv_cur_form lv_trow1 INTO lv_cur_form. * elseif lv_trow2 < 1. * CONCATENATE lv_cur_form lc_cell_reference_error INTO lv_cur_form. ELSE. CONCATENATE lv_cur_form lv_trow2 INTO lv_cur_form. ENDIF. ENDIF. lv_numchars = 0. IF lv_tchar CA lcv_operators OR lv_tchar CA ':)'. CONCATENATE lv_cur_form lv_tchar INTO lv_cur_form RESPECTING BLANKS. ENDIF. lv_offset1 = lv_cnt2. ENDIF. ENDIF. lv_numchars = lv_numchars + 1. lv_cnt = lv_cnt + 1. lv_cnt2 = lv_cnt + 1. ENDDO. *--------------------------------------------------------------------* * Return resulting formula *--------------------------------------------------------------------* IF lv_cur_form IS NOT INITIAL. MOVE lv_cur_form TO ev_resulting_formula. ENDIF. ENDMETHOD. METHOD shl01. DATA: lv_bit TYPE i, lv_curr_pos TYPE i VALUE 2, lv_prev_pos TYPE i VALUE 1. DO 15 TIMES. GET BIT lv_curr_pos OF i_pwd_hash INTO lv_bit. SET BIT lv_prev_pos OF r_pwd_hash TO lv_bit. ADD 1 TO lv_curr_pos. ADD 1 TO lv_prev_pos. ENDDO. SET BIT 16 OF r_pwd_hash TO 0. ENDMETHOD. METHOD shr14. DATA: lv_bit TYPE i, lv_curr_pos TYPE i, lv_next_pos TYPE i. r_pwd_hash = i_pwd_hash. DO 14 TIMES. lv_curr_pos = 15. lv_next_pos = 16. DO 15 TIMES. GET BIT lv_curr_pos OF r_pwd_hash INTO lv_bit. SET BIT lv_next_pos OF r_pwd_hash TO lv_bit. SUBTRACT 1 FROM lv_curr_pos. SUBTRACT 1 FROM lv_next_pos. ENDDO. SET BIT 1 OF r_pwd_hash TO 0. ENDDO. ENDMETHOD. METHOD split_file. DATA: lt_hlp TYPE TABLE OF text255, ls_hlp TYPE text255. DATA: lf_ext(10) TYPE c, lf_dot_ext(10) TYPE c. DATA: lf_anz TYPE i, lf_len TYPE i. ** --------------------------------------------------------------------- CLEAR: lt_hlp, ep_file, ep_extension, ep_dotextension. ** Split the whole file at '.' SPLIT ip_file AT '.' INTO TABLE lt_hlp. ** get the extenstion from the last line of table DESCRIBE TABLE lt_hlp LINES lf_anz. IF lf_anz <= 1. ep_file = ip_file. RETURN. ENDIF. READ TABLE lt_hlp INTO ls_hlp INDEX lf_anz. ep_extension = ls_hlp. lf_ext = ls_hlp. IF NOT lf_ext IS INITIAL. CONCATENATE '.' lf_ext INTO lf_dot_ext. ENDIF. ep_dotextension = lf_dot_ext. ** get only the filename lf_len = strlen( ip_file ) - strlen( lf_dot_ext ). IF lf_len > 0. ep_file = ip_file(lf_len). ENDIF. ENDMETHOD. METHOD structure_case. DATA: lt_comp_str TYPE abap_component_tab. CASE is_component-type->kind. WHEN cl_abap_typedescr=>kind_elem. ""E Elementary Type INSERT is_component INTO TABLE xt_components. WHEN cl_abap_typedescr=>kind_table. ""T Table INSERT is_component INTO TABLE xt_components. WHEN cl_abap_typedescr=>kind_struct. ""S Structure lt_comp_str = structure_recursive( is_component = is_component ). INSERT LINES OF lt_comp_str INTO TABLE xt_components. WHEN OTHERS. ""cl_abap_typedescr=>kind_ref or cl_abap_typedescr=>kind_class or cl_abap_typedescr=>kind_intf. * We skip it. for now. ENDCASE. ENDMETHOD. METHOD structure_recursive. DATA: lo_struct TYPE REF TO cl_abap_structdescr, lt_components TYPE abap_component_tab, ls_components TYPE abap_componentdescr. REFRESH rt_components. lo_struct ?= is_component-type. lt_components = lo_struct->get_components( ). LOOP AT lt_components INTO ls_components. structure_case( EXPORTING is_component = ls_components CHANGING xt_components = rt_components ) . ENDLOOP. ENDMETHOD. METHOD time_to_excel_string. DATA: lv_seconds_in_day TYPE i, lv_day_fraction TYPE f, lc_time_baseline TYPE t VALUE '000000', lc_seconds_in_day TYPE i VALUE 86400. lv_seconds_in_day = ip_value - lc_time_baseline. lv_day_fraction = lv_seconds_in_day / lc_seconds_in_day. ep_value = zcl_excel_common=>number_to_excel_string( ip_value = lv_day_fraction ). ENDMETHOD. METHOD unescape_string. CONSTANTS lcv_regex TYPE string VALUE `^'[^']` & `|` & "" Beginning single ' OR `[^']'$` & `|` & "" Trailing single ' OR `[^']'[^']`. "" Single ' somewhere in between DATA: lv_errormessage TYPE string. "" Can't pass '...'(abc) to exception-class *--------------------------------------------------------------------* * This method is used to extract the ""real"" string from an escaped string. * An escaped string can be identified by a beginning ' which must be * accompanied by a trailing ' * All '' in between beginning and trailing ' are treated as single ' *--------------------------------------------------------------------* *--------------------------------------------------------------------* * When allowing clike-input parameters we might encounter trailing * ""real"" blanks . These are automatically eliminated when moving * the input parameter to a string. *--------------------------------------------------------------------* ev_unescaped_string = iv_escaped. "" Pass through if not escaped CHECK ev_unescaped_string IS NOT INITIAL. "" Nothing to do if empty CHECK ev_unescaped_string(1) = `'`. "" Nothing to do if not escaped *--------------------------------------------------------------------* * Remove leading and trailing ' *--------------------------------------------------------------------* REPLACE REGEX `^'(.*)'$` IN ev_unescaped_string WITH '$1'. IF sy-subrc <> 0. lv_errormessage = 'Input not properly escaped - &'(002). zcx_excel=>raise_text( lv_errormessage ). ENDIF. *--------------------------------------------------------------------* * Any remaining single ' should not be here *--------------------------------------------------------------------* FIND REGEX lcv_regex IN ev_unescaped_string. IF sy-subrc = 0. lv_errormessage = 'Input not properly escaped - &'(002). zcx_excel=>raise_text( lv_errormessage ). ENDIF. *--------------------------------------------------------------------* * Replace '' with ' *--------------------------------------------------------------------* REPLACE ALL OCCURRENCES OF `''` IN ev_unescaped_string WITH `'`. ENDMETHOD. ENDCLASS. ",14446,True,2626.6620936644094,median "----------------------------------------------------------------------- -- AWA.Wikis.Models -- AWA.Wikis.Models ----------------------------------------------------------------------- -- File generated by ada-gen DO NOT MODIFY -- Template used: templates/model/package-spec.xhtml -- Ada Generator: https://ada-gen.googlecode.com/svn/trunk Revision 1095 ----------------------------------------------------------------------- -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the ""License""); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an ""AS IS"" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- pragma Warnings (Off); with ADO.Sessions; with ADO.Objects; with ADO.Statements; with ADO.SQL; with ADO.Schemas; with ADO.Queries; with ADO.Queries.Loaders; with Ada.Calendar; with Ada.Containers.Vectors; with Ada.Strings.Unbounded; with Util.Beans.Objects; with Util.Beans.Objects.Enums; with Util.Beans.Basic.Lists; with AWA.Images.Models; with AWA.Storages.Models; with AWA.Users.Models; with AWA.Workspaces.Models; with Util.Beans.Methods; pragma Warnings (On); package AWA.Wikis.Models is pragma Style_Checks (""-mr""); type Format_Type is (FORMAT_CREOLE, FORMAT_HTML, FORMAT_MARKDOWN, FORMAT_DOTCLEAR, FORMAT_MEDIAWIKI, FORMAT_PHPBB); for Format_Type use (FORMAT_CREOLE => 0, FORMAT_HTML => 1, FORMAT_MARKDOWN => 2, FORMAT_DOTCLEAR => 3, FORMAT_MEDIAWIKI => 4, FORMAT_PHPBB => 5); package Format_Type_Objects is new Util.Beans.Objects.Enums (Format_Type); type Wiki_Space_Ref is new ADO.Objects.Object_Ref with null record; type Wiki_Page_Ref is new ADO.Objects.Object_Ref with null record; type Wiki_Content_Ref is new ADO.Objects.Object_Ref with null record; -- -------------------- -- Permission is granted to display a wiki page if there is -- an ACL entry between the wiki space and the user. -- -------------------- -- Create an object key for Wiki_Space. function Wiki_Space_Key (Id : in ADO.Identifier) return ADO.Objects.Object_Key; -- Create an object key for Wiki_Space from a string. -- Raises Constraint_Error if the string cannot be converted into the object key. function Wiki_Space_Key (Id : in String) return ADO.Objects.Object_Key; Null_Wiki_Space : constant Wiki_Space_Ref; function ""="" (Left, Right : Wiki_Space_Ref'Class) return Boolean; -- Set the wiki space identifier procedure Set_Id (Object : in out Wiki_Space_Ref; Value : in ADO.Identifier); -- Get the wiki space identifier function Get_Id (Object : in Wiki_Space_Ref) return ADO.Identifier; -- Set the wiki name procedure Set_Name (Object : in out Wiki_Space_Ref; Value : in Ada.Strings.Unbounded.Unbounded_String); procedure Set_Name (Object : in out Wiki_Space_Ref; Value : in String); -- Get the wiki name function Get_Name (Object : in Wiki_Space_Ref) return Ada.Strings.Unbounded.Unbounded_String; function Get_Name (Object : in Wiki_Space_Ref) return String; -- Set whether the wiki is public procedure Set_Is_Public (Object : in out Wiki_Space_Ref; Value : in Boolean); -- Get whether the wiki is public function Get_Is_Public (Object : in Wiki_Space_Ref) return Boolean; -- function Get_Version (Object : in Wiki_Space_Ref) return Integer; -- Set the wiki creation date. procedure Set_Create_Date (Object : in out Wiki_Space_Ref; Value : in Ada.Calendar.Time); -- Get the wiki creation date. function Get_Create_Date (Object : in Wiki_Space_Ref) return Ada.Calendar.Time; -- Set the left panel side wiki text for every page. procedure Set_Left_Side (Object : in out Wiki_Space_Ref; Value : in Ada.Strings.Unbounded.Unbounded_String); procedure Set_Left_Side (Object : in out Wiki_Space_Ref; Value : in String); -- Get the left panel side wiki text for every page. function Get_Left_Side (Object : in Wiki_Space_Ref) return Ada.Strings.Unbounded.Unbounded_String; function Get_Left_Side (Object : in Wiki_Space_Ref) return String; -- Set the right panel wiki text for every page. procedure Set_Right_Side (Object : in out Wiki_Space_Ref; Value : in Ada.Strings.Unbounded.Unbounded_String); procedure Set_Right_Side (Object : in out Wiki_Space_Ref; Value : in String); -- Get the right panel wiki text for every page. function Get_Right_Side (Object : in Wiki_Space_Ref) return Ada.Strings.Unbounded.Unbounded_String; function Get_Right_Side (Object : in Wiki_Space_Ref) return String; -- Set the default wiki page format. procedure Set_Format (Object : in out Wiki_Space_Ref; Value : in AWA.Wikis.Models.Format_Type); -- Get the default wiki page format. function Get_Format (Object : in Wiki_Space_Ref) return AWA.Wikis.Models.Format_Type; -- procedure Set_Workspace (Object : in out Wiki_Space_Ref; Value : in AWA.Workspaces.Models.Workspace_Ref'Class); -- function Get_Workspace (Object : in Wiki_Space_Ref) return AWA.Workspaces.Models.Workspace_Ref'Class; -- Load the entity identified by 'Id'. -- Raises the NOT_FOUND exception if it does not exist. procedure Load (Object : in out Wiki_Space_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier); -- Load the entity identified by 'Id'. -- Returns True in Found if the object was found and False if it does not exist. procedure Load (Object : in out Wiki_Space_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier; Found : out Boolean); -- Find and load the entity. overriding procedure Find (Object : in out Wiki_Space_Ref; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean); -- Save the entity. If the entity does not have an identifier, an identifier is allocated -- and it is inserted in the table. Otherwise, only data fields which have been changed -- are updated. overriding procedure Save (Object : in out Wiki_Space_Ref; Session : in out ADO.Sessions.Master_Session'Class); -- Delete the entity. overriding procedure Delete (Object : in out Wiki_Space_Ref; Session : in out ADO.Sessions.Master_Session'Class); overriding function Get_Value (From : in Wiki_Space_Ref; Name : in String) return Util.Beans.Objects.Object; -- Table definition WIKI_SPACE_TABLE : constant ADO.Schemas.Class_Mapping_Access; -- Internal method to allocate the Object_Record instance overriding procedure Allocate (Object : in out Wiki_Space_Ref); -- Copy of the object. procedure Copy (Object : in Wiki_Space_Ref; Into : in out Wiki_Space_Ref); -- -------------------- -- The wiki page represents a page with its versions. -- It refers to the last version which is currently visible. -- It has an optional preview image which defines -- the thumbnail preview of the last/current wiki content. -- -------------------- -- Create an object key for Wiki_Page. function Wiki_Page_Key (Id : in ADO.Identifier) return ADO.Objects.Object_Key; -- Create an object key for Wiki_Page from a string. -- Raises Constraint_Error if the string cannot be converted into the object key. function Wiki_Page_Key (Id : in String) return ADO.Objects.Object_Key; Null_Wiki_Page : constant Wiki_Page_Ref; function ""="" (Left, Right : Wiki_Page_Ref'Class) return Boolean; -- Set the wiki page identifier procedure Set_Id (Object : in out Wiki_Page_Ref; Value : in ADO.Identifier); -- Get the wiki page identifier function Get_Id (Object : in Wiki_Page_Ref) return ADO.Identifier; -- Set the wiki page name procedure Set_Name (Object : in out Wiki_Page_Ref; Value : in Ada.Strings.Unbounded.Unbounded_String); procedure Set_Name (Object : in out Wiki_Page_Ref; Value : in String); -- Get the wiki page name function Get_Name (Object : in Wiki_Page_Ref) return Ada.Strings.Unbounded.Unbounded_String; function Get_Name (Object : in Wiki_Page_Ref) return String; -- Set the last page version number procedure Set_Last_Version (Object : in out Wiki_Page_Ref; Value : in Integer); -- Get the last page version number function Get_Last_Version (Object : in Wiki_Page_Ref) return Integer; -- Set whether the wiki page is public procedure Set_Is_Public (Object : in out Wiki_Page_Ref; Value : in Boolean); -- Get whether the wiki page is public function Get_Is_Public (Object : in Wiki_Page_Ref) return Boolean; -- Set the page title procedure Set_Title (Object : in out Wiki_Page_Ref; Value : in Ada.Strings.Unbounded.Unbounded_String); procedure Set_Title (Object : in out Wiki_Page_Ref; Value : in String); -- Get the page title function Get_Title (Object : in Wiki_Page_Ref) return Ada.Strings.Unbounded.Unbounded_String; function Get_Title (Object : in Wiki_Page_Ref) return String; -- function Get_Version (Object : in Wiki_Page_Ref) return Integer; -- Set a read counter which indicates how many times the page was read. procedure Set_Read_Count (Object : in out Wiki_Page_Ref; Value : in Integer); -- Get a read counter which indicates how many times the page was read. function Get_Read_Count (Object : in Wiki_Page_Ref) return Integer; -- Set the wiki page preview. procedure Set_Preview (Object : in out Wiki_Page_Ref; Value : in AWA.Images.Models.Image_Ref'Class); -- Get the wiki page preview. function Get_Preview (Object : in Wiki_Page_Ref) return AWA.Images.Models.Image_Ref'Class; -- Set the wiki space that this page belongs to procedure Set_Wiki (Object : in out Wiki_Page_Ref; Value : in AWA.Wikis.Models.Wiki_Space_Ref'Class); -- Get the wiki space that this page belongs to function Get_Wiki (Object : in Wiki_Page_Ref) return AWA.Wikis.Models.Wiki_Space_Ref'Class; -- Set the current content (or last version) procedure Set_Content (Object : in out Wiki_Page_Ref; Value : in AWA.Wikis.Models.Wiki_Content_Ref'Class); -- Get the current content (or last version) function Get_Content (Object : in Wiki_Page_Ref) return AWA.Wikis.Models.Wiki_Content_Ref'Class; -- Load the entity identified by 'Id'. -- Raises the NOT_FOUND exception if it does not exist. procedure Load (Object : in out Wiki_Page_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier); -- Load the entity identified by 'Id'. -- Returns True in Found if the object was found and False if it does not exist. procedure Load (Object : in out Wiki_Page_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier; Found : out Boolean); -- Find and load the entity. overriding procedure Find (Object : in out Wiki_Page_Ref; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean); -- Save the entity. If the entity does not have an identifier, an identifier is allocated -- and it is inserted in the table. Otherwise, only data fields which have been changed -- are updated. overriding procedure Save (Object : in out Wiki_Page_Ref; Session : in out ADO.Sessions.Master_Session'Class); -- Delete the entity. overriding procedure Delete (Object : in out Wiki_Page_Ref; Session : in out ADO.Sessions.Master_Session'Class); overriding function Get_Value (From : in Wiki_Page_Ref; Name : in String) return Util.Beans.Objects.Object; -- Table definition WIKI_PAGE_TABLE : constant ADO.Schemas.Class_Mapping_Access; -- Internal method to allocate the Object_Record instance overriding procedure Allocate (Object : in out Wiki_Page_Ref); -- Copy of the object. procedure Copy (Object : in Wiki_Page_Ref; Into : in out Wiki_Page_Ref); -- Create an object key for Wiki_Content. function Wiki_Content_Key (Id : in ADO.Identifier) return ADO.Objects.Object_Key; -- Create an object key for Wiki_Content from a string. -- Raises Constraint_Error if the string cannot be converted into the object key. function Wiki_Content_Key (Id : in String) return ADO.Objects.Object_Key; Null_Wiki_Content : constant Wiki_Content_Ref; function ""="" (Left, Right : Wiki_Content_Ref'Class) return Boolean; -- Set the wiki page content identifier procedure Set_Id (Object : in out Wiki_Content_Ref; Value : in ADO.Identifier); -- Get the wiki page content identifier function Get_Id (Object : in Wiki_Content_Ref) return ADO.Identifier; -- Set the wiki content creation date procedure Set_Create_Date (Object : in out Wiki_Content_Ref; Value : in Ada.Calendar.Time); -- Get the wiki content creation date function Get_Create_Date (Object : in Wiki_Content_Ref) return Ada.Calendar.Time; -- Set the wiki text content procedure Set_Content (Object : in out Wiki_Content_Ref; Value : in Ada.Strings.Unbounded.Unbounded_String); procedure Set_Content (Object : in out Wiki_Content_Ref; Value : in String); -- Get the wiki text content function Get_Content (Object : in Wiki_Content_Ref) return Ada.Strings.Unbounded.Unbounded_String; function Get_Content (Object : in Wiki_Content_Ref) return String; -- Set the format type used used by the wiki content procedure Set_Format (Object : in out Wiki_Content_Ref; Value : in AWA.Wikis.Models.Format_Type); -- Get the format type used used by the wiki content function Get_Format (Object : in Wiki_Content_Ref) return AWA.Wikis.Models.Format_Type; -- Set the content comment string procedure Set_Save_Comment (Object : in out Wiki_Content_Ref; Value : in Ada.Strings.Unbounded.Unbounded_String); procedure Set_Save_Comment (Object : in out Wiki_Content_Ref; Value : in String); -- Get the content comment string function Get_Save_Comment (Object : in Wiki_Content_Ref) return Ada.Strings.Unbounded.Unbounded_String; function Get_Save_Comment (Object : in Wiki_Content_Ref) return String; -- function Get_Version (Object : in Wiki_Content_Ref) return Integer; -- Set the wiki page version procedure Set_Page_Version (Object : in out Wiki_Content_Ref; Value : in Integer); -- Get the wiki page version function Get_Page_Version (Object : in Wiki_Content_Ref) return Integer; -- Set the wiki page that this Wiki_Content belongs to procedure Set_Page (Object : in out Wiki_Content_Ref; Value : in AWA.Wikis.Models.Wiki_Page_Ref'Class); -- Get the wiki page that this Wiki_Content belongs to function Get_Page (Object : in Wiki_Content_Ref) return AWA.Wikis.Models.Wiki_Page_Ref'Class; -- Set the page version author procedure Set_Author (Object : in out Wiki_Content_Ref; Value : in AWA.Users.Models.User_Ref'Class); -- Get the page version author function Get_Author (Object : in Wiki_Content_Ref) return AWA.Users.Models.User_Ref'Class; -- Load the entity identified by 'Id'. -- Raises the NOT_FOUND exception if it does not exist. procedure Load (Object : in out Wiki_Content_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier); -- Load the entity identified by 'Id'. -- Returns True in Found if the object was found and False if it does not exist. procedure Load (Object : in out Wiki_Content_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier; Found : out Boolean); -- Find and load the entity. overriding procedure Find (Object : in out Wiki_Content_Ref; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean); -- Save the entity. If the entity does not have an identifier, an identifier is allocated -- and it is inserted in the table. Otherwise, only data fields which have been changed -- are updated. overriding procedure Save (Object : in out Wiki_Content_Ref; Session : in out ADO.Sessions.Master_Session'Class); -- Delete the entity. overriding procedure Delete (Object : in out Wiki_Content_Ref; Session : in out ADO.Sessions.Master_Session'Class); overriding function Get_Value (From : in Wiki_Content_Ref; Name : in String) return Util.Beans.Objects.Object; -- Table definition WIKI_CONTENT_TABLE : constant ADO.Schemas.Class_Mapping_Access; -- Internal method to allocate the Object_Record instance overriding procedure Allocate (Object : in out Wiki_Content_Ref); -- Copy of the object. procedure Copy (Object : in Wiki_Content_Ref; Into : in out Wiki_Content_Ref); Query_Page_Access_Stats : constant ADO.Queries.Query_Definition_Access; -- -------------------- -- The information about an image used in a wiki page. -- -------------------- type Wiki_Image_Bean is abstract new Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with record -- the image folder identifier. Folder_Id : ADO.Identifier; -- the image file identifier. Id : ADO.Identifier; -- the file creation date. Create_Date : Ada.Calendar.Time; -- the file storage URI. Uri : Ada.Strings.Unbounded.Unbounded_String; -- the file storage URI. Storage : AWA.Storages.Models.Storage_Type; -- the file mime type. Mime_Type : Ada.Strings.Unbounded.Unbounded_String; -- the file size. File_Size : Integer; -- the image width. Width : Integer; -- the image height. Height : Integer; end record; -- This bean provides some methods that can be used in a Method_Expression. overriding function Get_Method_Bindings (From : in Wiki_Image_Bean) return Util.Beans.Methods.Method_Binding_Array_Access; -- Get the bean attribute identified by the name. overriding function Get_Value (From : in Wiki_Image_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the bean attribute identified by the name. overriding procedure Set_Value (Item : in out Wiki_Image_Bean; Name : in String; Value : in Util.Beans.Objects.Object); procedure Load (Bean : in out Wiki_Image_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is abstract; -- Read in the object the data from the query result and prepare to read the next row. -- If there is no row, raise the ADO.NOT_FOUND exception. procedure Read (Into : in out Wiki_Image_Bean; Stmt : in out ADO.Statements.Query_Statement'Class); -- Run the query controlled by Context and load the result in Object. procedure Load (Object : in out Wiki_Image_Bean'Class; Session : in out ADO.Sessions.Session'Class; Context : in out ADO.Queries.Context'Class); Query_Wiki_Image : constant ADO.Queries.Query_Definition_Access; -- -------------------- -- The information about an image used in a wiki page. -- -------------------- type Wiki_Image_Info is new Util.Beans.Basic.Bean with record -- the image folder identifier. Folder_Id : ADO.Identifier; -- the image file identifier. Id : ADO.Identifier; -- the file creation date. Create_Date : Ada.Calendar.Time; -- the file storage URI. Uri : Ada.Strings.Unbounded.Unbounded_String; -- the file storage URI. Storage : AWA.Storages.Models.Storage_Type; -- the file mime type. Mime_Type : Ada.Strings.Unbounded.Unbounded_String; -- the file size. File_Size : Integer; -- the image width. Width : Integer; -- the image height. Height : Integer; end record; -- Get the bean attribute identified by the name. overriding function Get_Value (From : in Wiki_Image_Info; Name : in String) return Util.Beans.Objects.Object; -- Set the bean attribute identified by the name. overriding procedure Set_Value (Item : in out Wiki_Image_Info; Name : in String; Value : in Util.Beans.Objects.Object); package Wiki_Image_Info_Beans is new Util.Beans.Basic.Lists (Element_Type => Wiki_Image_Info); package Wiki_Image_Info_Vectors renames Wiki_Image_Info_Beans.Vectors; subtype Wiki_Image_Info_List_Bean is Wiki_Image_Info_Beans.List_Bean; type Wiki_Image_Info_List_Bean_Access is access all Wiki_Image_Info_List_Bean; -- Run the query controlled by Context and append the list in Object. procedure List (Object : in out Wiki_Image_Info_List_Bean'Class; Session : in out ADO.Sessions.Session'Class; Context : in out ADO.Queries.Context'Class); subtype Wiki_Image_Info_Vector is Wiki_Image_Info_Vectors.Vector; -- Run the query controlled by Context and append the list in Object. procedure List (Object : in out Wiki_Image_Info_Vector; Session : in out ADO.Sessions.Session'Class; Context : in out ADO.Queries.Context'Class); Query_Wiki_Image_Get_Data : constant ADO.Queries.Query_Definition_Access; Query_Wiki_Image_Width_Get_Data : constant ADO.Queries.Query_Definition_Access; Query_Wiki_Image_Height_Get_Data : constant ADO.Queries.Query_Definition_Access; -- -------------------- -- The list of wikis. -- -------------------- type Wiki_Info is new Util.Beans.Basic.Bean with record -- the wiki space identifier. Id : ADO.Identifier; -- the wiki name. Name : Ada.Strings.Unbounded.Unbounded_String; -- whether the wiki is public. Is_Public : Boolean; -- the wiki creation date. Create_Date : Ada.Calendar.Time; -- the number of pages in the wiki. Page_Count : Integer; end record; -- Get the bean attribute identified by the name. overriding function Get_Value (From : in Wiki_Info; Name : in String) return Util.Beans.Objects.Object; -- Set the bean attribute identified by the name. overriding procedure Set_Value (Item : in out Wiki_Info; Name : in String; Value : in Util.Beans.Objects.Object); package Wiki_Info_Beans is new Util.Beans.Basic.Lists (Element_Type => Wiki_Info); package Wiki_Info_Vectors renames Wiki_Info_Beans.Vectors; subtype Wiki_Info_List_Bean is Wiki_Info_Beans.List_Bean; type Wiki_Info_List_Bean_Access is access all Wiki_Info_List_Bean; -- Run the query controlled by Context and append the list in Object. procedure List (Object : in out Wiki_Info_List_Bean'Class; Session : in out ADO.Sessions.Session'Class; Context : in out ADO.Queries.Context'Class); subtype Wiki_Info_Vector is Wiki_Info_Vectors.Vector; -- Run the query controlled by Context and append the list in Object. procedure List (Object : in out Wiki_Info_Vector; Session : in out ADO.Sessions.Session'Class; Context : in out ADO.Queries.Context'Class); Query_Wiki_List : constant ADO.Queries.Query_Definition_Access; -- -------------------- -- The information about a wiki page. -- -------------------- type Wiki_Page_Info is new Util.Beans.Basic.Bean with record -- the wiki page identifier. Id : ADO.Identifier; -- the wiki page name. Name : Ada.Strings.Unbounded.Unbounded_String; -- the wiki page title. Title : Ada.Strings.Unbounded.Unbounded_String; -- whether the wiki is public. Is_Public : Boolean; -- the last version. Last_Version : Integer; -- the read count. Read_Count : Integer; -- the wiki creation date. Create_Date : Ada.Calendar.Time; -- the wiki page author. Author : Ada.Strings.Unbounded.Unbounded_String; end record; -- Get the bean attribute identified by the name. overriding function Get_Value (From : in Wiki_Page_Info; Name : in String) return Util.Beans.Objects.Object; -- Set the bean attribute identified by the name. overriding procedure Set_Value (Item : in out Wiki_Page_Info; Name : in String; Value : in Util.Beans.Objects.Object); package Wiki_Page_Info_Beans is new Util.Beans.Basic.Lists (Element_Type => Wiki_Page_Info); package Wiki_Page_Info_Vectors renames Wiki_Page_Info_Beans.Vectors; subtype Wiki_Page_Info_List_Bean is Wiki_Page_Info_Beans.List_Bean; type Wiki_Page_Info_List_Bean_Access is access all Wiki_Page_Info_List_Bean; -- Run the query controlled by Context and append the list in Object. procedure List (Object : in out Wiki_Page_Info_List_Bean'Class; Session : in out ADO.Sessions.Session'Class; Context : in out ADO.Queries.Context'Class); subtype Wiki_Page_Info_Vector is Wiki_Page_Info_Vectors.Vector; -- Run the query controlled by Context and append the list in Object. procedure List (Object : in out Wiki_Page_Info_Vector; Session : in out ADO.Sessions.Session'Class; Context : in out ADO.Queries.Context'Class); Query_Wiki_Page_List : constant ADO.Queries.Query_Definition_Access; Query_Wiki_Page_Tag_List : constant ADO.Queries.Query_Definition_Access; -- -------------------- -- The information about a wiki page version. -- -------------------- type Wiki_Version_Info is new Util.Beans.Basic.Bean with record -- the wiki page identifier. Id : ADO.Identifier; -- the wiki page version comment. Comment : Ada.Strings.Unbounded.Unbounded_String; -- the wiki page creation date. Create_Date : Ada.Calendar.Time; -- the page version. Page_Version : Integer; -- the wiki page author. Author : Ada.Strings.Unbounded.Unbounded_String; end record; -- Get the bean attribute identified by the name. overriding function Get_Value (From : in Wiki_Version_Info; Name : in String) return Util.Beans.Objects.Object; -- Set the bean attribute identified by the name. overriding procedure Set_Value (Item : in out Wiki_Version_Info; Name : in String; Value : in Util.Beans.Objects.Object); package Wiki_Version_Info_Beans is new Util.Beans.Basic.Lists (Element_Type => Wiki_Version_Info); package Wiki_Version_Info_Vectors renames Wiki_Version_Info_Beans.Vectors; subtype Wiki_Version_Info_List_Bean is Wiki_Version_Info_Beans.List_Bean; type Wiki_Version_Info_List_Bean_Access is access all Wiki_Version_Info_List_Bean; -- Run the query controlled by Context and append the list in Object. procedure List (Object : in out Wiki_Version_Info_List_Bean'Class; Session : in out ADO.Sessions.Session'Class; Context : in out ADO.Queries.Context'Class); subtype Wiki_Version_Info_Vector is Wiki_Version_Info_Vectors.Vector; -- Run the query controlled by Context and append the list in Object. procedure List (Object : in out Wiki_Version_Info_Vector; Session : in out ADO.Sessions.Session'Class; Context : in out ADO.Queries.Context'Class); Query_Wiki_Version_List : constant ADO.Queries.Query_Definition_Access; -- -------------------- -- The information about a wiki page. -- -------------------- type Wiki_View_Info is abstract new Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with record -- the wiki page identifier. Id : ADO.Identifier; -- the wiki page name. Name : Ada.Strings.Unbounded.Unbounded_String; -- the wiki page title. Title : Ada.Strings.Unbounded.Unbounded_String; -- whether the wiki is public. Is_Public : Boolean; -- the last version. Version : Integer; -- the number of times the page was displayed. Read_Count : Integer; -- the wiki page creation date. Date : Ada.Calendar.Time; -- the wiki page format. Format : AWA.Wikis.Models.Format_Type; -- the wiki page content. Content : Ada.Strings.Unbounded.Unbounded_String; -- the wiki version comment. Save_Comment : Ada.Strings.Unbounded.Unbounded_String; -- the wiki page left side panel. Left_Side : Ada.Strings.Unbounded.Unbounded_String; -- the wiki page right side panel. Right_Side : Ada.Strings.Unbounded.Unbounded_String; -- the wiki side format. Side_Format : AWA.Wikis.Models.Format_Type; -- the wiki page author. Author : Ada.Strings.Unbounded.Unbounded_String; -- the acl Id if there is one. Acl_Id : ADO.Identifier; end record; -- This bean provides some methods that can be used in a Method_Expression. overriding function Get_Method_Bindings (From : in Wiki_View_Info) return Util.Beans.Methods.Method_Binding_Array_Access; -- Get the bean attribute identified by the name. overriding function Get_Value (From : in Wiki_View_Info; Name : in String) return Util.Beans.Objects.Object; -- Set the bean attribute identified by the name. overriding procedure Set_Value (Item : in out Wiki_View_Info; Name : in String; Value : in Util.Beans.Objects.Object); procedure Load (Bean : in out Wiki_View_Info; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is abstract; -- Read in the object the data from the query result and prepare to read the next row. -- If there is no row, raise the ADO.NOT_FOUND exception. procedure Read (Into : in out Wiki_View_Info; Stmt : in out ADO.Statements.Query_Statement'Class); -- Run the query controlled by Context and load the result in Object. procedure Load (Object : in out Wiki_View_Info'Class; Session : in out ADO.Sessions.Session'Class; Context : in out ADO.Queries.Context'Class); Query_Wiki_Page : constant ADO.Queries.Query_Definition_Access; Query_Wiki_Page_Id : constant ADO.Queries.Query_Definition_Access; Query_Wiki_Page_Content : constant ADO.Queries.Query_Definition_Access; Query_Wiki_Page_Name_Count : constant ADO.Queries.Query_Definition_Access; type Wiki_Space_Bean is abstract new AWA.Wikis.Models.Wiki_Space_Ref and Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with null record; -- This bean provides some methods that can be used in a Method_Expression. overriding function Get_Method_Bindings (From : in Wiki_Space_Bean) return Util.Beans.Methods.Method_Binding_Array_Access; -- Set the bean attribute identified by the name. overriding procedure Set_Value (Item : in out Wiki_Space_Bean; Name : in String; Value : in Util.Beans.Objects.Object); procedure Save (Bean : in out Wiki_Space_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is abstract; procedure Load (Bean : in out Wiki_Space_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is abstract; -- -------------------- -- setup the page bean when the wiki page is created. -- -------------------- type Wiki_Page_Bean is abstract new AWA.Wikis.Models.Wiki_Page_Ref and Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with null record; -- This bean provides some methods that can be used in a Method_Expression. overriding function Get_Method_Bindings (From : in Wiki_Page_Bean) return Util.Beans.Methods.Method_Binding_Array_Access; -- Set the bean attribute identified by the name. overriding procedure Set_Value (Item : in out Wiki_Page_Bean; Name : in String; Value : in Util.Beans.Objects.Object); procedure Save (Bean : in out Wiki_Page_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is abstract; procedure Delete (Bean : in out Wiki_Page_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is abstract; procedure Load (Bean : in out Wiki_Page_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is abstract; procedure Setup (Bean : in out Wiki_Page_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is abstract; -- -------------------- -- Load the list items -- -------------------- type Wiki_Page_List_Bean is abstract limited new Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with record -- the page number being displayed (for pagination) Page : Integer; -- The number of wiki pages Count : Integer; -- the number of items in the page Page_Size : Integer; -- the tag to filter the list Tag : Ada.Strings.Unbounded.Unbounded_String; -- the wiki identifier Wiki_Id : ADO.Identifier; -- the sort list mode. Sort : Ada.Strings.Unbounded.Unbounded_String; end record; -- This bean provides some methods that can be used in a Method_Expression. overriding function Get_Method_Bindings (From : in Wiki_Page_List_Bean) return Util.Beans.Methods.Method_Binding_Array_Access; -- Get the bean attribute identified by the name. overriding function Get_Value (From : in Wiki_Page_List_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the bean attribute identified by the name. overriding procedure Set_Value (Item : in out Wiki_Page_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object); procedure Load (Bean : in out Wiki_Page_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is abstract; type Wiki_Version_List_Bean is abstract limited new Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with record -- the page number. Page : Integer; -- the number of versions. Count : Integer; -- the number of wiki version per display page. Page_Size : Integer; -- the wiki identifier. Wiki_Id : ADO.Identifier; -- the wiki page id. Page_Id : ADO.Identifier; end record; -- This bean provides some methods that can be used in a Method_Expression. overriding function Get_Method_Bindings (From : in Wiki_Version_List_Bean) return Util.Beans.Methods.Method_Binding_Array_Access; -- Get the bean attribute identified by the name. overriding function Get_Value (From : in Wiki_Version_List_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the bean attribute identified by the name. overriding procedure Set_Value (Item : in out Wiki_Version_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object); procedure Load (Bean : in out Wiki_Version_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is abstract; type Wiki_Page_Info_Bean is abstract limited new Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with record -- the wiki identifier. Wiki_Id : ADO.Identifier; -- the wiki page identifier. Page_Id : ADO.Identifier; end record; -- This bean provides some methods that can be used in a Method_Expression. overriding function Get_Method_Bindings (From : in Wiki_Page_Info_Bean) return Util.Beans.Methods.Method_Binding_Array_Access; -- Get the bean attribute identified by the name. overriding function Get_Value (From : in Wiki_Page_Info_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the bean attribute identified by the name. overriding procedure Set_Value (Item : in out Wiki_Page_Info_Bean; Name : in String; Value : in Util.Beans.Objects.Object); procedure Load (Bean : in out Wiki_Page_Info_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is abstract; private WIKI_SPACE_NAME : aliased constant String := ""awa_wiki_space""; COL_0_1_NAME : aliased constant String := ""id""; COL_1_1_NAME : aliased constant String := ""name""; COL_2_1_NAME : aliased constant String := ""is_public""; COL_3_1_NAME : aliased constant String := ""version""; COL_4_1_NAME : aliased constant String := ""create_date""; COL_5_1_NAME : aliased constant String := ""left_side""; COL_6_1_NAME : aliased constant String := ""right_side""; COL_7_1_NAME : aliased constant String := ""format""; COL_8_1_NAME : aliased constant String := ""workspace_id""; WIKI_SPACE_DEF : aliased constant ADO.Schemas.Class_Mapping := (Count => 9, Table => WIKI_SPACE_NAME'Access, Members => ( 1 => COL_0_1_NAME'Access, 2 => COL_1_1_NAME'Access, 3 => COL_2_1_NAME'Access, 4 => COL_3_1_NAME'Access, 5 => COL_4_1_NAME'Access, 6 => COL_5_1_NAME'Access, 7 => COL_6_1_NAME'Access, 8 => COL_7_1_NAME'Access, 9 => COL_8_1_NAME'Access ) ); WIKI_SPACE_TABLE : constant ADO.Schemas.Class_Mapping_Access := WIKI_SPACE_DEF'Access; Null_Wiki_Space : constant Wiki_Space_Ref := Wiki_Space_Ref'(ADO.Objects.Object_Ref with null record); type Wiki_Space_Impl is new ADO.Objects.Object_Record (Key_Type => ADO.Objects.KEY_INTEGER, Of_Class => WIKI_SPACE_DEF'Access) with record Name : Ada.Strings.Unbounded.Unbounded_String; Is_Public : Boolean; Version : Integer; Create_Date : Ada.Calendar.Time; Left_Side : Ada.Strings.Unbounded.Unbounded_String; Right_Side : Ada.Strings.Unbounded.Unbounded_String; Format : AWA.Wikis.Models.Format_Type; Workspace : AWA.Workspaces.Models.Workspace_Ref; end record; type Wiki_Space_Access is access all Wiki_Space_Impl; overriding procedure Destroy (Object : access Wiki_Space_Impl); overriding procedure Find (Object : in out Wiki_Space_Impl; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean); overriding procedure Load (Object : in out Wiki_Space_Impl; Session : in out ADO.Sessions.Session'Class); procedure Load (Object : in out Wiki_Space_Impl; Stmt : in out ADO.Statements.Query_Statement'Class; Session : in out ADO.Sessions.Session'Class); overriding procedure Save (Object : in out Wiki_Space_Impl; Session : in out ADO.Sessions.Master_Session'Class); procedure Create (Object : in out Wiki_Space_Impl; Session : in out ADO.Sessions.Master_Session'Class); overriding procedure Delete (Object : in out Wiki_Space_Impl; Session : in out ADO.Sessions.Master_Session'Class); procedure Set_Field (Object : in out Wiki_Space_Ref'Class; Impl : out Wiki_Space_Access); WIKI_PAGE_NAME : aliased constant String := ""awa_wiki_page""; COL_0_2_NAME : aliased constant String := ""id""; COL_1_2_NAME : aliased constant String := ""name""; COL_2_2_NAME : aliased constant String := ""last_version""; COL_3_2_NAME : aliased constant String := ""is_public""; COL_4_2_NAME : aliased constant String := ""title""; COL_5_2_NAME : aliased constant String := ""version""; COL_6_2_NAME : aliased constant String := ""read_count""; COL_7_2_NAME : aliased constant String := ""preview_id""; COL_8_2_NAME : aliased constant String := ""wiki_id""; COL_9_2_NAME : aliased constant String := ""content_id""; WIKI_PAGE_DEF : aliased constant ADO.Schemas.Class_Mapping := (Count => 10, Table => WIKI_PAGE_NAME'Access, Members => ( 1 => COL_0_2_NAME'Access, 2 => COL_1_2_NAME'Access, 3 => COL_2_2_NAME'Access, 4 => COL_3_2_NAME'Access, 5 => COL_4_2_NAME'Access, 6 => COL_5_2_NAME'Access, 7 => COL_6_2_NAME'Access, 8 => COL_7_2_NAME'Access, 9 => COL_8_2_NAME'Access, 10 => COL_9_2_NAME'Access ) ); WIKI_PAGE_TABLE : constant ADO.Schemas.Class_Mapping_Access := WIKI_PAGE_DEF'Access; Null_Wiki_Page : constant Wiki_Page_Ref := Wiki_Page_Ref'(ADO.Objects.Object_Ref with null record); type Wiki_Page_Impl is new ADO.Objects.Object_Record (Key_Type => ADO.Objects.KEY_INTEGER, Of_Class => WIKI_PAGE_DEF'Access) with record Name : Ada.Strings.Unbounded.Unbounded_String; Last_Version : Integer; Is_Public : Boolean; Title : Ada.Strings.Unbounded.Unbounded_String; Version : Integer; Read_Count : Integer; Preview : AWA.Images.Models.Image_Ref; Wiki : AWA.Wikis.Models.Wiki_Space_Ref; Content : AWA.Wikis.Models.Wiki_Content_Ref; end record; type Wiki_Page_Access is access all Wiki_Page_Impl; overriding procedure Destroy (Object : access Wiki_Page_Impl); overriding procedure Find (Object : in out Wiki_Page_Impl; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean); overriding procedure Load (Object : in out Wiki_Page_Impl; Session : in out ADO.Sessions.Session'Class); procedure Load (Object : in out Wiki_Page_Impl; Stmt : in out ADO.Statements.Query_Statement'Class; Session : in out ADO.Sessions.Session'Class); overriding procedure Save (Object : in out Wiki_Page_Impl; Session : in out ADO.Sessions.Master_Session'Class); procedure Create (Object : in out Wiki_Page_Impl; Session : in out ADO.Sessions.Master_Session'Class); overriding procedure Delete (Object : in out Wiki_Page_Impl; Session : in out ADO.Sessions.Master_Session'Class); procedure Set_Field (Object : in out Wiki_Page_Ref'Class; Impl : out Wiki_Page_Access); WIKI_CONTENT_NAME : aliased constant String := ""awa_wiki_content""; COL_0_3_NAME : aliased constant String := ""id""; COL_1_3_NAME : aliased constant String := ""create_date""; COL_2_3_NAME : aliased constant String := ""content""; COL_3_3_NAME : aliased constant String := ""format""; COL_4_3_NAME : aliased constant String := ""save_comment""; COL_5_3_NAME : aliased constant String := ""version""; COL_6_3_NAME : aliased constant String := ""page_version""; COL_7_3_NAME : aliased constant String := ""page_id""; COL_8_3_NAME : aliased constant String := ""author_id""; WIKI_CONTENT_DEF : aliased constant ADO.Schemas.Class_Mapping := (Count => 9, Table => WIKI_CONTENT_NAME'Access, Members => ( 1 => COL_0_3_NAME'Access, 2 => COL_1_3_NAME'Access, 3 => COL_2_3_NAME'Access, 4 => COL_3_3_NAME'Access, 5 => COL_4_3_NAME'Access, 6 => COL_5_3_NAME'Access, 7 => COL_6_3_NAME'Access, 8 => COL_7_3_NAME'Access, 9 => COL_8_3_NAME'Access ) ); WIKI_CONTENT_TABLE : constant ADO.Schemas.Class_Mapping_Access := WIKI_CONTENT_DEF'Access; Null_Wiki_Content : constant Wiki_Content_Ref := Wiki_Content_Ref'(ADO.Objects.Object_Ref with null record); type Wiki_Content_Impl is new ADO.Objects.Object_Record (Key_Type => ADO.Objects.KEY_INTEGER, Of_Class => WIKI_CONTENT_DEF'Access) with record Create_Date : Ada.Calendar.Time; Content : Ada.Strings.Unbounded.Unbounded_String; Format : AWA.Wikis.Models.Format_Type; Save_Comment : Ada.Strings.Unbounded.Unbounded_String; Version : Integer; Page_Version : Integer; Page : AWA.Wikis.Models.Wiki_Page_Ref; Author : AWA.Users.Models.User_Ref; end record; type Wiki_Content_Access is access all Wiki_Content_Impl; overriding procedure Destroy (Object : access Wiki_Content_Impl); overriding procedure Find (Object : in out Wiki_Content_Impl; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean); overriding procedure Load (Object : in out Wiki_Content_Impl; Session : in out ADO.Sessions.Session'Class); procedure Load (Object : in out Wiki_Content_Impl; Stmt : in out ADO.Statements.Query_Statement'Class; Session : in out ADO.Sessions.Session'Class); overriding procedure Save (Object : in out Wiki_Content_Impl; Session : in out ADO.Sessions.Master_Session'Class); procedure Create (Object : in out Wiki_Content_Impl; Session : in out ADO.Sessions.Master_Session'Class); overriding procedure Delete (Object : in out Wiki_Content_Impl; Session : in out ADO.Sessions.Master_Session'Class); procedure Set_Field (Object : in out Wiki_Content_Ref'Class; Impl : out Wiki_Content_Access); package File_1 is new ADO.Queries.Loaders.File (Path => ""wiki-stat.xml"", Sha1 => ""9B2B599473F75F92CB5AB5045675E4CCEF926543""); package Def_Page_Access_Stats is new ADO.Queries.Loaders.Query (Name => ""page-access-stats"", File => File_1.File'Access); Query_Page_Access_Stats : constant ADO.Queries.Query_Definition_Access := Def_Page_Access_Stats.Query'Access; package File_2 is new ADO.Queries.Loaders.File (Path => ""wiki-images-info.xml"", Sha1 => ""ACC06A1E40987526FBEB39D13B94AC44B833D516""); package Def_Wikiimagebean_Wiki_Image is new ADO.Queries.Loaders.Query (Name => ""wiki-image"", File => File_2.File'Access); Query_Wiki_Image : constant ADO.Queries.Query_Definition_Access := Def_Wikiimagebean_Wiki_Image.Query'Access; package File_3 is new ADO.Queries.Loaders.File (Path => ""wiki-images.xml"", Sha1 => ""63109B4E802BF3B5AD1680973D6E7E348C4E57D2""); package Def_Wikiimageinfo_Wiki_Image_Get_Data is new ADO.Queries.Loaders.Query (Name => ""wiki-image-get-data"", File => File_3.File'Access); Query_Wiki_Image_Get_Data : constant ADO.Queries.Query_Definition_Access := Def_Wikiimageinfo_Wiki_Image_Get_Data.Query'Access; package Def_Wikiimageinfo_Wiki_Image_Width_Get_Data is new ADO.Queries.Loaders.Query (Name => ""wiki-image-width-get-data"", File => File_3.File'Access); Query_Wiki_Image_Width_Get_Data : constant ADO.Queries.Query_Definition_Access := Def_Wikiimageinfo_Wiki_Image_Width_Get_Data.Query'Access; package Def_Wikiimageinfo_Wiki_Image_Height_Get_Data is new ADO.Queries.Loaders.Query (Name => ""wiki-image-height-get-data"", File => File_3.File'Access); Query_Wiki_Image_Height_Get_Data : constant ADO.Queries.Query_Definition_Access := Def_Wikiimageinfo_Wiki_Image_Height_Get_Data.Query'Access; package File_4 is new ADO.Queries.Loaders.File (Path => ""wiki-list.xml"", Sha1 => ""134AA901EAD20B164194D37CC198D8B6092FF0DF""); package Def_Wikiinfo_Wiki_List is new ADO.Queries.Loaders.Query (Name => ""wiki-list"", File => File_4.File'Access); Query_Wiki_List : constant ADO.Queries.Query_Definition_Access := Def_Wikiinfo_Wiki_List.Query'Access; package File_5 is new ADO.Queries.Loaders.File (Path => ""wiki-pages.xml"", Sha1 => ""3D026597D06A525412B37B034831E5ABC1F9EFA5""); package Def_Wikipageinfo_Wiki_Page_List is new ADO.Queries.Loaders.Query (Name => ""wiki-page-list"", File => File_5.File'Access); Query_Wiki_Page_List : constant ADO.Queries.Query_Definition_Access := Def_Wikipageinfo_Wiki_Page_List.Query'Access; package Def_Wikipageinfo_Wiki_Page_Tag_List is new ADO.Queries.Loaders.Query (Name => ""wiki-page-tag-list"", File => File_5.File'Access); Query_Wiki_Page_Tag_List : constant ADO.Queries.Query_Definition_Access := Def_Wikipageinfo_Wiki_Page_Tag_List.Query'Access; package File_6 is new ADO.Queries.Loaders.File (Path => ""wiki-history.xml"", Sha1 => ""AC42BF3C04729AEE8ADED975B16EBB859D1E7276""); package Def_Wikiversioninfo_Wiki_Version_List is new ADO.Queries.Loaders.Query (Name => ""wiki-version-list"", File => File_6.File'Access); Query_Wiki_Version_List : constant ADO.Queries.Query_Definition_Access := Def_Wikiversioninfo_Wiki_Version_List.Query'Access; package File_7 is new ADO.Queries.Loaders.File (Path => ""wiki-page.xml"", Sha1 => ""AF1DAD113E5BB4F34507D92D188098C84BF1174A""); package Def_Wikiviewinfo_Wiki_Page is new ADO.Queries.Loaders.Query (Name => ""wiki-page"", File => File_7.File'Access); Query_Wiki_Page : constant ADO.Queries.Query_Definition_Access := Def_Wikiviewinfo_Wiki_Page.Query'Access; package Def_Wikiviewinfo_Wiki_Page_Id is new ADO.Queries.Loaders.Query (Name => ""wiki-page-id"", File => File_7.File'Access); Query_Wiki_Page_Id : constant ADO.Queries.Query_Definition_Access := Def_Wikiviewinfo_Wiki_Page_Id.Query'Access; package Def_Wikiviewinfo_Wiki_Page_Content is new ADO.Queries.Loaders.Query (Name => ""wiki-page-content"", File => File_7.File'Access); Query_Wiki_Page_Content : constant ADO.Queries.Query_Definition_Access := Def_Wikiviewinfo_Wiki_Page_Content.Query'Access; package Def_Wikiviewinfo_Wiki_Page_Name_Count is new ADO.Queries.Loaders.Query (Name => ""wiki-page-name-count"", File => File_7.File'Access); Query_Wiki_Page_Name_Count : constant ADO.Queries.Query_Definition_Access := Def_Wikiviewinfo_Wiki_Page_Name_Count.Query'Access; end AWA.Wikis.Models; ",12538,True,2678.6868113352807,median "-- Generated by Snowball 2.2.0 - https://snowballstem.org/ package body Stemmer.English is pragma Style_Checks (""-mr""); pragma Warnings (Off, ""*variable*is never read and never assigned*""); pragma Warnings (Off, ""*mode could be*instead of*""); pragma Warnings (Off, ""*formal parameter.*is not modified*""); pragma Warnings (Off, ""*this line is too long*""); pragma Warnings (Off, ""*is not referenced*""); procedure R_Exception2 (Z : in out Context_Type; Result : out Boolean); procedure R_Exception1 (Z : in out Context_Type; Result : out Boolean); procedure R_Step_5 (Z : in out Context_Type; Result : out Boolean); procedure R_Step_4 (Z : in out Context_Type; Result : out Boolean); procedure R_Step_3 (Z : in out Context_Type; Result : out Boolean); procedure R_Step_2 (Z : in out Context_Type; Result : out Boolean); procedure R_Step_1c (Z : in out Context_Type; Result : out Boolean); procedure R_Step_1b (Z : in out Context_Type; Result : out Boolean); procedure R_Step_1a (Z : in out Context_Type; Result : out Boolean); procedure R_R2 (Z : in out Context_Type; Result : out Boolean); procedure R_R1 (Z : in out Context_Type; Result : out Boolean); procedure R_Shortv (Z : in out Context_Type; Result : out Boolean); procedure R_Mark_regions (Z : in out Context_Type; Result : out Boolean); procedure R_Postlude (Z : in out Context_Type; Result : out Boolean); procedure R_Prelude (Z : in out Context_Type; Result : out Boolean); G_V : constant Grouping_Array (0 .. 31) := ( True, False, False, False, True, False, False, False, True, False, False, False, False, False, True, False, False, False, False, False, True, False, False, False, True, False, False, False, False, False, False, False ); G_V_WXY : constant Grouping_Array (0 .. 39) := ( True, False, False, False, False, False, False, False, True, False, False, False, True, False, False, False, True, False, False, False, False, False, True, False, False, False, False, False, True, False, True, True, True, False, False, False, False, False, False, False ); G_Valid_LI : constant Grouping_Array (0 .. 23) := ( True, True, True, False, True, True, False, False, True, False, True, True, False, False, False, True, False, True, False, False, False, False, False, False ); Among_String : constant String := ""arsen"" & ""commun"" & ""gener"" & ""'"" & ""'s'"" & ""'s"" & ""ied"" & ""s"" & ""ies"" & ""sses"" & ""ss"" & ""us"" & """" & ""bb"" & ""dd"" & ""ff"" & ""gg"" & ""bl"" & ""mm"" & ""nn"" & ""pp"" & ""rr"" & ""at"" & ""tt"" & ""iz"" & ""ed"" & ""eed"" & ""ing"" & ""edly"" & ""eedly"" & ""ingly"" & ""anci"" & ""enci"" & ""ogi"" & ""li"" & ""bli"" & ""abli"" & ""alli"" & ""fulli"" & ""lessli"" & ""ousli"" & ""entli"" & ""aliti"" & ""biliti"" & ""iviti"" & ""tional"" & ""ational"" & ""alism"" & ""ation"" & ""ization"" & ""izer"" & ""ator"" & ""iveness"" & ""fulness"" & ""ousness"" & ""icate"" & ""ative"" & ""alize"" & ""iciti"" & ""ical"" & ""tional"" & ""ational"" & ""ful"" & ""ness"" & ""ic"" & ""ance"" & ""ence"" & ""able"" & ""ible"" & ""ate"" & ""ive"" & ""ize"" & ""iti"" & ""al"" & ""ism"" & ""ion"" & ""er"" & ""ous"" & ""ant"" & ""ent"" & ""ment"" & ""ement"" & ""e"" & ""l"" & ""succeed"" & ""proceed"" & ""exceed"" & ""canning"" & ""inning"" & ""earring"" & ""herring"" & ""outing"" & ""andes"" & ""atlas"" & ""bias"" & ""cosmos"" & ""dying"" & ""early"" & ""gently"" & ""howe"" & ""idly"" & ""lying"" & ""news"" & ""only"" & ""singly"" & ""skies"" & ""skis"" & ""sky"" & ""tying"" & ""ugly""; A_0 : constant Among_Array_Type (0 .. 2) := ( (1, 5, -1, -1, 0), (6, 11, -1, -1, 0), (12, 16, -1, -1, 0)); A_1 : constant Among_Array_Type (0 .. 2) := ( (17, 17, -1, 1, 0), (18, 20, 0, 1, 0), (21, 22, -1, 1, 0)); A_2 : constant Among_Array_Type (0 .. 5) := ( (23, 25, -1, 2, 0), (26, 26, -1, 3, 0), (27, 29, 1, 2, 0), (30, 33, 1, 1, 0), (34, 35, 1, -1, 0), (36, 37, 1, -1, 0)); A_3 : constant Among_Array_Type (0 .. 12) := ( (38, 37, -1, 3, 0), (38, 39, 0, 2, 0), (40, 41, 0, 2, 0), (42, 43, 0, 2, 0), (44, 45, 0, 2, 0), (46, 47, 0, 1, 0), (48, 49, 0, 2, 0), (50, 51, 0, 2, 0), (52, 53, 0, 2, 0), (54, 55, 0, 2, 0), (56, 57, 0, 1, 0), (58, 59, 0, 2, 0), (60, 61, 0, 1, 0)); A_4 : constant Among_Array_Type (0 .. 5) := ( (62, 63, -1, 2, 0), (64, 66, 0, 1, 0), (67, 69, -1, 2, 0), (70, 73, -1, 2, 0), (74, 78, 3, 1, 0), (79, 83, -1, 2, 0)); A_5 : constant Among_Array_Type (0 .. 23) := ( (84, 87, -1, 3, 0), (88, 91, -1, 2, 0), (92, 94, -1, 13, 0), (95, 96, -1, 15, 0), (97, 99, 3, 12, 0), (100, 103, 4, 4, 0), (104, 107, 3, 8, 0), (108, 112, 3, 9, 0), (113, 118, 3, 14, 0), (119, 123, 3, 10, 0), (124, 128, 3, 5, 0), (129, 133, -1, 8, 0), (134, 139, -1, 12, 0), (140, 144, -1, 11, 0), (145, 150, -1, 1, 0), (151, 157, 14, 7, 0), (158, 162, -1, 8, 0), (163, 167, -1, 7, 0), (168, 174, 17, 6, 0), (175, 178, -1, 6, 0), (179, 182, -1, 7, 0), (183, 189, -1, 11, 0), (190, 196, -1, 9, 0), (197, 203, -1, 10, 0)); A_6 : constant Among_Array_Type (0 .. 8) := ( (204, 208, -1, 4, 0), (209, 213, -1, 6, 0), (214, 218, -1, 3, 0), (219, 223, -1, 4, 0), (224, 227, -1, 4, 0), (228, 233, -1, 1, 0), (234, 240, 5, 2, 0), (241, 243, -1, 5, 0), (244, 247, -1, 5, 0)); A_7 : constant Among_Array_Type (0 .. 17) := ( (248, 249, -1, 1, 0), (250, 253, -1, 1, 0), (254, 257, -1, 1, 0), (258, 261, -1, 1, 0), (262, 265, -1, 1, 0), (266, 268, -1, 1, 0), (269, 271, -1, 1, 0), (272, 274, -1, 1, 0), (275, 277, -1, 1, 0), (278, 279, -1, 1, 0), (280, 282, -1, 1, 0), (283, 285, -1, 2, 0), (286, 287, -1, 1, 0), (288, 290, -1, 1, 0), (291, 293, -1, 1, 0), (294, 296, -1, 1, 0), (297, 300, 15, 1, 0), (301, 305, 16, 1, 0)); A_8 : constant Among_Array_Type (0 .. 1) := ( (306, 306, -1, 1, 0), (307, 307, -1, 2, 0)); A_9 : constant Among_Array_Type (0 .. 7) := ( (308, 314, -1, -1, 0), (315, 321, -1, -1, 0), (322, 327, -1, -1, 0), (328, 334, -1, -1, 0), (335, 340, -1, -1, 0), (341, 347, -1, -1, 0), (348, 354, -1, -1, 0), (355, 360, -1, -1, 0)); A_10 : constant Among_Array_Type (0 .. 17) := ( (361, 365, -1, -1, 0), (366, 370, -1, -1, 0), (371, 374, -1, -1, 0), (375, 380, -1, -1, 0), (381, 385, -1, 3, 0), (386, 390, -1, 9, 0), (391, 396, -1, 7, 0), (397, 400, -1, -1, 0), (401, 404, -1, 6, 0), (405, 409, -1, 4, 0), (410, 413, -1, -1, 0), (414, 417, -1, 10, 0), (418, 423, -1, 11, 0), (424, 428, -1, 2, 0), (429, 432, -1, 1, 0), (433, 435, -1, -1, 0), (436, 440, -1, 5, 0), (441, 444, -1, 8, 0)); procedure R_Prelude (Z : in out Context_Type; Result : out Boolean) is C : Result_Index; A : Integer; v_1 : Char_Index; v_2 : Char_Index; v_3 : Char_Index; v_4 : Char_Index; v_5 : Char_Index; begin -- (, line 25 -- unset Y_found, line 26 Z.B_Y_found := False; -- do, line 27 v_1 := Z.C; -- (, line 27 Z.Bra := Z.C; -- [, line 27 -- literal, line 27 C := Eq_S (Z, ""'""); if C = 0 then goto lab0; end if; Z.C := Z.C + C; Z.Ket := Z.C; -- ], line 27 -- delete, line 27 Slice_Del (Z); <> Z.C := v_1; -- do, line 28 v_2 := Z.C; -- (, line 28 Z.Bra := Z.C; -- [, line 28 -- literal, line 28 C := Eq_S (Z, ""y""); if C = 0 then goto lab1; end if; Z.C := Z.C + C; Z.Ket := Z.C; -- ], line 28 -- <-, line 28 Slice_From (Z, ""Y""); -- set Y_found, line 28 Z.B_Y_found := True; <> Z.C := v_2; -- do, line 29 v_3 := Z.C; -- repeat, line 29 <> loop v_4 := Z.C; -- (, line 29 -- goto, line 29 loop v_5 := Z.C; -- (, line 29 In_Grouping (Z, G_V, 97, 121, False, C); if C /= 0 then goto lab6; end if; Z.Bra := Z.C; -- [, line 29 -- literal, line 29 C := Eq_S (Z, ""y""); if C = 0 then goto lab6; end if; Z.C := Z.C + C; Z.Ket := Z.C; -- ], line 29 Z.C := v_5; exit; <> Z.C := v_5; if Z.C >= Z.L then goto lab4; end if; -- goto, line 29 C := Skip_Utf8 (Z); if C < 0 then goto lab4; end if; Z.C := C; end loop; -- <-, line 29 Slice_From (Z, ""Y""); -- set Y_found, line 29 Z.B_Y_found := True; goto lab3; <> Z.C := v_4; exit; end loop; <> Z.C := v_3; Result := True; end R_Prelude; procedure R_Mark_regions (Z : in out Context_Type; Result : out Boolean) is C : Result_Index; A : Integer; v_1 : Char_Index; v_2 : Char_Index; begin -- (, line 32 Z.I_P1 := Z.L; Z.I_P2 := Z.L; -- do, line 35 v_1 := Z.C; -- (, line 35 -- or, line 41 v_2 := Z.C; -- among, line 36 if Z.C + 4 >= Z.L or else Check_Among (Z, Z.C + 4, 3, 16#244000#) then goto lab2; -- among, line 36 end if; Find_Among (Z, A_0, Among_String, null, A); if A = 0 then goto lab2; end if; goto lab1; <> Z.C := v_2; -- (, line 41 -- gopast, line 41 -- grouping v, line 41 Out_Grouping (Z, G_V, 97, 121, True, C); if C < 0 then goto lab0; end if; Z.C := Z.C + C; -- gopast, line 41 -- non v, line 41 In_Grouping (Z, G_V, 97, 121, True, C); if C < 0 then goto lab0; end if; Z.C := Z.C + C; <> -- setmark p1, line 42 Z.I_P1 := Z.C; -- gopast, line 43 -- grouping v, line 43 Out_Grouping (Z, G_V, 97, 121, True, C); if C < 0 then goto lab0; end if; Z.C := Z.C + C; -- gopast, line 43 -- non v, line 43 In_Grouping (Z, G_V, 97, 121, True, C); if C < 0 then goto lab0; end if; Z.C := Z.C + C; -- setmark p2, line 43 Z.I_P2 := Z.C; <> Z.C := v_1; Result := True; end R_Mark_regions; procedure R_Shortv (Z : in out Context_Type; Result : out Boolean) is C : Result_Index; A : Integer; v_1 : Char_Index; begin -- or, line 51 v_1 := Z.L - Z.C; -- (, line 50 Out_Grouping_Backward (Z, G_V_WXY, 89, 121, False, C); if C /= 0 then goto lab1; end if; In_Grouping_Backward (Z, G_V, 97, 121, False, C); if C /= 0 then goto lab1; end if; Out_Grouping_Backward (Z, G_V, 97, 121, False, C); if C /= 0 then goto lab1; end if; goto lab0; <> Z.C := Z.L - v_1; -- (, line 52 Out_Grouping_Backward (Z, G_V, 97, 121, False, C); if C /= 0 then Result := False; return; end if; In_Grouping_Backward (Z, G_V, 97, 121, False, C); if C /= 0 then Result := False; return; end if; -- atlimit, line 52 if Z.C > Z.Lb then Result := False; return; end if; <> Result := True; end R_Shortv; procedure R_R1 (Z : in out Context_Type; Result : out Boolean) is begin Result := (Z.I_P1 <= Z.C); end R_R1; procedure R_R2 (Z : in out Context_Type; Result : out Boolean) is begin Result := (Z.I_P2 <= Z.C); end R_R2; procedure R_Step_1a (Z : in out Context_Type; Result : out Boolean) is C : Result_Index; A : Integer; v_1 : Char_Index; v_2 : Char_Index; begin -- (, line 58 -- try, line 59 v_1 := Z.L - Z.C; -- (, line 59 Z.Ket := Z.C; -- [, line 60 -- substring, line 60 if Z.C <= Z.Lb or else (Character'Pos (Z.P (Z.C)) /= 39 and then Character'Pos (Z.P (Z.C)) /= 115) then Z.C := Z.L - v_1; goto lab0; -- substring, line 60 end if; Find_Among_Backward (Z, A_1, Among_String, null, A); if A = 0 then Z.C := Z.L - v_1; goto lab0; end if; Z.Bra := Z.C; -- ], line 60 -- (, line 62 -- delete, line 62 Slice_Del (Z); <> Z.Ket := Z.C; -- [, line 65 -- substring, line 65 if Z.C <= Z.Lb or else (Character'Pos (Z.P (Z.C)) /= 100 and then Character'Pos (Z.P (Z.C)) /= 115) then Result := False; return; -- substring, line 65 end if; Find_Among_Backward (Z, A_2, Among_String, null, A); if A = 0 then Result := False; return; end if; Z.Bra := Z.C; -- ], line 65 -- among, line 65 case A is when 1 => -- (, line 66 -- <-, line 66 Slice_From (Z, ""ss""); when 2 => -- (, line 68 -- or, line 68 v_2 := Z.L - Z.C; -- (, line 68 C := Skip_Utf8_Backward (Z, 2); -- hop, line 68 if C < 0 then goto lab2; end if; Z.C := C; -- <-, line 68 Slice_From (Z, ""i""); goto lab1; <> Z.C := Z.L - v_2; -- <-, line 68 Slice_From (Z, ""ie""); <> when 3 => -- (, line 69 -- next, line 69 C := Skip_Utf8_Backward (Z); if C < 0 then Result := False; return; end if; Z.C := C; -- gopast, line 69 -- grouping v, line 69 Out_Grouping_Backward (Z, G_V, 97, 121, True, C); if C < 0 then Result := False; return; end if; Z.C := Z.C - C; -- delete, line 69 Slice_Del (Z); when others => null; end case; Result := True; end R_Step_1a; procedure R_Step_1b (Z : in out Context_Type; Result : out Boolean) is C : Result_Index; A : Integer; v_1 : Char_Index; v_2 : Char_Index; v_3 : Char_Index; begin -- (, line 74 Z.Ket := Z.C; -- [, line 75 -- substring, line 75 if Z.C - 1 <= Z.Lb or else Check_Among (Z, Z.C - 1, 3, 16#2000090#) then Result := False; return; -- substring, line 75 end if; Find_Among_Backward (Z, A_4, Among_String, null, A); if A = 0 then Result := False; return; end if; Z.Bra := Z.C; -- ], line 75 -- among, line 75 case A is when 1 => -- (, line 77 -- call R1, line 77 R_R1 (Z, Result); if not Result then Result := False; return; end if; -- <-, line 77 Slice_From (Z, ""ee""); when 2 => -- (, line 79 -- test, line 80 v_1 := Z.L - Z.C; -- gopast, line 80 -- grouping v, line 80 Out_Grouping_Backward (Z, G_V, 97, 121, True, C); if C < 0 then Result := False; return; end if; Z.C := Z.C - C; Z.C := Z.L - v_1; -- delete, line 80 Slice_Del (Z); -- test, line 81 v_2 := Z.L - Z.C; -- substring, line 81 if Z.C - 1 <= Z.Lb or else Check_Among (Z, Z.C - 1, 3, 16#41570d4#) then A := 3; else -- substring, line 81 Find_Among_Backward (Z, A_3, Among_String, null, A); if A = 0 then Result := False; return; end if; end if; Z.C := Z.L - v_2; -- among, line 81 case A is when 1 => -- (, line 83 -- <+, line 83 C := Z.C; Insert (Z, Z.C, Z.C, ""e""); Z.C := C; when 2 => -- (, line 86 Z.Ket := Z.C; -- [, line 86 -- next, line 86 C := Skip_Utf8_Backward (Z); if C < 0 then Result := False; return; end if; Z.C := C; Z.Bra := Z.C; -- ], line 86 -- delete, line 86 Slice_Del (Z); when 3 => -- (, line 87 -- atmark, line 87 if Z.C /= Z.I_P1 then Result := False; return; end if; -- test, line 87 v_3 := Z.L - Z.C; -- call shortv, line 87 R_Shortv (Z, Result); if not Result then Result := False; return; end if; Z.C := Z.L - v_3; -- <+, line 87 C := Z.C; Insert (Z, Z.C, Z.C, ""e""); Z.C := C; when others => null; end case; when others => null; end case; Result := True; end R_Step_1b; procedure R_Step_1c (Z : in out Context_Type; Result : out Boolean) is C : Result_Index; A : Integer; v_1 : Char_Index; begin -- (, line 93 Z.Ket := Z.C; -- [, line 94 -- or, line 94 v_1 := Z.L - Z.C; -- literal, line 94 C := Eq_S_Backward (Z, ""y""); if C = 0 then goto lab1; end if; Z.C := Z.C - C; goto lab0; <> Z.C := Z.L - v_1; -- literal, line 94 C := Eq_S_Backward (Z, ""Y""); if C = 0 then Result := False; return; end if; Z.C := Z.C - C; <> Z.Bra := Z.C; -- ], line 94 Out_Grouping_Backward (Z, G_V, 97, 121, False, C); if C /= 0 then Result := False; return; end if; -- not, line 95 -- atlimit, line 95 if Z.C > Z.Lb then goto lab2; end if; Result := False; return; <> -- <-, line 96 Slice_From (Z, ""i""); Result := True; end R_Step_1c; procedure R_Step_2 (Z : in out Context_Type; Result : out Boolean) is C : Result_Index; A : Integer; begin -- (, line 99 Z.Ket := Z.C; -- [, line 100 -- substring, line 100 if Z.C - 1 <= Z.Lb or else Check_Among (Z, Z.C - 1, 3, 16#c7200#) then Result := False; return; -- substring, line 100 end if; Find_Among_Backward (Z, A_5, Among_String, null, A); if A = 0 then Result := False; return; end if; Z.Bra := Z.C; -- ], line 100 -- call R1, line 100 R_R1 (Z, Result); if not Result then Result := False; return; end if; -- among, line 100 case A is when 1 => -- (, line 101 -- <-, line 101 Slice_From (Z, ""tion""); when 2 => -- (, line 102 -- <-, line 102 Slice_From (Z, ""ence""); when 3 => -- (, line 103 -- <-, line 103 Slice_From (Z, ""ance""); when 4 => -- (, line 104 -- <-, line 104 Slice_From (Z, ""able""); when 5 => -- (, line 105 -- <-, line 105 Slice_From (Z, ""ent""); when 6 => -- (, line 107 -- <-, line 107 Slice_From (Z, ""ize""); when 7 => -- (, line 109 -- <-, line 109 Slice_From (Z, ""ate""); when 8 => -- (, line 111 -- <-, line 111 Slice_From (Z, ""al""); when 9 => -- (, line 112 -- <-, line 112 Slice_From (Z, ""ful""); when 10 => -- (, line 114 -- <-, line 114 Slice_From (Z, ""ous""); when 11 => -- (, line 116 -- <-, line 116 Slice_From (Z, ""ive""); when 12 => -- (, line 118 -- <-, line 118 Slice_From (Z, ""ble""); when 13 => -- (, line 119 -- literal, line 119 C := Eq_S_Backward (Z, ""l""); if C = 0 then Result := False; return; end if; Z.C := Z.C - C; -- <-, line 119 Slice_From (Z, ""og""); when 14 => -- (, line 121 -- <-, line 121 Slice_From (Z, ""less""); when 15 => -- (, line 122 In_Grouping_Backward (Z, G_Valid_LI, 99, 116, False, C); if C /= 0 then Result := False; return; end if; -- delete, line 122 Slice_Del (Z); when others => null; end case; Result := True; end R_Step_2; procedure R_Step_3 (Z : in out Context_Type; Result : out Boolean) is C : Result_Index; A : Integer; begin -- (, line 126 Z.Ket := Z.C; -- [, line 127 -- substring, line 127 if Z.C - 2 <= Z.Lb or else Check_Among (Z, Z.C - 1, 3, 16#81220#) then Result := False; return; -- substring, line 127 end if; Find_Among_Backward (Z, A_6, Among_String, null, A); if A = 0 then Result := False; return; end if; Z.Bra := Z.C; -- ], line 127 -- call R1, line 127 R_R1 (Z, Result); if not Result then Result := False; return; end if; -- among, line 127 case A is when 1 => -- (, line 128 -- <-, line 128 Slice_From (Z, ""tion""); when 2 => -- (, line 129 -- <-, line 129 Slice_From (Z, ""ate""); when 3 => -- (, line 130 -- <-, line 130 Slice_From (Z, ""al""); when 4 => -- (, line 132 -- <-, line 132 Slice_From (Z, ""ic""); when 5 => -- (, line 134 -- delete, line 134 Slice_Del (Z); when 6 => -- (, line 136 -- call R2, line 136 R_R2 (Z, Result); if not Result then Result := False; return; end if; -- delete, line 136 Slice_Del (Z); when others => null; end case; Result := True; end R_Step_3; procedure R_Step_4 (Z : in out Context_Type; Result : out Boolean) is C : Result_Index; A : Integer; v_1 : Char_Index; begin -- (, line 140 Z.Ket := Z.C; -- [, line 141 -- substring, line 141 if Z.C - 1 <= Z.Lb or else Check_Among (Z, Z.C - 1, 3, 16#1c7228#) then Result := False; return; -- substring, line 141 end if; Find_Among_Backward (Z, A_7, Among_String, null, A); if A = 0 then Result := False; return; end if; Z.Bra := Z.C; -- ], line 141 -- call R2, line 141 R_R2 (Z, Result); if not Result then Result := False; return; end if; -- among, line 141 case A is when 1 => -- (, line 144 -- delete, line 144 Slice_Del (Z); when 2 => -- (, line 145 -- or, line 145 v_1 := Z.L - Z.C; -- literal, line 145 C := Eq_S_Backward (Z, ""s""); if C = 0 then goto lab1; end if; Z.C := Z.C - C; goto lab0; <> Z.C := Z.L - v_1; -- literal, line 145 C := Eq_S_Backward (Z, ""t""); if C = 0 then Result := False; return; end if; Z.C := Z.C - C; <> -- delete, line 145 Slice_Del (Z); when others => null; end case; Result := True; end R_Step_4; procedure R_Step_5 (Z : in out Context_Type; Result : out Boolean) is C : Result_Index; A : Integer; v_1 : Char_Index; v_2 : Char_Index; begin -- (, line 149 Z.Ket := Z.C; -- [, line 150 -- substring, line 150 if Z.C <= Z.Lb or else (Character'Pos (Z.P (Z.C)) /= 101 and then Character'Pos (Z.P (Z.C)) /= 108) then Result := False; return; -- substring, line 150 end if; Find_Among_Backward (Z, A_8, Among_String, null, A); if A = 0 then Result := False; return; end if; Z.Bra := Z.C; -- ], line 150 -- among, line 150 case A is when 1 => -- (, line 151 -- or, line 151 v_1 := Z.L - Z.C; -- call R2, line 151 R_R2 (Z, Result); if not Result then goto lab1; end if; goto lab0; <> Z.C := Z.L - v_1; -- (, line 151 -- call R1, line 151 R_R1 (Z, Result); if not Result then Result := False; return; end if; -- not, line 151 v_2 := Z.L - Z.C; -- call shortv, line 151 R_Shortv (Z, Result); if not Result then goto lab2; end if; Result := False; return; <> Z.C := Z.L - v_2; <> -- delete, line 151 Slice_Del (Z); when 2 => -- (, line 152 -- call R2, line 152 R_R2 (Z, Result); if not Result then Result := False; return; end if; -- literal, line 152 C := Eq_S_Backward (Z, ""l""); if C = 0 then Result := False; return; end if; Z.C := Z.C - C; -- delete, line 152 Slice_Del (Z); when others => null; end case; Result := True; end R_Step_5; procedure R_Exception2 (Z : in out Context_Type; Result : out Boolean) is C : Result_Index; A : Integer; begin -- (, line 156 Z.Ket := Z.C; -- [, line 158 -- substring, line 158 if Z.C - 5 <= Z.Lb or else (Character'Pos (Z.P (Z.C)) /= 100 and then Character'Pos (Z.P (Z.C)) /= 103) then Result := False; return; -- substring, line 158 end if; Find_Among_Backward (Z, A_9, Among_String, null, A); if A = 0 then Result := False; return; end if; Z.Bra := Z.C; -- ], line 158 -- atlimit, line 158 if Z.C > Z.Lb then Result := False; return; end if; Result := True; end R_Exception2; procedure R_Exception1 (Z : in out Context_Type; Result : out Boolean) is C : Result_Index; A : Integer; begin -- (, line 168 Z.Bra := Z.C; -- [, line 170 -- substring, line 170 if Z.C + 2 >= Z.L or else Check_Among (Z, Z.C + 2, 3, 16#28c5212#) then Result := False; return; -- substring, line 170 end if; Find_Among (Z, A_10, Among_String, null, A); if A = 0 then Result := False; return; end if; Z.Ket := Z.C; -- ], line 170 -- atlimit, line 170 if Z.C < Z.L then Result := False; return; end if; -- among, line 170 case A is when 1 => -- (, line 174 -- <-, line 174 Slice_From (Z, ""ski""); when 2 => -- (, line 175 -- <-, line 175 Slice_From (Z, ""sky""); when 3 => -- (, line 176 -- <-, line 176 Slice_From (Z, ""die""); when 4 => -- (, line 177 -- <-, line 177 Slice_From (Z, ""lie""); when 5 => -- (, line 178 -- <-, line 178 Slice_From (Z, ""tie""); when 6 => -- (, line 182 -- <-, line 182 Slice_From (Z, ""idl""); when 7 => -- (, line 183 -- <-, line 183 Slice_From (Z, ""gentl""); when 8 => -- (, line 184 -- <-, line 184 Slice_From (Z, ""ugli""); when 9 => -- (, line 185 -- <-, line 185 Slice_From (Z, ""earli""); when 10 => -- (, line 186 -- <-, line 186 Slice_From (Z, ""onli""); when 11 => -- (, line 187 -- <-, line 187 Slice_From (Z, ""singl""); when others => null; end case; Result := True; end R_Exception1; procedure R_Postlude (Z : in out Context_Type; Result : out Boolean) is C : Result_Index; A : Integer; v_1 : Char_Index; v_2 : Char_Index; begin -- (, line 203 -- Boolean test Y_found, line 203 if not Z.B_Y_found then Result := False; return; end if; -- repeat, line 203 <> loop v_1 := Z.C; -- (, line 203 -- goto, line 203 loop v_2 := Z.C; -- (, line 203 Z.Bra := Z.C; -- [, line 203 -- literal, line 203 C := Eq_S (Z, ""Y""); if C = 0 then goto lab3; end if; Z.C := Z.C + C; Z.Ket := Z.C; -- ], line 203 Z.C := v_2; exit; <> Z.C := v_2; if Z.C >= Z.L then goto lab1; end if; -- goto, line 203 C := Skip_Utf8 (Z); if C < 0 then goto lab1; end if; Z.C := C; end loop; -- <-, line 203 Slice_From (Z, ""y""); goto lab0; <> Z.C := v_1; exit; end loop; Result := True; end R_Postlude; procedure Stem (Z : in out Context_Type; Result : out Boolean) is C : Result_Index; A : Integer; v_1 : Char_Index; v_2 : Char_Index; v_5 : Char_Index; v_6 : Char_Index; v_7 : Char_Index; v_8 : Char_Index; v_9 : Char_Index; v_10 : Char_Index; v_11 : Char_Index; v_12 : Char_Index; v_13 : Char_Index; begin -- or, line 207 v_1 := Z.C; -- call exception1, line 207 R_Exception1 (Z, Result); if not Result then goto lab1; end if; goto lab0; <> Z.C := v_1; -- not, line 208 v_2 := Z.C; C := Skip_Utf8 (Z, 3); -- hop, line 208 if C < 0 then goto lab3; end if; Z.C := C; goto lab2; <> Z.C := v_2; goto lab0; <> Z.C := v_1; -- (, line 208 -- do, line 209 -- call prelude, line 209 R_Prelude (Z, Result); -- do, line 210 -- call mark_regions, line 210 R_Mark_regions (Z, Result); Z.Lb := Z.C; Z.C := Z.L; -- backwards, line 211 -- (, line 211 -- do, line 213 v_5 := Z.L - Z.C; -- call Step_1a, line 213 R_Step_1a (Z, Result); Z.C := Z.L - v_5; -- or, line 215 v_6 := Z.L - Z.C; -- call exception2, line 215 R_Exception2 (Z, Result); if not Result then goto lab5; end if; goto lab4; <> Z.C := Z.L - v_6; -- (, line 215 -- do, line 217 v_7 := Z.L - Z.C; -- call Step_1b, line 217 R_Step_1b (Z, Result); Z.C := Z.L - v_7; -- do, line 218 v_8 := Z.L - Z.C; -- call Step_1c, line 218 R_Step_1c (Z, Result); Z.C := Z.L - v_8; -- do, line 220 v_9 := Z.L - Z.C; -- call Step_2, line 220 R_Step_2 (Z, Result); Z.C := Z.L - v_9; -- do, line 221 v_10 := Z.L - Z.C; -- call Step_3, line 221 R_Step_3 (Z, Result); Z.C := Z.L - v_10; -- do, line 222 v_11 := Z.L - Z.C; -- call Step_4, line 222 R_Step_4 (Z, Result); Z.C := Z.L - v_11; -- do, line 224 v_12 := Z.L - Z.C; -- call Step_5, line 224 R_Step_5 (Z, Result); Z.C := Z.L - v_12; <> Z.C := Z.Lb; -- do, line 227 v_13 := Z.C; -- call postlude, line 227 R_Postlude (Z, Result); Z.C := v_13; <> Result := True; end Stem; end Stemmer.English; ",12442,True,2565.184786248375,median "------------------------------------------------------------------------------ -- -- -- GNU ADA RUN-TIME LIBRARY (GNARL) COMPONENTS -- -- -- -- S Y S T E M . T A S K I N G . S T A G E S -- -- -- -- B o d y -- -- -- -- $Revision$ -- -- -- Copyright (C) 1991-2001 Florida State University -- -- -- -- GNARL is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 2, or (at your option) any later ver- -- -- sion. GNARL is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNARL; see file COPYING. If not, write -- -- to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, -- -- MA 02111-1307, USA. -- -- -- -- As a special exception, if other files instantiate generics from this -- -- unit, or you link this unit with other files to produce an executable, -- -- this unit does not by itself cause the resulting executable to be -- -- covered by the GNU General Public License. This exception does not -- -- however invalidate any other reasons why the executable file might be -- -- covered by the GNU Public License. -- -- -- -- GNARL was developed by the GNARL team at Florida State University. It is -- -- now maintained by Ada Core Technologies Inc. in cooperation with Florida -- -- State University (http://www.gnat.com). -- -- -- ------------------------------------------------------------------------------ pragma Polling (Off); -- Turn off polling, we do not want ATC polling to take place during -- tasking operations. It causes infinite loops and other problems. with Ada.Exceptions; -- used for Raise_Exception with System.Tasking.Debug; pragma Warnings (Off, System.Tasking.Debug); -- used for enabling tasking facilities with gdb with System.Address_Image; -- used for the function itself. with System.Parameters; -- used for Size_Type with System.Task_Info; -- used for Task_Info_Type -- Task_Image_Type with System.Task_Primitives.Operations; -- used for Finalize_Lock -- Enter_Task -- Write_Lock -- Unlock -- Sleep -- Wakeup -- Get_Priority -- Lock/Unlock_All_Tasks_List -- New_ATCB with System.Soft_Links; -- These are procedure pointers to non-tasking routines that use -- task specific data. In the absence of tasking, these routines -- refer to global data. In the presense of tasking, they must be -- replaced with pointers to task-specific versions. -- Also used for Create_TSD, Destroy_TSD, Get_Current_Excep with System.Tasking.Initialization; -- Used for Remove_From_All_Tasks_List -- Defer_Abort -- Undefer_Abort -- Initialization.Poll_Base_Priority_Change -- Finalize_Attributes_Link -- Initialize_Attributes_Link pragma Elaborate_All (System.Tasking.Initialization); -- This insures that tasking is initialized if any tasks are created. with System.Tasking.Utilities; -- Used for Make_Passive -- Abort_One_Task with System.Tasking.Queuing; -- Used for Dequeue_Head with System.Tasking.Rendezvous; -- Used for Call_Simple with System.OS_Primitives; -- Used for Delay_Modes with System.Finalization_Implementation; -- Used for System.Finalization_Implementation.Finalize_Global_List with Interfaces.C; -- Used for type Unsigned. with System.Secondary_Stack; -- used for SS_Init; with System.Storage_Elements; -- used for Storage_Array; with System.Standard_Library; -- used for Exception_Trace package body System.Tasking.Stages is package STPO renames System.Task_Primitives.Operations; package SSL renames System.Soft_Links; package SSE renames System.Storage_Elements; package SST renames System.Secondary_Stack; use Ada.Exceptions; use System.Task_Primitives; use System.Task_Primitives.Operations; use System.Task_Info; procedure Wakeup_Entry_Caller (Self_ID : Task_ID; Entry_Call : Entry_Call_Link; New_State : Entry_Call_State) renames Initialization.Wakeup_Entry_Caller; procedure Cancel_Queued_Entry_Calls (T : Task_ID) renames Utilities.Cancel_Queued_Entry_Calls; procedure Abort_One_Task (Self_ID : Task_ID; T : Task_ID) renames Utilities.Abort_One_Task; ----------------------- -- Local Subprograms -- ----------------------- procedure Notify_Exception (Self_Id : Task_ID; Excep : Exception_Occurrence); -- This procedure will output the task ID and the exception information, -- including traceback if available. procedure Task_Wrapper (Self_ID : Task_ID); -- This is the procedure that is called by the GNULL from the -- new context when a task is created. It waits for activation -- and then calls the task body procedure. When the task body -- procedure completes, it terminates the task. procedure Vulnerable_Complete_Task (Self_ID : Task_ID); -- Complete the calling task. -- This procedure must be called with abort deferred. -- It should only be called by Complete_Task and -- Finalizate_Global_Tasks (for the environment task). procedure Vulnerable_Complete_Master (Self_ID : Task_ID); -- Complete the current master of the calling task. -- This procedure must be called with abort deferred. -- It should only be called by Vulnerable_Complete_Task and -- Complete_Master. procedure Vulnerable_Complete_Activation (Self_ID : Task_ID); -- Signal to Self_ID's activator that Self_ID has -- completed activation. -- -- Does not defer abortion (unlike Complete_Activation). procedure Abort_Dependents (Self_ID : Task_ID); -- Abort all the dependents of Self at our current master -- nesting level. procedure Vulnerable_Free_Task (T : Task_ID); -- Recover all runtime system storage associated with the task T. -- This should only be called after T has terminated and will no -- longer be referenced. -- -- For tasks created by an allocator that fails, due to an exception, -- it is called from Expunge_Unactivated_Tasks. -- -- It is also called from Unchecked_Deallocation, for objects that -- are or contain tasks. -- -- Different code is used at master completion, in Terminate_Dependents, -- due to a need for tighter synchronization with the master. procedure Terminate_Task (Self_ID : Task_ID); -- Terminate the calling task. -- This should only be called by the Task_Wrapper procedure. ---------------------- -- Abort_Dependents -- ---------------------- -- Abort all the direct dependents of Self at its current master -- nesting level, plus all of their dependents, transitively. -- No locks should be held when this routine is called. procedure Abort_Dependents (Self_ID : Task_ID) is C : Task_ID; P : Task_ID; begin Lock_All_Tasks_List; C := All_Tasks_List; while C /= null loop P := C.Common.Parent; while P /= null loop if P = Self_ID then -- ??? C is supposed to take care of its own dependents, so -- there should be no need to take worry about them. Need to -- double check this. if C.Master_of_Task = Self_ID.Master_Within then Abort_One_Task (Self_ID, C); C.Dependents_Aborted := True; end if; exit; end if; P := P.Common.Parent; end loop; C := C.Common.All_Tasks_Link; end loop; Self_ID.Dependents_Aborted := True; Unlock_All_Tasks_List; end Abort_Dependents; ----------------- -- Abort_Tasks -- ----------------- procedure Abort_Tasks (Tasks : Task_List) is begin Utilities.Abort_Tasks (Tasks); end Abort_Tasks; -------------------- -- Activate_Tasks -- -------------------- -- Note that locks of activator and activated task are both locked -- here. This is necessary because C.Common.State and -- Self.Common.Wait_Count have to be synchronized. This is safe from -- deadlock because the activator is always created before the activated -- task. That satisfies our in-order-of-creation ATCB locking policy. -- At one point, we may also lock the parent, if the parent is -- different from the activator. That is also consistent with the -- lock ordering policy, since the activator cannot be created -- before the parent. -- Since we are holding both the activator's lock, and Task_Wrapper -- locks that before it does anything more than initialize the -- low-level ATCB components, it should be safe to wait to update -- the counts until we see that the thread creation is successful. -- If the thread creation fails, we do need to close the entries -- of the task. The first phase, of dequeuing calls, only requires -- locking the acceptor's ATCB, but the waking up of the callers -- requires locking the caller's ATCB. We cannot safely do this -- while we are holding other locks. Therefore, the queue-clearing -- operation is done in a separate pass over the activation chain. procedure Activate_Tasks (Chain_Access : Activation_Chain_Access) is Self_ID : constant Task_ID := STPO.Self; P : Task_ID; C : Task_ID; Next_C, Last_C : Task_ID; Activate_Prio : System.Any_Priority; Success : Boolean; All_Elaborated : Boolean := True; begin pragma Debug (Debug.Trace (Self_ID, ""Activate_Tasks"", 'C')); Initialization.Defer_Abort_Nestable (Self_ID); pragma Assert (Self_ID.Common.Wait_Count = 0); -- Lock All_Tasks_L, to prevent activated tasks -- from racing ahead before we finish activating the chain. -- ????? -- Is there some less heavy-handed way? -- In an earlier version, we used the activator's lock here, -- but that violated the locking order rule when we had -- to lock the parent later. Lock_All_Tasks_List; -- Check that all task bodies have been elaborated. C := Chain_Access.T_ID; Last_C := null; while C /= null loop if C.Common.Elaborated /= null and then not C.Common.Elaborated.all then All_Elaborated := False; end if; -- Reverse the activation chain so that tasks are -- activated in the same order they're declared. Next_C := C.Common.Activation_Link; C.Common.Activation_Link := Last_C; Last_C := C; C := Next_C; end loop; Chain_Access.T_ID := Last_C; if not All_Elaborated then Unlock_All_Tasks_List; Initialization.Undefer_Abort_Nestable (Self_ID); Raise_Exception (Program_Error'Identity, ""Some tasks have not been elaborated""); end if; -- Activate all the tasks in the chain. -- Creation of the thread of control was deferred until -- activation. So create it now. C := Chain_Access.T_ID; while C /= null loop if C.Common.State /= Terminated then pragma Assert (C.Common.State = Unactivated); P := C.Common.Parent; Write_Lock (P); Write_Lock (C); if C.Common.Base_Priority < Get_Priority (Self_ID) then Activate_Prio := Get_Priority (Self_ID); else Activate_Prio := C.Common.Base_Priority; end if; System.Task_Primitives.Operations.Create_Task (C, Task_Wrapper'Address, Parameters.Size_Type (C.Common.Compiler_Data.Pri_Stack_Info.Size), Activate_Prio, Success); -- There would be a race between the created task and -- the creator to do the following initialization, -- if we did not have a Lock/Unlock_All_Tasks_List pair -- in the task wrapper, to prevent it from racing ahead. if Success then C.Common.State := Runnable; C.Awake_Count := 1; C.Alive_Count := 1; P.Awake_Count := P.Awake_Count + 1; P.Alive_Count := P.Alive_Count + 1; if P.Common.State = Master_Completion_Sleep and then C.Master_of_Task = P.Master_Within then pragma Assert (Self_ID /= P); P.Common.Wait_Count := P.Common.Wait_Count + 1; end if; Unlock (C); Unlock (P); else -- No need to set Awake_Count, State, etc. here since the loop -- below will do that for any Unactivated tasks. Unlock (C); Unlock (P); Self_ID.Common.Activation_Failed := True; end if; end if; C := C.Common.Activation_Link; end loop; Unlock_All_Tasks_List; -- Close the entries of any tasks that failed thread creation, -- and count those that have not finished activation. Write_Lock (Self_ID); Self_ID.Common.State := Activator_Sleep; C := Chain_Access.T_ID; while C /= null loop Write_Lock (C); if C.Common.State = Unactivated then C.Common.Activator := null; C.Common.State := Terminated; C.Callable := False; Cancel_Queued_Entry_Calls (C); elsif C.Common.Activator /= null then Self_ID.Common.Wait_Count := Self_ID.Common.Wait_Count + 1; end if; Unlock (C); P := C.Common.Activation_Link; C.Common.Activation_Link := null; C := P; end loop; -- Wait for the activated tasks to complete activation. -- It is unsafe to abort any of these tasks until the count goes to -- zero. loop Initialization.Poll_Base_Priority_Change (Self_ID); exit when Self_ID.Common.Wait_Count = 0; Sleep (Self_ID, Activator_Sleep); end loop; Self_ID.Common.State := Runnable; Unlock (Self_ID); -- Remove the tasks from the chain. Chain_Access.T_ID := null; Initialization.Undefer_Abort_Nestable (Self_ID); if Self_ID.Common.Activation_Failed then Self_ID.Common.Activation_Failed := False; Raise_Exception (Tasking_Error'Identity, ""Failure during activation""); end if; end Activate_Tasks; ------------------------- -- Complete_Activation -- ------------------------- procedure Complete_Activation is Self_ID : constant Task_ID := STPO.Self; begin Initialization.Defer_Abort_Nestable (Self_ID); Vulnerable_Complete_Activation (Self_ID); Initialization.Undefer_Abort_Nestable (Self_ID); -- ????? -- Why do we need to allow for nested deferral here? end Complete_Activation; --------------------- -- Complete_Master -- --------------------- procedure Complete_Master is Self_ID : Task_ID := STPO.Self; begin pragma Assert (Self_ID.Deferral_Level > 0); Vulnerable_Complete_Master (Self_ID); end Complete_Master; ------------------- -- Complete_Task -- ------------------- -- See comments on Vulnerable_Complete_Task for details. procedure Complete_Task is Self_ID : constant Task_ID := STPO.Self; begin pragma Assert (Self_ID.Deferral_Level > 0); Vulnerable_Complete_Task (Self_ID); -- All of our dependents have terminated. -- Never undefer abort again! end Complete_Task; ----------------- -- Create_Task -- ----------------- -- Compiler interface only. Do not call from within the RTS. -- This must be called to create a new task. procedure Create_Task (Priority : Integer; Size : System.Parameters.Size_Type; Task_Info : System.Task_Info.Task_Info_Type; Num_Entries : Task_Entry_Index; Master : Master_Level; State : Task_Procedure_Access; Discriminants : System.Address; Elaborated : Access_Boolean; Chain : in out Activation_Chain; Task_Image : System.Task_Info.Task_Image_Type; Created_Task : out Task_ID) is T, P : Task_ID; Self_ID : constant Task_ID := STPO.Self; Success : Boolean; Base_Priority : System.Any_Priority; begin pragma Debug (Debug.Trace (Self_ID, ""Create_Task"", 'C')); if Priority = Unspecified_Priority then Base_Priority := Self_ID.Common.Base_Priority; else Base_Priority := System.Any_Priority (Priority); end if; -- Find parent P of new Task, via master level number. P := Self_ID; if P /= null then while P.Master_of_Task >= Master loop P := P.Common.Parent; exit when P = null; end loop; end if; Initialization.Defer_Abort_Nestable (Self_ID); begin T := New_ATCB (Num_Entries); exception when others => Initialization.Undefer_Abort_Nestable (Self_ID); Raise_Exception (Storage_Error'Identity, ""Cannot allocate task""); end; -- All_Tasks_L is used by Abort_Dependents and Abort_Tasks. -- Up to this point, it is possible that we may be part of -- a family of tasks that is being aborted. Lock_All_Tasks_List; Write_Lock (Self_ID); -- Now, we must check that we have not been aborted. -- If so, we should give up on creating this task, -- and simply return. if not Self_ID.Callable then pragma Assert (Self_ID.Pending_ATC_Level = 0); pragma Assert (Self_ID.Pending_Action); pragma Assert (Chain.T_ID = null or else Chain.T_ID.Common.State = Unactivated); Unlock (Self_ID); Unlock_All_Tasks_List; Initialization.Undefer_Abort_Nestable (Self_ID); -- ??? Should never get here pragma Assert (False); raise Standard'Abort_Signal; end if; Initialize_ATCB (Self_ID, State, Discriminants, P, Elaborated, Base_Priority, Task_Info, Size, T, Success); if not Success then Unlock (Self_ID); Unlock_All_Tasks_List; Initialization.Undefer_Abort_Nestable (Self_ID); Raise_Exception (Storage_Error'Identity, ""Failed to initialize task""); end if; T.Master_of_Task := Master; T.Master_Within := T.Master_of_Task + 1; for L in T.Entry_Calls'Range loop T.Entry_Calls (L).Self := T; T.Entry_Calls (L).Level := L; end loop; T.Common.Task_Image := Task_Image; Unlock (Self_ID); Unlock_All_Tasks_List; -- Create TSD as early as possible in the creation of a task, since it -- may be used by the operation of Ada code within the task. SSL.Create_TSD (T.Common.Compiler_Data); T.Common.Activation_Link := Chain.T_ID; Chain.T_ID := T; Initialization.Initialize_Attributes_Link.all (T); Created_Task := T; Initialization.Undefer_Abort_Nestable (Self_ID); end Create_Task; -------------------- -- Current_Master -- -------------------- function Current_Master return Master_Level is Self_ID : constant Task_ID := STPO.Self; begin return Self_ID.Master_Within; end Current_Master; ------------------ -- Enter_Master -- ------------------ procedure Enter_Master is Self_ID : constant Task_ID := STPO.Self; begin Self_ID.Master_Within := Self_ID.Master_Within + 1; end Enter_Master; ------------------------------- -- Expunge_Unactivated_Tasks -- ------------------------------- -- See procedure Close_Entries for the general case. procedure Expunge_Unactivated_Tasks (Chain : in out Activation_Chain) is Self_ID : constant Task_ID := STPO.Self; C : Task_ID; Call : Entry_Call_Link; Temp : Task_ID; begin pragma Debug (Debug.Trace (Self_ID, ""Expunge_Unactivated_Tasks"", 'C')); Initialization.Defer_Abort_Nestable (Self_ID); -- ???? -- Experimentation has shown that abort is sometimes (but not -- always) already deferred when this is called. -- That may indicate an error. Find out what is going on. C := Chain.T_ID; while C /= null loop pragma Assert (C.Common.State = Unactivated); Temp := C.Common.Activation_Link; if C.Common.State = Unactivated then Write_Lock (C); for J in 1 .. C.Entry_Num loop Queuing.Dequeue_Head (C.Entry_Queues (J), Call); pragma Assert (Call = null); end loop; Unlock (C); Initialization.Remove_From_All_Tasks_List (C); Vulnerable_Free_Task (C); C := Temp; end if; end loop; Chain.T_ID := null; Initialization.Undefer_Abort_Nestable (Self_ID); end Expunge_Unactivated_Tasks; --------------------------- -- Finalize_Global_Tasks -- --------------------------- -- ???? -- We have a potential problem here if finalization of global -- objects does anything with signals or the timer server, since -- by that time those servers have terminated. -- It is hard to see how that would occur. -- However, a better solution might be to do all this finalization -- using the global finalization chain. procedure Finalize_Global_Tasks is Self_ID : constant Task_ID := STPO.Self; Zero_Independent : Boolean; begin if Self_ID.Deferral_Level = 0 then -- ?????? -- In principle, we should be able to predict whether -- abort is already deferred here (and it should not be deferred -- yet but in practice it seems Finalize_Global_Tasks is being -- called sometimes, from RTS code for exceptions, with abort already -- deferred. Initialization.Defer_Abort_Nestable (Self_ID); -- Never undefer again!!! end if; -- This code is only executed by the environment task pragma Assert (Self_ID = Environment_Task); -- Set Environment_Task'Callable to false to notify library-level tasks -- that it is waiting for them (cf 5619-003). Self_ID.Callable := False; -- Exit level 2 master, for normal tasks in library-level packages. Complete_Master; -- Force termination of ""independent"" library-level server tasks. Abort_Dependents (Self_ID); -- We need to explicitly wait for the task to be -- terminated here because on true concurrent system, we -- may end this procedure before the tasks are really -- terminated. loop Write_Lock (Self_ID); Zero_Independent := Utilities.Independent_Task_Count = 0; Unlock (Self_ID); -- We used to yield here, but this did not take into account -- low priority tasks that would cause dead lock in some cases. -- See 8126-020. Timed_Delay (Self_ID, 0.01, System.OS_Primitives.Relative); exit when Zero_Independent; end loop; -- ??? On multi-processor environments, it seems that the above loop -- isn't sufficient, so we need to add an additional delay. Timed_Delay (Self_ID, 0.1, System.OS_Primitives.Relative); -- Complete the environment task. Vulnerable_Complete_Task (Self_ID); System.Finalization_Implementation.Finalize_Global_List; SSL.Abort_Defer := SSL.Abort_Defer_NT'Access; SSL.Abort_Undefer := SSL.Abort_Undefer_NT'Access; SSL.Lock_Task := SSL.Task_Lock_NT'Access; SSL.Unlock_Task := SSL.Task_Unlock_NT'Access; SSL.Get_Jmpbuf_Address := SSL.Get_Jmpbuf_Address_NT'Access; SSL.Set_Jmpbuf_Address := SSL.Set_Jmpbuf_Address_NT'Access; SSL.Get_Sec_Stack_Addr := SSL.Get_Sec_Stack_Addr_NT'Access; SSL.Set_Sec_Stack_Addr := SSL.Set_Sec_Stack_Addr_NT'Access; SSL.Get_Exc_Stack_Addr := SSL.Get_Exc_Stack_Addr_NT'Access; SSL.Set_Exc_Stack_Addr := SSL.Set_Exc_Stack_Addr_NT'Access; SSL.Check_Abort_Status := SSL.Check_Abort_Status_NT'Access; SSL.Get_Stack_Info := SSL.Get_Stack_Info_NT'Access; -- Don't bother trying to finalize Initialization.Global_Task_Lock -- and System.Task_Primitives.All_Tasks_L. end Finalize_Global_Tasks; --------------- -- Free_Task -- --------------- procedure Free_Task (T : Task_ID) is Self_Id : constant Task_ID := Self; begin if T.Common.State = Terminated then -- It is not safe to call Abort_Defer or Write_Lock at this stage Initialization.Task_Lock (Self_Id); if T.Common.Task_Image /= null then Free_Task_Image (T.Common.Task_Image); end if; Initialization.Remove_From_All_Tasks_List (T); Initialization.Task_Unlock (Self_Id); System.Task_Primitives.Operations.Finalize_TCB (T); -- If the task is not terminated, then we simply ignore the call. This -- happens when a user program attempts an unchecked deallocation on -- a non-terminated task. else null; end if; end Free_Task; ---------------------- -- Notify_Exception -- ---------------------- procedure Notify_Exception (Self_Id : Task_ID; Excep : Exception_Occurrence) is procedure To_Stderr (S : String); pragma Import (Ada, To_Stderr, ""__gnat_to_stderr""); use System.Task_Info; use System.Soft_Links; function To_Address is new Unchecked_Conversion (Task_ID, System.Address); function Tailored_Exception_Information (E : Exception_Occurrence) return String; pragma Import (Ada, Tailored_Exception_Information, ""__gnat_tailored_exception_information""); begin To_Stderr (""task ""); if Self_Id.Common.Task_Image /= null then To_Stderr (Self_Id.Common.Task_Image.all); To_Stderr (""_""); end if; To_Stderr (System.Address_Image (To_Address (Self_Id))); To_Stderr ("" terminated by unhandled exception""); To_Stderr ((1 => ASCII.LF)); To_Stderr (Tailored_Exception_Information (Excep)); end Notify_Exception; ------------------ -- Task_Wrapper -- ------------------ -- The task wrapper is a procedure that is called first for each task -- task body, and which in turn calls the compiler-generated task body -- procedure. The wrapper's main job is to do initialization for the task. -- It also has some locally declared objects that server as per-task local -- data. Task finalization is done by Complete_Task, which is called from -- an at-end handler that the compiler generates. -- The variable ID in the task wrapper is used to implement the Self -- function on targets where there is a fast way to find the stack base -- of the current thread, since it should be at a fixed offset from the -- stack base. -- The variable Magic_Number is also used in such implementations -- of Self, to check whether the current task is an Ada task, as -- compared to other-language threads. -- Both act as constants, once initialized, but need to be marked as -- volatile or aliased to prevent the compiler from optimizing away the -- storage. See System.Task_Primitives.Operations.Self for more info. procedure Task_Wrapper (Self_ID : Task_ID) is ID : Task_ID := Self_ID; pragma Volatile (ID); -- Do not delete this variable. -- In some targets, we need this variable to implement a fast Self. Magic_Number : Interfaces.C.unsigned := 16#ADAADAAD#; pragma Volatile (Magic_Number); -- We use this to verify that we are looking at an Ada task, -- inside of System.Task_Primitives.Operations.Self. use type System.Parameters.Size_Type; use type SSE.Storage_Offset; use System.Standard_Library; Secondary_Stack : aliased SSE.Storage_Array (1 .. ID.Common.Compiler_Data.Pri_Stack_Info.Size * SSE.Storage_Offset (Parameters.Sec_Stack_Ratio) / 100); Secondary_Stack_Address : System.Address := Secondary_Stack'Address; begin pragma Assert (Self_ID.Deferral_Level = 1); if not Parameters.Sec_Stack_Dynamic then ID.Common.Compiler_Data.Sec_Stack_Addr := Secondary_Stack'Address; SST.SS_Init (Secondary_Stack_Address, Integer (Secondary_Stack'Last)); end if; -- Set the guard page at the bottom of the stack. -- The call to unprotect the page is done in Terminate_Task Stack_Guard (Self_ID, True); -- Initialize low-level TCB components, that -- cannot be initialized by the creator. -- Enter_Task sets Self_ID.Known_Tasks_Index -- and Self_ID.LL.Thread Enter_Task (Self_ID); -- We lock All_Tasks_L to wait for activator to finish activating -- the rest of the chain, so that everyone in the chain comes out -- in priority order. -- This also protects the value of -- Self_ID.Common.Activator.Common.Wait_Count. Lock_All_Tasks_List; Unlock_All_Tasks_List; begin -- We are separating the following portion of the code in order to -- place the exception handlers in a different block. -- In this way we do not call Set_Jmpbuf_Address (which needs -- Self) before we set Self in Enter_Task -- Call the task body procedure. -- The task body is called with abort still deferred. That -- eliminates a dangerous window, for which we had to patch-up in -- Terminate_Task. -- During the expansion of the task body, we insert an RTS-call -- to Abort_Undefer, at the first point where abort should be -- allowed. Self_ID.Common.Task_Entry_Point (Self_ID.Common.Task_Arg); Terminate_Task (Self_ID); exception when Standard'Abort_Signal => Terminate_Task (Self_ID); when others => -- ??? Using an E : others here causes CD2C11A to fail on -- DEC Unix, see 7925-005. if Exception_Trace = Unhandled_Raise then Notify_Exception (Self_ID, SSL.Get_Current_Excep.all.all); end if; Terminate_Task (Self_ID); end; end Task_Wrapper; -------------------- -- Terminate_Task -- -------------------- -- Before we allow the thread to exit, we must clean up. This is a -- a delicate job. We must wake up the task's master, who may immediately -- try to deallocate the ATCB out from under the current task WHILE IT IS -- STILL EXECUTING. -- To avoid this, the parent task must be blocked up to the last thing -- done before the call to Exit_Task. The trouble is that we have another -- step that we also want to postpone to the very end, i.e., calling -- SSL.Destroy_TSD. We have to postpone that until the end because -- compiler-generated code is likely to try to access that data at just -- about any point. -- We can't call Destroy_TSD while we are holding any other locks, because -- it locks Global_Task_Lock, and our deadlock prevention rules require -- that to be the outermost lock. Our first ""solution"" was to just lock -- Global_Task_Lock in addition to the other locks, and force the parent -- to also lock this lock between its wakeup and its freeing of the ATCB. -- See Complete_Task for the parent-side of the code that has the matching -- calls to Task_Lock and Task_Unlock. That was not really a solution, -- since the operation Task_Unlock continued to access the ATCB after -- unlocking, after which the parent was observed to race ahead, -- deallocate the ATCB, and then reallocate it to another task. The -- call to Undefer_Abortion in Task_Unlock by the ""terminated"" task was -- overwriting the data of the new task that reused the ATCB! To solve -- this problem, we introduced the new operation Final_Task_Unlock. procedure Terminate_Task (Self_ID : Task_ID) is Environment_Task : constant Task_ID := STPO.Environment_Task; begin pragma Assert (Self_ID.Common.Activator = null); -- Since GCC cannot allocate stack chunks efficiently without reordering -- some of the allocations, we have to handle this unexpected situation -- here. We should normally never have to call Vulnerable_Complete_Task -- here. See 6602-003 for more details. if Self_ID.Common.Activator /= null then Vulnerable_Complete_Task (Self_ID); end if; -- Check if the current task is an independent task -- If so, decrement the Independent_Task_Count value. if Self_ID.Master_of_Task = 2 then Write_Lock (Environment_Task); Utilities.Independent_Task_Count := Utilities.Independent_Task_Count - 1; Unlock (Environment_Task); end if; -- Unprotect the guard page if needed. Stack_Guard (Self_ID, False); Initialization.Task_Lock (Self_ID); Utilities.Make_Passive (Self_ID, Task_Completed => True); pragma Assert (Check_Exit (Self_ID)); SSL.Destroy_TSD (Self_ID.Common.Compiler_Data); Initialization.Final_Task_Unlock (Self_ID); -- WARNING -- past this point, this thread must assume that the ATCB -- has been deallocated. It should not be accessed again. STPO.Exit_Task; end Terminate_Task; ---------------- -- Terminated -- ---------------- function Terminated (T : Task_ID) return Boolean is Result : Boolean; Self_ID : Task_ID := STPO.Self; begin Initialization.Defer_Abort_Nestable (Self_ID); Write_Lock (T); Result := T.Common.State = Terminated; Unlock (T); Initialization.Undefer_Abort_Nestable (Self_ID); return Result; end Terminated; ------------------------------------ -- Vulnerable_Complete_Activation -- ------------------------------------ -- Only call this procedure with abortion deferred. -- As in several other places, the locks of the activator and activated -- task are both locked here. This follows our deadlock prevention lock -- ordering policy, since the activated task must be created after the -- activator. procedure Vulnerable_Complete_Activation (Self_ID : Task_ID) is Activator : Task_ID := Self_ID.Common.Activator; begin pragma Debug (Debug.Trace (Self_ID, ""V_Complete_Activation"", 'C')); Write_Lock (Activator); Write_Lock (Self_ID); pragma Assert (Self_ID.Common.Activator /= null); -- Remove dangling reference to Activator, -- since a task may outlive its activator. Self_ID.Common.Activator := null; -- Wake up the activator, if it is waiting for a chain -- of tasks to activate, and we are the last in the chain -- to complete activation if Activator.Common.State = Activator_Sleep then Activator.Common.Wait_Count := Activator.Common.Wait_Count - 1; if Activator.Common.Wait_Count = 0 then Wakeup (Activator, Activator_Sleep); end if; end if; -- The activator raises a Tasking_Error if any task -- it is activating is completed before the activation is -- done. However, if the reason for the task completion is -- an abortion, we do not raise an exception. ARM 9.2(5). if not Self_ID.Callable and then Self_ID.Pending_ATC_Level /= 0 then Activator.Common.Activation_Failed := True; end if; Unlock (Self_ID); Unlock (Activator); -- After the activation, active priority should be the same -- as base priority. We must unlock the Activator first, -- though, since it should not wait if we have lower priority. if Get_Priority (Self_ID) /= Self_ID.Common.Base_Priority then Write_Lock (Self_ID); Set_Priority (Self_ID, Self_ID.Common.Base_Priority); Unlock (Self_ID); end if; end Vulnerable_Complete_Activation; -------------------------------- -- Vulnerable_Complete_Master -- -------------------------------- procedure Vulnerable_Complete_Master (Self_ID : Task_ID) is C : Task_ID; P : Task_ID; CM : Master_Level := Self_ID.Master_Within; T : aliased Task_ID; To_Be_Freed : Task_ID; -- This is a list of ATCBs to be freed, after we have released -- all RTS locks. This is necessary because of the locking order -- rules, since the storage manager uses Global_Task_Lock. pragma Warnings (Off); function Check_Unactivated_Tasks return Boolean; pragma Warnings (On); -- Temporary error-checking code below. This is part of the checks -- added in the new run time. Call it only inside a pragma Assert. function Check_Unactivated_Tasks return Boolean is begin Lock_All_Tasks_List; Write_Lock (Self_ID); C := All_Tasks_List; while C /= null loop if C.Common.Activator = Self_ID then return False; end if; if C.Common.Parent = Self_ID and then C.Master_of_Task = CM then Write_Lock (C); if C.Common.State = Unactivated then return False; end if; Unlock (C); end if; C := C.Common.All_Tasks_Link; end loop; Unlock (Self_ID); Unlock_All_Tasks_List; return True; end Check_Unactivated_Tasks; -- Start of processing for Vulnerable_Complete_Master begin pragma Debug (Debug.Trace (Self_ID, ""V_Complete_Master"", 'C')); pragma Assert (Self_ID.Common.Wait_Count = 0); pragma Assert (Self_ID.Deferral_Level > 0); -- Count how many active dependent tasks this master currently -- has, and record this in Wait_Count. -- This count should start at zero, since it is initialized to -- zero for new tasks, and the task should not exit the -- sleep-loops that use this count until the count reaches zero. Lock_All_Tasks_List; Write_Lock (Self_ID); C := All_Tasks_List; while C /= null loop if C.Common.Activator = Self_ID then pragma Assert (C.Common.State = Unactivated); Write_Lock (C); C.Common.Activator := null; C.Common.State := Terminated; C.Callable := False; Cancel_Queued_Entry_Calls (C); Unlock (C); end if; if C.Common.Parent = Self_ID and then C.Master_of_Task = CM then Write_Lock (C); if C.Awake_Count /= 0 then Self_ID.Common.Wait_Count := Self_ID.Common.Wait_Count + 1; end if; Unlock (C); end if; C := C.Common.All_Tasks_Link; end loop; Self_ID.Common.State := Master_Completion_Sleep; Unlock (Self_ID); Unlock_All_Tasks_List; -- Wait until dependent tasks are all terminated or ready to terminate. -- While waiting, the task may be awakened if the task's priority needs -- changing, or this master is aborted. In the latter case, we want -- to abort the dependents, and resume waiting until Wait_Count goes -- to zero. Write_Lock (Self_ID); loop Initialization.Poll_Base_Priority_Change (Self_ID); exit when Self_ID.Common.Wait_Count = 0; -- Here is a difference as compared to Complete_Master if Self_ID.Pending_ATC_Level < Self_ID.ATC_Nesting_Level and then not Self_ID.Dependents_Aborted then Unlock (Self_ID); Abort_Dependents (Self_ID); Write_Lock (Self_ID); else Sleep (Self_ID, Master_Completion_Sleep); end if; end loop; Self_ID.Common.State := Runnable; Unlock (Self_ID); -- Dependents are all terminated or on terminate alternatives. -- Now, force those on terminate alternatives to terminate, by -- aborting them. pragma Assert (Check_Unactivated_Tasks); if Self_ID.Alive_Count > 1 then -- ????? -- Consider finding a way to skip the following extra steps if -- there are no dependents with terminate alternatives. This -- could be done by adding another count to the ATCB, similar to -- Awake_Count, but keeping track of count of tasks that are on -- terminate alternatives. pragma Assert (Self_ID.Common.Wait_Count = 0); -- Force any remaining dependents to terminate, by aborting them. Abort_Dependents (Self_ID); -- Above, when we ""abort"" the dependents we are simply using this -- operation for convenience. We are not required to support the full -- abort-statement semantics; in particular, we are not required to -- immediately cancel any queued or in-service entry calls. That is -- good, because if we tried to cancel a call we would need to lock -- the caller, in order to wake the caller up. Our anti-deadlock -- rules prevent us from doing that without releasing the locks on C -- and Self_ID. Releasing and retaking those locks would be -- wasteful, at best, and should not be considered further without -- more detailed analysis of potential concurrent accesses to the -- ATCBs of C and Self_ID. -- Count how many ""alive"" dependent tasks this master currently -- has, and record this in Wait_Count. -- This count should start at zero, since it is initialized to -- zero for new tasks, and the task should not exit the -- sleep-loops that use this count until the count reaches zero. pragma Assert (Self_ID.Common.Wait_Count = 0); Lock_All_Tasks_List; Write_Lock (Self_ID); C := All_Tasks_List; while C /= null loop if C.Common.Parent = Self_ID and then C.Master_of_Task = CM then Write_Lock (C); pragma Assert (C.Awake_Count = 0); if C.Alive_Count > 0 then pragma Assert (C.Terminate_Alternative); Self_ID.Common.Wait_Count := Self_ID.Common.Wait_Count + 1; end if; Unlock (C); end if; C := C.Common.All_Tasks_Link; end loop; Self_ID.Common.State := Master_Phase_2_Sleep; Unlock (Self_ID); Unlock_All_Tasks_List; -- Wait for all counted tasks to finish terminating themselves. Write_Lock (Self_ID); loop Initialization.Poll_Base_Priority_Change (Self_ID); exit when Self_ID.Common.Wait_Count = 0; Sleep (Self_ID, Master_Phase_2_Sleep); end loop; Self_ID.Common.State := Runnable; Unlock (Self_ID); end if; -- We don't wake up for abortion here. We are already terminating -- just as fast as we can, so there is no point. -- ???? -- Consider whether we want to bother checking for priority -- changes in the loop above, though. -- Remove terminated tasks from the list of Self_ID's dependents, but -- don't free their ATCBs yet, because of lock order restrictions, -- which don't allow us to call ""free"" or ""malloc"" while holding any -- other locks. Instead, we put those ATCBs to be freed onto a -- temporary list, called To_Be_Freed. Lock_All_Tasks_List; C := All_Tasks_List; P := null; while C /= null loop if C.Common.Parent = Self_ID and then C.Master_of_Task >= CM then if P /= null then P.Common.All_Tasks_Link := C.Common.All_Tasks_Link; else All_Tasks_List := C.Common.All_Tasks_Link; end if; T := C.Common.All_Tasks_Link; C.Common.All_Tasks_Link := To_Be_Freed; To_Be_Freed := C; C := T; else P := C; C := C.Common.All_Tasks_Link; end if; end loop; Unlock_All_Tasks_List; -- Free all the ATCBs on the list To_Be_Freed. -- The ATCBs in the list are no longer in All_Tasks_List, and after -- any interrupt entries are detached from them they should no longer -- be referenced. -- Global_Task_Lock (Task_Lock/Unlock) is locked in the loop below to -- avoid a race between a terminating task and its parent. The parent -- might try to deallocate the ACTB out from underneath the exiting -- task. Note that Free will also lock Global_Task_Lock, but that is -- OK, since this is the *one* lock for which we have a mechanism to -- support nested locking. See Task_Wrapper and its finalizer for more -- explanation. -- ??? -- The check ""T.Common.Parent /= null ..."" below is to prevent dangling -- references to terminated library-level tasks, which could -- otherwise occur during finalization of library-level objects. -- A better solution might be to hook task objects into the -- finalization chain and deallocate the ATCB when the task -- object is deallocated. However, this change is not likely -- to gain anything significant, since all this storage should -- be recovered en-masse when the process exits. while To_Be_Freed /= null loop T := To_Be_Freed; To_Be_Freed := T.Common.All_Tasks_Link; -- ??? On SGI there is currently no Interrupt_Manager, that's -- why we need to check if the Interrupt_Manager_ID is null if T.Interrupt_Entry and Interrupt_Manager_ID /= null then declare Detach_Interrupt_Entries_Index : Task_Entry_Index := 6; -- Corresponds to the entry index of System.Interrupts. -- Interrupt_Manager.Detach_Interrupt_Entries. -- Be sure to update this value when changing -- Interrupt_Manager specs. type Param_Type is access all Task_ID; Param : aliased Param_Type := T'Access; begin System.Tasking.Rendezvous.Call_Simple (Interrupt_Manager_ID, Detach_Interrupt_Entries_Index, Param'Address); end; end if; if (T.Common.Parent /= null and then T.Common.Parent.Common.Parent /= null) or else T.Master_of_Task > 3 then Initialization.Task_Lock (Self_ID); -- If Sec_Stack_Addr is not null, it means that Destroy_TSD -- has not been called yet (case of an unactivated task). if T.Common.Compiler_Data.Sec_Stack_Addr /= Null_Address then SSL.Destroy_TSD (T.Common.Compiler_Data); end if; Vulnerable_Free_Task (T); Initialization.Task_Unlock (Self_ID); end if; end loop; -- It might seem nice to let the terminated task deallocate -- its own ATCB. That would not cover the case of unactivated -- tasks. It also would force us to keep the underlying thread -- around past termination, since references to the ATCB are -- possible past termination. Currently, we get rid of the -- thread as soon as the task terminates, and let the parent -- recover the ATCB later. -- ???? -- Some day, if we want to recover the ATCB earlier, at task -- termination, we could consider using ""fat task IDs"", that -- include the serial number with the ATCB pointer, to catch -- references to tasks that no longer have ATCBs. It is not -- clear how much this would gain, since the user-level task -- object would still be occupying storage. -- Make next master level up active. -- We don't need to lock the ATCB, since the value is only -- updated by each task for itself. Self_ID.Master_Within := CM - 1; end Vulnerable_Complete_Master; ------------------------------ -- Vulnerable_Complete_Task -- ------------------------------ -- Complete the calling task. -- This procedure must be called with abort deferred. (That's why the -- name has ""Vulnerable"" in it.) It should only be called by Complete_Task -- and Finalizate_Global_Tasks (for the environment task). -- The effect is similar to that of Complete_Master. Differences include -- the closing of entries here, and computation of the number of active -- dependent tasks in Complete_Master. -- We don't lock Self_ID before the call to Vulnerable_Complete_Activation, -- because that does its own locking, and because we do not need the lock -- to test Self_ID.Common.Activator. That value should only be read and -- modified by Self. procedure Vulnerable_Complete_Task (Self_ID : Task_ID) is begin pragma Assert (Self_ID.Deferral_Level > 0); pragma Assert (Self_ID = Self); pragma Assert (Self_ID.Master_Within = Self_ID.Master_of_Task + 1 or else Self_ID.Master_Within = Self_ID.Master_of_Task + 2); pragma Assert (Self_ID.Common.Wait_Count = 0); pragma Assert (Self_ID.Open_Accepts = null); pragma Assert (Self_ID.ATC_Nesting_Level = 1); pragma Debug (Debug.Trace (Self_ID, ""V_Complete_Task"", 'C')); Write_Lock (Self_ID); Self_ID.Callable := False; -- In theory, Self should have no pending entry calls -- left on its call-stack. Each async. select statement should -- clean its own call, and blocking entry calls should -- defer abort until the calls are cancelled, then clean up. Cancel_Queued_Entry_Calls (Self_ID); Unlock (Self_ID); if Self_ID.Common.Activator /= null then Vulnerable_Complete_Activation (Self_ID); end if; -- If Self_ID.Master_Within = Self_ID.Master_of_Task + 2 -- we may have dependent tasks for which we need to wait. -- Otherwise, we can just exit. if Self_ID.Master_Within = Self_ID.Master_of_Task + 2 then Vulnerable_Complete_Master (Self_ID); end if; end Vulnerable_Complete_Task; -------------------------- -- Vulnerable_Free_Task -- -------------------------- -- Recover all runtime system storage associated with the task T. -- This should only be called after T has terminated and will no -- longer be referenced. -- For tasks created by an allocator that fails, due to an exception, -- it is called from Expunge_Unactivated_Tasks. -- For tasks created by elaboration of task object declarations it -- is called from the finalization code of the Task_Wrapper procedure. -- It is also called from Unchecked_Deallocation, for objects that -- are or contain tasks. procedure Vulnerable_Free_Task (T : Task_ID) is begin pragma Debug (Debug.Trace (""Vulnerable_Free_Task"", T, 'C')); Write_Lock (T); Initialization.Finalize_Attributes_Link.all (T); Unlock (T); if T.Common.Task_Image /= null then Free_Task_Image (T.Common.Task_Image); end if; System.Task_Primitives.Operations.Finalize_TCB (T); end Vulnerable_Free_Task; begin -- Establish the Adafinal softlink. -- This is not done inside the central RTS initialization routine -- to avoid with-ing this package from System.Tasking.Initialization. SSL.Adafinal := Finalize_Global_Tasks'Access; -- Establish soft links for subprograms that manipulate master_id's. -- This cannot be done when the RTS is initialized, because of various -- elaboration constraints. SSL.Current_Master := Stages.Current_Master'Access; SSL.Enter_Master := Stages.Enter_Master'Access; SSL.Complete_Master := Stages.Complete_Master'Access; end System.Tasking.Stages; ",12490,True,2634.0453749482135,median "= Rails == Rails/ActionFilter |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.19 | - |=== This cop enforces the consistent use of action filter methods. The cop is configurable and can enforce the use of the older something_filter methods or the newer something_action methods. === Examples ==== EnforcedStyle: action (default) [source,ruby] ---- # bad after_filter :do_stuff append_around_filter :do_stuff skip_after_filter :do_stuff # good after_action :do_stuff append_around_action :do_stuff skip_after_action :do_stuff ---- ==== EnforcedStyle: filter [source,ruby] ---- # bad after_action :do_stuff append_around_action :do_stuff skip_after_action :do_stuff # good after_filter :do_stuff append_around_filter :do_stuff skip_after_filter :do_stuff ---- === Configurable attributes |=== | Name | Default value | Configurable values | EnforcedStyle | `action` | `action`, `filter` | Include | `app/controllers/**/*.rb` | Array |=== == Rails/ActiveRecordAliases |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes (Unsafe) | 0.53 | - |=== Checks that ActiveRecord aliases are not used. The direct method names are more clear and easier to read. === Examples [source,ruby] ---- #bad Book.update_attributes!(author: 'Alice') #good Book.update!(author: 'Alice') ---- == Rails/ActiveRecordOverride |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.67 | - |=== Checks for overriding built-in Active Record methods instead of using callbacks. === Examples [source,ruby] ---- # bad class Book < ApplicationRecord def save self.title = title.upcase! super end end # good class Book < ApplicationRecord before_save :upcase_title def upcase_title self.title = title.upcase! end end ---- === Configurable attributes |=== | Name | Default value | Configurable values | Include | `app/models/**/*.rb` | Array |=== == Rails/ActiveSupportAliases |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.48 | - |=== This cop checks that ActiveSupport aliases to core ruby methods are not used. === Examples [source,ruby] ---- # good 'some_string'.start_with?('prefix') 'some_string'.end_with?('suffix') [1, 2, 'a'] << 'b' [1, 2, 'a'].unshift('b') # bad 'some_string'.starts_with?('prefix') 'some_string'.ends_with?('suffix') [1, 2, 'a'].append('b') [1, 2, 'a'].prepend('b') ---- == Rails/ApplicationController |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes (Unsafe) | 2.4 | 2.5 |=== This cop checks that controllers subclass ApplicationController. === Examples [source,ruby] ---- # good class MyController < ApplicationController # ... end # bad class MyController < ActionController::Base # ... end ---- == Rails/ApplicationJob |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes (Unsafe) | 0.49 | 2.5 |=== This cop checks that jobs subclass ApplicationJob with Rails 5.0. === Examples [source,ruby] ---- # good class Rails5Job < ApplicationJob # ... end # bad class Rails4Job < ActiveJob::Base # ... end ---- == Rails/ApplicationMailer |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes (Unsafe) | 2.4 | 2.5 |=== This cop checks that mailers subclass ApplicationMailer with Rails 5.0. === Examples [source,ruby] ---- # good class MyMailer < ApplicationMailer # ... end # bad class MyMailer < ActionMailer::Base # ... end ---- == Rails/ApplicationRecord |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes (Unsafe) | 0.49 | 2.5 |=== This cop checks that models subclass ApplicationRecord with Rails 5.0. === Examples [source,ruby] ---- # good class Rails5Model < ApplicationRecord # ... end # bad class Rails4Model < ActiveRecord::Base # ... end ---- == Rails/AssertNot |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.56 | - |=== Use `assert_not` instead of `assert !`. === Examples [source,ruby] ---- # bad assert !x # good assert_not x ---- === Configurable attributes |=== | Name | Default value | Configurable values | Include | `+**/test/**/*+` | Array |=== == Rails/BelongsTo |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.62 | - |=== This cop looks for belongs_to associations where we control whether the association is required via the deprecated `required` option instead. Since Rails 5, belongs_to associations are required by default and this can be controlled through the use of `optional: true`. From the release notes: belongs_to will now trigger a validation error by default if the association is not present. You can turn this off on a per-association basis with optional: true. Also deprecate required option in favor of optional for belongs_to. (Pull Request) In the case that the developer is doing `required: false`, we definitely want to autocorrect to `optional: true`. However, without knowing whether they've set overridden the default value of `config.active_record.belongs_to_required_by_default`, we can't say whether it's safe to remove `required: true` or whether we should replace it with `optional: false` (or, similarly, remove a superfluous `optional: false`). Therefore, in the cases we're using `required: true`, we'll simply invert it to `optional: false` and the user can remove depending on their defaults. === Examples [source,ruby] ---- # bad class Post < ApplicationRecord belongs_to :blog, required: false end # good class Post < ApplicationRecord belongs_to :blog, optional: true end # bad class Post < ApplicationRecord belongs_to :blog, required: true end # good class Post < ApplicationRecord belongs_to :blog, optional: false end ---- == Rails/Blank |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.48 | 0.67 |=== This cop checks for code that can be written with simpler conditionals using `Object#blank?` defined by Active Support. Interaction with `Style/UnlessElse`: The configuration of `NotPresent` will not produce an offense in the context of `unless else` if `Style/UnlessElse` is inabled. This is to prevent interference between the auto-correction of the two cops. === Examples ==== NilOrEmpty: true (default) [source,ruby] ---- # Converts usages of `nil? || empty?` to `blank?` # bad foo.nil? || foo.empty? foo == nil || foo.empty? # good foo.blank? ---- ==== NotPresent: true (default) [source,ruby] ---- # Converts usages of `!present?` to `blank?` # bad !foo.present? # good foo.blank? ---- ==== UnlessPresent: true (default) [source,ruby] ---- # Converts usages of `unless present?` to `if blank?` # bad something unless foo.present? # good something if foo.blank? # bad unless foo.present? something end # good if foo.blank? something end # good def blank? !present? end ---- === Configurable attributes |=== | Name | Default value | Configurable values | NilOrEmpty | `true` | Boolean | NotPresent | `true` | Boolean | UnlessPresent | `true` | Boolean |=== == Rails/BulkChangeTable |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.57 | - |=== This Cop checks whether alter queries are combinable. If combinable queries are detected, it suggests to you to use `change_table` with `bulk: true` instead. This option causes the migration to generate a single ALTER TABLE statement combining multiple column alterations. The `bulk` option is only supported on the MySQL and the PostgreSQL (5.2 later) adapter; thus it will automatically detect an adapter from `development` environment in `config/database.yml` when the `Database` option is not set. If the adapter is not `mysql2` or `postgresql`, this Cop ignores offenses. === Examples [source,ruby] ---- # bad def change add_column :users, :name, :string, null: false add_column :users, :nickname, :string # ALTER TABLE `users` ADD `name` varchar(255) NOT NULL # ALTER TABLE `users` ADD `nickname` varchar(255) end # good def change change_table :users, bulk: true do |t| t.string :name, null: false t.string :nickname end # ALTER TABLE `users` ADD `name` varchar(255) NOT NULL, # ADD `nickname` varchar(255) end ---- [source,ruby] ---- # bad def change change_table :users do |t| t.string :name, null: false t.string :nickname end end # good def change change_table :users, bulk: true do |t| t.string :name, null: false t.string :nickname end end # good # When you don't want to combine alter queries. def change change_table :users, bulk: false do |t| t.string :name, null: false t.string :nickname end end ---- === Configurable attributes |=== | Name | Default value | Configurable values | Database | `` | `mysql`, `postgresql` | Include | `db/migrate/*.rb` | Array |=== == Rails/ContentTag |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 2.6 | - |=== This cop checks that `tag` is used instead of `content_tag` because `content_tag` is legacy syntax. NOTE: Allow `content_tag` when the first argument is a variable because `content_tag(name)` is simpler rather than `tag.public_send(name)`. === Examples [source,ruby] ---- # bad content_tag(:p, 'Hello world!') content_tag(:br) # good tag.p('Hello world!') tag.br content_tag(name, 'Hello world!') ---- === References * https://github.com/rails/rails/issues/25195 * https://api.rubyonrails.org/classes/ActionView/Helpers/TagHelper.html#method-i-content_tag == Rails/CreateTableWithTimestamps |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.52 | - |=== This cop checks the migration for which timestamps are not included when creating a new table. In many cases, timestamps are useful information and should be added. === Examples [source,ruby] ---- # bad create_table :users # bad create_table :users do |t| t.string :name t.string :email end # good create_table :users do |t| t.string :name t.string :email t.timestamps end # good create_table :users do |t| t.string :name t.string :email t.datetime :created_at, default: -> { 'CURRENT_TIMESTAMP' } end # good create_table :users do |t| t.string :name t.string :email t.datetime :updated_at, default: -> { 'CURRENT_TIMESTAMP' } end ---- === Configurable attributes |=== | Name | Default value | Configurable values | Include | `db/migrate/*.rb` | Array |=== == Rails/Date |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.30 | 0.33 |=== This cop checks for the correct use of Date methods, such as Date.today, Date.current etc. Using `Date.today` is dangerous, because it doesn't know anything about Rails time zone. You must use `Time.zone.today` instead. The cop also reports warnings when you are using `to_time` method, because it doesn't know about Rails time zone either. Two styles are supported for this cop. When EnforcedStyle is 'strict' then the Date methods `today`, `current`, `yesterday`, and `tomorrow` are prohibited and the usage of both `to_time` and 'to_time_in_current_zone' are reported as warning. When EnforcedStyle is 'flexible' then only `Date.today` is prohibited and only `to_time` is reported as warning. === Examples ==== EnforcedStyle: strict [source,ruby] ---- # bad Date.current Date.yesterday Date.today date.to_time # good Time.zone.today Time.zone.today - 1.day ---- ==== EnforcedStyle: flexible (default) [source,ruby] ---- # bad Date.today date.to_time # good Time.zone.today Time.zone.today - 1.day Date.current Date.yesterday date.in_time_zone ---- === Configurable attributes |=== | Name | Default value | Configurable values | EnforcedStyle | `flexible` | `strict`, `flexible` |=== == Rails/Delegate |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.21 | 0.50 |=== This cop looks for delegations that could have been created automatically with the `delegate` method. Safe navigation `&.` is ignored because Rails' `allow_nil` option checks not just for nil but also delegates if nil responds to the delegated method. The `EnforceForPrefixed` option (defaulted to `true`) means that using the target object as a prefix of the method name without using the `delegate` method will be a violation. When set to `false`, this case is legal. === Examples [source,ruby] ---- # bad def bar foo.bar end # good delegate :bar, to: :foo # good def bar foo&.bar end # good private def bar foo.bar end ---- ==== EnforceForPrefixed: true (default) [source,ruby] ---- # bad def foo_bar foo.bar end # good delegate :bar, to: :foo, prefix: true ---- ==== EnforceForPrefixed: false [source,ruby] ---- # good def foo_bar foo.bar end # good delegate :bar, to: :foo, prefix: true ---- === Configurable attributes |=== | Name | Default value | Configurable values | EnforceForPrefixed | `true` | Boolean |=== == Rails/DelegateAllowBlank |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.44 | - |=== This cop looks for delegations that pass :allow_blank as an option instead of :allow_nil. :allow_blank is not a valid option to pass to ActiveSupport#delegate. === Examples [source,ruby] ---- # bad delegate :foo, to: :bar, allow_blank: true # good delegate :foo, to: :bar, allow_nil: true ---- == Rails/DynamicFindBy |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.44 | 2.6 |=== This cop checks dynamic `find_by_*` methods. Use `find_by` instead of dynamic method. See. https://rails.rubystyle.guide#find_by === Examples [source,ruby] ---- # bad User.find_by_name(name) User.find_by_name_and_email(name) User.find_by_email!(name) # good User.find_by(name: name) User.find_by(name: name, email: email) User.find_by!(email: email) ---- ==== AllowedMethods: find_by_sql [source,ruby] ---- # bad User.find_by_query(users_query) # good User.find_by_sql(users_sql) ---- ==== AllowedReceivers: Gem::Specification [source,ruby] ---- # bad Specification.find_by_name('backend').gem_dir # good Gem::Specification.find_by_name('backend').gem_dir ---- === Configurable attributes |=== | Name | Default value | Configurable values | Whitelist | `find_by_sql` | Array | AllowedMethods | `find_by_sql` | Array | AllowedReceivers | `Gem::Specification` | Array |=== === References * https://rails.rubystyle.guide#find_by == Rails/EnumHash |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 2.3 | - |=== This cop looks for enums written with array syntax. When using array syntax, adding an element in a position other than the last causes all previous definitions to shift. Explicitly specifying the value for each key prevents this from happening. === Examples [source,ruby] ---- # bad enum status: [:active, :archived] # good enum status: { active: 0, archived: 1 } ---- === Configurable attributes |=== | Name | Default value | Configurable values | Include | `app/models/**/*.rb` | Array |=== === References * https://rails.rubystyle.guide#enums == Rails/EnumUniqueness |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.46 | - |=== This cop looks for duplicate values in enum declarations. === Examples [source,ruby] ---- # bad enum status: { active: 0, archived: 0 } # good enum status: { active: 0, archived: 1 } # bad enum status: [:active, :archived, :active] # good enum status: [:active, :archived] ---- === Configurable attributes |=== | Name | Default value | Configurable values | Include | `app/models/**/*.rb` | Array |=== == Rails/EnvironmentComparison |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.52 | - |=== This cop checks that Rails.env is compared using `.production?`-like methods instead of equality against a string or symbol. === Examples [source,ruby] ---- # bad Rails.env == 'production' # bad, always returns false Rails.env == :test # good Rails.env.production? ---- == Rails/Exit |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.41 | - |=== This cop enforces that `exit` calls are not used within a rails app. Valid options are instead to raise an error, break, return, or some other form of stopping execution of current request. There are two obvious cases where `exit` is particularly harmful: * Usage in library code for your application. Even though Rails will rescue from a `SystemExit` and continue on, unit testing that library code will result in specs exiting (potentially silently if `exit(0)` is used.) * Usage in application code outside of the web process could result in the program exiting, which could result in the code failing to run and do its job. === Examples [source,ruby] ---- # bad exit(0) # good raise 'a bad error has happened' ---- === Configurable attributes |=== | Name | Default value | Configurable values | Include | `app/**/*.rb`, `config/**/*.rb`, `lib/**/*.rb` | Array | Exclude | `lib/**/*.rake` | Array |=== == Rails/FilePath |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.47 | 2.4 |=== This cop is used to identify usages of file path joining process to use `Rails.root.join` clause. It is used to add uniformity when joining paths. === Examples ==== EnforcedStyle: arguments [source,ruby] ---- # bad Rails.root.join('app/models/goober') File.join(Rails.root, 'app/models/goober') ""#{Rails.root}/app/models/goober"" # good Rails.root.join('app', 'models', 'goober') ---- ==== EnforcedStyle: slashes (default) [source,ruby] ---- # bad Rails.root.join('app', 'models', 'goober') File.join(Rails.root, 'app/models/goober') ""#{Rails.root}/app/models/goober"" # good Rails.root.join('app/models/goober') ---- === Configurable attributes |=== | Name | Default value | Configurable values | EnforcedStyle | `slashes` | `slashes`, `arguments` |=== == Rails/FindBy |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.30 | - |=== This cop is used to identify usages of `where.first` and change them to use `find_by` instead. === Examples [source,ruby] ---- # bad User.where(name: 'Bruce').first User.where(name: 'Bruce').take # good User.find_by(name: 'Bruce') ---- === Configurable attributes |=== | Name | Default value | Configurable values | Include | `app/models/**/*.rb` | Array |=== === References * https://rails.rubystyle.guide#find_by == Rails/FindEach |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.30 | - |=== This cop is used to identify usages of `all.each` and change them to use `all.find_each` instead. === Examples [source,ruby] ---- # bad User.all.each # good User.all.find_each ---- === Configurable attributes |=== | Name | Default value | Configurable values | Include | `app/models/**/*.rb` | Array |=== === References * https://rails.rubystyle.guide#find-each == Rails/HasAndBelongsToMany |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.12 | - |=== This cop checks for the use of the has_and_belongs_to_many macro. === Examples [source,ruby] ---- # bad # has_and_belongs_to_many :ingredients # good # has_many :ingredients, through: :recipe_ingredients ---- === Configurable attributes |=== | Name | Default value | Configurable values | Include | `app/models/**/*.rb` | Array |=== === References * https://rails.rubystyle.guide#has-many-through == Rails/HasManyOrHasOneDependent |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.50 | - |=== This cop looks for `has_many` or `has_one` associations that don't specify a `:dependent` option. It doesn't register an offense if `:through` option was specified. === Examples [source,ruby] ---- # bad class User < ActiveRecord::Base has_many :comments has_one :avatar end # good class User < ActiveRecord::Base has_many :comments, dependent: :restrict_with_exception has_one :avatar, dependent: :destroy has_many :patients, through: :appointments end ---- === Configurable attributes |=== | Name | Default value | Configurable values | Include | `app/models/**/*.rb` | Array |=== === References * https://rails.rubystyle.guide#has_many-has_one-dependent-option == Rails/HelperInstanceVariable |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 2.0 | - |=== This cop checks for use of the helper methods which reference instance variables. Relying on instance variables makes it difficult to re-use helper methods. If it seems awkward to explicitly pass in each dependent variable, consider moving the behaviour elsewhere, for example to a model, decorator or presenter. === Examples [source,ruby] ---- # bad def welcome_message ""Hello #{@user.name}"" end # good def welcome_message(user) ""Hello #{user.name}"" end ---- === Configurable attributes |=== | Name | Default value | Configurable values | Include | `app/helpers/**/*.rb` | Array |=== == Rails/HttpPositionalArguments |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.44 | - |=== This cop is used to identify usages of http methods like `get`, `post`, `put`, `patch` without the usage of keyword arguments in your tests and change them to use keyword args. This cop only applies to Rails >= 5. If you are running Rails < 5 you should disable the Rails/HttpPositionalArguments cop or set your TargetRailsVersion in your .rubocop.yml file to 4.2. === Examples [source,ruby] ---- # bad get :new, { user_id: 1} # good get :new, params: { user_id: 1 } ---- === Configurable attributes |=== | Name | Default value | Configurable values | Include | `spec/**/*`, `test/**/*` | Array |=== == Rails/HttpStatus |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.54 | - |=== Enforces use of symbolic or numeric value to define HTTP status. === Examples ==== EnforcedStyle: symbolic (default) [source,ruby] ---- # bad render :foo, status: 200 render json: { foo: 'bar' }, status: 200 render plain: 'foo/bar', status: 304 redirect_to root_url, status: 301 # good render :foo, status: :ok render json: { foo: 'bar' }, status: :ok render plain: 'foo/bar', status: :not_modified redirect_to root_url, status: :moved_permanently ---- ==== EnforcedStyle: numeric [source,ruby] ---- # bad render :foo, status: :ok render json: { foo: 'bar' }, status: :not_found render plain: 'foo/bar', status: :not_modified redirect_to root_url, status: :moved_permanently # good render :foo, status: 200 render json: { foo: 'bar' }, status: 404 render plain: 'foo/bar', status: 304 redirect_to root_url, status: 301 ---- === Configurable attributes |=== | Name | Default value | Configurable values | EnforcedStyle | `symbolic` | `numeric`, `symbolic` |=== == Rails/IgnoredSkipActionFilterOption |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.63 | - |=== This cop checks that `if` and `only` (or `except`) are not used together as options of `skip_*` action filter. The `if` option will be ignored when `if` and `only` are used together. Similarly, the `except` option will be ignored when `if` and `except` are used together. === Examples [source,ruby] ---- # bad class MyPageController < ApplicationController skip_before_action :login_required, only: :show, if: :trusted_origin? end # good class MyPageController < ApplicationController skip_before_action :login_required, if: -> { trusted_origin? && action_name == ""show"" } end ---- [source,ruby] ---- # bad class MyPageController < ApplicationController skip_before_action :login_required, except: :admin, if: :trusted_origin? end # good class MyPageController < ApplicationController skip_before_action :login_required, if: -> { trusted_origin? && action_name != ""admin"" } end ---- === Configurable attributes |=== | Name | Default value | Configurable values | Include | `app/controllers/**/*.rb` | Array |=== === References * https://api.rubyonrails.org/classes/AbstractController/Callbacks/ClassMethods.html#method-i-_normalize_callback_options == Rails/IndexBy |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 2.5 | - |=== This cop looks for uses of `each_with_object({}) { ... }`, `map { ... }.to_h`, and `Hash[map { ... }]` that are transforming an enumerable into a hash where the values are the original elements. Rails provides the `index_by` method for this purpose. === Examples [source,ruby] ---- # bad [1, 2, 3].each_with_object({}) { |el, h| h[foo(el)] = el } [1, 2, 3].map { |el| [foo(el), el] }.to_h Hash[[1, 2, 3].collect { |el| [foo(el), el] }] # good [1, 2, 3].index_by { |el| foo(el) } ---- == Rails/IndexWith |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 2.5 | - |=== This cop looks for uses of `each_with_object({}) { ... }`, `map { ... }.to_h`, and `Hash[map { ... }]` that are transforming an enumerable into a hash where the keys are the original elements. Rails provides the `index_with` method for this purpose. === Examples [source,ruby] ---- # bad [1, 2, 3].each_with_object({}) { |el, h| h[el] = foo(el) } [1, 2, 3].map { |el| [el, foo(el)] }.to_h Hash[[1, 2, 3].collect { |el| [el, foo(el)] }] # good [1, 2, 3].index_with { |el| foo(el) } ---- == Rails/InverseOf |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.52 | - |=== This cop looks for has_(one|many) and belongs_to associations where Active Record can't automatically determine the inverse association because of a scope or the options used. Using the blog with order scope example below, traversing the a Blog's association in both directions with `blog.posts.first.blog` would cause the `blog` to be loaded from the database twice. `:inverse_of` must be manually specified for Active Record to use the associated object in memory, or set to `false` to opt-out. Note that setting `nil` does not stop Active Record from trying to determine the inverse automatically, and is not considered a valid value for this. === Examples [source,ruby] ---- # good class Blog < ApplicationRecord has_many :posts end class Post < ApplicationRecord belongs_to :blog end ---- [source,ruby] ---- # bad class Blog < ApplicationRecord has_many :posts, -> { order(published_at: :desc) } end class Post < ApplicationRecord belongs_to :blog end # good class Blog < ApplicationRecord has_many(:posts, -> { order(published_at: :desc) }, inverse_of: :blog) end class Post < ApplicationRecord belongs_to :blog end # good class Blog < ApplicationRecord with_options inverse_of: :blog do has_many :posts, -> { order(published_at: :desc) } end end class Post < ApplicationRecord belongs_to :blog end # good # When you don't want to use the inverse association. class Blog < ApplicationRecord has_many(:posts, -> { order(published_at: :desc) }, inverse_of: false) end ---- [source,ruby] ---- # bad class Picture < ApplicationRecord belongs_to :imageable, polymorphic: true end class Employee < ApplicationRecord has_many :pictures, as: :imageable end class Product < ApplicationRecord has_many :pictures, as: :imageable end # good class Picture < ApplicationRecord belongs_to :imageable, polymorphic: true end class Employee < ApplicationRecord has_many :pictures, as: :imageable, inverse_of: :imageable end class Product < ApplicationRecord has_many :pictures, as: :imageable, inverse_of: :imageable end ---- [source,ruby] ---- # bad # However, RuboCop can not detect this pattern... class Physician < ApplicationRecord has_many :appointments has_many :patients, through: :appointments end class Appointment < ApplicationRecord belongs_to :physician belongs_to :patient end class Patient < ApplicationRecord has_many :appointments has_many :physicians, through: :appointments end # good class Physician < ApplicationRecord has_many :appointments has_many :patients, through: :appointments end class Appointment < ApplicationRecord belongs_to :physician, inverse_of: :appointments belongs_to :patient, inverse_of: :appointments end class Patient < ApplicationRecord has_many :appointments has_many :physicians, through: :appointments end ---- === Configurable attributes |=== | Name | Default value | Configurable values | Include | `app/models/**/*.rb` | Array |=== == Rails/LexicallyScopedActionFilter |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | No | No | 0.52 | - |=== This cop checks that methods specified in the filter's `only` or `except` options are defined within the same class or module. You can technically specify methods of superclass or methods added by mixins on the filter, but these can confuse developers. If you specify methods that are defined in other classes or modules, you should define the filter in that class or module. If you rely on behaviour defined in the superclass actions, you must remember to invoke `super` in the subclass actions. === Examples [source,ruby] ---- # bad class LoginController < ApplicationController before_action :require_login, only: %i[index settings logout] def index end end # good class LoginController < ApplicationController before_action :require_login, only: %i[index settings logout] def index end def settings end def logout end end ---- [source,ruby] ---- # bad module FooMixin extend ActiveSupport::Concern included do before_action proc { authenticate }, only: :foo end end # good module FooMixin extend ActiveSupport::Concern included do before_action proc { authenticate }, only: :foo end def foo # something end end ---- [source,ruby] ---- class ContentController < ApplicationController def update @content.update(content_attributes) end end class ArticlesController < ContentController before_action :load_article, only: [:update] # the cop requires this method, but it relies on behaviour defined # in the superclass, so needs to invoke `super` def update super end private def load_article @content = Article.find(params[:article_id]) end end ---- === Configurable attributes |=== | Name | Default value | Configurable values | Include | `app/controllers/**/*.rb` | Array |=== === References * https://rails.rubystyle.guide#lexically-scoped-action-filter == Rails/LinkToBlank |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.62 | - |=== This cop checks for calls to `link_to` that contain a `target: '_blank'` but no `rel: 'noopener'`. This can be a security risk as the loaded page will have control over the previous page and could change its location for phishing purposes. The option `rel: 'noreferrer'` also blocks this behavior and removes the http-referrer header. === Examples [source,ruby] ---- # bad link_to 'Click here', url, target: '_blank' # good link_to 'Click here', url, target: '_blank', rel: 'noopener' # good link_to 'Click here', url, target: '_blank', rel: 'noreferrer' ---- === References * https://mathiasbynens.github.io/rel-noopener/ * https://html.spec.whatwg.org/multipage/links.html#link-type-noopener * https://html.spec.whatwg.org/multipage/links.html#link-type-noreferrer == Rails/NotNullColumn |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.43 | - |=== This cop checks for add_column call with NOT NULL constraint in migration file. === Examples [source,ruby] ---- # bad add_column :users, :name, :string, null: false add_reference :products, :category, null: false # good add_column :users, :name, :string, null: true add_column :users, :name, :string, null: false, default: '' add_reference :products, :category add_reference :products, :category, null: false, default: 1 ---- === Configurable attributes |=== | Name | Default value | Configurable values | Include | `db/migrate/*.rb` | Array |=== == Rails/Output |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.15 | 0.19 |=== This cop checks for the use of output calls like puts and print === Examples [source,ruby] ---- # bad puts 'A debug message' pp 'A debug message' print 'A debug message' # good Rails.logger.debug 'A debug message' ---- === Configurable attributes |=== | Name | Default value | Configurable values | Include | `app/**/*.rb`, `config/**/*.rb`, `db/**/*.rb`, `lib/**/*.rb` | Array |=== == Rails/OutputSafety |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.41 | - |=== This cop checks for the use of output safety calls like `html_safe`, `raw`, and `safe_concat`. These methods do not escape content. They simply return a SafeBuffer containing the content as is. Instead, use `safe_join` to join content and escape it and concat to concatenate content and escape it, ensuring its safety. === Examples [source,ruby] ---- user_content = ""hi"" # bad ""

#{user_content}

"".html_safe # => ActiveSupport::SafeBuffer ""

hi

"" # good content_tag(:p, user_content) # => ActiveSupport::SafeBuffer ""

<b>hi</b>

"" # bad out = """" out << ""
  • #{user_content}
  • "" out << ""
  • #{user_content}
  • "" out.html_safe # => ActiveSupport::SafeBuffer ""
  • hi
  • hi
  • "" # good out = [] out << content_tag(:li, user_content) out << content_tag(:li, user_content) safe_join(out) # => ActiveSupport::SafeBuffer # ""
  • <b>hi</b>
  • <b>hi</b>
  • "" # bad out = ""

    trusted content

    "".html_safe out.safe_concat(user_content) # => ActiveSupport::SafeBuffer ""

    trusted_content

    hi"" # good out = ""

    trusted content

    "".html_safe out.concat(user_content) # => ActiveSupport::SafeBuffer # ""

    trusted_content

    <b>hi</b>"" # safe, though maybe not good style out = ""trusted content"" result = out.concat(user_content) # => String ""trusted contenthi"" # because when rendered in ERB the String will be escaped: # <%= result %> # => trusted content<b>hi</b> # bad (user_content + "" "" + content_tag(:span, user_content)).html_safe # => ActiveSupport::SafeBuffer ""hi hi"" # good safe_join([user_content, "" "", content_tag(:span, user_content)]) # => ActiveSupport::SafeBuffer # ""<b>hi</b> <b>hi</b>"" ---- == Rails/Pick |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | No | Yes (Unsafe) | 2.6 | - |=== This cop enforces the use `pick` over `pluck(...).first`. === Examples [source,ruby] ---- # bad Model.pluck(:a).first Model.pluck(:a, :b).first # good Model.pick(:a) Model.pick(:a, :b) ---- == Rails/PluralizationGrammar |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.35 | - |=== This cop checks for correct grammar when using ActiveSupport's core extensions to the numeric classes. === Examples [source,ruby] ---- # bad 3.day.ago 1.months.ago # good 3.days.ago 1.month.ago ---- == Rails/Presence |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.52 | - |=== This cop checks code that can be written more easily using `Object#presence` defined by Active Support. === Examples [source,ruby] ---- # bad a.present? ? a : nil # bad !a.present? ? nil : a # bad a.blank? ? nil : a # bad !a.blank? ? a : nil # good a.presence ---- [source,ruby] ---- # bad a.present? ? a : b # bad !a.present? ? b : a # bad a.blank? ? b : a # bad !a.blank? ? a : b # good a.presence || b ---- == Rails/Present |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.48 | 0.67 |=== This cop checks for code that can be written with simpler conditionals using `Object#present?` defined by Active Support. Interaction with `Style/UnlessElse`: The configuration of `NotBlank` will not produce an offense in the context of `unless else` if `Style/UnlessElse` is inabled. This is to prevent interference between the auto-correction of the two cops. === Examples ==== NotNilAndNotEmpty: true (default) [source,ruby] ---- # Converts usages of `!nil? && !empty?` to `present?` # bad !foo.nil? && !foo.empty? # bad foo != nil && !foo.empty? # good foo.present? ---- ==== NotBlank: true (default) [source,ruby] ---- # Converts usages of `!blank?` to `present?` # bad !foo.blank? # bad not foo.blank? # good foo.present? ---- ==== UnlessBlank: true (default) [source,ruby] ---- # Converts usages of `unless blank?` to `if present?` # bad something unless foo.blank? # good something if foo.present? ---- === Configurable attributes |=== | Name | Default value | Configurable values | NotNilAndNotEmpty | `true` | Boolean | NotBlank | `true` | Boolean | UnlessBlank | `true` | Boolean |=== == Rails/RakeEnvironment |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | No | Yes (Unsafe) | 2.4 | 2.6 |=== This cop checks for Rake tasks without the `:environment` task dependency. The `:environment` task loads application code for other Rake tasks. Without it, tasks cannot make use of application code like models. You can ignore the offense if the task satisfies at least one of the following conditions: * The task does not need application code. * The task invokes the `:environment` task. === Examples [source,ruby] ---- # bad task :foo do do_something end # good task foo: :environment do do_something end ---- === Configurable attributes |=== | Name | Default value | Configurable values | Include | `+**/Rakefile+`, `+**/*.rake+` | Array | Exclude | `lib/capistrano/tasks/**/*.rake` | Array |=== == Rails/ReadWriteAttribute |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.20 | 0.29 |=== This cop checks for the use of the `read_attribute` or `write_attribute` methods and recommends square brackets instead. If an attribute is missing from the instance (for example, when initialized by a partial `select`) then `read_attribute` will return nil, but square brackets will raise an `ActiveModel::MissingAttributeError`. Explicitly raising an error in this situation is preferable, and that is why rubocop recommends using square brackets. === Examples [source,ruby] ---- # bad x = read_attribute(:attr) write_attribute(:attr, val) # good x = self[:attr] self[:attr] = val ---- === Configurable attributes |=== | Name | Default value | Configurable values | Include | `app/models/**/*.rb` | Array |=== === References * https://rails.rubystyle.guide#read-attribute == Rails/RedundantAllowNil |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.67 | - |=== Checks Rails model validations for a redundant `allow_nil` when `allow_blank` is present. === Examples [source,ruby] ---- # bad validates :x, length: { is: 5 }, allow_nil: true, allow_blank: true # bad validates :x, length: { is: 5 }, allow_nil: false, allow_blank: true # bad validates :x, length: { is: 5 }, allow_nil: false, allow_blank: false # good validates :x, length: { is: 5 }, allow_blank: true # good validates :x, length: { is: 5 }, allow_blank: false # good # Here, `nil` is valid but `''` is not validates :x, length: { is: 5 }, allow_nil: true, allow_blank: false ---- === Configurable attributes |=== | Name | Default value | Configurable values | Include | `app/models/**/*.rb` | Array |=== == Rails/RedundantForeignKey |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 2.6 | - |=== This cop detects cases where the `:foreign_key` option on associations is redundant. === Examples [source,ruby] ---- # bad class Post has_many :comments, foreign_key: 'post_id' end class Comment belongs_to :post, foreign_key: 'post_id' end # good class Post has_many :comments end class Comment belongs_to :author, foreign_key: 'user_id' end ---- == Rails/RedundantReceiverInWithOptions |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.52 | - |=== This cop checks for redundant receiver in `with_options`. Receiver is implicit from Rails 4.2 or higher. === Examples [source,ruby] ---- # bad class Account < ApplicationRecord with_options dependent: :destroy do |assoc| assoc.has_many :customers assoc.has_many :products assoc.has_many :invoices assoc.has_many :expenses end end # good class Account < ApplicationRecord with_options dependent: :destroy do has_many :customers has_many :products has_many :invoices has_many :expenses end end ---- [source,ruby] ---- # bad with_options options: false do |merger| merger.invoke(merger.something) end # good with_options options: false do invoke(something) end # good client = Client.new with_options options: false do |merger| client.invoke(merger.something, something) end # ok # When `with_options` includes a block, all scoping scenarios # cannot be evaluated. Thus, it is ok to include the explicit # receiver. with_options options: false do |merger| merger.invoke with_another_method do |another_receiver| merger.invoke(another_receiver) end end ---- == Rails/ReflectionClassName |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.64 | - |=== This cop checks if the value of the option `class_name`, in the definition of a reflection is a string. === Examples [source,ruby] ---- # bad has_many :accounts, class_name: Account has_many :accounts, class_name: Account.name # good has_many :accounts, class_name: 'Account' ---- == Rails/RefuteMethods |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.56 | - |=== Use `assert_not` methods instead of `refute` methods. === Examples ==== EnforcedStyle: assert_not (default) [source,ruby] ---- # bad refute false refute_empty [1, 2, 3] refute_equal true, false # good assert_not false assert_not_empty [1, 2, 3] assert_not_equal true, false ---- ==== EnforcedStyle: refute [source,ruby] ---- # bad assert_not false assert_not_empty [1, 2, 3] assert_not_equal true, false # good refute false refute_empty [1, 2, 3] refute_equal true, false ---- === Configurable attributes |=== | Name | Default value | Configurable values | EnforcedStyle | `assert_not` | `assert_not`, `refute` | Include | `+**/test/**/*+` | Array |=== == Rails/RelativeDateConstant |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.48 | 0.59 |=== This cop checks whether constant value isn't relative date. Because the relative date will be evaluated only once. === Examples [source,ruby] ---- # bad class SomeClass EXPIRED_AT = 1.week.since end # good class SomeClass EXPIRES = 1.week def self.expired_at EXPIRES.since end end # good class SomeClass def self.expired_at 1.week.since end end ---- === Configurable attributes |=== | Name | Default value | Configurable values | AutoCorrect | `false` | Boolean |=== == Rails/RequestReferer |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.41 | - |=== This cop checks for consistent uses of `request.referer` or `request.referrer`, depending on the cop's configuration. === Examples ==== EnforcedStyle: referer (default) [source,ruby] ---- # bad request.referrer # good request.referer ---- ==== EnforcedStyle: referrer [source,ruby] ---- # bad request.referer # good request.referrer ---- === Configurable attributes |=== | Name | Default value | Configurable values | EnforcedStyle | `referer` | `referer`, `referrer` |=== == Rails/ReversibleMigration |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.47 | - |=== This cop checks whether the change method of the migration file is reversible. === Examples [source,ruby] ---- # bad def change change_table :users do |t| t.remove :name end end # good def change create_table :users do |t| t.string :name end end # good def change reversible do |dir| change_table :users do |t| dir.up do t.column :name, :string end dir.down do t.remove :name end end end end ---- [source,ruby] ---- # drop_table # bad def change drop_table :users end # good def change drop_table :users do |t| t.string :name end end ---- [source,ruby] ---- # change_column_default # bad def change change_column_default(:suppliers, :qualification, 'new') end # good def change change_column_default(:posts, :state, from: nil, to: ""draft"") end ---- [source,ruby] ---- # remove_column # bad def change remove_column(:suppliers, :qualification) end # good def change remove_column(:suppliers, :qualification, :string) end ---- [source,ruby] ---- # remove_foreign_key # bad def change remove_foreign_key :accounts, column: :owner_id end # good def change remove_foreign_key :accounts, :branches end # good def change remove_foreign_key :accounts, to_table: :branches end ---- [source,ruby] ---- # change_table # bad def change change_table :users do |t| t.remove :name t.change_default :authorized, 1 t.change :price, :string end end # good def change change_table :users do |t| t.string :name end end # good def change reversible do |dir| change_table :users do |t| dir.up do t.change :price, :string end dir.down do t.change :price, :integer end end end end ---- === Configurable attributes |=== | Name | Default value | Configurable values | Include | `db/migrate/*.rb` | Array |=== === References * https://rails.rubystyle.guide#reversible-migration * https://api.rubyonrails.org/classes/ActiveRecord/Migration/CommandRecorder.html == Rails/SafeNavigation |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.43 | - |=== This cop converts usages of `try!` to `&.`. It can also be configured to convert `try`. It will convert code to use safe navigation. === Examples ==== ConvertTry: false (default) [source,ruby] ---- # bad foo.try!(:bar) foo.try!(:bar, baz) foo.try!(:bar) { |e| e.baz } foo.try!(:[], 0) # good foo.try(:bar) foo.try(:bar, baz) foo.try(:bar) { |e| e.baz } foo&.bar foo&.bar(baz) foo&.bar { |e| e.baz } ---- ==== ConvertTry: true [source,ruby] ---- # bad foo.try!(:bar) foo.try!(:bar, baz) foo.try!(:bar) { |e| e.baz } foo.try(:bar) foo.try(:bar, baz) foo.try(:bar) { |e| e.baz } # good foo&.bar foo&.bar(baz) foo&.bar { |e| e.baz } ---- === Configurable attributes |=== | Name | Default value | Configurable values | ConvertTry | `false` | Boolean |=== == Rails/SafeNavigationWithBlank |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes (Unsafe) | 2.4 | - |=== This cop checks to make sure safe navigation isn't used with `blank?` in a conditional. While the safe navigation operator is generally a good idea, when checking `foo&.blank?` in a conditional, `foo` being `nil` will actually do the opposite of what the author intends. === Examples [source,ruby] ---- # bad do_something if foo&.blank? do_something unless foo&.blank? # good do_something if foo.blank? do_something unless foo.blank? ---- == Rails/SaveBang |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Disabled | Yes | Yes (Unsafe) | 0.42 | 0.59 |=== This cop identifies possible cases where Active Record save! or related should be used instead of save because the model might have failed to save and an exception is better than unhandled failure. This will allow: * update or save calls, assigned to a variable, or used as a condition in an if/unless/case statement. * create calls, assigned to a variable that then has a call to `persisted?`, or whose return value is checked by `persisted?` immediately * calls if the result is explicitly returned from methods and blocks, or provided as arguments. * calls whose signature doesn't look like an ActiveRecord persistence method. By default it will also allow implicit returns from methods and blocks. that behavior can be turned off with `AllowImplicitReturn: false`. You can permit receivers that are giving false positives with `AllowedReceivers: []` === Examples [source,ruby] ---- # bad user.save user.update(name: 'Joe') user.find_or_create_by(name: 'Joe') user.destroy # good unless user.save # ... end user.save! user.update!(name: 'Joe') user.find_or_create_by!(name: 'Joe') user.destroy! user = User.find_or_create_by(name: 'Joe') unless user.persisted? # ... end def save_user return user.save end ---- ==== AllowImplicitReturn: true (default) [source,ruby] ---- # good users.each { |u| u.save } def save_user user.save end ---- ==== AllowImplicitReturn: false [source,ruby] ---- # bad users.each { |u| u.save } def save_user user.save end # good users.each { |u| u.save! } def save_user user.save! end def save_user return user.save end ---- ==== AllowedReceivers: ['merchant.customers', 'Service::Mailer'] [source,ruby] ---- # bad merchant.create customers.builder.save Mailer.create module Service::Mailer self.create end # good merchant.customers.create MerchantService.merchant.customers.destroy Service::Mailer.update(message: 'Message') ::Service::Mailer.update Services::Service::Mailer.update(message: 'Message') Service::Mailer::update ---- === Configurable attributes |=== | Name | Default value | Configurable values | AllowImplicitReturn | `true` | Boolean | AllowedReceivers | `[]` | Array |=== === References * https://rails.rubystyle.guide#save-bang == Rails/ScopeArgs |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.19 | - |=== This cop checks for scope calls where it was passed a method (usually a scope) instead of a lambda/proc. === Examples [source,ruby] ---- # bad scope :something, where(something: true) # good scope :something, -> { where(something: true) } ---- === Configurable attributes |=== | Name | Default value | Configurable values | Include | `app/models/**/*.rb` | Array |=== == Rails/SkipsModelValidations |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.47 | 0.60 |=== This cop checks for the use of methods which skip validations which are listed in https://guides.rubyonrails.org/active_record_validations.html#skipping-validations Methods may be ignored from this rule by configuring a `Whitelist`. === Examples [source,ruby] ---- # bad Article.first.decrement!(:view_count) DiscussionBoard.decrement_counter(:post_count, 5) Article.first.increment!(:view_count) DiscussionBoard.increment_counter(:post_count, 5) person.toggle :active product.touch Billing.update_all(""category = 'authorized', author = 'David'"") user.update_attribute(:website, 'example.com') user.update_columns(last_request_at: Time.current) Post.update_counters 5, comment_count: -1, action_count: 1 # good user.update(website: 'example.com') FileUtils.touch('file') ---- ==== Whitelist: [""touch""] [source,ruby] ---- # bad DiscussionBoard.decrement_counter(:post_count, 5) DiscussionBoard.increment_counter(:post_count, 5) person.toggle :active # good user.touch ---- === Configurable attributes |=== | Name | Default value | Configurable values | Blacklist | `decrement!`, `decrement_counter`, `increment!`, `increment_counter`, `toggle!`, `touch`, `update_all`, `update_attribute`, `update_column`, `update_columns`, `update_counters` | Array | Whitelist | `[]` | Array |=== === References * https://guides.rubyonrails.org/active_record_validations.html#skipping-validations == Rails/TimeZone |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | No | Yes (Unsafe) | 0.30 | 0.68 |=== This cop checks for the use of Time methods without zone. Built on top of Ruby on Rails style guide (https://rails.rubystyle.guide#time) and the article http://danilenko.org/2012/7/6/rails_timezones/ Two styles are supported for this cop. When EnforcedStyle is 'strict' then only use of Time.zone is allowed. When EnforcedStyle is 'flexible' then it's also allowed to use Time.in_time_zone. === Examples ==== EnforcedStyle: strict [source,ruby] ---- # `strict` means that `Time` should be used with `zone`. # bad Time.now Time.parse('2015-03-02 19:05:37') # bad Time.current Time.at(timestamp).in_time_zone # good Time.zone.now Time.zone.parse('2015-03-02 19:05:37') ---- ==== EnforcedStyle: flexible (default) [source,ruby] ---- # `flexible` allows usage of `in_time_zone` instead of `zone`. # bad Time.now Time.parse('2015-03-02 19:05:37') # good Time.zone.now Time.zone.parse('2015-03-02 19:05:37') # good Time.current Time.at(timestamp).in_time_zone ---- === Configurable attributes |=== | Name | Default value | Configurable values | EnforcedStyle | `flexible` | `strict`, `flexible` |=== === References * https://rails.rubystyle.guide#time * http://danilenko.org/2012/7/6/rails_timezones == Rails/UniqBeforePluck |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.40 | 2.6 |=== Prefer the use of distinct, before pluck instead of after. The use of distinct before pluck is preferred because it executes within the database. This cop has two different enforcement modes. When the EnforcedStyle is conservative (the default) then only calls to pluck on a constant (i.e. a model class) before distinct are added as offenses. When the EnforcedStyle is aggressive then all calls to pluck before distinct are added as offenses. This may lead to false positives as the cop cannot distinguish between calls to pluck on an ActiveRecord::Relation vs a call to pluck on an ActiveRecord::Associations::CollectionProxy. Autocorrect is disabled by default for this cop since it may generate false positives. === Examples ==== EnforcedStyle: conservative (default) [source,ruby] ---- # bad Model.pluck(:id).uniq # good Model.distinct.pluck(:id) ---- ==== EnforcedStyle: aggressive [source,ruby] ---- # bad # this will return a Relation that pluck is called on Model.where(cond: true).pluck(:id).uniq # bad # an association on an instance will return a CollectionProxy instance.assoc.pluck(:id).uniq # bad Model.pluck(:id).uniq # good Model.distinct.pluck(:id) ---- === Configurable attributes |=== | Name | Default value | Configurable values | EnforcedStyle | `conservative` | `conservative`, `aggressive` | AutoCorrect | `false` | Boolean |=== == Rails/UniqueValidationWithoutIndex |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 2.5 | - |=== When you define a uniqueness validation in Active Record model, you also should add a unique index for the column. There are two reasons First, duplicated records may occur even if Active Record's validation is defined. Second, it will cause slow queries. The validation executes a `SELECT` statement with the target column when inserting/updating a record. If the column does not have an index and the table is large, the query will be heavy. Note that the cop does nothing if db/schema.rb does not exist. === Examples [source,ruby] ---- # bad - if the schema does not have a unique index validates :account, uniqueness: true # good - if the schema has a unique index validates :account, uniqueness: true # good - even if the schema does not have a unique index validates :account, length: { minimum: MIN_LENGTH } ---- === Configurable attributes |=== | Name | Default value | Configurable values | Include | `app/models/**/*.rb` | Array |=== == Rails/UnknownEnv |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.51 | - |=== This cop checks that environments called with `Rails.env` predicates exist. === Examples [source,ruby] ---- # bad Rails.env.proudction? Rails.env == 'proudction' # good Rails.env.production? Rails.env == 'production' ---- === Configurable attributes |=== | Name | Default value | Configurable values | Environments | `development`, `test`, `production` | Array |=== == Rails/Validation |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.9 | 0.41 |=== This cop checks for the use of old-style attribute validation macros. === Examples [source,ruby] ---- # bad validates_acceptance_of :foo validates_confirmation_of :foo validates_exclusion_of :foo validates_format_of :foo validates_inclusion_of :foo validates_length_of :foo validates_numericality_of :foo validates_presence_of :foo validates_absence_of :foo validates_size_of :foo validates_uniqueness_of :foo # good validates :foo, acceptance: true validates :foo, confirmation: true validates :foo, exclusion: true validates :foo, format: true validates :foo, inclusion: true validates :foo, length: true validates :foo, numericality: true validates :foo, presence: true validates :foo, absence: true validates :foo, size: true validates :foo, uniqueness: true ---- === Configurable attributes |=== | Name | Default value | Configurable values | Include | `app/models/**/*.rb` | Array |=== ",16256,True,3575.316270210809,median "-- Copyright (c) 2020-2021 Bartek thindil Jasicki -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see . with Ada.Calendar.Formatting; with Ada.Calendar.Time_Zones; with Ada.Characters.Latin_1; use Ada.Characters.Latin_1; with Ada.Containers.Vectors; with Ada.Directories; use Ada.Directories; with Ada.Exceptions; with Ada.Strings; with Ada.Strings.Fixed; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with Ada.Text_IO; use Ada.Text_IO; with Interfaces.C.Strings; use Interfaces.C.Strings; with GNAT.OS_Lib; with GNAT.String_Split; with Tcl.Ada; use Tcl.Ada; with Tcl.Tk.Ada; use Tcl.Tk.Ada; with Tcl.Tk.Ada.Grid; with Tcl.Tk.Ada.Pack; with Tcl.Tk.Ada.Widgets; use Tcl.Tk.Ada.Widgets; with Tcl.Tk.Ada.Widgets.Menu; with Tcl.Tk.Ada.Widgets.Text; use Tcl.Tk.Ada.Widgets.Text; with Tcl.Tk.Ada.Widgets.Toplevel; with Tcl.Tk.Ada.Widgets.Toplevel.MainWindow; use Tcl.Tk.Ada.Widgets.Toplevel.MainWindow; with Tcl.Tk.Ada.Widgets.TtkButton; use Tcl.Tk.Ada.Widgets.TtkButton; with Tcl.Tk.Ada.Widgets.TtkEntry; use Tcl.Tk.Ada.Widgets.TtkEntry; with Tcl.Tk.Ada.Widgets.TtkEntry.TtkComboBox; use Tcl.Tk.Ada.Widgets.TtkEntry.TtkComboBox; with Tcl.Tk.Ada.Widgets.TtkEntry.TtkSpinBox; with Tcl.Tk.Ada.Widgets.TtkFrame; use Tcl.Tk.Ada.Widgets.TtkFrame; with Tcl.Tk.Ada.Widgets.TtkLabel; with Tcl.Tk.Ada.Widgets.TtkTreeView; with Tcl.Tk.Ada.Winfo; use Tcl.Tk.Ada.Winfo; with Tcl.Tk.Ada.Wm; with Tcl.Tklib.Ada.Tooltip; with BasesTypes; use BasesTypes; with Config; use Config; with Crew; with Dialogs; use Dialogs; with Events; with Factions; use Factions; with Game; use Game; with Game.SaveLoad; with Goals; with HallOfFame; with Maps.UI; with Ships; with Table; use Table; with Utils; with Utils.UI; package body MainMenu.Commands is function Open_Link_Command (Client_Data: Integer; Interp: Tcl.Tcl_Interp; Argc: Interfaces.C.int; Argv: CArgv.Chars_Ptr_Ptr) return Interfaces.C.int is pragma Unreferenced(Client_Data, Interp, Argc); use GNAT.OS_Lib; Os_Name: constant String := Tcl_GetVar(interp => Get_Context, varName => ""tcl_platform(os)""); Command: constant String := Locate_Exec_On_Path (Exec_Name => (if Os_Name = ""Windows"" then ""start"" elsif Os_Name = ""Darwin"" then ""open"" else ""xdg-open"")).all; begin if Non_Blocking_Spawn (Program_Name => Command, Args => Argument_String_To_List (Arg_String => CArgv.Arg(Argv => Argv, N => 1)).all) = Invalid_Pid then return TCL_ERROR; end if; return TCL_OK; end Open_Link_Command; -- ****o* MCommands/MCommands.Show_File_Command -- FUNCTION -- Show the selected file content -- PARAMETERS -- Client_Data - Custom data send to the command. Unused -- Interp - Tcl interpreter in which command was executed. -- Argc - Number of arguments passed to the command. Unused -- Argv - Values of arguments passed to the command. -- RESULT -- This function always return TCL_OK -- COMMANDS -- ShowFile filename -- Filename is the name of the file in the documentation directory which -- will be show -- SOURCE function Show_File_Command (Client_Data: Integer; Interp: Tcl.Tcl_Interp; Argc: Interfaces.C.int; Argv: CArgv.Chars_Ptr_Ptr) return Interfaces.C.int with Convention => C; -- **** function Show_File_Command (Client_Data: Integer; Interp: Tcl.Tcl_Interp; Argc: Interfaces.C.int; Argv: CArgv.Chars_Ptr_Ptr) return Interfaces.C.int is pragma Unreferenced(Client_Data, Argc); Text_View: constant Tk_Text := Get_Widget(pathName => "".showfilemenu.text"", Interp => Interp); Show_File: File_Type; File_Name: constant String := CArgv.Arg(Argv => Argv, N => 1); begin configure(Widgt => Text_View, options => ""-state normal""); Delete(TextWidget => Text_View, StartIndex => ""1.0"", Indexes => ""end""); if Exists(Name => To_String(Source => Doc_Directory) & File_Name) then Open (File => Show_File, Mode => In_File, Name => To_String(Source => Doc_Directory) & File_Name); Load_File_Line_Loop : while not End_Of_File(File => Show_File) loop Insert (TextWidget => Text_View, Index => ""end"", Text => ""{"" & Get_Line(File => Show_File) & LF & ""}""); end loop Load_File_Line_Loop; Close(File => Show_File); else Insert (TextWidget => Text_View, Index => ""end"", Text => ""{Can't find file to load. Did '"" & File_Name & ""' file is in '"" & To_String(Source => Doc_Directory) & ""' directory?}""); end if; configure(Widgt => Text_View, options => ""-state disabled""); Bind_To_Main_Window (Interp => Interp, Sequence => """", Script => ""{InvokeButton .showfilemenu.back}""); Bind_To_Main_Window (Interp => Interp, Sequence => """", Script => ""{InvokeButton .showfilemenu.back}""); return TCL_OK; end Show_File_Command; -- ****iv* MCommands/MCommands.AllNews -- FUNCTION -- If true, show all news, not only from last version. Default is false -- SOURCE All_News: Boolean := False; -- **** -- ****o* MCommands/MCommands.Show_News_Command -- FUNCTION -- Show changes in the game, all or just recent -- PARAMETERS -- Client_Data - Custom data send to the command. Unused -- Interp - Tcl interpreter in which command was executed. -- Argc - Number of arguments passed to the command. Unused -- Argv - Values of arguments passed to the command. -- RESULT -- This function always return TCL_OK -- COMMANDS -- ShowNews boolean -- If boolean is true, show all news, otherwise only recent -- SOURCE function Show_News_Command (Client_Data: Integer; Interp: Tcl.Tcl_Interp; Argc: Interfaces.C.int; Argv: CArgv.Chars_Ptr_Ptr) return Interfaces.C.int with Convention => C; -- **** function Show_News_Command (Client_Data: Integer; Interp: Tcl.Tcl_Interp; Argc: Interfaces.C.int; Argv: CArgv.Chars_Ptr_Ptr) return Interfaces.C.int is pragma Unreferenced(Client_Data, Argc); use Tcl.Tklib.Ada.Tooltip; Text_View: constant Tk_Text := Get_Widget(pathName => "".newsmenu.text"", Interp => Interp); Changes_File: File_Type; File_Text: Unbounded_String := Null_Unbounded_String; All_News_Button: constant Ttk_Button := Get_Widget(pathName => "".newsmenu.showall"", Interp => Interp); begin if CArgv.Arg(Argv => Argv, N => 1) = ""false"" then All_News := False; configure (Widgt => All_News_Button, options => ""-text {Show all changes} -command {ShowNews true}""); Add (Widget => All_News_Button, Message => ""Show all changes to the game since previous big stable version""); else All_News := True; configure (Widgt => All_News_Button, options => ""-text {Show only newest changes} -command {ShowNews false}""); Add (Widget => All_News_Button, Message => ""Show only changes to the game since previous relese""); end if; configure(Widgt => Text_View, options => ""-state normal""); Delete(TextWidget => Text_View, StartIndex => ""1.0"", Indexes => ""end""); if Exists (Name => To_String(Source => Doc_Directory) & ""CHANGELOG.md"") then Open (File => Changes_File, Mode => In_File, Name => To_String(Source => Doc_Directory) & ""CHANGELOG.md""); Set_Line(File => Changes_File, To => 6); Load_Changes_File_Loop : while not End_Of_File(File => Changes_File) loop File_Text := To_Unbounded_String(Source => Get_Line(File => Changes_File)); if Length(Source => File_Text) > 1 and not All_News then exit Load_Changes_File_Loop when Slice (Source => File_Text, Low => 1, High => 3) = ""## ""; end if; Insert (TextWidget => Text_View, Index => ""end"", Text => ""{"" & To_String(Source => File_Text) & LF & ""}""); end loop Load_Changes_File_Loop; Close(File => Changes_File); else Insert (TextWidget => Text_View, Index => ""end"", Text => ""{Can't find changelog file. Did 'CHANGELOG.md' file is in '"" & To_String(Source => Doc_Directory) & ""' directory?}""); end if; configure(Widgt => Text_View, options => ""-state disabled""); return TCL_OK; end Show_News_Command; -- ****o* MCommands/MCommands.Show_Hall_Of_Fame_Command -- FUNCTION -- Show the Hall of Fame -- PARAMETERS -- Client_Data - Custom data send to the command. Unused -- Interp - Tcl interpreter in which command was executed. -- Argc - Number of arguments passed to the command. Unused -- Argv - Values of arguments passed to the command. Unused -- RESULT -- This function always return TCL_OK -- COMMANDS -- ShowHallOfFame -- SOURCE function Show_Hall_Of_Fame_Command (Client_Data: Integer; Interp: Tcl.Tcl_Interp; Argc: Interfaces.C.int; Argv: CArgv.Chars_Ptr_Ptr) return Interfaces.C.int with Convention => C; -- **** function Show_Hall_Of_Fame_Command (Client_Data: Integer; Interp: Tcl.Tcl_Interp; Argc: Interfaces.C.int; Argv: CArgv.Chars_Ptr_Ptr) return Interfaces.C.int is pragma Unreferenced(Client_Data, Argc, Argv); use Tcl.Tk.Ada.Widgets.TtkTreeView; use HallOfFame; Hof_View: constant Ttk_Tree_View := Get_Widget(pathName => "".hofmenu.view"", Interp => Interp); begin Delete (TreeViewWidget => Hof_View, ItemsList => ""[list "" & Children(TreeViewWidget => Hof_View, Item => ""{}"") & ""]""); Load_Hall_Of_Fame_Loop : for I in Hall_Of_Fame_Array'Range loop exit Load_Hall_Of_Fame_Loop when Hall_Of_Fame_Array(I).Name = Null_Unbounded_String; Insert (TreeViewWidget => Hof_View, Options => ""{} end -values [list "" & Positive'Image(I) & "" "" & To_String(Source => Hall_Of_Fame_Array(I).Name) & "" "" & Natural'Image(Hall_Of_Fame_Array(I).Points) & "" "" & To_String(Source => Hall_Of_Fame_Array(I).Death_Reason) & ""]""); end loop Load_Hall_Of_Fame_Loop; return TCL_OK; end Show_Hall_Of_Fame_Command; -- ****iv* MCommands/MCommands.LoadTable -- FUNCTION -- Table with info about the available saved games -- SOURCE Load_Table: Table_Widget (Amount => 3); -- **** -- ****if* MCommands/MCommands.Get_Load_Table -- FUNCTION -- Get the table with the list of the saved games -- RESULT -- The Table_Widtget with the list of available saved games -- HISTORY -- 6.6 - Added -- SOURCE function Get_Load_Table return Table_Widget is -- **** begin return Load_Table; end Get_Load_Table; -- ****it* MCommands/MCommands.Save_Sort_Orders -- FUNCTION -- Sorting orders for the saved games list -- OPTIONS -- PLAYERASC - Sort by player name ascending -- PLAYERDESC - Sort by player name descending -- SHIPASC - Sort by ship name ascending -- SHIPDESC - Sort by ship name descending -- TIMEASC - Sort by save time ascending -- TIMEDESC - Sort by save time descending -- SOURCE type Save_Sort_Orders is (PLAYERASC, PLAYERDESC, SHIPASC, SHIPDESC, TIMEASC, TIMEDESC) with Default_Value => TIMEDESC; -- **** -- ****id* MCommands/MCommands.Default_Save_Sort_Order -- FUNCTION -- Default sorting order for the saved game list -- HISTORY -- 6.6 - Added -- SOURCE Default_Save_Sort_Order: constant Save_Sort_Orders := TIMEDESC; -- **** -- ****iv* MCommands/MCommands.Save_Sort_Order -- FUNCTION -- The current sorting order for the saved game list -- SOURCE Save_Sort_Order: Save_Sort_Orders := Default_Save_Sort_Order; -- **** -- ****if* MCommands/MCommands.Get_Save_Sort_Order -- FUNCTION -- Get the current sorting order for the saved games list -- RESULT -- The current sorting order of the saved games list -- HISTORY -- 6.5 - Added -- SOURCE function Get_Save_Sort_Order return Save_Sort_Orders is begin return Save_Sort_Order; end Get_Save_Sort_Order; -- **** -- ****o* MCommands/MCommads.Show_Load_Game_Command -- FUNCTION -- Show available saved games -- PARAMETERS -- Client_Data - Custom data send to the command. Unused -- Interp - Tcl interpreter in which command was executed. -- Argc - Number of arguments passed to the command. Unused -- Argv - Values of arguments passed to the command. Unused -- RESULT -- This function always return TCL_OK -- COMMANDS -- ShowLoadGame -- SOURCE function Show_Load_Game_Command (Client_Data: Integer; Interp: Tcl.Tcl_Interp; Argc: Interfaces.C.int; Argv: CArgv.Chars_Ptr_Ptr) return Interfaces.C.int with Convention => C; -- **** function Show_Load_Game_Command (Client_Data: Integer; Interp: Tcl.Tcl_Interp; Argc: Interfaces.C.int; Argv: CArgv.Chars_Ptr_Ptr) return Interfaces.C.int is pragma Unreferenced(Client_Data, Argc, Argv); use Ada.Calendar.Time_Zones; use Ada.Containers; use GNAT.String_Split; Files: Search_Type; Found_File: Directory_Entry_Type; Tokens: Slice_Set; --## rule line off IMPROPER_INITIALIZATION type Save_Record is record --## rule line off TYPE_INITIAL_VALUES Player_Name: Unbounded_String; Ship_Name: Unbounded_String; Save_Time: Unbounded_String; File_Name: Unbounded_String; end record; package Saves_Container is new Vectors (Index_Type => Positive, Element_Type => Save_Record); Saves: Saves_Container.Vector := Saves_Container.Empty_Vector; function ""<""(Left, Right: Save_Record) return Boolean is begin if Get_Save_Sort_Order = PLAYERASC and then Left.Player_Name < Right.Player_Name then return True; end if; if Get_Save_Sort_Order = PLAYERDESC and then Left.Player_Name > Right.Player_Name then return True; end if; if Get_Save_Sort_Order = SHIPASC and then Left.Ship_Name < Right.Ship_Name then return True; end if; if Get_Save_Sort_Order = SHIPDESC and then Left.Ship_Name > Right.Ship_Name then return True; end if; if Get_Save_Sort_Order = TIMEASC and then Left.Save_Time < Right.Save_Time then return True; end if; if Get_Save_Sort_Order = TIMEDESC and then Left.Save_Time > Right.Save_Time then return True; end if; return False; end ""<""; package Saves_Sorting is new Saves_Container.Generic_Sorting; Local_Load_Table: Table_Widget := Get_Load_Table; begin if Local_Load_Table.Row_Height = 1 then Local_Load_Table := CreateTable (Parent => "".loadmenu.list"", Headers => (1 => To_Unbounded_String(Source => ""Player name""), 2 => To_Unbounded_String(Source => ""Ship name""), 3 => To_Unbounded_String(Source => ""Last saved"")), Command => ""SortSaves"", Tooltip => ""Press mouse button to sort the saved games.""); else ClearTable(Table => Local_Load_Table); end if; Start_Search (Search => Files, Directory => To_String(Source => Save_Directory), Pattern => ""*.sav""); Load_Saves_List_Loop : while More_Entries(Search => Files) loop Get_Next_Entry(Search => Files, Directory_Entry => Found_File); Create (S => Tokens, From => Simple_Name(Directory_Entry => Found_File), Separators => ""_""); Saves.Append (New_Item => (Player_Name => To_Unbounded_String(Source => Slice(S => Tokens, Index => 1)), Ship_Name => To_Unbounded_String(Source => Slice(S => Tokens, Index => 2)), Save_Time => To_Unbounded_String (Source => Ada.Calendar.Formatting.Image (Date => Modification_Time(Directory_Entry => Found_File), Include_Time_Fraction => False, Time_Zone => UTC_Time_Offset)), File_Name => To_Unbounded_String (Source => Simple_Name(Directory_Entry => Found_File)))); end loop Load_Saves_List_Loop; End_Search(Search => Files); Saves_Sorting.Sort(Container => Saves); Show_Saved_Games_Loop : for Save of Saves loop AddButton (Table => Local_Load_Table, Text => To_String(Source => Save.Player_Name), Tooltip => ""Press mouse "" & (if Game_Settings.Right_Button then ""right"" else ""left"") & "" button to show available options"", Command => ""ShowLoadGameMenu "" & To_String(Source => Save.File_Name), Column => 1); AddButton (Table => Local_Load_Table, Text => To_String(Source => Save.Ship_Name), Tooltip => ""Press mouse "" & (if Game_Settings.Right_Button then ""right"" else ""left"") & "" button to show available options"", Command => ""ShowLoadGameMenu "" & To_String(Source => Save.File_Name), Column => 2); AddButton (Table => Local_Load_Table, Text => To_String(Source => Save.Save_Time), Tooltip => ""Press mouse "" & (if Game_Settings.Right_Button then ""right"" else ""left"") & "" button to show available options"", Command => ""ShowLoadGameMenu "" & To_String(Source => Save.File_Name), Column => 3, NewRow => True); end loop Show_Saved_Games_Loop; UpdateTable(Table => Local_Load_Table); if Local_Load_Table.Row = 1 then Unbind_From_Main_Window(Interp => Interp, Sequence => """"); Unbind_From_Main_Window(Interp => Interp, Sequence => """"); Tcl.Tk.Ada.Pack.Pack_Forget (Slave => Ttk_Frame'(Get_Widget(pathName => "".loadmenu""))); Show_Main_Menu; end if; Load_Table := Local_Load_Table; return TCL_OK; end Show_Load_Game_Command; -- ****o* MCommands/MCommands.Delete_Game_Command -- FUNCTION -- Delete the selected save file -- PARAMETERS -- Client_Data - Custom data send to the command. Unused -- Interp - Tcl interpreter in which command was executed. -- Argc - Number of arguments passed to the command. Unused -- Argv - Values of arguments passed to the command. Unused -- RESULT -- This function always return TCL_OK -- COMMANDS -- DeleteGame file -- File is the name of the saved game to delete -- SOURCE function Delete_Game_Command (Client_Data: Integer; Interp: Tcl.Tcl_Interp; Argc: Interfaces.C.int; Argv: CArgv.Chars_Ptr_Ptr) return Interfaces.C.int with Convention => C; -- **** function Delete_Game_Command (Client_Data: Integer; Interp: Tcl.Tcl_Interp; Argc: Interfaces.C.int; Argv: CArgv.Chars_Ptr_Ptr) return Interfaces.C.int is pragma Unreferenced(Client_Data, Argc); begin Tcl_SetVar (interp => Interp, varName => ""deletesave"", newValue => CArgv.Arg(Argv => Argv, N => 1)); ShowQuestion (Question => ""Are you sure you want delete this savegame?"", Result => ""deletesave"", In_Game => False); return TCL_OK; end Delete_Game_Command; -- ****if* MCommands/MCommands.StartGame -- FUNCTION -- Start the game -- SOURCE procedure Start_Game is -- **** use Ada.Strings; use Ada.Strings.Fixed; use Tcl.Tk.Ada.Widgets.Toplevel; use Tcl.Tk.Ada.Wm; use Events; use Maps.UI; Main_Window: constant Tk_Toplevel := Get_Main_Window(Interp => Get_Context); X, Y: Integer; begin X := (Positive'Value (Winfo_Get(Widgt => Main_Window, Info => ""vrootwidth"")) - Game_Settings.Window_Width) / 2; if X < 0 then X := 0; end if; Y := (Positive'Value (Winfo_Get(Widgt => Main_Window, Info => ""vrootheight"")) - Game_Settings.Window_Height) / 2; if Y < 0 then Y := 0; end if; Wm_Set (Widgt => Main_Window, Action => ""geometry"", Options => Trim (Source => Positive'Image(Game_Settings.Window_Width), Side => Left) & ""x"" & Trim (Source => Positive'Image(Game_Settings.Window_Height), Side => Left) & ""+"" & Trim(Source => Positive'Image(X), Side => Left) & ""+"" & Trim(Source => Positive'Image(Y), Side => Left)); GenerateTraders; CreateGameUI; end Start_Game; -- ****o* MCommands/MCommands.Load_Game_Command -- FUNCTION -- Load the selected save file and start the game -- PARAMETERS -- Client_Data - Custom data send to the command. Unused -- Interp - Tcl interpreter in which command was executed. Unused -- Argc - Number of arguments passed to the command. Unused -- Argv - Values of arguments passed to the command. -- RESULT -- This function always return TCL_OK -- COMMANDS -- LoadGame file -- File is the name of the saved game which will be loaded -- SOURCE function Load_Game_Command (Client_Data: Integer; Interp: Tcl.Tcl_Interp; Argc: Interfaces.C.int; Argv: CArgv.Chars_Ptr_Ptr) return Interfaces.C.int with Convention => C; -- **** function Load_Game_Command (Client_Data: Integer; Interp: Tcl.Tcl_Interp; Argc: Interfaces.C.int; Argv: CArgv.Chars_Ptr_Ptr) return Interfaces.C.int is pragma Unreferenced(Client_Data, Interp, Argc); use Ada.Exceptions; use Game.SaveLoad; begin Tcl.Tk.Ada.Pack.Pack_Forget (Slave => Ttk_Frame'(Get_Widget(pathName => "".loadmenu""))); Save_Name := Save_Directory & CArgv.Arg(Argv => Argv, N => 1); Load_Game; Start_Game; return TCL_OK; exception when An_Exception : Save_Game_Invalid_Data => Show_Main_Menu; ShowMessage (Text => ""Can't load this game. Reason: "" & Exception_Message(X => An_Exception), ParentFrame => ""."", Title => ""Can't load the game""); return TCL_OK; end Load_Game_Command; -- ****o* MCommands/MCommands.Set_Faction_Command -- FUNCTION -- Set faction destription and available bases and careers -- PARAMETERS -- Client_Data - Custom data send to the command. Unused -- Interp - Tcl interpreter in which command was executed. -- Argc - Number of arguments passed to the command. Unused -- Argv - Values of arguments passed to the command. Unused -- RESULT -- This function always return TCL_OK -- COMMANDS -- SetFaction -- SOURCE function Set_Faction_Command (Client_Data: Integer; Interp: Tcl.Tcl_Interp; Argc: Interfaces.C.int; Argv: CArgv.Chars_Ptr_Ptr) return Interfaces.C.int with Convention => C; -- **** function Set_Faction_Command (Client_Data: Integer; Interp: Tcl.Tcl_Interp; Argc: Interfaces.C.int; Argv: CArgv.Chars_Ptr_Ptr) return Interfaces.C.int is pragma Unreferenced(Client_Data, Argc, Argv); use Tcl.Tk.Ada.Grid; use Tcl.Tk.Ada.Widgets.TtkLabel; Faction_Name: Unbounded_String; Values: Unbounded_String := Null_Unbounded_String; Frame_Name: constant String := "".newgamemenu.canvas.player""; Combo_Box: Ttk_ComboBox := Get_Widget(pathName => Frame_Name & "".faction"", Interp => Interp); Label: Ttk_Label := Get_Widget(pathName => ""."", Interp => Interp); Gender_Frame: constant Ttk_Frame := Get_Widget(pathName => Frame_Name & "".gender"", Interp => Interp); procedure Update_Info(New_Text: String) is Info_Text: constant Tk_Text := Get_Widget(pathName => "".newgamemenu.info.text"", Interp => Interp); begin configure(Widgt => Info_Text, options => ""-state normal""); Delete (TextWidget => Info_Text, StartIndex => ""1.0"", Indexes => ""end""); Insert (TextWidget => Info_Text, Index => ""end"", Text => ""{Select your faction from a list. Factions have the biggest impact on game. They determine the amount of bases and some playing styles. More information about each faction can be found after selecting it. You can't change this later."" & LF & LF & ""}""); Insert(TextWidget => Info_Text, Index => ""end"", Text => New_Text); configure(Widgt => Info_Text, options => ""-state disabled""); end Update_Info; begin Faction_Name := To_Unbounded_String(Source => Get(Widgt => Combo_Box)); if Faction_Name = To_Unbounded_String(Source => ""Random"") then Label.Name := New_String(Str => Frame_Name & "".labelcareer""); Grid_Remove(Slave => Label); Combo_Box.Name := New_String(Str => Frame_Name & "".career""); Set(ComboBox => Combo_Box, Value => ""Random""); Grid_Remove(Slave => Combo_Box); Label.Name := New_String(Str => Frame_Name & "".labelbase""); Grid_Remove(Slave => Label); Combo_Box.Name := New_String(Str => Frame_Name & "".base""); Set(ComboBox => Combo_Box, Value => ""Any""); Grid_Remove(Slave => Combo_Box); Update_Info (New_Text => ""{Faction, career and base type will be randomly selected for you during creating new game. Not recommended for new player.}""); return TCL_OK; end if; Label.Name := New_String(Str => Frame_Name & "".labelcareer""); Tcl.Tk.Ada.Grid.Grid(Slave => Label); Combo_Box.Name := New_String(Str => Frame_Name & "".career""); Tcl.Tk.Ada.Grid.Grid(Slave => Combo_Box); Label.Name := New_String(Str => Frame_Name & "".labelbase""); Tcl.Tk.Ada.Grid.Grid(Slave => Label); Combo_Box.Name := New_String(Str => Frame_Name & "".base""); Tcl.Tk.Ada.Grid.Grid(Slave => Combo_Box); Load_Faction_Based_Info_Loop : for Faction of Factions_List loop if Faction.Name /= Faction_Name then goto End_Of_Faction_Info_Loop; end if; if Faction.Flags.Contains (Item => To_Unbounded_String(Source => ""nogender"")) then Label.Name := New_String(Str => Frame_Name & "".labelgender""); Grid_Remove(Slave => Label); Grid_Remove(Slave => Gender_Frame); Tcl_SetVar (interp => Interp, varName => ""playergender"", newValue => ""M""); else Label.Name := New_String(Str => Frame_Name & "".labelgender""); Tcl.Tk.Ada.Grid.Grid(Slave => Label); Tcl.Tk.Ada.Grid.Grid(Slave => Gender_Frame); end if; Values := Null_Unbounded_String; Load_Careers_Loop : for I in Faction.Careers.Iterate loop Append (Source => Values, New_Item => "" "" & Faction.Careers(I).Name); end loop Load_Careers_Loop; Append(Source => Values, New_Item => "" Random""); Combo_Box.Name := New_String(Str => Frame_Name & "".career""); configure (Widgt => Combo_Box, options => ""-values [list "" & To_String(Source => Values) & ""]""); Set(ComboBox => Combo_Box, Value => ""General""); Values := To_Unbounded_String(Source => "" Any""); Load_Bases_Types_Loop : for I in Faction.BasesTypes.Iterate loop Append (Source => Values, New_Item => "" {"" & Bases_Types_List(BaseType_Container.Key(Position => I)).Name & ""}""); end loop Load_Bases_Types_Loop; Combo_Box.Name := New_String(Str => Frame_Name & "".base""); configure (Widgt => Combo_Box, options => ""-values [list "" & To_String(Source => Values) & ""]""); Set(ComboBox => Combo_Box, Value => ""Any""); Update_Info (New_Text => ""{"" & To_String(Source => Faction.Description) & ""}""); exit Load_Faction_Based_Info_Loop; <> end loop Load_Faction_Based_Info_Loop; return TCL_OK; end Set_Faction_Command; -- ****o* MCommands/MCommands.Set_Career_Command -- FUNCTION -- Set career description -- PARAMETERS -- ClientData - Custom data send to the command. Unused -- Interp - Tcl interpreter in which command was executed. -- Argc - Number of arguments passed to the command. Unused -- Argv - Values of arguments passed to the command. Unused -- RESULT -- This function always return TCL_OK -- COMMANDS -- SetCareer -- SOURCE function Set_Career_Command (Client_Data: Integer; Interp: Tcl.Tcl_Interp; Argc: Interfaces.C.int; Argv: CArgv.Chars_Ptr_Ptr) return Interfaces.C.int with Convention => C; -- **** function Set_Career_Command (Client_Data: Integer; Interp: Tcl.Tcl_Interp; Argc: Interfaces.C.int; Argv: CArgv.Chars_Ptr_Ptr) return Interfaces.C.int is pragma Unreferenced(Client_Data, Argc, Argv); Faction_Name, Career_Name: Unbounded_String; Frame_Name: constant String := "".newgamemenu.canvas.player""; Combo_Box: Ttk_ComboBox := Get_Widget(pathName => Frame_Name & "".faction"", Interp => Interp); Info_Text: constant Tk_Text := Get_Widget(pathName => "".newgamemenu.info.text"", Interp => Interp); begin Faction_Name := To_Unbounded_String(Source => Get(Widgt => Combo_Box)); Combo_Box.Name := New_String(Str => Frame_Name & "".career""); Career_Name := To_Unbounded_String(Source => Get(Widgt => Combo_Box)); configure(Widgt => Info_Text, options => ""-state normal""); Delete(TextWidget => Info_Text, StartIndex => ""1.0"", Indexes => ""end""); Insert (TextWidget => Info_Text, Index => ""end"", Text => ""{Select your career from a list. Careers have some impact on gameplay (each have bonuses to gaining experience in some fields plus they determine your starting ship and crew). More info about each career can be found after selecting it. You can't change career later."" & LF & LF & ""}""); Set_Faction_Careers_Loop : for Faction of Factions_List loop if Faction.Name = Faction_Name then Load_Careers_Loop : for Career of Faction.Careers loop if Career.Name = Career_Name then Insert (TextWidget => Info_Text, Index => ""end"", Text => ""{"" & To_String(Source => Career.Description) & ""}""); exit Set_Faction_Careers_Loop; end if; end loop Load_Careers_Loop; end if; end loop Set_Faction_Careers_Loop; if Career_Name = ""Random"" then Insert (TextWidget => Info_Text, Index => ""end"", Text => ""{Career will be randomly selected for you during creating new game. Not recommended for new player.}""); end if; configure(Widgt => Info_Text, options => ""-state disabled""); return TCL_OK; end Set_Career_Command; -- ****o* MCommands/MCommands.Set_Base_Command -- FUNCTION -- Set starting base description -- PARAMETERS -- ClientData - Custom data send to the command. Unused -- Interp - Tcl interpreter in which command was executed. -- Argc - Number of arguments passed to the command. Unused -- Argv - Values of arguments passed to the command. Unused -- RESULT -- This function always return TCL_OK -- COMMANDS -- SetBase -- SOURCE function Set_Base_Command (Client_Data: Integer; Interp: Tcl.Tcl_Interp; Argc: Interfaces.C.int; Argv: CArgv.Chars_Ptr_Ptr) return Interfaces.C.int with Convention => C; -- **** function Set_Base_Command (Client_Data: Integer; Interp: Tcl.Tcl_Interp; Argc: Interfaces.C.int; Argv: CArgv.Chars_Ptr_Ptr) return Interfaces.C.int is pragma Unreferenced(Client_Data, Argc, Argv); Base_Name: Unbounded_String; Combo_Box: constant Ttk_ComboBox := Get_Widget (pathName => "".newgamemenu.canvas.player.base"", Interp => Interp); Info_Text: constant Tk_Text := Get_Widget(pathName => "".newgamemenu.info.text"", Interp => Interp); begin Base_Name := To_Unbounded_String(Source => Get(Widgt => Combo_Box)); configure(Widgt => Info_Text, options => ""-state normal""); Delete(TextWidget => Info_Text, StartIndex => ""1.0"", Indexes => ""end""); Insert (TextWidget => Info_Text, Index => ""end"", Text => ""{Select your career from a list. Careers have some impact on gameplay (each have bonuses to gaining experience in some fields plus they determine your starting ship and crew). More info about each career can be found after selecting it. You can't change career later."" & LF & LF & ""}""); Find_Base_Type_Loop : for Base of Bases_Types_List loop if Base.Name = Base_Name then Insert (TextWidget => Info_Text, Index => ""end"", Text => ""{"" & To_String(Source => Base.Description) & ""}""); exit Find_Base_Type_Loop; end if; end loop Find_Base_Type_Loop; if Base_Name = ""Any"" then Insert (TextWidget => Info_Text, Index => ""end"", Text => ""{Start the game in randomly selected base type.}""); end if; configure(Widgt => Info_Text, options => ""-state disabled""); return TCL_OK; end Set_Base_Command; -- ****o* MCommands/MCommands.Random_Name_Command -- FUNCTION -- Generate random player or ship name -- PARAMETERS -- ClientData - Custom data send to the command. Unused -- Interp - Tcl interpreter in which command was executed. -- Argc - Number of arguments passed to the command. Unused -- Argv - Values of arguments passed to the command. -- RESULT -- This function always return TCL_OK -- COMMANDS -- RandomName type -- Type is type of name which should be generated. Possible options are -- player or ship -- SOURCE function Random_Name_Command (Client_Data: Integer; Interp: Tcl.Tcl_Interp; Argc: Interfaces.C.int; Argv: CArgv.Chars_Ptr_Ptr) return Interfaces.C.int with Convention => C; -- **** function Random_Name_Command (Client_Data: Integer; Interp: Tcl.Tcl_Interp; Argc: Interfaces.C.int; Argv: CArgv.Chars_Ptr_Ptr) return Interfaces.C.int is pragma Unreferenced(Client_Data, Argc); use Crew; use Ships; Combo_Box: constant Ttk_ComboBox := Get_Widget (pathName => "".newgamemenu.canvas.player.faction"", Interp => Interp); Faction_Name: constant Unbounded_String := To_Unbounded_String(Source => Get(Widgt => Combo_Box)); Faction_Index: Unbounded_String := Null_Unbounded_String; Gender: Character := 'M'; Name_Entry: constant Ttk_Entry := Get_Widget (pathName => "".newgamemenu.canvas.player."" & CArgv.Arg(Argv => Argv, N => 1) & ""name"", Interp => Interp); begin Find_Faction_Index_Loop : for I in Factions_List.Iterate loop if Factions_List(I).Name = Faction_Name then Faction_Index := Factions_Container.Key(Position => I); exit Find_Faction_Index_Loop; end if; end loop Find_Faction_Index_Loop; if CArgv.Arg(Argv => Argv, N => 1) = ""player"" then Gender := Tcl_GetVar(interp => Interp, varName => ""playergender"")(1); Delete (TextEntry => Name_Entry, FirstIndex => ""0"", LastIndex => ""end""); Insert (TextEntry => Name_Entry, Index => ""end"", Text => To_String (Source => GenerateMemberName (Gender => Gender, FactionIndex => Faction_Index))); return TCL_OK; end if; Delete(TextEntry => Name_Entry, FirstIndex => ""0"", LastIndex => ""end""); Insert (TextEntry => Name_Entry, Index => ""end"", Text => To_String(Source => Generate_Ship_Name(Owner => Faction_Index))); return TCL_OK; end Random_Name_Command; -- ****o* MCommands/MCommands.New_Game_Command -- FUNCTION -- Set all parameters and start a new game -- PARAMETERS -- ClientData - Custom data send to the command. Unused -- Interp - Tcl interpreter in which command was executed. -- Argc - Number of arguments passed to the command. Unused -- Argv - Values of arguments passed to the command. Unused -- RESULT -- This function always return TCL_OK -- COMMANDS -- NewGame -- SOURCE function New_Game_Command (Client_Data: Integer; Interp: Tcl.Tcl_Interp; Argc: Interfaces.C.int; Argv: CArgv.Chars_Ptr_Ptr) return Interfaces.C.int with Convention => C; -- **** function New_Game_Command (Client_Data: Integer; Interp: Tcl.Tcl_Interp; Argc: Interfaces.C.int; Argv: CArgv.Chars_Ptr_Ptr) return Interfaces.C.int is pragma Unreferenced(Client_Data, Argc, Argv); use Tcl.Tk.Ada.Widgets.TtkEntry.TtkSpinBox; use Goals; use Utils; Player_Frame_Name: constant String := "".newgamemenu.canvas.player""; Difficulty_Frame_Name: constant String := "".newgamemenu.canvas.difficulty""; Combo_Box: Ttk_ComboBox := Get_Widget (pathName => Player_Frame_Name & "".faction"", Interp => Interp); Goal_Button: constant Ttk_Button := Get_Widget(pathName => Player_Frame_Name & "".goal"", Interp => Interp); Text_Entry: Ttk_Entry := Get_Widget (pathName => Player_Frame_Name & "".playername"", Interp => Interp); Spin_Box: Ttk_SpinBox := Get_Widget (pathName => Difficulty_Frame_Name & "".enemydamage"", Interp => Interp); begin New_Game_Settings.Player_Gender := Tcl_GetVar(interp => Interp, varName => ""playergender"")(1); if cget(Widgt => Goal_Button, option => ""-text"") = ""Random"" then ClearCurrentGoal; CurrentGoal := Goals_List (Get_Random (Min => Goals_List.First_Index, Max => Goals_List.Last_Index)); end if; New_Game_Settings.Player_Name := To_Unbounded_String(Source => Get(Widgt => Text_Entry)); Text_Entry.Name := New_String(Str => Player_Frame_Name & "".shipname""); New_Game_Settings.Ship_Name := To_Unbounded_String(Source => Get(Widgt => Text_Entry)); Find_Faction_Loop : for I in Factions_List.Iterate loop if Factions_List(I).Name = To_Unbounded_String(Source => Get(Widgt => Combo_Box)) then New_Game_Settings.Player_Faction := Factions_Container.Key(Position => I); Combo_Box.Name := New_String(Str => Player_Frame_Name & "".career""); Find_Career_Loop : for J in Factions_List(I).Careers.Iterate loop if Factions_List(I).Careers(J).Name = To_Unbounded_String(Source => Get(Widgt => Combo_Box)) then New_Game_Settings.Player_Career := Careers_Container.Key(Position => J); exit Find_Faction_Loop; end if; end loop Find_Career_Loop; end if; end loop Find_Faction_Loop; Combo_Box.Name := New_String(Str => Player_Frame_Name & "".base""); Set_Starting_Base_Loop : for I in Bases_Types_List.Iterate loop if Bases_Types_List(I).Name = To_Unbounded_String(Source => Get(Widgt => Combo_Box)) then New_Game_Settings.Starting_Base := BasesTypes_Container.Key(Position => I); exit Set_Starting_Base_Loop; end if; end loop Set_Starting_Base_Loop; Combo_Box.Name := New_String(Str => Difficulty_Frame_Name & "".difficultylevel""); New_Game_Settings.Difficulty_Level := Difficulty_Type'Val(Natural'Value(Current(ComboBox => Combo_Box))); New_Game_Settings.Enemy_Damage_Bonus := Bonus_Type'Value(Get(Widgt => Spin_Box)) / 100.0; Spin_Box.Name := New_String(Str => Difficulty_Frame_Name & "".playerdamage""); New_Game_Settings.Player_Damage_Bonus := Bonus_Type'Value(Get(Widgt => Spin_Box)) / 100.0; --## rule off ASSIGNMENTS Spin_Box.Name := New_String(Str => Difficulty_Frame_Name & "".enemymeleedamage""); New_Game_Settings.Enemy_Melee_Damage_Bonus := Bonus_Type'Value(Get(Widgt => Spin_Box)) / 100.0; Spin_Box.Name := New_String(Str => Difficulty_Frame_Name & "".playermeleedamage""); New_Game_Settings.Player_Melee_Damage_Bonus := Bonus_Type'Value(Get(Widgt => Spin_Box)) / 100.0; Spin_Box.Name := New_String(Str => Difficulty_Frame_Name & "".experience""); New_Game_Settings.Experience_Bonus := Bonus_Type'Value(Get(Widgt => Spin_Box)) / 100.0; Spin_Box.Name := New_String(Str => Difficulty_Frame_Name & "".reputation""); New_Game_Settings.Reputation_Bonus := Bonus_Type'Value(Get(Widgt => Spin_Box)) / 100.0; Spin_Box.Name := New_String(Str => Difficulty_Frame_Name & "".upgrade""); New_Game_Settings.Upgrade_Cost_Bonus := Bonus_Type'Value(Get(Widgt => Spin_Box)) / 100.0; Spin_Box.Name := New_String(Str => Difficulty_Frame_Name & "".prices""); --## rule on ASSIGNMENTS New_Game_Settings.Prices_Bonus := Bonus_Type'Value(Get(Widgt => Spin_Box)) / 100.0; New_Game; Start_Game; return TCL_OK; end New_Game_Command; -- ****o* MCommands/MCommands.Show_Main_Menu_Command -- FUNCTION -- Clear the main game window and show main menu -- PARAMETERS -- ClientData - Custom data send to the command. Unused -- Interp - Tcl interpreter in which command was executed. Unused -- Argc - Number of arguments passed to the command. Unused -- Argv - Values of arguments passed to the command. Unused -- RESULT -- This function always return TCL_OK -- COMMANDS -- ShowMainMenu -- SOURCE function Show_Main_Menu_Command (Client_Data: Integer; Interp: Tcl.Tcl_Interp; Argc: Interfaces.C.int; Argv: CArgv.Chars_Ptr_Ptr) return Interfaces.C.int with Convention => C; -- **** function Show_Main_Menu_Command (Client_Data: Integer; Interp: Tcl.Tcl_Interp; Argc: Interfaces.C.int; Argv: CArgv.Chars_Ptr_Ptr) return Interfaces.C.int is pragma Unreferenced(Client_Data, Interp, Argc, Argv); begin Show_Main_Menu; return TCL_OK; end Show_Main_Menu_Command; -- ****o* MCommands/MCommands.Show_Load_Game_Menu_Command -- FUNCTION -- Show available options for the selected saved game -- PARAMETERS -- ClientData - Custom data send to the command. Unused -- Interp - Tcl interpreter in which command was executed. -- Argc - Number of arguments passed to the command. Unused -- Argv - Values of arguments passed to the command. -- RESULT -- This function always return TCL_OK -- COMMANDS -- ShowLoadGameMenu file -- File is the filename of the saved game to manipulate -- SOURCE function Show_Load_Game_Menu_Command (Client_Data: Integer; Interp: Tcl.Tcl_Interp; Argc: Interfaces.C.int; Argv: CArgv.Chars_Ptr_Ptr) return Interfaces.C.int with Convention => C; -- **** function Show_Load_Game_Menu_Command (Client_Data: Integer; Interp: Tcl.Tcl_Interp; Argc: Interfaces.C.int; Argv: CArgv.Chars_Ptr_Ptr) return Interfaces.C.int is pragma Unreferenced(Client_Data, Argc); use Tcl.Tk.Ada.Widgets.Menu; Load_Menu: Tk_Menu := Get_Widget(pathName => "".loadfilemenu"", Interp => Interp); begin if Winfo_Get(Widgt => Load_Menu, Info => ""exists"") = ""0"" then Load_Menu := Create(pathName => "".loadfilemenu"", options => ""-tearoff false""); end if; Delete(MenuWidget => Load_Menu, StartIndex => ""0"", EndIndex => ""end""); Menu.Add (MenuWidget => Load_Menu, EntryType => ""command"", Options => ""-label {Load the game} -command {LoadGame "" & CArgv.Arg(Argv => Argv, N => 1) & ""}""); Menu.Add (MenuWidget => Load_Menu, EntryType => ""command"", Options => ""-label {Delete the game} -command {DeleteGame "" & CArgv.Arg(Argv => Argv, N => 1) & ""}""); Tk_Popup (MenuWidget => Load_Menu, X => Winfo_Get (Widgt => Get_Main_Window(Interp => Interp), Info => ""pointerx""), Y => Winfo_Get (Widgt => Get_Main_Window(Interp => Interp), Info => ""pointery"")); return TCL_OK; end Show_Load_Game_Menu_Command; -- ****o* MCommands/MCommands.Sort_Saves_Command -- FUNCTION -- Sort the saved games list -- PARAMETERS -- ClientData - Custom data send to the command. Unused -- Interp - Tcl interpreter in which command was executed. -- Argc - Number of arguments passed to the command. Unused -- Argv - Values of arguments passed to the command. Unused -- RESULT -- This function always return TCL_OK -- COMMANDS -- SortSaves x -- X is X axis coordinate where the player clicked the mouse button -- SOURCE function Sort_Saves_Command (Client_Data: Integer; Interp: Tcl.Tcl_Interp; Argc: Interfaces.C.int; Argv: CArgv.Chars_Ptr_Ptr) return Interfaces.C.int with Convention => C; -- **** function Sort_Saves_Command (Client_Data: Integer; Interp: Tcl.Tcl_Interp; Argc: Interfaces.C.int; Argv: CArgv.Chars_Ptr_Ptr) return Interfaces.C.int is Column: constant Positive := Get_Column_Number (Table => Get_Load_Table, X_Position => Natural'Value(CArgv.Arg(Argv => Argv, N => 1))); begin case Column is when 1 => if Get_Save_Sort_Order = PLAYERASC then Save_Sort_Order := PLAYERDESC; else Save_Sort_Order := PLAYERASC; end if; when 2 => if Get_Save_Sort_Order = SHIPASC then Save_Sort_Order := SHIPDESC; else Save_Sort_Order := SHIPASC; end if; when 3 => if Get_Save_Sort_Order = TIMEASC then Save_Sort_Order := TIMEDESC; else Save_Sort_Order := TIMEASC; end if; when others => null; end case; return Show_Load_Game_Command (Client_Data => Client_Data, Interp => Interp, Argc => Argc, Argv => Argv); end Sort_Saves_Command; procedure Add_Commands is use Utils.UI; begin Add_Command(Name => ""OpenLink"", Ada_Command => Open_Link_Command'Access); Add_Command(Name => ""ShowFile"", Ada_Command => Show_File_Command'Access); Add_Command(Name => ""ShowNews"", Ada_Command => Show_News_Command'Access); Add_Command (Name => ""ShowHallOfFame"", Ada_Command => Show_Hall_Of_Fame_Command'Access); Add_Command (Name => ""ShowLoadGame"", Ada_Command => Show_Load_Game_Command'Access); Add_Command (Name => ""DeleteGame"", Ada_Command => Delete_Game_Command'Access); Add_Command(Name => ""LoadGame"", Ada_Command => Load_Game_Command'Access); Add_Command (Name => ""SetFaction"", Ada_Command => Set_Faction_Command'Access); Add_Command (Name => ""SetCareer"", Ada_Command => Set_Career_Command'Access); Add_Command(Name => ""SetBase"", Ada_Command => Set_Base_Command'Access); Add_Command (Name => ""RandomName"", Ada_Command => Random_Name_Command'Access); Add_Command(Name => ""NewGame"", Ada_Command => New_Game_Command'Access); Add_Command (Name => ""ShowMainMenu"", Ada_Command => Show_Main_Menu_Command'Access); Add_Command (Name => ""ShowLoadGameMenu"", Ada_Command => Show_Load_Game_Menu_Command'Access); Add_Command (Name => ""SortSaves"", Ada_Command => Sort_Saves_Command'Access); end Add_Commands; end MainMenu.Commands; ",12146,True,2750.98809627727,median "[[kafka-component]] == Kafka Component *Available as of Camel version 2.13* The *kafka:* component is used for communicating with http://kafka.apache.org/[Apache Kafka] message broker. Maven users will need to add the following dependency to their `pom.xml` for this component. [source,xml] ------------------------------------------------------------ org.apache.camel camel-kafka x.x.x ------------------------------------------------------------ === URI format [source,java] --------------------------- kafka:topic[?options] --------------------------- === Options // component options: START The Kafka component supports 8 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *configuration* (common) | Allows to pre-configure the Kafka component with common options that the endpoints will reuse. | | KafkaConfiguration | *brokers* (common) | URL of the Kafka brokers to use. The format is host1:port1,host2:port2, and the list can be a subset of brokers or a VIP pointing to a subset of brokers. This option is known as bootstrap.servers in the Kafka documentation. | | String | *workerPool* (advanced) | To use a shared custom worker pool for continue routing Exchange after kafka server has acknowledge the message that was sent to it from KafkaProducer using asynchronous non-blocking processing. If using this option then you must handle the lifecycle of the thread pool to shut the pool down when no longer needed. | | ExecutorService | *useGlobalSslContext Parameters* (security) | Enable usage of global SSL context parameters. | false | boolean | *breakOnFirstError* (consumer) | This options controls what happens when a consumer is processing an exchange and it fails. If the option is false then the consumer continues to the next message and processes it. If the option is true then the consumer breaks out, and will seek back to offset of the message that caused a failure, and then re-attempt to process this message. However this can lead to endless processing of the same message if its bound to fail every time, eg a poison message. Therefore its recommended to deal with that for example by using Camel's error handler. | false | boolean | *allowManualCommit* (consumer) | Whether to allow doing manual commits via KafkaManualCommit. If this option is enabled then an instance of KafkaManualCommit is stored on the Exchange message header, which allows end users to access this API and perform manual offset commits via the Kafka consumer. | false | boolean | *kafkaManualCommit Factory* (consumer) | Factory to use for creating KafkaManualCommit instances. This allows to plugin a custom factory to create custom KafkaManualCommit instances in case special logic is needed when doing manual commits that deviates from the default implementation that comes out of the box. | | KafkaManualCommit Factory | *resolveProperty Placeholders* (advanced) | Whether the component should resolve property placeholders on itself when starting. Only properties which are of String type can use property placeholders. | true | boolean |=== // component options: END // endpoint options: START The Kafka endpoint is configured using URI syntax: ---- kafka:topic ---- with the following path and query parameters: ==== Path Parameters (1 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *topic* | *Required* Name of the topic to use. On the consumer you can use comma to separate multiple topics. A producer can only send a message to a single topic. | | String |=== ==== Query Parameters (95 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *brokers* (common) | URL of the Kafka brokers to use. The format is host1:port1,host2:port2, and the list can be a subset of brokers or a VIP pointing to a subset of brokers. This option is known as bootstrap.servers in the Kafka documentation. | | String | *clientId* (common) | The client id is a user-specified string sent in each request to help trace calls. It should logically identify the application making the request. | | String | *headerFilterStrategy* (common) | To use a custom HeaderFilterStrategy to filter header to and from Camel message. | | HeaderFilterStrategy | *reconnectBackoffMaxMs* (common) | The maximum amount of time in milliseconds to wait when reconnecting to a broker that has repeatedly failed to connect. If provided, the backoff per host will increase exponentially for each consecutive connection failure, up to this maximum. After calculating the backoff increase, 20% random jitter is added to avoid connection storms. | 1000 | Integer | *allowManualCommit* (consumer) | Whether to allow doing manual commits via KafkaManualCommit. If this option is enabled then an instance of KafkaManualCommit is stored on the Exchange message header, which allows end users to access this API and perform manual offset commits via the Kafka consumer. | false | boolean | *autoCommitEnable* (consumer) | If true, periodically commit to ZooKeeper the offset of messages already fetched by the consumer. This committed offset will be used when the process fails as the position from which the new consumer will begin. | true | Boolean | *autoCommitIntervalMs* (consumer) | The frequency in ms that the consumer offsets are committed to zookeeper. | 5000 | Integer | *autoCommitOnStop* (consumer) | Whether to perform an explicit auto commit when the consumer stops to ensure the broker has a commit from the last consumed message. This requires the option autoCommitEnable is turned on. The possible values are: sync, async, or none. And sync is the default value. | sync | String | *autoOffsetReset* (consumer) | What to do when there is no initial offset in ZooKeeper or if an offset is out of range: earliest : automatically reset the offset to the earliest offset latest : automatically reset the offset to the latest offset fail: throw exception to the consumer | latest | String | *breakOnFirstError* (consumer) | This options controls what happens when a consumer is processing an exchange and it fails. If the option is false then the consumer continues to the next message and processes it. If the option is true then the consumer breaks out, and will seek back to offset of the message that caused a failure, and then re-attempt to process this message. However this can lead to endless processing of the same message if its bound to fail every time, eg a poison message. Therefore its recommended to deal with that for example by using Camel's error handler. | false | boolean | *bridgeErrorHandler* (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | *checkCrcs* (consumer) | Automatically check the CRC32 of the records consumed. This ensures no on-the-wire or on-disk corruption to the messages occurred. This check adds some overhead, so it may be disabled in cases seeking extreme performance. | true | Boolean | *consumerRequestTimeoutMs* (consumer) | The configuration controls the maximum amount of time the client will wait for the response of a request. If the response is not received before the timeout elapses the client will resend the request if necessary or fail the request if retries are exhausted. | 40000 | Integer | *consumersCount* (consumer) | The number of consumers that connect to kafka server | 1 | int | *consumerStreams* (consumer) | Number of concurrent consumers on the consumer | 10 | int | *fetchMaxBytes* (consumer) | The maximum amount of data the server should return for a fetch request This is not an absolute maximum, if the first message in the first non-empty partition of the fetch is larger than this value, the message will still be returned to ensure that the consumer can make progress. The maximum message size accepted by the broker is defined via message.max.bytes (broker config) or max.message.bytes (topic config). Note that the consumer performs multiple fetches in parallel. | 52428800 | Integer | *fetchMinBytes* (consumer) | The minimum amount of data the server should return for a fetch request. If insufficient data is available the request will wait for that much data to accumulate before answering the request. | 1 | Integer | *fetchWaitMaxMs* (consumer) | The maximum amount of time the server will block before answering the fetch request if there isn't sufficient data to immediately satisfy fetch.min.bytes | 500 | Integer | *groupId* (consumer) | A string that uniquely identifies the group of consumer processes to which this consumer belongs. By setting the same group id multiple processes indicate that they are all part of the same consumer group. This option is required for consumers. | | String | *heartbeatIntervalMs* (consumer) | The expected time between heartbeats to the consumer coordinator when using Kafka's group management facilities. Heartbeats are used to ensure that the consumer's session stays active and to facilitate rebalancing when new consumers join or leave the group. The value must be set lower than session.timeout.ms, but typically should be set no higher than 1/3 of that value. It can be adjusted even lower to control the expected time for normal rebalances. | 3000 | Integer | *kafkaHeaderDeserializer* (consumer) | Sets custom KafkaHeaderDeserializer for deserialization kafka headers values to camel headers values. | | KafkaHeaderDeserializer | *keyDeserializer* (consumer) | Deserializer class for key that implements the Deserializer interface. | org.apache.kafka.common.serialization.StringDeserializer | String | *maxPartitionFetchBytes* (consumer) | The maximum amount of data per-partition the server will return. The maximum total memory used for a request will be #partitions max.partition.fetch.bytes. This size must be at least as large as the maximum message size the server allows or else it is possible for the producer to send messages larger than the consumer can fetch. If that happens, the consumer can get stuck trying to fetch a large message on a certain partition. | 1048576 | Integer | *maxPollIntervalMs* (consumer) | The maximum delay between invocations of poll() when using consumer group management. This places an upper bound on the amount of time that the consumer can be idle before fetching more records. If poll() is not called before expiration of this timeout, then the consumer is considered failed and the group will rebalance in order to reassign the partitions to another member. | | Long | *maxPollRecords* (consumer) | The maximum number of records returned in a single call to poll() | 500 | Integer | *offsetRepository* (consumer) | The offset repository to use in order to locally store the offset of each partition of the topic. Defining one will disable the autocommit. | | StateRepository | *partitionAssignor* (consumer) | The class name of the partition assignment strategy that the client will use to distribute partition ownership amongst consumer instances when group management is used | org.apache.kafka.clients.consumer.RangeAssignor | String | *pollTimeoutMs* (consumer) | The timeout used when polling the KafkaConsumer. | 5000 | Long | *seekTo* (consumer) | Set if KafkaConsumer will read from beginning or end on startup: beginning : read from beginning end : read from end This is replacing the earlier property seekToBeginning | | String | *sessionTimeoutMs* (consumer) | The timeout used to detect failures when using Kafka's group management facilities. | 10000 | Integer | *specificAvroReader* (consumer) | This enables the use of a specific Avro reader for use with the Confluent Platform schema registry and the io.confluent.kafka.serializers.KafkaAvroDeserializer. This option is only available in the Confluent Platform (not standard Apache Kafka) | false | boolean | *topicIsPattern* (consumer) | Whether the topic is a pattern (regular expression). This can be used to subscribe to dynamic number of topics matching the pattern. | false | boolean | *valueDeserializer* (consumer) | Deserializer class for value that implements the Deserializer interface. | org.apache.kafka.common.serialization.StringDeserializer | String | *exceptionHandler* (consumer) | To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored. | | ExceptionHandler | *exchangePattern* (consumer) | Sets the exchange pattern when the consumer creates an exchange. | | ExchangePattern | *bridgeEndpoint* (producer) | If the option is true, then KafkaProducer will ignore the KafkaConstants.TOPIC header setting of the inbound message. | false | boolean | *bufferMemorySize* (producer) | The total bytes of memory the producer can use to buffer records waiting to be sent to the server. If records are sent faster than they can be delivered to the server the producer will either block or throw an exception based on the preference specified by block.on.buffer.full.This setting should correspond roughly to the total memory the producer will use, but is not a hard bound since not all memory the producer uses is used for buffering. Some additional memory will be used for compression (if compression is enabled) as well as for maintaining in-flight requests. | 33554432 | Integer | *circularTopicDetection* (producer) | If the option is true, then KafkaProducer will detect if the message is attempted to be sent back to the same topic it may come from, if the message was original from a kafka consumer. If the KafkaConstants.TOPIC header is the same as the original kafka consumer topic, then the header setting is ignored, and the topic of the producer endpoint is used. In other words this avoids sending the same message back to where it came from. This option is not in use if the option bridgeEndpoint is set to true. | true | boolean | *compressionCodec* (producer) | This parameter allows you to specify the compression codec for all data generated by this producer. Valid values are none, gzip and snappy. | none | String | *connectionMaxIdleMs* (producer) | Close idle connections after the number of milliseconds specified by this config. | 540000 | Integer | *enableIdempotence* (producer) | If set to 'true' the producer will ensure that exactly one copy of each message is written in the stream. If 'false', producer retries may write duplicates of the retried message in the stream. If set to true this option will require max.in.flight.requests.per.connection to be set to 1 and retries cannot be zero and additionally acks must be set to 'all'. | false | boolean | *kafkaHeaderSerializer* (producer) | Sets custom KafkaHeaderDeserializer for serialization camel headers values to kafka headers values. | | KafkaHeaderSerializer | *key* (producer) | The record key (or null if no key is specified). If this option has been configured then it take precedence over header KafkaConstants#KEY | | String | *keySerializerClass* (producer) | The serializer class for keys (defaults to the same as for messages if nothing is given). | org.apache.kafka.common.serialization.StringSerializer | String | *lingerMs* (producer) | The producer groups together any records that arrive in between request transmissions into a single batched request. Normally this occurs only under load when records arrive faster than they can be sent out. However in some circumstances the client may want to reduce the number of requests even under moderate load. This setting accomplishes this by adding a small amount of artificial delaythat is, rather than immediately sending out a record the producer will wait for up to the given delay to allow other records to be sent so that the sends can be batched together. This can be thought of as analogous to Nagle's algorithm in TCP. This setting gives the upper bound on the delay for batching: once we get batch.size worth of records for a partition it will be sent immediately regardless of this setting, however if we have fewer than this many bytes accumulated for this partition we will 'linger' for the specified time waiting for more records to show up. This setting defaults to 0 (i.e. no delay). Setting linger.ms=5, for example, would have the effect of reducing the number of requests sent but would add up to 5ms of latency to records sent in the absense of load. | 0 | Integer | *maxBlockMs* (producer) | The configuration controls how long sending to kafka will block. These methods can be blocked for multiple reasons. For e.g: buffer full, metadata unavailable.This configuration imposes maximum limit on the total time spent in fetching metadata, serialization of key and value, partitioning and allocation of buffer memory when doing a send(). In case of partitionsFor(), this configuration imposes a maximum time threshold on waiting for metadata | 60000 | Integer | *maxInFlightRequest* (producer) | The maximum number of unacknowledged requests the client will send on a single connection before blocking. Note that if this setting is set to be greater than 1 and there are failed sends, there is a risk of message re-ordering due to retries (i.e., if retries are enabled). | 5 | Integer | *maxRequestSize* (producer) | The maximum size of a request. This is also effectively a cap on the maximum record size. Note that the server has its own cap on record size which may be different from this. This setting will limit the number of record batches the producer will send in a single request to avoid sending huge requests. | 1048576 | Integer | *metadataMaxAgeMs* (producer) | The period of time in milliseconds after which we force a refresh of metadata even if we haven't seen any partition leadership changes to proactively discover any new brokers or partitions. | 300000 | Integer | *metricReporters* (producer) | A list of classes to use as metrics reporters. Implementing the MetricReporter interface allows plugging in classes that will be notified of new metric creation. The JmxReporter is always included to register JMX statistics. | | String | *metricsSampleWindowMs* (producer) | The number of samples maintained to compute metrics. | 30000 | Integer | *noOfMetricsSample* (producer) | The number of samples maintained to compute metrics. | 2 | Integer | *partitioner* (producer) | The partitioner class for partitioning messages amongst sub-topics. The default partitioner is based on the hash of the key. | org.apache.kafka.clients.producer.internals.DefaultPartitioner | String | *partitionKey* (producer) | The partition to which the record will be sent (or null if no partition was specified). If this option has been configured then it take precedence over header KafkaConstants#PARTITION_KEY | | Integer | *producerBatchSize* (producer) | The producer will attempt to batch records together into fewer requests whenever multiple records are being sent to the same partition. This helps performance on both the client and the server. This configuration controls the default batch size in bytes. No attempt will be made to batch records larger than this size.Requests sent to brokers will contain multiple batches, one for each partition with data available to be sent.A small batch size will make batching less common and may reduce throughput (a batch size of zero will disable batching entirely). A very large batch size may use memory a bit more wastefully as we will always allocate a buffer of the specified batch size in anticipation of additional records. | 16384 | Integer | *queueBufferingMaxMessages* (producer) | The maximum number of unsent messages that can be queued up the producer when using async mode before either the producer must be blocked or data must be dropped. | 10000 | Integer | *receiveBufferBytes* (producer) | The size of the TCP receive buffer (SO_RCVBUF) to use when reading data. | 65536 | Integer | *reconnectBackoffMs* (producer) | The amount of time to wait before attempting to reconnect to a given host. This avoids repeatedly connecting to a host in a tight loop. This backoff applies to all requests sent by the consumer to the broker. | 50 | Integer | *recordMetadata* (producer) | Whether the producer should store the RecordMetadata results from sending to Kafka. The results are stored in a List containing the RecordMetadata metadata's. The list is stored on a header with the key KafkaConstants#KAFKA_RECORDMETA | true | boolean | *requestRequiredAcks* (producer) | The number of acknowledgments the producer requires the leader to have received before considering a request complete. This controls the durability of records that are sent. The following settings are common: acks=0 If set to zero then the producer will not wait for any acknowledgment from the server at all. The record will be immediately added to the socket buffer and considered sent. No guarantee can be made that the server has received the record in this case, and the retries configuration will not take effect (as the client won't generally know of any failures). The offset given back for each record will always be set to -1. acks=1 This will mean the leader will write the record to its local log but will respond without awaiting full acknowledgement from all followers. In this case should the leader fail immediately after acknowledging the record but before the followers have replicated it then the record will be lost. acks=all This means the leader will wait for the full set of in-sync replicas to acknowledge the record. This guarantees that the record will not be lost as long as at least one in-sync replica remains alive. This is the strongest available guarantee. | 1 | String | *requestTimeoutMs* (producer) | The amount of time the broker will wait trying to meet the request.required.acks requirement before sending back an error to the client. | 305000 | Integer | *retries* (producer) | Setting a value greater than zero will cause the client to resend any record whose send fails with a potentially transient error. Note that this retry is no different than if the client resent the record upon receiving the error. Allowing retries will potentially change the ordering of records because if two records are sent to a single partition, and the first fails and is retried but the second succeeds, then the second record may appear first. | 0 | Integer | *retryBackoffMs* (producer) | Before each retry, the producer refreshes the metadata of relevant topics to see if a new leader has been elected. Since leader election takes a bit of time, this property specifies the amount of time that the producer waits before refreshing the metadata. | 100 | Integer | *sendBufferBytes* (producer) | Socket write buffer size | 131072 | Integer | *serializerClass* (producer) | The serializer class for messages. | org.apache.kafka.common.serialization.StringSerializer | String | *workerPool* (producer) | To use a custom worker pool for continue routing Exchange after kafka server has acknowledge the message that was sent to it from KafkaProducer using asynchronous non-blocking processing. | | ExecutorService | *workerPoolCoreSize* (producer) | Number of core threads for the worker pool for continue routing Exchange after kafka server has acknowledge the message that was sent to it from KafkaProducer using asynchronous non-blocking processing. | 10 | Integer | *workerPoolMaxSize* (producer) | Maximum number of threads for the worker pool for continue routing Exchange after kafka server has acknowledge the message that was sent to it from KafkaProducer using asynchronous non-blocking processing. | 20 | Integer | *synchronous* (advanced) | Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported). | false | boolean | *interceptorClasses* (monitoring) | Sets interceptors for producer or consumers. Producer interceptors have to be classes implementing org.apache.kafka.clients.producer.ProducerInterceptor Consumer interceptors have to be classes implementing org.apache.kafka.clients.consumer.ConsumerInterceptor Note that if you use Producer interceptor on a consumer it will throw a class cast exception in runtime | | String | *kerberosBeforeReloginMin Time* (security) | Login thread sleep time between refresh attempts. | 60000 | Integer | *kerberosInitCmd* (security) | Kerberos kinit command path. Default is /usr/bin/kinit | /usr/bin/kinit | String | *kerberosPrincipalToLocal Rules* (security) | A list of rules for mapping from principal names to short names (typically operating system usernames). The rules are evaluated in order and the first rule that matches a principal name is used to map it to a short name. Any later rules in the list are ignored. By default, principal names of the form {username}/{hostname}{REALM} are mapped to {username}. For more details on the format please see the security authorization and acls documentation.. Multiple values can be separated by comma | DEFAULT | String | *kerberosRenewJitter* (security) | Percentage of random jitter added to the renewal time. | 0.05 | Double | *kerberosRenewWindowFactor* (security) | Login thread will sleep until the specified window factor of time from last refresh to ticket's expiry has been reached, at which time it will try to renew the ticket. | 0.8 | Double | *saslJaasConfig* (security) | Expose the kafka sasl.jaas.config parameter Example: org.apache.kafka.common.security.plain.PlainLoginModule required username=USERNAME password=PASSWORD; | | String | *saslKerberosServiceName* (security) | The Kerberos principal name that Kafka runs as. This can be defined either in Kafka's JAAS config or in Kafka's config. | | String | *saslMechanism* (security) | The Simple Authentication and Security Layer (SASL) Mechanism used. For the valid values see a href= http://www.iana.org/assignments/sasl-mechanisms/sasl-mechanisms.xhtmlhttp://www.iana.org/assignments/sasl-mechanisms/sasl-mechanisms.xhtml | GSSAPI | String | *securityProtocol* (security) | Protocol used to communicate with brokers. SASL_PLAINTEXT, PLAINTEXT and SSL are supported | PLAINTEXT | String | *sslCipherSuites* (security) | A list of cipher suites. This is a named combination of authentication, encryption, MAC and key exchange algorithm used to negotiate the security settings for a network connection using TLS or SSL network protocol.By default all the available cipher suites are supported. | | String | *sslContextParameters* (security) | SSL configuration using a Camel SSLContextParameters object. If configured it's applied before the other SSL endpoint parameters. | | SSLContextParameters | *sslEnabledProtocols* (security) | The list of protocols enabled for SSL connections. TLSv1.2, TLSv1.1 and TLSv1 are enabled by default. | TLSv1.2,TLSv1.1,TLSv1 | String | *sslEndpointAlgorithm* (security) | The endpoint identification algorithm to validate server hostname using server certificate. | | String | *sslKeymanagerAlgorithm* (security) | The algorithm used by key manager factory for SSL connections. Default value is the key manager factory algorithm configured for the Java Virtual Machine. | SunX509 | String | *sslKeyPassword* (security) | The password of the private key in the key store file. This is optional for client. | | String | *sslKeystoreLocation* (security) | The location of the key store file. This is optional for client and can be used for two-way authentication for client. | | String | *sslKeystorePassword* (security) | The store password for the key store file.This is optional for client and only needed if ssl.keystore.location is configured. | | String | *sslKeystoreType* (security) | The file format of the key store file. This is optional for client. Default value is JKS | JKS | String | *sslProtocol* (security) | The SSL protocol used to generate the SSLContext. Default setting is TLS, which is fine for most cases. Allowed values in recent JVMs are TLS, TLSv1.1 and TLSv1.2. SSL, SSLv2 and SSLv3 may be supported in older JVMs, but their usage is discouraged due to known security vulnerabilities. | TLS | String | *sslProvider* (security) | The name of the security provider used for SSL connections. Default value is the default security provider of the JVM. | | String | *sslTrustmanagerAlgorithm* (security) | The algorithm used by trust manager factory for SSL connections. Default value is the trust manager factory algorithm configured for the Java Virtual Machine. | PKIX | String | *sslTruststoreLocation* (security) | The location of the trust store file. | | String | *sslTruststoreType* (security) | The file format of the trust store file. Default value is JKS. | JKS | String | *schemaRegistryURL* (confluent) | URL of the Confluent Platform schema registry servers to use. The format is host1:port1,host2:port2. This is known as schema.registry.url in the Confluent Platform documentation. This option is only available in the Confluent Platform (not standard Apache Kafka) | | String | *sslTruststorePassword* (security) | The password for the trust store file. | | String |=== // endpoint options: END // spring-boot-auto-configure options: START === Spring Boot Auto-Configuration When using Spring Boot make sure to use the following Maven dependency to have support for auto configuration: [source,xml] ---- org.apache.camel camel-kafka-starter x.x.x ---- The component supports 100 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *camel.component.kafka.allow-manual-commit* | Whether to allow doing manual commits via KafkaManualCommit. If this option is enabled then an instance of KafkaManualCommit is stored on the Exchange message header, which allows end users to access this API and perform manual offset commits via the Kafka consumer. | false | Boolean | *camel.component.kafka.break-on-first-error* | This options controls what happens when a consumer is processing an exchange and it fails. If the option is false then the consumer continues to the next message and processes it. If the option is true then the consumer breaks out, and will seek back to offset of the message that caused a failure, and then re-attempt to process this message. However this can lead to endless processing of the same message if its bound to fail every time, eg a poison message. Therefore its recommended to deal with that for example by using Camel's error handler. | false | Boolean | *camel.component.kafka.brokers* | URL of the Kafka brokers to use. The format is host1:port1,host2:port2, and the list can be a subset of brokers or a VIP pointing to a subset of brokers. This option is known as bootstrap.servers in the Kafka documentation. | | String | *camel.component.kafka.configuration.allow-manual-commit* | Whether to allow doing manual commits via {@link KafkaManualCommit}.

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

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

    Multiple values can be separated by comma | DEFAULT | String | *camel.component.kafka.configuration.kerberos-renew-jitter* | Percentage of random jitter added to the renewal time. | 0.05 | Double | *camel.component.kafka.configuration.kerberos-renew-window-factor* | Login thread will sleep until the specified window factor of time from last refresh to ticket's expiry has been reached, at which time it will try to renew the ticket. | 0.8 | Double | *camel.component.kafka.configuration.key* | The record key (or null if no key is specified). If this option has been configured then it take precedence over header {@link KafkaConstants#KEY} | | String | *camel.component.kafka.configuration.key-deserializer* | Deserializer class for key that implements the Deserializer interface. | org.apache.kafka.common.serialization.StringDeserializer | String | *camel.component.kafka.configuration.key-serializer-class* | The serializer class for keys (defaults to the same as for messages if nothing is given). | org.apache.kafka.common.serialization.StringSerializer | String | *camel.component.kafka.configuration.linger-ms* | The producer groups together any records that arrive in between request transmissions into a single batched request. Normally this occurs only under load when records arrive faster than they can be sent out. However in some circumstances the client may want to reduce the number of requests even under moderate load. This setting accomplishes this by adding a small amount of artificial delay—that is, rather than immediately sending out a record the producer will wait for up to the given delay to allow other records to be sent so that the sends can be batched together. This can be thought of as analogous to Nagle's algorithm in TCP. This setting gives the upper bound on the delay for batching: once we get batch.size worth of records for a partition it will be sent immediately regardless of this setting, however if we have fewer than this many bytes accumulated for this partition we will 'linger' for the specified time waiting for more records to show up. This setting defaults to 0 (i.e. no delay). Setting linger.ms=5, for example, would have the effect of reducing the number of requests sent but would add up to 5ms of latency to records sent in the absense of load. | 0 | Integer | *camel.component.kafka.configuration.max-block-ms* | The configuration controls how long sending to kafka will block. These methods can be blocked for multiple reasons. For e.g: buffer full, metadata unavailable.This configuration imposes maximum limit on the total time spent in fetching metadata, serialization of key and value, partitioning and allocation of buffer memory when doing a send(). In case of partitionsFor(), this configuration imposes a maximum time threshold on waiting for metadata | 60000 | Integer | *camel.component.kafka.configuration.max-in-flight-request* | The maximum number of unacknowledged requests the client will send on a single connection before blocking. Note that if this setting is set to be greater than 1 and there are failed sends, there is a risk of message re-ordering due to retries (i.e., if retries are enabled). | 5 | Integer | *camel.component.kafka.configuration.max-partition-fetch-bytes* | The maximum amount of data per-partition the server will return. The maximum total memory used for a request will be #partitions * max.partition.fetch.bytes. This size must be at least as large as the maximum message size the server allows or else it is possible for the producer to send messages larger than the consumer can fetch. If that happens, the consumer can get stuck trying to fetch a large message on a certain partition. | 1048576 | Integer | *camel.component.kafka.configuration.max-poll-interval-ms* | The maximum delay between invocations of poll() when using consumer group management. This places an upper bound on the amount of time that the consumer can be idle before fetching more records. If poll() is not called before expiration of this timeout, then the consumer is considered failed and the group will rebalance in order to reassign the partitions to another member. | | Long | *camel.component.kafka.configuration.max-poll-records* | The maximum number of records returned in a single call to poll() | 500 | Integer | *camel.component.kafka.configuration.max-request-size* | The maximum size of a request. This is also effectively a cap on the maximum record size. Note that the server has its own cap on record size which may be different from this. This setting will limit the number of record batches the producer will send in a single request to avoid sending huge requests. | 1048576 | Integer | *camel.component.kafka.configuration.metadata-max-age-ms* | The period of time in milliseconds after which we force a refresh of metadata even if we haven't seen any partition leadership changes to proactively discover any new brokers or partitions. | 300000 | Integer | *camel.component.kafka.configuration.metric-reporters* | A list of classes to use as metrics reporters. Implementing the MetricReporter interface allows plugging in classes that will be notified of new metric creation. The JmxReporter is always included to register JMX statistics. | | String | *camel.component.kafka.configuration.metrics-sample-window-ms* | The number of samples maintained to compute metrics. | 30000 | Integer | *camel.component.kafka.configuration.no-of-metrics-sample* | The number of samples maintained to compute metrics. | 2 | Integer | *camel.component.kafka.configuration.offset-repository* | The offset repository to use in order to locally store the offset of each partition of the topic. Defining one will disable the autocommit. | | StateRepository | *camel.component.kafka.configuration.partition-assignor* | The class name of the partition assignment strategy that the client will use to distribute partition ownership amongst consumer instances when group management is used | org.apache.kafka.clients.consumer.RangeAssignor | String | *camel.component.kafka.configuration.partition-key* | The partition to which the record will be sent (or null if no partition was specified). If this option has been configured then it take precedence over header {@link KafkaConstants#PARTITION_KEY} | | Integer | *camel.component.kafka.configuration.partitioner* | The partitioner class for partitioning messages amongst sub-topics. The default partitioner is based on the hash of the key. | org.apache.kafka.clients.producer.internals.DefaultPartitioner | String | *camel.component.kafka.configuration.poll-timeout-ms* | The timeout used when polling the KafkaConsumer. | 5000 | Long | *camel.component.kafka.configuration.producer-batch-size* | The producer will attempt to batch records together into fewer requests whenever multiple records are being sent to the same partition. This helps performance on both the client and the server. This configuration controls the default batch size in bytes. No attempt will be made to batch records larger than this size.Requests sent to brokers will contain multiple batches, one for each partition with data available to be sent.A small batch size will make batching less common and may reduce throughput (a batch size of zero will disable batching entirely). A very large batch size may use memory a bit more wastefully as we will always allocate a buffer of the specified batch size in anticipation of additional records. | 16384 | Integer | *camel.component.kafka.configuration.queue-buffering-max-messages* | The maximum number of unsent messages that can be queued up the producer when using async mode before either the producer must be blocked or data must be dropped. | 10000 | Integer | *camel.component.kafka.configuration.receive-buffer-bytes* | The size of the TCP receive buffer (SO_RCVBUF) to use when reading data. | 65536 | Integer | *camel.component.kafka.configuration.reconnect-backoff-max-ms* | The maximum amount of time in milliseconds to wait when reconnecting to a broker that has repeatedly failed to connect. If provided, the backoff per host will increase exponentially for each consecutive connection failure, up to this maximum. After calculating the backoff increase, 20% random jitter is added to avoid connection storms. | 1000 | Integer | *camel.component.kafka.configuration.reconnect-backoff-ms* | The amount of time to wait before attempting to reconnect to a given host. This avoids repeatedly connecting to a host in a tight loop. This backoff applies to all requests sent by the consumer to the broker. | 50 | Integer | *camel.component.kafka.configuration.record-metadata* | Whether the producer should store the {@link RecordMetadata} results from sending to Kafka. The results are stored in a {@link List} containing the {@link RecordMetadata} metadata's. The list is stored on a header with the key {@link KafkaConstants#KAFKA_RECORDMETA} | true | Boolean | *camel.component.kafka.configuration.request-required-acks* | The number of acknowledgments the producer requires the leader to have received before considering a request complete. This controls the durability of records that are sent. The following settings are common: acks=0 If set to zero then the producer will not wait for any acknowledgment from the server at all. The record will be immediately added to the socket buffer and considered sent. No guarantee can be made that the server has received the record in this case, and the retries configuration will not take effect (as the client won't generally know of any failures). The offset given back for each record will always be set to -1. acks=1 This will mean the leader will write the record to its local log but will respond without awaiting full acknowledgement from all followers. In this case should the leader fail immediately after acknowledging the record but before the followers have replicated it then the record will be lost. acks=all This means the leader will wait for the full set of in-sync replicas to acknowledge the record. This guarantees that the record will not be lost as long as at least one in-sync replica remains alive. This is the strongest available guarantee. | 1 | String | *camel.component.kafka.configuration.request-timeout-ms* | The amount of time the broker will wait trying to meet the request.required.acks requirement before sending back an error to the client. | 305000 | Integer | *camel.component.kafka.configuration.retries* | Setting a value greater than zero will cause the client to resend any record whose send fails with a potentially transient error. Note that this retry is no different than if the client resent the record upon receiving the error. Allowing retries will potentially change the ordering of records because if two records are sent to a single partition, and the first fails and is retried but the second succeeds, then the second record may appear first. | 0 | Integer | *camel.component.kafka.configuration.retry-backoff-ms* | Before each retry, the producer refreshes the metadata of relevant topics to see if a new leader has been elected. Since leader election takes a bit of time, this property specifies the amount of time that the producer waits before refreshing the metadata. | 100 | Integer | *camel.component.kafka.configuration.sasl-jaas-config* | Expose the kafka sasl.jaas.config parameter Example: org.apache.kafka.common.security.plain.PlainLoginModule required username=""USERNAME"" password=""PASSWORD""; | | String | *camel.component.kafka.configuration.sasl-kerberos-service-name* | The Kerberos principal name that Kafka runs as. This can be defined either in Kafka's JAAS config or in Kafka's config. | | String | *camel.component.kafka.configuration.sasl-mechanism* | The Simple Authentication and Security Layer (SASL) Mechanism used. For the valid values see http://www.iana.org/assignments/sasl-mechanisms/sasl-mechanisms.xhtml | GSSAPI | String | *camel.component.kafka.configuration.schema-registry-u-r-l* | URL of the Confluent Platform schema registry servers to use. The format is host1:port1,host2:port2. This is known as schema.registry.url in the Confluent Platform documentation. This option is only available in the Confluent Platform (not standard Apache Kafka) | | String | *camel.component.kafka.configuration.security-protocol* | Protocol used to communicate with brokers. SASL_PLAINTEXT, PLAINTEXT and SSL are supported | PLAINTEXT | String | *camel.component.kafka.configuration.seek-to* | Set if KafkaConsumer will read from beginning or end on startup: beginning : read from beginning end : read from end This is replacing the earlier property seekToBeginning | | String | *camel.component.kafka.configuration.send-buffer-bytes* | Socket write buffer size | 131072 | Integer | *camel.component.kafka.configuration.serializer-class* | The serializer class for messages. | org.apache.kafka.common.serialization.StringSerializer | String | *camel.component.kafka.configuration.session-timeout-ms* | The timeout used to detect failures when using Kafka's group management facilities. | 10000 | Integer | *camel.component.kafka.configuration.specific-avro-reader* | This enables the use of a specific Avro reader for use with the Confluent Platform schema registry and the io.confluent.kafka.serializers.KafkaAvroDeserializer. This option is only available in the Confluent Platform (not standard Apache Kafka) | false | Boolean | *camel.component.kafka.configuration.ssl-cipher-suites* | A list of cipher suites. This is a named combination of authentication, encryption, MAC and key exchange algorithm used to negotiate the security settings for a network connection using TLS or SSL network protocol.By default all the available cipher suites are supported. | | String | *camel.component.kafka.configuration.ssl-context-parameters* | SSL configuration using a Camel {@link SSLContextParameters} object. If configured it's applied before the other SSL endpoint parameters. | | SSLContextParameters | *camel.component.kafka.configuration.ssl-enabled-protocols* | The list of protocols enabled for SSL connections. TLSv1.2, TLSv1.1 and TLSv1 are enabled by default. | TLSv1.2,TLSv1.1,TLSv1 | String | *camel.component.kafka.configuration.ssl-endpoint-algorithm* | The endpoint identification algorithm to validate server hostname using server certificate. | | String | *camel.component.kafka.configuration.ssl-key-password* | The password of the private key in the key store file. This is optional for client. | | String | *camel.component.kafka.configuration.ssl-keymanager-algorithm* | The algorithm used by key manager factory for SSL connections. Default value is the key manager factory algorithm configured for the Java Virtual Machine. | SunX509 | String | *camel.component.kafka.configuration.ssl-keystore-location* | The location of the key store file. This is optional for client and can be used for two-way authentication for client. | | String | *camel.component.kafka.configuration.ssl-keystore-password* | The store password for the key store file.This is optional for client and only needed if ssl.keystore.location is configured. | | String | *camel.component.kafka.configuration.ssl-keystore-type* | The file format of the key store file. This is optional for client. Default value is JKS | JKS | String | *camel.component.kafka.configuration.ssl-protocol* | The SSL protocol used to generate the SSLContext. Default setting is TLS, which is fine for most cases. Allowed values in recent JVMs are TLS, TLSv1.1 and TLSv1.2. SSL, SSLv2 and SSLv3 may be supported in older JVMs, but their usage is discouraged due to known security vulnerabilities. | TLS | String | *camel.component.kafka.configuration.ssl-provider* | The name of the security provider used for SSL connections. Default value is the default security provider of the JVM. | | String | *camel.component.kafka.configuration.ssl-trustmanager-algorithm* | The algorithm used by trust manager factory for SSL connections. Default value is the trust manager factory algorithm configured for the Java Virtual Machine. | PKIX | String | *camel.component.kafka.configuration.ssl-truststore-location* | The location of the trust store file. | | String | *camel.component.kafka.configuration.ssl-truststore-password* | The password for the trust store file. | | String | *camel.component.kafka.configuration.ssl-truststore-type* | The file format of the trust store file. Default value is JKS. | JKS | String | *camel.component.kafka.configuration.topic* | Name of the topic to use. On the consumer you can use comma to separate multiple topics. A producer can only send a message to a single topic. | | String | *camel.component.kafka.configuration.topic-is-pattern* | Whether the topic is a pattern (regular expression). This can be used to subscribe to dynamic number of topics matching the pattern. | false | Boolean | *camel.component.kafka.configuration.value-deserializer* | Deserializer class for value that implements the Deserializer interface. | org.apache.kafka.common.serialization.StringDeserializer | String | *camel.component.kafka.configuration.worker-pool* | To use a custom worker pool for continue routing {@link Exchange} after kafka server has acknowledge the message that was sent to it from {@link KafkaProducer} using asynchronous non-blocking processing. | | ExecutorService | *camel.component.kafka.configuration.worker-pool-core-size* | Number of core threads for the worker pool for continue routing {@link Exchange} after kafka server has acknowledge the message that was sent to it from {@link KafkaProducer} using asynchronous non-blocking processing. | 10 | Integer | *camel.component.kafka.configuration.worker-pool-max-size* | Maximum number of threads for the worker pool for continue routing {@link Exchange} after kafka server has acknowledge the message that was sent to it from {@link KafkaProducer} using asynchronous non-blocking processing. | 20 | Integer | *camel.component.kafka.enabled* | Enable kafka component | true | Boolean | *camel.component.kafka.kafka-manual-commit-factory* | Factory to use for creating KafkaManualCommit instances. This allows to plugin a custom factory to create custom KafkaManualCommit instances in case special logic is needed when doing manual commits that deviates from the default implementation that comes out of the box. The option is a org.apache.camel.component.kafka.KafkaManualCommitFactory type. | | String | *camel.component.kafka.resolve-property-placeholders* | Whether the component should resolve property placeholders on itself when starting. Only properties which are of String type can use property placeholders. | true | Boolean | *camel.component.kafka.use-global-ssl-context-parameters* | Enable usage of global SSL context parameters. | false | Boolean | *camel.component.kafka.worker-pool* | To use a shared custom worker pool for continue routing Exchange after kafka server has acknowledge the message that was sent to it from KafkaProducer using asynchronous non-blocking processing. If using this option then you must handle the lifecycle of the thread pool to shut the pool down when no longer needed. The option is a java.util.concurrent.ExecutorService type. | | String |=== // spring-boot-auto-configure options: END For more information about Producer/Consumer configuration: http://kafka.apache.org/documentation.html#newconsumerconfigs[http://kafka.apache.org/documentation.html#newconsumerconfigs] http://kafka.apache.org/documentation.html#producerconfigs[http://kafka.apache.org/documentation.html#producerconfigs] === Message headers ==== Consumer headers The following headers are available when consuming messages from Kafka. [width=""100%"",cols=""2m,2m,1m,5"",options=""header""] |=== | Header constant | Header value | Type | Description | KafkaConstants.TOPIC | ""kafka.TOPIC"" | String | The topic from where the message originated | KafkaConstants.PARTITION | ""kafka.PARTITION"" | Integer | The partition where the message was stored | KafkaConstants.OFFSET | ""kafka.OFFSET"" | Long | The offset of the message | KafkaConstants.KEY | ""kafka.KEY"" | Object | The key of the message if configured | KafkaConstants.HEADERS | ""kafka.HEADERS"" | org.apache.kafka.common.header.Headers | The record headers | KafkaConstants.LAST_RECORD_BEFORE_COMMIT | ""kafka.LAST_RECORD_BEFORE_COMMIT"" | Boolean | Whether or not it's the last record before commit (only available if `autoCommitEnable` endpoint parameter is `false`) | KafkaConstants.MANUAL_COMMIT | ""CamelKafkaManualCommit"" | KafkaManualCommit | Can be used for forcing manual offset commit when using Kafka consumer. | |=== ==== Producer headers Before sending a message to Kafka you can configure the following headers. [width=""100%"",cols=""2m,2m,1m,5"",options=""header""] |=== | Header constant | Header value | Type | Description | KafkaConstants.KEY | ""kafka.KEY"" | Object | *Required* The key of the message in order to ensure that all related message goes in the same partition | KafkaConstants.TOPIC | ""kafka.TOPIC"" | String | The topic to which send the message (only read if the `bridgeEndpoint` endpoint parameter is `true`) | KafkaConstants.PARTITION_KEY | ""kafka.PARTITION_KEY"" | Integer | Explicitly specify the partition (only used if the `KafkaConstants.KEY` header is defined) |=== After the message is sent to Kafka, the following headers are available [width=""100%"",cols=""2m,2m,1m,5"",options=""header""] |=== | Header constant | Header value | Type | Description | KafkaConstants.KAFKA_RECORDMETA | ""org.apache.kafka.clients.producer.RecordMetadata"" | List | The metadata (only configured if `recordMetadata` endpoint parameter is `true` |=== === Samples ==== Consuming messages from Kafka Here is the minimal route you need in order to read messages from Kafka. [source,java] ---- from(""kafka:test?brokers=localhost:9092"") .log(""Message received from Kafka : ${body}"") .log("" on the topic ${headers[kafka.TOPIC]}"") .log("" on the partition ${headers[kafka.PARTITION]}"") .log("" with the offset ${headers[kafka.OFFSET]}"") .log("" with the key ${headers[kafka.KEY]}"") ---- If you need to consume messages from multiple topics you can use a comma separated list of topic names [source,java] ---- from(""kafka:test,test1,test2?brokers=localhost:9092"") .log(""Message received from Kafka : ${body}"") .log("" on the topic ${headers[kafka.TOPIC]}"") .log("" on the partition ${headers[kafka.PARTITION]}"") .log("" with the offset ${headers[kafka.OFFSET]}"") .log("" with the key ${headers[kafka.KEY]}"") ---- When consuming messages from Kafka you can use your own offset management and not delegate this management to Kafka. In order to keep the offsets the component needs a `StateRepository` implementation such as `FileStateRepository`. This bean should be available in the registry. Here how to use it : [source,java] ---- // Create the repository in which the Kafka offsets will be persisted FileStateRepository repository = FileStateRepository.fileStateRepository(new File(""/path/to/repo.dat"")); // Bind this repository into the Camel registry JndiRegistry registry = new JndiRegistry(); registry.bind(""offsetRepo"", repository); // Configure the camel context DefaultCamelContext camelContext = new DefaultCamelContext(registry); camelContext.addRoutes(new RouteBuilder() { @Override public void configure() throws Exception { from(""kafka:"" + TOPIC + ""?brokers=localhost:{{kafkaPort}}"" + // Setup the topic and broker address ""&groupId=A"" + // The consumer processor group ID ""&autoOffsetReset=earliest"" + // Ask to start from the beginning if we have unknown offset ""&offsetRepository=#offsetRepo"") // Keep the offsets in the previously configured repository .to(""mock:result""); } }); ----   ==== Producing messages to Kafka Here is the minimal route you need in order to write messages to Kafka. [source,java] ---- from(""direct:start"") .setBody(constant(""Message from Camel"")) // Message to send .setHeader(KafkaConstants.KEY, constant(""Camel"")) // Key of the message .to(""kafka:test?brokers=localhost:9092""); ---- === SSL configuration You have 2 different ways to configure the SSL communication on the Kafka` component. The first way is through the many SSL endpoint parameters [source,java] ---- from(""kafka:"" + TOPIC + ""?brokers=localhost:{{kafkaPort}}"" + ""&groupId=A"" + ""&sslKeystoreLocation=/path/to/keystore.jks"" + ""&sslKeystorePassword=changeit"" + ""&sslKeyPassword=changeit"" + ""&securityProtocol=SSL"") .to(""mock:result""); ---- The second way is to use the `sslContextParameters` endpoint parameter. [source,java] ---- // Configure the SSLContextParameters object KeyStoreParameters ksp = new KeyStoreParameters(); ksp.setResource(""/path/to/keystore.jks""); ksp.setPassword(""changeit""); KeyManagersParameters kmp = new KeyManagersParameters(); kmp.setKeyStore(ksp); kmp.setKeyPassword(""changeit""); SSLContextParameters scp = new SSLContextParameters(); scp.setKeyManagers(kmp); // Bind this SSLContextParameters into the Camel registry JndiRegistry registry = new JndiRegistry(); registry.bind(""ssl"", scp); // Configure the camel context DefaultCamelContext camelContext = new DefaultCamelContext(registry); camelContext.addRoutes(new RouteBuilder() { @Override public void configure() throws Exception { from(""kafka:"" + TOPIC + ""?brokers=localhost:{{kafkaPort}}"" + // Setup the topic and broker address ""&groupId=A"" + // The consumer processor group ID ""&sslContextParameters=#ssl"" + // The security protocol ""&securityProtocol=SSL) // Reference the SSL configuration .to(""mock:result""); } }); ---- === Using the Kafka idempotent repository *Available from Camel 2.19* The `camel-kafka` library provides a Kafka topic-based idempotent repository. This repository stores broadcasts all changes to idempotent state (add/remove) in a Kafka topic, and populates a local in-memory cache for each repository's process instance through event sourcing. The topic used must be unique per idempotent repository instance. The mechanism does not have any requirements about the number of topic partitions; as the repository consumes from all partitions at the same time. It also does not have any requirements about the replication factor of the topic. Each repository instance that uses the topic (e.g. typically on different machines running in parallel) controls its own consumer group, so in a cluster of 10 Camel processes using the same topic each will control its own offset. On startup, the instance subscribes to the topic and rewinds the offset to the beginning, rebuilding the cache to the latest state. The cache will not be considered warmed up until one poll of `pollDurationMs` in length returns 0 records. Startup will not be completed until either the cache has warmed up, or 30 seconds go by; if the latter happens the idempotent repository may be in an inconsistent state until its consumer catches up to the end of the topic. A `KafkaIdempotentRepository` has the following properties: [width=""100%"",cols=""2m,5"",options=""header""] |=== | Property | Description | topic | The name of the Kafka topic to use to broadcast changes. (required) | bootstrapServers | The `bootstrap.servers` property on the internal Kafka producer and consumer. Use this as shorthand if not setting `consumerConfig` and `producerConfig`. If used, this component will apply sensible default configurations for the producer and consumer. | producerConfig | Sets the properties that will be used by the Kafka producer that broadcasts changes. Overrides `bootstrapServers`, so must define the Kafka `bootstrap.servers` property itself | consumerConfig | Sets the properties that will be used by the Kafka consumer that populates the cache from the topic. Overrides `bootstrapServers`, so must define the Kafka `bootstrap.servers` property itself | maxCacheSize | How many of the most recently used keys should be stored in memory (default 1000). | pollDurationMs | The poll duration of the Kafka consumer. The local caches are updated immediately. This value will affect how far behind other peers that update their caches from the topic are relative to the idempotent consumer instance that sent the cache action message. The default value of this is 100 ms. + If setting this value explicitly, be aware that there is a tradeoff between the remote cache liveness and the volume of network traffic between this repository's consumer and the Kafka brokers. The cache warmup process also depends on there being one poll that fetches nothing - this indicates that the stream has been consumed up to the current point. If the poll duration is excessively long for the rate at which messages are sent on the topic, there exists a possibility that the cache cannot be warmed up and will operate in an inconsistent state relative to its peers until it catches up. |=== The repository can be instantiated by defining the `topic` and `bootstrapServers`, or the `producerConfig` and `consumerConfig` property sets can be explicitly defined to enable features such as SSL/SASL. To use, this repository must be placed in the Camel registry, either manually or by registration as a bean in Spring/Blueprint, as it is `CamelContext` aware. Sample usage is as follows: [source,java] ---- KafkaIdempotentRepository kafkaIdempotentRepository = new KafkaIdempotentRepository(""idempotent-db-inserts"", ""localhost:9091""); SimpleRegistry registry = new SimpleRegistry(); registry.put(""insertDbIdemRepo"", kafkaIdempotentRepository); // must be registered in the registry, to enable access to the CamelContext CamelContext context = new CamelContext(registry); // later in RouteBuilder... from(""direct:performInsert"") .idempotentConsumer(header(""id"")).messageIdRepositoryRef(""insertDbIdemRepo"") // once-only insert into database .end() ---- In XML: [source,xml] ---- localhost:9091 localhost:9091 ---- === Using manual commit with Kafka consumer *Available as of Camel 2.21* By default the Kafka consumer will use auto commit, where the offset will be committed automatically in the background using a given interval. In case you want to force manual commits, you can use `KafkaManualCommit` API from the Camel Exchange, stored on the message header. This requires to turn on manual commits by either setting the option `allowManualCommit` to `true` on the `KafkaComponent` or on the endpoint, for example: [source,java] ---- KafkaComponent kafka = new KafkaComponent(); kafka.setAllowManualCommit(true); ... camelContext.addComponent(""kafka"", kafka); ---- You can then use the `KafkaManualCommit` from Java code such as a Camel `Processor`: [source,java] ---- public void process(Exchange exchange) { KafkaManualCommit manual = exchange.getIn().getHeader(KafkaConstants.MANUAL_COMMIT, KafkaManualCommit.class); manual.commitSync(); } ---- This will force a synchronous commit which will block until the commit is acknowledge on Kafka, or if it fails an exception is thrown. If you want to use a custom implementation of `KafkaManualCommit` then you can configure a custom `KafkaManualCommitFactory` on the `KafkaComponent` that creates instances of your custom implementation. === Kafka Headers propagation *Available as of Camel 2.22* When consuming messages from Kafka, headers will be propagated to camel exchange headers automatically. Producing flow backed by same behaviour - camel headers of particular exchange will be propagated to kafka message headers. Since kafka headers allows only `byte[]` values, in order camel exchnage header to be propagated its value should be serialized to `bytes[]`, otherwise header will be skipped. Following header value types are supported: `String`, `Integer`, `Long`, `Double`, `Boolean`, `byte[]`. Note: all headers propagated *from* kafka *to* camel exchange will contain `byte[]` value by default. In order to override default functionality uri parameters can be set: `kafkaHeaderDeserializer` for `from` route and `kafkaHeaderSerializer` for `to` route. Example: ``` from(""kafka:my_topic?kafkaHeaderDeserializer=#myDeserializer"") ... .to(""kafka:my_topic?kafkaHeaderSerializer=#mySerializer"") ``` By default all headers are being filtered by `KafkaHeaderFilterStrategy`. Strategy filters out headers which start with `Camel` or `org.apache.camel` prefixes. Default strategy can be overridden by using `headerFilterStrategy` uri parameter in both `to` and `from` routes: ``` from(""kafka:my_topic?headerFilterStrategy=#myStrategy"") ... .to(""kafka:my_topic?headerFilterStrategy=#myStrategy"") ``` `myStrategy` object should be subclass of `HeaderFilterStrategy` and must be placed in the Camel registry, either manually or by registration as a bean in Spring/Blueprint, as it is `CamelContext` aware. ",16263,True,3446.3482550556428,median "------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- U R E A L P -- -- -- -- B o d y -- -- -- -- Copyright (C) 1992-2010, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- As a special exception under Section 7 of GPL version 3, you are granted -- -- additional permissions described in the GCC Runtime Library Exception, -- -- version 3.1, as published by the Free Software Foundation. -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- . -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ with Alloc; with Output; use Output; with Table; with Tree_IO; use Tree_IO; package body Urealp is Ureal_First_Entry : constant Ureal := Ureal'Succ (No_Ureal); -- First subscript allocated in Ureal table (note that we can't just -- add 1 to No_Ureal, since ""+"" means something different for Ureals! type Ureal_Entry is record Num : Uint; -- Numerator (always non-negative) Den : Uint; -- Denominator (always non-zero, always positive if base is zero) Rbase : Nat; -- Base value. If Rbase is zero, then the value is simply Num / Den. -- If Rbase is non-zero, then the value is Num / (Rbase ** Den) Negative : Boolean; -- Flag set if value is negative end record; -- The following representation clause ensures that the above record -- has no holes. We do this so that when instances of this record are -- written by Tree_Gen, we do not write uninitialized values to the file. for Ureal_Entry use record Num at 0 range 0 .. 31; Den at 4 range 0 .. 31; Rbase at 8 range 0 .. 31; Negative at 12 range 0 .. 31; end record; for Ureal_Entry'Size use 16 * 8; -- This ensures that we did not leave out any fields package Ureals is new Table.Table ( Table_Component_Type => Ureal_Entry, Table_Index_Type => Ureal'Base, Table_Low_Bound => Ureal_First_Entry, Table_Initial => Alloc.Ureals_Initial, Table_Increment => Alloc.Ureals_Increment, Table_Name => ""Ureals""); -- The following universal reals are the values returned by the constant -- functions. They are initialized by the initialization procedure. UR_0 : Ureal; UR_M_0 : Ureal; UR_Tenth : Ureal; UR_Half : Ureal; UR_1 : Ureal; UR_2 : Ureal; UR_10 : Ureal; UR_10_36 : Ureal; UR_M_10_36 : Ureal; UR_100 : Ureal; UR_2_128 : Ureal; UR_2_80 : Ureal; UR_2_M_128 : Ureal; UR_2_M_80 : Ureal; Num_Ureal_Constants : constant := 10; -- This is used for an assertion check in Tree_Read and Tree_Write to -- help remember to add values to these routines when we add to the list. Normalized_Real : Ureal := No_Ureal; -- Used to memoize Norm_Num and Norm_Den, if either of these functions -- is called, this value is set and Normalized_Entry contains the result -- of the normalization. On subsequent calls, this is used to avoid the -- call to Normalize if it has already been made. Normalized_Entry : Ureal_Entry; -- Entry built by most recent call to Normalize ----------------------- -- Local Subprograms -- ----------------------- function Decimal_Exponent_Hi (V : Ureal) return Int; -- Returns an estimate of the exponent of Val represented as a normalized -- decimal number (non-zero digit before decimal point), The estimate is -- either correct, or high, but never low. The accuracy of the estimate -- affects only the efficiency of the comparison routines. function Decimal_Exponent_Lo (V : Ureal) return Int; -- Returns an estimate of the exponent of Val represented as a normalized -- decimal number (non-zero digit before decimal point), The estimate is -- either correct, or low, but never high. The accuracy of the estimate -- affects only the efficiency of the comparison routines. function Equivalent_Decimal_Exponent (U : Ureal_Entry) return Int; -- U is a Ureal entry for which the base value is non-zero, the value -- returned is the equivalent decimal exponent value, i.e. the value of -- Den, adjusted as though the base were base 10. The value is rounded -- to the nearest integer, and so can be one off. function Is_Integer (Num, Den : Uint) return Boolean; -- Return true if the real quotient of Num / Den is an integer value function Normalize (Val : Ureal_Entry) return Ureal_Entry; -- Normalizes the Ureal_Entry by reducing it to lowest terms (with a base -- value of 0). function Same (U1, U2 : Ureal) return Boolean; pragma Inline (Same); -- Determines if U1 and U2 are the same Ureal. Note that we cannot use -- the equals operator for this test, since that tests for equality, not -- identity. function Store_Ureal (Val : Ureal_Entry) return Ureal; -- This store a new entry in the universal reals table and return its index -- in the table. function Store_Ureal_Normalized (Val : Ureal_Entry) return Ureal; pragma Inline (Store_Ureal_Normalized); -- Like Store_Ureal, but normalizes its operand first. ------------------------- -- Decimal_Exponent_Hi -- ------------------------- function Decimal_Exponent_Hi (V : Ureal) return Int is Val : constant Ureal_Entry := Ureals.Table (V); begin -- Zero always returns zero if UR_Is_Zero (V) then return 0; -- For numbers in rational form, get the maximum number of digits in the -- numerator and the minimum number of digits in the denominator, and -- subtract. For example: -- 1000 / 99 = 1.010E+1 -- 9999 / 10 = 9.999E+2 -- This estimate may of course be high, but that is acceptable elsif Val.Rbase = 0 then return UI_Decimal_Digits_Hi (Val.Num) - UI_Decimal_Digits_Lo (Val.Den); -- For based numbers, just subtract the decimal exponent from the -- high estimate of the number of digits in the numerator and add -- one to accommodate possible round off errors for non-decimal -- bases. For example: -- 1_500_000 / 10**4 = 1.50E-2 else -- Val.Rbase /= 0 return UI_Decimal_Digits_Hi (Val.Num) - Equivalent_Decimal_Exponent (Val) + 1; end if; end Decimal_Exponent_Hi; ------------------------- -- Decimal_Exponent_Lo -- ------------------------- function Decimal_Exponent_Lo (V : Ureal) return Int is Val : constant Ureal_Entry := Ureals.Table (V); begin -- Zero always returns zero if UR_Is_Zero (V) then return 0; -- For numbers in rational form, get min digits in numerator, max digits -- in denominator, and subtract and subtract one more for possible loss -- during the division. For example: -- 1000 / 99 = 1.010E+1 -- 9999 / 10 = 9.999E+2 -- This estimate may of course be low, but that is acceptable elsif Val.Rbase = 0 then return UI_Decimal_Digits_Lo (Val.Num) - UI_Decimal_Digits_Hi (Val.Den) - 1; -- For based numbers, just subtract the decimal exponent from the -- low estimate of the number of digits in the numerator and subtract -- one to accommodate possible round off errors for non-decimal -- bases. For example: -- 1_500_000 / 10**4 = 1.50E-2 else -- Val.Rbase /= 0 return UI_Decimal_Digits_Lo (Val.Num) - Equivalent_Decimal_Exponent (Val) - 1; end if; end Decimal_Exponent_Lo; ----------------- -- Denominator -- ----------------- function Denominator (Real : Ureal) return Uint is begin return Ureals.Table (Real).Den; end Denominator; --------------------------------- -- Equivalent_Decimal_Exponent -- --------------------------------- function Equivalent_Decimal_Exponent (U : Ureal_Entry) return Int is -- The following table is a table of logs to the base 10 Logs : constant array (Nat range 1 .. 16) of Long_Float := ( 1 => 0.000000000000000, 2 => 0.301029995663981, 3 => 0.477121254719662, 4 => 0.602059991327962, 5 => 0.698970004336019, 6 => 0.778151250383644, 7 => 0.845098040014257, 8 => 0.903089986991944, 9 => 0.954242509439325, 10 => 1.000000000000000, 11 => 1.041392685158230, 12 => 1.079181246047620, 13 => 1.113943352306840, 14 => 1.146128035678240, 15 => 1.176091259055680, 16 => 1.204119982655920); begin pragma Assert (U.Rbase /= 0); return Int (Long_Float (UI_To_Int (U.Den)) * Logs (U.Rbase)); end Equivalent_Decimal_Exponent; ---------------- -- Initialize -- ---------------- procedure Initialize is begin Ureals.Init; UR_0 := UR_From_Components (Uint_0, Uint_1, 0, False); UR_M_0 := UR_From_Components (Uint_0, Uint_1, 0, True); UR_Half := UR_From_Components (Uint_1, Uint_1, 2, False); UR_Tenth := UR_From_Components (Uint_1, Uint_1, 10, False); UR_1 := UR_From_Components (Uint_1, Uint_1, 0, False); UR_2 := UR_From_Components (Uint_1, Uint_Minus_1, 2, False); UR_10 := UR_From_Components (Uint_1, Uint_Minus_1, 10, False); UR_10_36 := UR_From_Components (Uint_1, Uint_Minus_36, 10, False); UR_M_10_36 := UR_From_Components (Uint_1, Uint_Minus_36, 10, True); UR_100 := UR_From_Components (Uint_1, Uint_Minus_2, 10, False); UR_2_128 := UR_From_Components (Uint_1, Uint_Minus_128, 2, False); UR_2_M_128 := UR_From_Components (Uint_1, Uint_128, 2, False); UR_2_80 := UR_From_Components (Uint_1, Uint_Minus_80, 2, False); UR_2_M_80 := UR_From_Components (Uint_1, Uint_80, 2, False); end Initialize; ---------------- -- Is_Integer -- ---------------- function Is_Integer (Num, Den : Uint) return Boolean is begin return (Num / Den) * Den = Num; end Is_Integer; ---------- -- Mark -- ---------- function Mark return Save_Mark is begin return Save_Mark (Ureals.Last); end Mark; -------------- -- Norm_Den -- -------------- function Norm_Den (Real : Ureal) return Uint is begin if not Same (Real, Normalized_Real) then Normalized_Real := Real; Normalized_Entry := Normalize (Ureals.Table (Real)); end if; return Normalized_Entry.Den; end Norm_Den; -------------- -- Norm_Num -- -------------- function Norm_Num (Real : Ureal) return Uint is begin if not Same (Real, Normalized_Real) then Normalized_Real := Real; Normalized_Entry := Normalize (Ureals.Table (Real)); end if; return Normalized_Entry.Num; end Norm_Num; --------------- -- Normalize -- --------------- function Normalize (Val : Ureal_Entry) return Ureal_Entry is J : Uint; K : Uint; Tmp : Uint; Num : Uint; Den : Uint; M : constant Uintp.Save_Mark := Uintp.Mark; begin -- Start by setting J to the greatest of the absolute values of the -- numerator and the denominator (taking into account the base value), -- and K to the lesser of the two absolute values. The gcd of Num and -- Den is the gcd of J and K. if Val.Rbase = 0 then J := Val.Num; K := Val.Den; elsif Val.Den < 0 then J := Val.Num * Val.Rbase ** (-Val.Den); K := Uint_1; else J := Val.Num; K := Val.Rbase ** Val.Den; end if; Num := J; Den := K; if K > J then Tmp := J; J := K; K := Tmp; end if; J := UI_GCD (J, K); Num := Num / J; Den := Den / J; Uintp.Release_And_Save (M, Num, Den); -- Divide numerator and denominator by gcd and return result return (Num => Num, Den => Den, Rbase => 0, Negative => Val.Negative); end Normalize; --------------- -- Numerator -- --------------- function Numerator (Real : Ureal) return Uint is begin return Ureals.Table (Real).Num; end Numerator; -------- -- pr -- -------- procedure pr (Real : Ureal) is begin UR_Write (Real); Write_Eol; end pr; ----------- -- Rbase -- ----------- function Rbase (Real : Ureal) return Nat is begin return Ureals.Table (Real).Rbase; end Rbase; ------------- -- Release -- ------------- procedure Release (M : Save_Mark) is begin Ureals.Set_Last (Ureal (M)); end Release; ---------- -- Same -- ---------- function Same (U1, U2 : Ureal) return Boolean is begin return Int (U1) = Int (U2); end Same; ----------------- -- Store_Ureal -- ----------------- function Store_Ureal (Val : Ureal_Entry) return Ureal is begin Ureals.Append (Val); -- Normalize representation of signed values if Val.Num < 0 then Ureals.Table (Ureals.Last).Negative := True; Ureals.Table (Ureals.Last).Num := -Val.Num; end if; return Ureals.Last; end Store_Ureal; ---------------------------- -- Store_Ureal_Normalized -- ---------------------------- function Store_Ureal_Normalized (Val : Ureal_Entry) return Ureal is begin return Store_Ureal (Normalize (Val)); end Store_Ureal_Normalized; --------------- -- Tree_Read -- --------------- procedure Tree_Read is begin pragma Assert (Num_Ureal_Constants = 10); Ureals.Tree_Read; Tree_Read_Int (Int (UR_0)); Tree_Read_Int (Int (UR_M_0)); Tree_Read_Int (Int (UR_Tenth)); Tree_Read_Int (Int (UR_Half)); Tree_Read_Int (Int (UR_1)); Tree_Read_Int (Int (UR_2)); Tree_Read_Int (Int (UR_10)); Tree_Read_Int (Int (UR_100)); Tree_Read_Int (Int (UR_2_128)); Tree_Read_Int (Int (UR_2_M_128)); -- Clear the normalization cache Normalized_Real := No_Ureal; end Tree_Read; ---------------- -- Tree_Write -- ---------------- procedure Tree_Write is begin pragma Assert (Num_Ureal_Constants = 10); Ureals.Tree_Write; Tree_Write_Int (Int (UR_0)); Tree_Write_Int (Int (UR_M_0)); Tree_Write_Int (Int (UR_Tenth)); Tree_Write_Int (Int (UR_Half)); Tree_Write_Int (Int (UR_1)); Tree_Write_Int (Int (UR_2)); Tree_Write_Int (Int (UR_10)); Tree_Write_Int (Int (UR_100)); Tree_Write_Int (Int (UR_2_128)); Tree_Write_Int (Int (UR_2_M_128)); end Tree_Write; ------------ -- UR_Abs -- ------------ function UR_Abs (Real : Ureal) return Ureal is Val : constant Ureal_Entry := Ureals.Table (Real); begin return Store_Ureal ((Num => Val.Num, Den => Val.Den, Rbase => Val.Rbase, Negative => False)); end UR_Abs; ------------ -- UR_Add -- ------------ function UR_Add (Left : Uint; Right : Ureal) return Ureal is begin return UR_From_Uint (Left) + Right; end UR_Add; function UR_Add (Left : Ureal; Right : Uint) return Ureal is begin return Left + UR_From_Uint (Right); end UR_Add; function UR_Add (Left : Ureal; Right : Ureal) return Ureal is Lval : Ureal_Entry := Ureals.Table (Left); Rval : Ureal_Entry := Ureals.Table (Right); Num : Uint; begin -- Note, in the temporary Ureal_Entry values used in this procedure, -- we store the sign as the sign of the numerator (i.e. xxx.Num may -- be negative, even though in stored entries this can never be so) if Lval.Rbase /= 0 and then Lval.Rbase = Rval.Rbase then declare Opd_Min, Opd_Max : Ureal_Entry; Exp_Min, Exp_Max : Uint; begin if Lval.Negative then Lval.Num := (-Lval.Num); end if; if Rval.Negative then Rval.Num := (-Rval.Num); end if; if Lval.Den < Rval.Den then Exp_Min := Lval.Den; Exp_Max := Rval.Den; Opd_Min := Lval; Opd_Max := Rval; else Exp_Min := Rval.Den; Exp_Max := Lval.Den; Opd_Min := Rval; Opd_Max := Lval; end if; Num := Opd_Min.Num * Lval.Rbase ** (Exp_Max - Exp_Min) + Opd_Max.Num; if Num = 0 then return Store_Ureal ((Num => Uint_0, Den => Uint_1, Rbase => 0, Negative => Lval.Negative)); else return Store_Ureal ((Num => abs Num, Den => Exp_Max, Rbase => Lval.Rbase, Negative => (Num < 0))); end if; end; else declare Ln : Ureal_Entry := Normalize (Lval); Rn : Ureal_Entry := Normalize (Rval); begin if Ln.Negative then Ln.Num := (-Ln.Num); end if; if Rn.Negative then Rn.Num := (-Rn.Num); end if; Num := (Ln.Num * Rn.Den) + (Rn.Num * Ln.Den); if Num = 0 then return Store_Ureal ((Num => Uint_0, Den => Uint_1, Rbase => 0, Negative => Lval.Negative)); else return Store_Ureal_Normalized ((Num => abs Num, Den => Ln.Den * Rn.Den, Rbase => 0, Negative => (Num < 0))); end if; end; end if; end UR_Add; ---------------- -- UR_Ceiling -- ---------------- function UR_Ceiling (Real : Ureal) return Uint is Val : constant Ureal_Entry := Normalize (Ureals.Table (Real)); begin if Val.Negative then return UI_Negate (Val.Num / Val.Den); else return (Val.Num + Val.Den - 1) / Val.Den; end if; end UR_Ceiling; ------------ -- UR_Div -- ------------ function UR_Div (Left : Uint; Right : Ureal) return Ureal is begin return UR_From_Uint (Left) / Right; end UR_Div; function UR_Div (Left : Ureal; Right : Uint) return Ureal is begin return Left / UR_From_Uint (Right); end UR_Div; function UR_Div (Left, Right : Ureal) return Ureal is Lval : constant Ureal_Entry := Ureals.Table (Left); Rval : constant Ureal_Entry := Ureals.Table (Right); Rneg : constant Boolean := Rval.Negative xor Lval.Negative; begin pragma Assert (Rval.Num /= Uint_0); if Lval.Rbase = 0 then if Rval.Rbase = 0 then return Store_Ureal_Normalized ((Num => Lval.Num * Rval.Den, Den => Lval.Den * Rval.Num, Rbase => 0, Negative => Rneg)); elsif Is_Integer (Lval.Num, Rval.Num * Lval.Den) then return Store_Ureal ((Num => Lval.Num / (Rval.Num * Lval.Den), Den => (-Rval.Den), Rbase => Rval.Rbase, Negative => Rneg)); elsif Rval.Den < 0 then return Store_Ureal_Normalized ((Num => Lval.Num, Den => Rval.Rbase ** (-Rval.Den) * Rval.Num * Lval.Den, Rbase => 0, Negative => Rneg)); else return Store_Ureal_Normalized ((Num => Lval.Num * Rval.Rbase ** Rval.Den, Den => Rval.Num * Lval.Den, Rbase => 0, Negative => Rneg)); end if; elsif Is_Integer (Lval.Num, Rval.Num) then if Rval.Rbase = Lval.Rbase then return Store_Ureal ((Num => Lval.Num / Rval.Num, Den => Lval.Den - Rval.Den, Rbase => Lval.Rbase, Negative => Rneg)); elsif Rval.Rbase = 0 then return Store_Ureal ((Num => (Lval.Num / Rval.Num) * Rval.Den, Den => Lval.Den, Rbase => Lval.Rbase, Negative => Rneg)); elsif Rval.Den < 0 then declare Num, Den : Uint; begin if Lval.Den < 0 then Num := (Lval.Num / Rval.Num) * (Lval.Rbase ** (-Lval.Den)); Den := Rval.Rbase ** (-Rval.Den); else Num := Lval.Num / Rval.Num; Den := (Lval.Rbase ** Lval.Den) * (Rval.Rbase ** (-Rval.Den)); end if; return Store_Ureal ((Num => Num, Den => Den, Rbase => 0, Negative => Rneg)); end; else return Store_Ureal ((Num => (Lval.Num / Rval.Num) * (Rval.Rbase ** Rval.Den), Den => Lval.Den, Rbase => Lval.Rbase, Negative => Rneg)); end if; else declare Num, Den : Uint; begin if Lval.Den < 0 then Num := Lval.Num * (Lval.Rbase ** (-Lval.Den)); Den := Rval.Num; else Num := Lval.Num; Den := Rval.Num * (Lval.Rbase ** Lval.Den); end if; if Rval.Rbase /= 0 then if Rval.Den < 0 then Den := Den * (Rval.Rbase ** (-Rval.Den)); else Num := Num * (Rval.Rbase ** Rval.Den); end if; else Num := Num * Rval.Den; end if; return Store_Ureal_Normalized ((Num => Num, Den => Den, Rbase => 0, Negative => Rneg)); end; end if; end UR_Div; ----------- -- UR_Eq -- ----------- function UR_Eq (Left, Right : Ureal) return Boolean is begin return not UR_Ne (Left, Right); end UR_Eq; --------------------- -- UR_Exponentiate -- --------------------- function UR_Exponentiate (Real : Ureal; N : Uint) return Ureal is X : constant Uint := abs N; Bas : Ureal; Val : Ureal_Entry; Neg : Boolean; IBas : Uint; begin -- If base is negative, then the resulting sign depends on whether -- the exponent is even or odd (even => positive, odd = negative) if UR_Is_Negative (Real) then Neg := (N mod 2) /= 0; Bas := UR_Negate (Real); else Neg := False; Bas := Real; end if; Val := Ureals.Table (Bas); -- If the base is a small integer, then we can return the result in -- exponential form, which can save a lot of time for junk exponents. IBas := UR_Trunc (Bas); if IBas <= 16 and then UR_From_Uint (IBas) = Bas then return Store_Ureal ((Num => Uint_1, Den => -N, Rbase => UI_To_Int (UR_Trunc (Bas)), Negative => Neg)); -- If the exponent is negative then we raise the numerator and the -- denominator (after normalization) to the absolute value of the -- exponent and we return the reciprocal. An assert error will happen -- if the numerator is zero. elsif N < 0 then pragma Assert (Val.Num /= 0); Val := Normalize (Val); return Store_Ureal ((Num => Val.Den ** X, Den => Val.Num ** X, Rbase => 0, Negative => Neg)); -- If positive, we distinguish the case when the base is not zero, in -- which case the new denominator is just the product of the old one -- with the exponent, else if Val.Rbase /= 0 then return Store_Ureal ((Num => Val.Num ** X, Den => Val.Den * X, Rbase => Val.Rbase, Negative => Neg)); -- And when the base is zero, in which case we exponentiate -- the old denominator. else return Store_Ureal ((Num => Val.Num ** X, Den => Val.Den ** X, Rbase => 0, Negative => Neg)); end if; end if; end UR_Exponentiate; -------------- -- UR_Floor -- -------------- function UR_Floor (Real : Ureal) return Uint is Val : constant Ureal_Entry := Normalize (Ureals.Table (Real)); begin if Val.Negative then return UI_Negate ((Val.Num + Val.Den - 1) / Val.Den); else return Val.Num / Val.Den; end if; end UR_Floor; ------------------------ -- UR_From_Components -- ------------------------ function UR_From_Components (Num : Uint; Den : Uint; Rbase : Nat := 0; Negative : Boolean := False) return Ureal is begin return Store_Ureal ((Num => Num, Den => Den, Rbase => Rbase, Negative => Negative)); end UR_From_Components; ------------------ -- UR_From_Uint -- ------------------ function UR_From_Uint (UI : Uint) return Ureal is begin return UR_From_Components (abs UI, Uint_1, Negative => (UI < 0)); end UR_From_Uint; ----------- -- UR_Ge -- ----------- function UR_Ge (Left, Right : Ureal) return Boolean is begin return not (Left < Right); end UR_Ge; ----------- -- UR_Gt -- ----------- function UR_Gt (Left, Right : Ureal) return Boolean is begin return (Right < Left); end UR_Gt; -------------------- -- UR_Is_Negative -- -------------------- function UR_Is_Negative (Real : Ureal) return Boolean is begin return Ureals.Table (Real).Negative; end UR_Is_Negative; -------------------- -- UR_Is_Positive -- -------------------- function UR_Is_Positive (Real : Ureal) return Boolean is begin return not Ureals.Table (Real).Negative and then Ureals.Table (Real).Num /= 0; end UR_Is_Positive; ---------------- -- UR_Is_Zero -- ---------------- function UR_Is_Zero (Real : Ureal) return Boolean is begin return Ureals.Table (Real).Num = 0; end UR_Is_Zero; ----------- -- UR_Le -- ----------- function UR_Le (Left, Right : Ureal) return Boolean is begin return not (Right < Left); end UR_Le; ----------- -- UR_Lt -- ----------- function UR_Lt (Left, Right : Ureal) return Boolean is begin -- An operand is not less than itself if Same (Left, Right) then return False; -- Deal with zero cases elsif UR_Is_Zero (Left) then return UR_Is_Positive (Right); elsif UR_Is_Zero (Right) then return Ureals.Table (Left).Negative; -- Different signs are decisive (note we dealt with zero cases) elsif Ureals.Table (Left).Negative and then not Ureals.Table (Right).Negative then return True; elsif not Ureals.Table (Left).Negative and then Ureals.Table (Right).Negative then return False; -- Signs are same, do rapid check based on worst case estimates of -- decimal exponent, which will often be decisive. Precise test -- depends on whether operands are positive or negative. elsif Decimal_Exponent_Hi (Left) < Decimal_Exponent_Lo (Right) then return UR_Is_Positive (Left); elsif Decimal_Exponent_Lo (Left) > Decimal_Exponent_Hi (Right) then return UR_Is_Negative (Left); -- If we fall through, full gruesome test is required. This happens -- if the numbers are close together, or in some weird (/=10) base. else declare Imrk : constant Uintp.Save_Mark := Mark; Rmrk : constant Urealp.Save_Mark := Mark; Lval : Ureal_Entry; Rval : Ureal_Entry; Result : Boolean; begin Lval := Ureals.Table (Left); Rval := Ureals.Table (Right); -- An optimization. If both numbers are based, then subtract -- common value of base to avoid unnecessarily giant numbers if Lval.Rbase = Rval.Rbase and then Lval.Rbase /= 0 then if Lval.Den < Rval.Den then Rval.Den := Rval.Den - Lval.Den; Lval.Den := Uint_0; else Lval.Den := Lval.Den - Rval.Den; Rval.Den := Uint_0; end if; end if; Lval := Normalize (Lval); Rval := Normalize (Rval); if Lval.Negative then Result := (Lval.Num * Rval.Den) > (Rval.Num * Lval.Den); else Result := (Lval.Num * Rval.Den) < (Rval.Num * Lval.Den); end if; Release (Imrk); Release (Rmrk); return Result; end; end if; end UR_Lt; ------------ -- UR_Max -- ------------ function UR_Max (Left, Right : Ureal) return Ureal is begin if Left >= Right then return Left; else return Right; end if; end UR_Max; ------------ -- UR_Min -- ------------ function UR_Min (Left, Right : Ureal) return Ureal is begin if Left <= Right then return Left; else return Right; end if; end UR_Min; ------------ -- UR_Mul -- ------------ function UR_Mul (Left : Uint; Right : Ureal) return Ureal is begin return UR_From_Uint (Left) * Right; end UR_Mul; function UR_Mul (Left : Ureal; Right : Uint) return Ureal is begin return Left * UR_From_Uint (Right); end UR_Mul; function UR_Mul (Left, Right : Ureal) return Ureal is Lval : constant Ureal_Entry := Ureals.Table (Left); Rval : constant Ureal_Entry := Ureals.Table (Right); Num : Uint := Lval.Num * Rval.Num; Den : Uint; Rneg : constant Boolean := Lval.Negative xor Rval.Negative; begin if Lval.Rbase = 0 then if Rval.Rbase = 0 then return Store_Ureal_Normalized ((Num => Num, Den => Lval.Den * Rval.Den, Rbase => 0, Negative => Rneg)); elsif Is_Integer (Num, Lval.Den) then return Store_Ureal ((Num => Num / Lval.Den, Den => Rval.Den, Rbase => Rval.Rbase, Negative => Rneg)); elsif Rval.Den < 0 then return Store_Ureal_Normalized ((Num => Num * (Rval.Rbase ** (-Rval.Den)), Den => Lval.Den, Rbase => 0, Negative => Rneg)); else return Store_Ureal_Normalized ((Num => Num, Den => Lval.Den * (Rval.Rbase ** Rval.Den), Rbase => 0, Negative => Rneg)); end if; elsif Lval.Rbase = Rval.Rbase then return Store_Ureal ((Num => Num, Den => Lval.Den + Rval.Den, Rbase => Lval.Rbase, Negative => Rneg)); elsif Rval.Rbase = 0 then if Is_Integer (Num, Rval.Den) then return Store_Ureal ((Num => Num / Rval.Den, Den => Lval.Den, Rbase => Lval.Rbase, Negative => Rneg)); elsif Lval.Den < 0 then return Store_Ureal_Normalized ((Num => Num * (Lval.Rbase ** (-Lval.Den)), Den => Rval.Den, Rbase => 0, Negative => Rneg)); else return Store_Ureal_Normalized ((Num => Num, Den => Rval.Den * (Lval.Rbase ** Lval.Den), Rbase => 0, Negative => Rneg)); end if; else Den := Uint_1; if Lval.Den < 0 then Num := Num * (Lval.Rbase ** (-Lval.Den)); else Den := Den * (Lval.Rbase ** Lval.Den); end if; if Rval.Den < 0 then Num := Num * (Rval.Rbase ** (-Rval.Den)); else Den := Den * (Rval.Rbase ** Rval.Den); end if; return Store_Ureal_Normalized ((Num => Num, Den => Den, Rbase => 0, Negative => Rneg)); end if; end UR_Mul; ----------- -- UR_Ne -- ----------- function UR_Ne (Left, Right : Ureal) return Boolean is begin -- Quick processing for case of identical Ureal values (note that -- this also deals with comparing two No_Ureal values). if Same (Left, Right) then return False; -- Deal with case of one or other operand is No_Ureal, but not both elsif Same (Left, No_Ureal) or else Same (Right, No_Ureal) then return True; -- Do quick check based on number of decimal digits elsif Decimal_Exponent_Hi (Left) < Decimal_Exponent_Lo (Right) or else Decimal_Exponent_Lo (Left) > Decimal_Exponent_Hi (Right) then return True; -- Otherwise full comparison is required else declare Imrk : constant Uintp.Save_Mark := Mark; Rmrk : constant Urealp.Save_Mark := Mark; Lval : constant Ureal_Entry := Normalize (Ureals.Table (Left)); Rval : constant Ureal_Entry := Normalize (Ureals.Table (Right)); Result : Boolean; begin if UR_Is_Zero (Left) then return not UR_Is_Zero (Right); elsif UR_Is_Zero (Right) then return not UR_Is_Zero (Left); -- Both operands are non-zero else Result := Rval.Negative /= Lval.Negative or else Rval.Num /= Lval.Num or else Rval.Den /= Lval.Den; Release (Imrk); Release (Rmrk); return Result; end if; end; end if; end UR_Ne; --------------- -- UR_Negate -- --------------- function UR_Negate (Real : Ureal) return Ureal is begin return Store_Ureal ((Num => Ureals.Table (Real).Num, Den => Ureals.Table (Real).Den, Rbase => Ureals.Table (Real).Rbase, Negative => not Ureals.Table (Real).Negative)); end UR_Negate; ------------ -- UR_Sub -- ------------ function UR_Sub (Left : Uint; Right : Ureal) return Ureal is begin return UR_From_Uint (Left) + UR_Negate (Right); end UR_Sub; function UR_Sub (Left : Ureal; Right : Uint) return Ureal is begin return Left + UR_From_Uint (-Right); end UR_Sub; function UR_Sub (Left, Right : Ureal) return Ureal is begin return Left + UR_Negate (Right); end UR_Sub; ---------------- -- UR_To_Uint -- ---------------- function UR_To_Uint (Real : Ureal) return Uint is Val : constant Ureal_Entry := Normalize (Ureals.Table (Real)); Res : Uint; begin Res := (Val.Num + (Val.Den / 2)) / Val.Den; if Val.Negative then return UI_Negate (Res); else return Res; end if; end UR_To_Uint; -------------- -- UR_Trunc -- -------------- function UR_Trunc (Real : Ureal) return Uint is Val : constant Ureal_Entry := Normalize (Ureals.Table (Real)); begin if Val.Negative then return -(Val.Num / Val.Den); else return Val.Num / Val.Den; end if; end UR_Trunc; -------------- -- UR_Write -- -------------- procedure UR_Write (Real : Ureal; Brackets : Boolean := False) is Val : constant Ureal_Entry := Ureals.Table (Real); T : Uint; begin -- If value is negative, we precede the constant by a minus sign if Val.Negative then Write_Char ('-'); end if; -- Zero is zero if Val.Num = 0 then Write_Str (""0.0""); -- For constants with a denominator of zero, the value is simply the -- numerator value, since we are dividing by base**0, which is 1. elsif Val.Den = 0 then UI_Write (Val.Num, Decimal); Write_Str ("".0""); -- Small powers of 2 get written in decimal fixed-point format elsif Val.Rbase = 2 and then Val.Den <= 3 and then Val.Den >= -16 then if Val.Den = 1 then T := Val.Num * (10/2); UI_Write (T / 10, Decimal); Write_Char ('.'); UI_Write (T mod 10, Decimal); elsif Val.Den = 2 then T := Val.Num * (100/4); UI_Write (T / 100, Decimal); Write_Char ('.'); UI_Write (T mod 100 / 10, Decimal); if T mod 10 /= 0 then UI_Write (T mod 10, Decimal); end if; elsif Val.Den = 3 then T := Val.Num * (1000 / 8); UI_Write (T / 1000, Decimal); Write_Char ('.'); UI_Write (T mod 1000 / 100, Decimal); if T mod 100 /= 0 then UI_Write (T mod 100 / 10, Decimal); if T mod 10 /= 0 then UI_Write (T mod 10, Decimal); end if; end if; else UI_Write (Val.Num * (Uint_2 ** (-Val.Den)), Decimal); Write_Str ("".0""); end if; -- Constants in base 10 or 16 can be written in normal Ada literal -- style, as long as they fit in the UI_Image_Buffer. Using hexadecimal -- notation, 4 bytes are required for the 16# # part, and every fifth -- character is an underscore. So, a buffer of size N has room for -- ((N - 4) - (N - 4) / 5) * 4 bits, -- or at least -- N * 16 / 5 - 12 bits. elsif (Val.Rbase = 10 or else Val.Rbase = 16) and then Num_Bits (Val.Num) < UI_Image_Buffer'Length * 16 / 5 - 12 then pragma Assert (Val.Den /= 0); -- Use fixed-point format for small scaling values if (Val.Rbase = 10 and then Val.Den < 0 and then Val.Den > -3) or else (Val.Rbase = 16 and then Val.Den = -1) then UI_Write (Val.Num * Val.Rbase**(-Val.Den), Decimal); Write_Str ("".0""); -- Write hexadecimal constants in exponential notation with a zero -- unit digit. This matches the Ada canonical form for floating point -- numbers, and also ensures that the underscores end up in the -- correct place. elsif Val.Rbase = 16 then UI_Image (Val.Num, Hex); pragma Assert (Val.Rbase = 16); Write_Str (""16#0.""); Write_Str (UI_Image_Buffer (4 .. UI_Image_Length)); -- For exponent, exclude 16# # and underscores from length UI_Image_Length := UI_Image_Length - 4; UI_Image_Length := UI_Image_Length - UI_Image_Length / 5; Write_Char ('E'); UI_Write (Int (UI_Image_Length) - Val.Den, Decimal); elsif Val.Den = 1 then UI_Write (Val.Num / 10, Decimal); Write_Char ('.'); UI_Write (Val.Num mod 10, Decimal); elsif Val.Den = 2 then UI_Write (Val.Num / 100, Decimal); Write_Char ('.'); UI_Write (Val.Num / 10 mod 10, Decimal); UI_Write (Val.Num mod 10, Decimal); -- Else use decimal exponential format else -- Write decimal constants with a non-zero unit digit. This -- matches usual scientific notation. UI_Image (Val.Num, Decimal); Write_Char (UI_Image_Buffer (1)); Write_Char ('.'); if UI_Image_Length = 1 then Write_Char ('0'); else Write_Str (UI_Image_Buffer (2 .. UI_Image_Length)); end if; Write_Char ('E'); UI_Write (Int (UI_Image_Length - 1) - Val.Den, Decimal); end if; -- Constants in a base other than 10 can still be easily written in -- normal Ada literal style if the numerator is one. elsif Val.Rbase /= 0 and then Val.Num = 1 then Write_Int (Val.Rbase); Write_Str (""#1.0#E""); UI_Write (-Val.Den); -- Other constants with a base other than 10 are written using one -- of the following forms, depending on the sign of the number -- and the sign of the exponent (= minus denominator value) -- numerator.0*base**exponent -- numerator.0*base**-exponent -- And of course an exponent of 0 can be omitted elsif Val.Rbase /= 0 then if Brackets then Write_Char ('['); end if; UI_Write (Val.Num, Decimal); Write_Str ("".0""); if Val.Den /= 0 then Write_Char ('*'); Write_Int (Val.Rbase); Write_Str (""**""); if Val.Den <= 0 then UI_Write (-Val.Den, Decimal); else Write_Str (""(-""); UI_Write (Val.Den, Decimal); Write_Char (')'); end if; end if; if Brackets then Write_Char (']'); end if; -- Rationals where numerator is divisible by denominator can be output -- as literals after we do the division. This includes the common case -- where the denominator is 1. elsif Val.Num mod Val.Den = 0 then UI_Write (Val.Num / Val.Den, Decimal); Write_Str ("".0""); -- Other non-based (rational) constants are written in num/den style else if Brackets then Write_Char ('['); end if; UI_Write (Val.Num, Decimal); Write_Str ("".0/""); UI_Write (Val.Den, Decimal); Write_Str ("".0""); if Brackets then Write_Char (']'); end if; end if; end UR_Write; ------------- -- Ureal_0 -- ------------- function Ureal_0 return Ureal is begin return UR_0; end Ureal_0; ------------- -- Ureal_1 -- ------------- function Ureal_1 return Ureal is begin return UR_1; end Ureal_1; ------------- -- Ureal_2 -- ------------- function Ureal_2 return Ureal is begin return UR_2; end Ureal_2; -------------- -- Ureal_10 -- -------------- function Ureal_10 return Ureal is begin return UR_10; end Ureal_10; --------------- -- Ureal_100 -- --------------- function Ureal_100 return Ureal is begin return UR_100; end Ureal_100; ----------------- -- Ureal_10_36 -- ----------------- function Ureal_10_36 return Ureal is begin return UR_10_36; end Ureal_10_36; ---------------- -- Ureal_2_80 -- ---------------- function Ureal_2_80 return Ureal is begin return UR_2_80; end Ureal_2_80; ----------------- -- Ureal_2_128 -- ----------------- function Ureal_2_128 return Ureal is begin return UR_2_128; end Ureal_2_128; ------------------- -- Ureal_2_M_80 -- ------------------- function Ureal_2_M_80 return Ureal is begin return UR_2_M_80; end Ureal_2_M_80; ------------------- -- Ureal_2_M_128 -- ------------------- function Ureal_2_M_128 return Ureal is begin return UR_2_M_128; end Ureal_2_M_128; ---------------- -- Ureal_Half -- ---------------- function Ureal_Half return Ureal is begin return UR_Half; end Ureal_Half; --------------- -- Ureal_M_0 -- --------------- function Ureal_M_0 return Ureal is begin return UR_M_0; end Ureal_M_0; ------------------- -- Ureal_M_10_36 -- ------------------- function Ureal_M_10_36 return Ureal is begin return UR_M_10_36; end Ureal_M_10_36; ----------------- -- Ureal_Tenth -- ----------------- function Ureal_Tenth return Ureal is begin return UR_Tenth; end Ureal_Tenth; end Urealp; ",12448,True,2542.208950711676,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. //// anchor:gremlin-variants[] [[gremlin-drivers-variants]] = Gremlin Drivers and Variants image::gremlin-house-of-mirrors.png[width=1024] At this point, readers should be well familiar with the <> to this Reference Documentation and will likely be thinking about implementation details specific to the graph provider they have selected as well as the programming language they intend to use. The choice of programming language could have implications to the architecture and design of the application and the choice itself may have limits imposed upon it by the chosen graph provider. For example, a <> will require the selection of a driver to interact with it. On the other hand, a graph system that is designed for embedded use, like TinkerGraph, needs the Java Virtual Machine (JVM) environment so will require <>, if using a programming language that is not on the JVM and will further require driver selection. TinkerPop provides an array of drivers in different programming languages as a way to connect to a remote Gremlin Server or Remote Gremlin Provider. Drivers allow the developer to make requests to that remote system and get back results from the TinkerPop-enabled graphs hosted within. A driver can submit Gremlin strings and Gremlin bytecode over this sub-protocol. Gremlin strings are written in the scripting language made available by the remote system that the driver is connecting to (typically, Groovy-based). This connection approach is quite similar to what developers are likely familiar with when using JDBC and SQL. While it is familiar, it is not recommended and for TinkerPop it is considered an out-dated concept and is largely still present for the purpose of supporting applications that might still be using that method of interaction. The preferred approach is to use bytecode-based requests, which essentially allows the ability to craft Gremlin directly in the programming language of choice. As Gremlin makes use of two fundamental programming constructs: link:https://en.wikipedia.org/wiki/Function_composition[function composition] and link:https://en.wikipedia.org/wiki/Nested_function[function nesting]. it is possible to embed the Gremlin language in any modern programming language. It is a far more natural way to program, because it enables IDE interaction, compile time checks, and language level checks that can help prevent errors prior to execution. The differences between these two approaches were outlined in the <> Section, which applies to Gremlin Server, but also to Remote Gremlin Providers. In addition to the languages and drivers that TinkerPop supports, there are also third-party implementations, as well as extensions to the Gremlin language that might be specific to a particular graph provider. That listing can be found on the TinkerPop link:https://tinkerpop.apache.org/#graph-systems[home page]. Their description is beyond the scope of this documentation. TIP: When possible, it is typically best to align the version of TinkerPop used on the client with the version supported on the server. While it is not impossible to have a different version between client and server, it may require additional configuration and/or a deeper knowledge of that changes introduced between versions. It's simply safer to avoid the conflict, when allowed to do so. IMPORTANT: Gremlin-Java is the canonical representation of Gremlin and any (proper) Gremlin language variant will emulate its structure as best as possible given the constructs of the host language. A strong correspondence between variants ensures that the general Gremlin reference documentation is applicable to all variants and that users moving between development languages can easily adopt the Gremlin variant for that language. image::gremlin-variant-architecture.png[width=650,float=left] NOTE: The information herein describes how to use the Gremlin language variants distributed with Apache TinkerPop. For information on how to build a Gremlin language variant, please review the link:https://tinkerpop.apache.org/docs/x.y.z/tutorials/gremlin-language-variants/[Gremlin Language Variants] tutorial. The following sections describe each language variant and driver that is officially TinkerPop a part of the project, provided more detailed information about usage, configuration and known limitations. anchor:connecting-via-remotegraph[] anchor:connecting-via-java[] [[gremlin-java]] == Gremlin-Java image:gremlin-java-drawing.png[width=130,float=right] Apache TinkerPop's Gremlin-Java implements Gremlin within the Java language and can be used by any Java Virtual Machine. Gremlin-Java is considered the canonical, reference implementation of Gremlin and serves as the foundation by which all other Gremlin language variants should emulate. As the Gremlin Traversal Machine that processes Gremlin queries is also written in Java, it can be used in all three connection methods described in the <> Section. [source,xml] ---- org.apache.tinkerpop gremlin-core x.y.z org.apache.tinkerpop gremlin-driver x.y.z ---- === Connecting The pattern for connecting is described in <> and it basically distills down to creating a `GraphTraversalSource`. For <> mode, this involves first creating a `Graph` and then spawning the `GraphTraversalSource`: [source,java] ---- Graph graph = ...; GraphTraversalSource g = graph.traversal(); ---- Using ""g"" it is then possible to start writing Gremlin. The ""g"" allows for the setting of many configuration options which affect traversal execution. The <> Section describes some of these options and some are only suitable with <> style usage. For remote options however there are some added configurations to consider and this section looks to address those. When connecting to <> or <> it is possible to configure the `DriverRemoteConnection` manually as shown in earlier examples where the host and port are provided as follows: [source,java] ---- GraphTraversalSource g = traversal().withRemote(DriverRemoteConnection.using(""localhost"",8182,""g"")); ---- It is also possible to create it from a configuration. The most basic way to do so involves the following line of code: [source,java] ---- GraphTraversalSource g = traversal().withRemote('conf/remote-graph.properties'); ---- The `remote-graph.properties` file simply provides connection information to the `GraphTraversalSource` which is used to configure a `RemoteConnection`. That file looks like this: [source,text] ---- gremlin.remote.remoteConnectionClass=org.apache.tinkerpop.gremlin.driver.remote.DriverRemoteConnection gremlin.remote.driver.clusterFile=conf/remote-objects.yaml gremlin.remote.driver.sourceName=g ---- The `RemoteConnection` is an interface that provides the transport mechanism for ""g"" and makes it possible to for that mechanism to be altered (typically by graph providers who have their own protocols). TinkerPop provides one such implementation called the `DriverRemoteConnection` which enables transport over Gremlin Server protocols using the TinkerPop driver. The driver is configured by the specified `gremlin.remote.driver.clusterFile` and the local ""g"" is bound to the `GraphTraversalSource` on the remote end with `gremlin.remote.driver.sourceName` which in this case is also ""g"". There are other ways to configure the traversal using `withRemote()` as it has other overloads. It can take an Apache Commons `Configuration` object which would have keys similar to those shown in the properties file and it can also take a `RemoteConnection` instance directly. The latter is interesting in that it means it is possible to programmatically construct all aspects of the `RemoteConnection`. For TinkerPop usage, that might mean directly constructing the `DriverRemoteConnection` and the driver instance that supplies the transport mechanism. For example, the command shown above could be re-written using programmatic construction as follows: [source,java] ---- Cluster cluster = Cluster.open(); GraphTraversalSource g = traversal().withRemote(DriverRemoteConnection.using(cluster, ""g"")); ---- Please consider the following example: [gremlin-groovy] ---- g = traversal().withRemote('conf/remote-graph.properties') g.V().elementMap() g.close() ---- [source,java] ---- GraphTraversalSource g = traversal().withRemote(""conf/remote-graph.properties""); List list = g.V().elementMap(); g.close(); ---- Note the call to `close()` above. The call to `withRemote()` internally instantiates a connection via the driver that can only be released by ""closing"" the `GraphTraversalSource`. It is important to take that step to release resources created in that step. If working with multiple remote `TraversalSource` instances it is more efficient to construct `Cluster` and `Client objects and then re-use them. [gremlin-groovy] ---- cluster = Cluster.open('conf/remote-objects.yaml') client = cluster.connect() g = traversal().withRemote(DriverRemoteConnection.using(client, ""g"")) g.V().elementMap() g.close() client.close() cluster.close() ---- If the `Client` instance is supplied externally, as is shown above, then it is not closed implicitly by the close of ""g"". Closing ""g"" will have no effect on ""client"" or ""cluster"". When supplying them externally, the `Client` and `Cluster` objects must also be closed explicitly. It's worth noting that the close of a `Cluster` will close all `Client` instances spawned by the `Cluster`. IMPORTANT: Bytecode-based traversals use the `TraversalOpProcessor` in Gremlin Server which requires a cache to enable the retrieval of side-effects (if the `Traversal` produces any). That cache can be configured (e.g. controlling eviction times and sizing) in the Gremlin Server configuration file as described <>. Some connection options can also be set on individual requests made through the Java driver using `with()` step on the `TraversalSource`. For instance to set request timeout to 500 milliseconds: [source,java] ---- GraphTraversalSource g = traversal().withRemote(conf); List vertices = g.with(Tokens.ARGS_EVAL_TIMEOUT, 500L).V().out(""knows"").toList() ---- [[java-imports]] === Common Imports There are a number of classes, functions and tokens that are typically used with Gremlin. The following imports provide most of the common functionality required to use Gremlin: [source,java] ---- import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; import org.apache.tinkerpop.gremlin.process.traversal.IO; import static org.apache.tinkerpop.gremlin.process.traversal.AnonymousTraversalSource.traversal; import static org.apache.tinkerpop.gremlin.process.traversal.Operator.*; import static org.apache.tinkerpop.gremlin.process.traversal.Order.*; import static org.apache.tinkerpop.gremlin.process.traversal.P.*; import static org.apache.tinkerpop.gremlin.process.traversal.Pop.*; import static org.apache.tinkerpop.gremlin.process.traversal.SackFunctions.*; import static org.apache.tinkerpop.gremlin.process.traversal.Scope.*; import static org.apache.tinkerpop.gremlin.process.traversal.TextP.*; import static org.apache.tinkerpop.gremlin.structure.Column.*; import static org.apache.tinkerpop.gremlin.structure.Direction.*; import static org.apache.tinkerpop.gremlin.structure.T.*; import static org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__.*; ---- === Configuration The following table describes the various configuration options for the Gremlin Driver: [width=""100%"",cols=""3,10,^2"",options=""header""] |========================================================= |Key |Description |Default |connectionPool.channelizer |The fully qualified classname of the client `Channelizer` that defines how to connect to the server. |`Channelizer.WebSocketChannelizer` |connectionPool.enableSsl |Determines if SSL should be enabled or not. If enabled on the server then it must be enabled on the client. |false |connectionPool.keepAliveInterval |Length of time in milliseconds to wait on an idle connection before sending a keep-alive request. Set to zero to disable this feature. |180000 |connectionPool.keyStore |The private key in JKS or PKCS#12 format. |_none_ |connectionPool.keyStorePassword |The password of the `keyStore` if it is password-protected. |_none_ |connectionPool.keyStoreType |`JKS` (Java 8 default) or `PKCS12` (Java 9+ default)|_none_ |connectionPool.maxContentLength |The maximum length in bytes that a message can be sent to the server. This number can be no greater than the setting of the same name in the server configuration. |65536 |connectionPool.maxInProcessPerConnection |The maximum number of in-flight requests that can occur on a connection. |4 |connectionPool.maxSimultaneousUsagePerConnection |The maximum number of times that a connection can be borrowed from the pool simultaneously. |16 |connectionPool.maxSize |The maximum size of a connection pool for a host. |8 |connectionPool.maxWaitForConnection |The amount of time in milliseconds to wait for a new connection before timing out. |3000 |connectionPool.maxWaitForClose |The amount of time in milliseconds to wait for pending messages to be returned from the server before closing the connection. |3000 |connectionPool.minInProcessPerConnection |The minimum number of in-flight requests that can occur on a connection. |1 |connectionPool.minSimultaneousUsagePerConnection |The maximum number of times that a connection can be borrowed from the pool simultaneously. |8 |connectionPool.minSize |The minimum size of a connection pool for a host. |2 |connectionPool.reconnectInterval |The amount of time in milliseconds to wait before trying to reconnect to a dead host. |1000 |connectionPool.resultIterationBatchSize |The override value for the size of the result batches to be returned from the server. |64 |connectionPool.sslCipherSuites |The list of JSSE ciphers to support for SSL connections. If specified, only the ciphers that are listed and supported will be enabled. If not specified, the JVM default is used. |_none_ |connectionPool.sslEnabledProtocols |The list of SSL protocols to support for SSL connections. If specified, only the protocols that are listed and supported will be enabled. If not specified, the JVM default is used. |_none_ |connectionPool.sslSkipCertValidation |Configures the `TrustManager` to trust all certs without any validation. Should not be used in production.|false |connectionPool.trustStore |File location for a SSL Certificate Chain to use when SSL is enabled. If this value is not provided and SSL is enabled, the default `TrustManager` will be used. |_none_ |connectionPool.trustStorePassword |The password of the `trustStore` if it is password-protected |_none_ |connectionPool.validationRequest |A script that is used to test server connectivity. A good script to use is one that evaluates quickly and returns no data. The default simply returns an empty string, but if a graph is required by a particular provider, a good traversal might be `g.inject()`. |_''_ |hosts |The list of hosts that the driver will connect to. |localhost |jaasEntry |Sets the `AuthProperties.Property.JAAS_ENTRY` properties for authentication to Gremlin Server. |_none_ |nioPoolSize |Size of the pool for handling request/response operations. |available processors |password |The password to submit on requests that require authentication. |_none_ |path |The URL path to the Gremlin Server. |_/gremlin_ |port |The port of the Gremlin Server to connect to. The same port will be applied for all hosts. |8192 |protocol |Sets the `AuthProperties.Property.PROTOCOL` properties for authentication to Gremlin Server. |_none_ |serializer.className |The fully qualified class name of the `MessageSerializer` that will be used to communicate with the server. Note that the serializer configured on the client should be supported by the server configuration. |_none_ |serializer.config |A `Map` of configuration settings for the serializer. |_none_ |username |The username to submit on requests that require authentication. |_none_ |workerPoolSize |Size of the pool for handling background work. |available processors * 2 |========================================================= Please see the link:https://tinkerpop.apache.org/javadocs/x.y.z/core/org/apache/tinkerpop/gremlin/driver/Cluster.Builder.html[Cluster.Builder javadoc] to get more information on these settings. === Serialization Remote systems like Gremlin Server and Remote Gremlin Providers respond to requests made in a particular serialization format and respond by serializing results to some format to be interpreted by the client. For JVM-based languages, there are three options for serialization: Gryo, GraphSON and GraphBinary. It is important that the client and server have the same serializers configured in the same way or else one or the other will experience serialization exceptions and fail to always communicate. Discrepancy in serializer registration between client and server can happen fairly easily as different graph systems may automatically include serializers on the server-side, thus leaving the client to be configured manually. As an example: [source,java] ---- IoRegistry registry = ...; // an IoRegistry instance exposed by a specific graph provider TypeSerializerRegistry typeSerializerRegistry = TypeSerializerRegistry.build().addRegistry(registry).create(); MessageSerializer serializer = new GraphBinaryMessageSerializerV1(typeSerializerRegistry); Cluster cluster = Cluster.build(). serializer(serializer). create(); Client client = cluster.connect(); GraphTraversalSource g = traversal().withRemote(DriverRemoteConnection.using(client, ""g"")); ---- The `IoRegistry` tells the serializer what classes from the graph provider to auto-register during serialization. Gremlin Server roughly uses this same approach when it configures its serializers, so using this same model will ensure compatibility when making requests. Obviously, it is possible to switch to GraphSON or Gryo by using the appropriate `MessageSerializer` (e.g. `GraphSONMessageSerializerV3d0` or `GryoMessageSerializerV3d0` respectively) in the same way and building that into the `Cluster` object. NOTE: Gryo is no longer the preferred binary serialization format for Gremlin Server - please prefer GraphBinary. === The Lambda Solution Supporting link:https://en.wikipedia.org/wiki/Anonymous_function[anonymous functions] across languages is difficult as most languages do not support lambda introspection and thus, code analysis. In Gremlin-Java and with <> usage, lambdas can be leveraged directly: [source,java] ---- g.V().out(""knows"").map(t -> t.get().value(""name"") + "" is the friend name"") <1> g.V().out(""knows"").sideEffect(System.out::println) <2> g.V().as(""a"").out(""knows"").as(""b"").select(""b"").by((Function) v -> v.value(""name"").length()) <3> ---- <1> A Java `Function` is used to map a `Traverser` to an object `E`. <2> Gremlin steps that take consumer arguments can be passed Java method references. <3> Gremlin-Java may sometimes require explicit lambda typing when types can not be automatically inferred. When sending traversals remotely to <> or <>, the static methods of `Lambda` should be used and should denote a particular JSR-223 `ScriptEngine` that is available on the remote end (typically, this is Groovy). `Lambda` creates a string-based lambda that is then converted into a lambda/closure/anonymous-function/etc. by the respective lambda language's JSR-223 `ScriptEngine` implementation. [source,java] ---- g.V().out(""knows"").map(Lambda.function(""it.get().value('name') + ' is the friend name'"")) g.V().out(""knows"").sideEffect(Lambda.consumer(""println it"")) g.V().as(""a"").out(""knows"").as(""b"").select(""b"").by(Lambda.function(""it.value('name').length()"")) ---- Finally, Gremlin `Bytecode` that includes lambdas requires that the traversal be processed by the `ScriptEngine`. To avoid continued recompilation costs, it supports the encoding of bindings, which allow Gremlin Server to cache traversals that will be reused over and over again save that some parameterization may change. Thus, instead of translating, compiling, and then executing each submitted bytecode request, it is possible to simply execute. To express bindings in Java, use `Bindings`. [source,java] ---- b = Bindings.instance() g.V(b.of('id',1)).out('created').values('name').map{t -> ""name: "" + t.get() } g.V(b.of('id',4)).out('created').values('name').map{t -> ""name: "" + t.get() } g.V(b.of('id',4)).out('created').values('name').getBytecode() g.V(b.of('id',4)).out('created').values('name').getBytecode().getBindings() cluster.close() ---- Both traversals are abstractly defined as `g.V(id).out('created').values('name').map{t -> ""name: "" + t.get() }` and thus, the first submission can be cached for faster evaluation on the next submission. WARNING: It is generally advised to avoid lambda usage. Please consider <> for more information. === Submitting Scripts WARNING: TinkerPop does not recommend submitting script-based requests and generally continues to support this feature for legacy reasons and corner use cases which are still not completely addressed by the Gremlin language. Please consider using bytecode-based requests instead when possible. image:gremlin-java.png[width=175,float=left] TinkerPop comes equipped with a reference client for Java-based applications. It is referred to as `gremlin-driver`, which enables applications to send requests to Gremlin Server and get back results. Gremlin scripts are sent to the server from a `Client` instance. A `Client` is created as follows: [source,java] ---- Cluster cluster = Cluster.open(); <1> Client client = cluster.connect(); <2> ---- <1> Opens a reference to `localhost` - note that there are many configuration options available in defining a `Cluster` object. <2> Creates a `Client` given the configuration options of the `Cluster`. Once a `Client` instance is ready, it is possible to issue some Gremlin Groovy scripts: [source,java] ---- ResultSet results = client.submit(""[1,2,3,4]""); <1> results.stream().map(i -> i.get(Integer.class) * 2); <2> CompletableFuture> results = client.submit(""[1,2,3,4]"").all(); <3> CompletableFuture future = client.submitAsync(""[1,2,3,4]""); <4> Map params = new HashMap<>(); params.put(""x"",4); client.submit(""[1,2,3,x]"", params); <5> ---- <1> Submits a script that simply returns a `List` of integers. This method blocks until the request is written to the server and a `ResultSet` is constructed. <2> Even though the `ResultSet` is constructed, it does not mean that the server has sent back the results (or even evaluated the script potentially). The `ResultSet` is just a holder that is awaiting the results from the server. In this case, they are streamed from the server as they arrive. <3> Submit a script, get a `ResultSet`, then return a `CompletableFuture` that will be called when all results have been returned. <4> Submit a script asynchronously without waiting for the request to be written to the server. <5> Parameterized request are considered the most efficient way to send Gremlin to the server as they can be cached, which will boost performance and reduce resources required on the server. ==== Per Request Settings There are a number of overloads to `Client.submit()` that accept a `RequestOptions` object. The `RequestOptions` provide a way to include options that are specific to the request made with the call to `submit()`. A good use-case for this feature is to set a per-request override to the `evaluationTimeout` so that it only applies to the current request. [source,java] ---- Cluster cluster = Cluster.open(); Client client = cluster.connect(); RequestOptions options = RequestOptions.build().timeout(500).create(); List result = client.submit(""g.V()"", options).all().get(); ---- ==== Aliases Scripts submitted to Gremlin Server automatically have the globally configured `Graph` and `TraversalSource` instances made available to them. Therefore, if Gremlin Server configures two `TraversalSource` instances called ""g1"" and ""g2"" a script can simply reference them directly as: [source,java] ---- client.submit(""g1.V()"") client.submit(""g2.V()"") ---- While this is an acceptable way to submit scripts, it has the downside of forcing the client to encode the server-side variable name directly into the script being sent. If the server configuration ever changed such that ""g1"" became ""g100"", the client-side code might have to see a significant amount of change. Decoupling the script code from the server configuration can be managed by the `alias` method on `Client` as follows: [source,java] ---- Client g1Client = client.alias(""g1"") Client g2Client = client.alias(""g2"") g1Client.submit(""g.V()"") g2Client.submit(""g.V()"") ---- The above code demonstrates how the `alias` method can be used such that the script need only contain a reference to ""g"" and ""g1"" and ""g2"" are automatically rebound into ""g"" on the server-side. [[gremlin-java-dsl]] === Domain Specific Languages Creating a <> (DSL) in Java requires the `@GremlinDsl` Java annotation in `gremlin-core`. This annotation should be applied to a ""DSL interface"" that extends `GraphTraversal.Admin`: [source,java] ---- @GremlinDsl public interface SocialTraversalDsl extends GraphTraversal.Admin { } ---- IMPORTANT: The name of the DSL interface should be suffixed with ""TraversalDSL"". All characters in the interface name before that become the ""name"" of the DSL. In this interface, define the methods that the DSL will be composed of: [source,java] ---- @GremlinDsl public interface SocialTraversalDsl extends GraphTraversal.Admin { public default GraphTraversal knows(String personName) { return out(""knows"").hasLabel(""person"").has(""name"", personName); } public default GraphTraversal youngestFriendsAge() { return out(""knows"").hasLabel(""person"").values(""age"").min(); } public default GraphTraversal createdAtLeast(int number) { return outE(""created"").count().is(P.gte(number)); } } ---- IMPORTANT: Follow the TinkerPop convention of using `` in naming generics as those conventions are taken into account when generating the anonymous traversal class. The processor attempts to infer the appropriate type parameters when generating the anonymous traversal class. If it cannot do it correctly, it is possible to avoid the inference by using the `GremlinDsl.AnonymousMethod` annotation on the DSL method. It allows explicit specification of the types to use. The `@GremlinDsl` annotation is used by the link:https://docs.oracle.com/javase/8/docs/api/index.html?javax/annotation/processing/Processor.html[Java Annotation Processor] to generate the boilerplate class structure required to properly use the DSL within the TinkerPop framework. These classes can be generated and maintained by hand, but it would be time consuming, monotonous and error-prone to do so. Typically, the Java compilation process is automatically configured to detect annotation processors on the classpath and will automatically use them when found. If that does not happen, it may be necessary to make configuration changes to the build to allow for the compilation process to be aware of the following `javax.annotation.processing.Processor` implementation: [source,java] ---- org.apache.tinkerpop.gremlin.process.traversal.dsl.GremlinDslProcessor ---- The annotation processor will generate several classes for the DSL: * `SocialTraversal` - A `Traversal` interface that extends the `SocialTraversalDsl` proxying methods to its underlying interfaces (such as `GraphTraversal`) to instead return a `SocialTraversal` * `DefaultSocialTraversal` - A default implementation of `SocialTraversal` (typically not used directly by the user) * `SocialTraversalSource` - Spawns `DefaultSocialTraversal` instances. * `__` - Spawns anonymous `DefaultSocialTraversal` instances. Using the DSL then just involves telling the `Graph` to use it: [source,java] ---- SocialTraversalSource social = graph.traversal(SocialTraversalSource.class); social.V().has(""name"",""marko"").knows(""josh""); ---- The `SocialTraversalSource` can also be customized with DSL functions. As an additional step, include a class that extends from `GraphTraversalSource` and with a name that is suffixed with ""TraversalSourceDsl"". Include in this class, any custom methods required by the DSL: [source,java] ---- public class SocialTraversalSourceDsl extends GraphTraversalSource { public SocialTraversalSourceDsl(Graph graph, TraversalStrategies traversalStrategies) { super(graph, traversalStrategies); } public SocialTraversalSourceDsl(Graph graph) { super(graph); } public GraphTraversal persons(String... names) { GraphTraversalSource clone = this.clone(); // Manually add a ""start"" step for the traversal in this case the equivalent of V(). GraphStep is marked // as a ""start"" step by passing ""true"" in the constructor. clone.getBytecode().addStep(GraphTraversal.Symbols.V); GraphTraversal traversal = new DefaultGraphTraversal<>(clone); traversal.asAdmin().addStep(new GraphStep<>(traversal.asAdmin(), Vertex.class, true)); traversal = traversal.hasLabel(""person""); if (names.length > 0) traversal = traversal.has(""name"", P.within(names)); return traversal; } } ---- Then, back in the `SocialTraversal` interface, update the `GremlinDsl` annotation with the `traversalSource` argument to point to the fully qualified class name of the `SocialTraversalSourceDsl`: [source,java] ---- @GremlinDsl(traversalSource = ""com.company.SocialTraversalSourceDsl"") public interface SocialTraversalDsl extends GraphTraversal.Admin { ... } ---- It is then possible to use the `persons()` method to start traversals: [source,java] ---- SocialTraversalSource social = graph.traversal(SocialTraversalSource.class); social.persons(""marko"").knows(""josh""); ---- NOTE: Using Maven, as shown in the `gremlin-archetype-dsl` module, makes developing DSLs with the annotation processor straightforward in that it sets up appropriate paths to the generated code automatically. anchor:java-application-examples[] [[gremlin-archetypes]] === Application Examples The available link:https://maven.apache.org/guides/introduction/introduction-to-archetypes.html[Maven archetypes] are as follows: * `gremlin-archetype-dsl` - An example project that demonstrates how to build Domain Specific Languages with Gremlin in Java. * `gremlin-archetype-server` - An example project that demonstrates the basic structure of a <> project, how to connect with the Gremlin Driver, and how to embed Gremlin Server in a testing framework. * `gremlin-archetype-tinkergraph` - A basic example of how to structure a TinkerPop project with Maven. Use Maven to generate these example projects with a command like: [source,shell] $ mvn archetype:generate -DarchetypeGroupId=org.apache.tinkerpop -DarchetypeArtifactId=gremlin-archetype-server \\ -DarchetypeVersion=x.y.z -DgroupId=com.my -DartifactId=app -Dversion=0.1 -DinteractiveMode=false This command will generate a new Maven project in a directory called ""app"" with a `pom.xml` specifying a `groupId` of `com.my`. Please see the `README.asciidoc` in the root of each generated project for information on how to build and execute it. [[gremlin-groovy]] == Gremlin-Groovy image:gremlin-groovy-drawing.png[width=130,float=right] Apache TinkerPop's Gremlin-Groovy implements Gremlin within the link:http://groovy.apache.org[Apache Groovy] language. As a JVM-based language variant, Gremlin-Groovy is backed by Gremlin-Java constructs. Moreover, given its scripting nature, Gremlin-Groovy serves as the language of <> and <>. [source,groovy] ---- compile group: 'org.apache.tinkerpop', name: 'gremlin-core', version: '3.3.4' compile group: 'org.apache.tinkerpop', name: 'gremlin-driver', version: '3.3.4' ---- [[gremlin-groovy-differences]] === Differences In Groovy, `as`, `in`, and `not` are reserved words. Gremlin-Groovy does not allow these steps to be called statically from the anonymous traversal `+__+` and therefore, must always be prefixed with `+__.+` For instance: `+g.V().as('a').in().as('b').where(__.not(__.as('a').out().as('b')))+` [[gremlin-python]] == Gremlin-Python image:gremlin-python-drawing.png[width=130,float=right] Apache TinkerPop's Gremlin-Python implements Gremlin within the link:https://www.python.org/[Python] language and can be used on any Python virtual machine including the popular link:https://en.wikipedia.org/wiki/CPython[CPython] machine. Python's syntax has the same constructs as Java including ""dot notation"" for function chaining (`a.b.c`), round bracket function arguments (`a(b,c)`), and support for global namespaces (`a(b())` vs `a(__.b())`). As such, anyone familiar with Gremlin-Java will immediately be able to work with Gremlin-Python. Moreover, there are a few added constructs to Gremlin-Python that make traversals a bit more succinct. To install Gremlin-Python, use Python's link:https://en.wikipedia.org/wiki/Pip_(package_manager)[pip] package manager. [source,bash] ---- pip install gremlinpython ---- === Connecting The pattern for connecting is described in <> and it basically distills down to creating a `GraphTraversalSource`. A `GraphTraversalSource` is created from the anonymous `traversal()` method where the ""g"" provided to the `DriverRemoteConnection` corresponds to the name of a `GraphTraversalSource` on the remote end. [source,python] ---- g = traversal().withRemote(DriverRemoteConnection('ws://localhost:8182/gremlin','g')) ---- If you need to send additional headers in the websockets connection, you can pass an optional `headers` parameter to the `DriverRemoteConnection` constructor. [source,python] ---- g = traversal().withRemote(DriverRemoteConnection('ws://localhost:8182/gremlin','g',headers={'Header':'Value'})) ---- NOTE: If connecting from an inherently single-threaded Python process where blocking while waiting for Gremlin traversals to complete is acceptable, it might be helpful to set `pool_size` and `max_workers` parameters to 1. See the <> section just below. Examples where this could apply are serverless cloud functions or WSGI worker processes. [[python-imports]] === Common Imports There are a number of classes, functions and tokens that are typically used with Gremlin. The following imports provide most of the typical functionality required to use Gremlin: [source,python] ---- from gremlin_python import statics from gremlin_python.process.anonymous_traversal import traversal from gremlin_python.process.graph_traversal import __ from gremlin_python.process.strategies import * from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection from gremlin_python.process.traversal import T from gremlin_python.process.traversal import Order from gremlin_python.process.traversal import Cardinality from gremlin_python.process.traversal import Column from gremlin_python.process.traversal import Direction from gremlin_python.process.traversal import Operator from gremlin_python.process.traversal import P from gremlin_python.process.traversal import Pop from gremlin_python.process.traversal import Scope from gremlin_python.process.traversal import Barrier from gremlin_python.process.traversal import Bindings from gremlin_python.process.traversal import WithOptions ---- These can be used analogously to how they are used in Gremlin-Java. [source,python] ---- >>> g.V().hasLabel('person').has('age',P.gt(30)).order().by('age',Order.desc).toList() [v[6], v[4]] ---- Moreover, by importing the `statics` of Gremlin-Python, the class prefixes can be omitted. [source,python] ---- >>> statics.load_statics(globals()) ---- With statics loaded its possible to represent the above traversal as below. [source,python] ---- >>> g.V().hasLabel('person').has('age',gt(30)).order().by('age',desc).toList() [v[6], v[4]] ---- Finally, statics includes all the `+__+`-methods and thus, anonymous traversals like `+__.out()+` can be expressed as below. That is, without the `+__+`-prefix. [source,python] ---- >>> g.V().repeat(out()).times(2).name.fold().toList() [['ripple', 'lop']] ---- [[python-configuration]] === Configuration The following table describes the various configuration options for the Gremlin-Python Driver. They can be passed to the `Client` or `DriverRemoteConnection` instance as keyword arguments: [width=""100%"",cols=""3,10,^2"",options=""header""] |========================================================= |Key |Description |Default |protocol_factory |A callable that returns an instance of `AbstractBaseProtocol`. |`gremlin_python.driver.protocol.GremlinServerWSProtocol` |transport_factory |A callable that returns an instance of `AbstractBaseTransport`. |`gremlin_python.driver.tornado.transport.TornadoTransport` |pool_size |The number of connections used by the pool. |4 |max_workers |Maximum number of worker threads. |Number of CPUs * 5 |message_serializer |The message serializer implementation.|`gremlin_python.driver.serializer.GraphSONMessageSerializer` |password |The password to submit on requests that require authentication. |"""" |username |The username to submit on requests that require authentication. |"""" |session | A unique string-based identifier (typically a UUID) to enable a <>. This is not a valid configuration for `DriverRemoteConnection`. |None |========================================================= === Traversal Strategies In order to add and remove <> from a traversal source, Gremlin-Python has a `TraversalStrategy` class along with a collection of subclasses that mirror the standard Gremlin-Java strategies. [source,python] ---- >>> g = g.withStrategies(SubgraphStrategy(vertices=hasLabel('person'),edges=has('weight',gt(0.5)))) >>> g.V().name.toList() ['marko', 'vadas', 'josh', 'peter'] >>> g.V().outE().elementMap().toList() [{: 8, : 'knows', : {: 4, : 'person'}, : {: 1, : 'person'}, 'weight': 1.0}] >>> g = g.withoutStrategies(SubgraphStrategy) >>> g.V().name.toList() ['marko', 'vadas', 'lop', 'josh', 'ripple', 'peter'] >>> g.V().outE().elementMap().toList() [{: 9, : 'created', : {: 3, : 'software'}, : {: 1, : 'person'}, 'weight': 0.4}, {: 7, : 'knows', : {: 2, : 'person'}, : {: 1, : 'person'}, 'weight': 0.5}, {: 8, : 'knows', : {: 4, : 'person'}, : {: 1, : 'person'}, 'weight': 1.0}, {: 10, : 'created', : {: 5, : 'software'}, : {: 4, : 'person'}, 'weight': 1.0}, {: 11, : 'created', : {: 3, : 'software'}, : {: 4, : 'person'}, 'weight': 0.4}, {: 12, : 'created', : {: 3, : 'software'}, : {: 6, : 'person'}, 'weight': 0.2}] >>> g = g.withComputer(workers=2,vertices=has('name','marko')) >>> g.V().name.toList() ['marko'] >>> g.V().outE().valueMap().with_(WithOptions.tokens).toList() [{: 9, : 'created', 'weight': 0.4}, {: 7, : 'knows', 'weight': 0.5}, {: 8, : 'knows', 'weight': 1.0}] ---- NOTE: Many of the `TraversalStrategy` classes in Gremlin-Python are proxies to the respective strategy on Apache TinkerPop's JVM-based Gremlin traversal machine. As such, their `apply(Traversal)` method does nothing. However, the strategy is encoded in the Gremlin-Python bytecode and transmitted to the Gremlin traversal machine for re-construction machine-side. === The Lambda Solution Supporting link:https://en.wikipedia.org/wiki/Anonymous_function[anonymous functions] across languages is difficult as most languages do not support lambda introspection and thus, code analysis. In Gremlin-Python, a link:https://docs.python.org/2/reference/expressions.html#lambda[Python lambda] should be represented as a zero-arg callable that returns a string representation of a lambda. The lambda should be written as a `Gremlin-Groovy`string. When the lambda is represented in `Bytecode` its language is encoded such that the remote connection host can infer which translator and ultimate execution engine to use. [source,python] ---- >>> g.V().out().map(lambda: ""it.get().value('name').length()"").sum().toList() [24] ---- TIP: When running into situations where Groovy cannot properly discern a method signature based on the `Lambda` instance created, it will help to fully define the closure in the lambda expression - so rather than `lambda: (""it.get().value(""name')"",""gremlin-groovy"")`, prefer `lambda: (""x -> x.get().value(""name""),""gremlin-groovy"")`. Finally, Gremlin `Bytecode` that includes lambdas requires that the traversal be processed by the `ScriptEngine`. To avoid continued recompilation costs, it supports the encoding of bindings, which allow a remote engine to to cache traversals that will be reused over and over again save that some parameterization may change. Thus, instead of translating, compiling, and then executing each submitted bytecode, it is possible to simply execute. [source,python] ---- >>> g.V(Bindings.of('x',1)).out('created').map(lambda: ""it.get().value('name').length()"").sum().toList() [3] >>> g.V(Bindings.of('x',4)).out('created').map(lambda: ""it.get().value('name').length()"").sum().toList() [9] ---- WARNING: As explained throughout the documentation, when possible <> lambdas. === Submitting Scripts WARNING: TinkerPop does not recommend submitting script-based requests and generally continues to support this feature for legacy reasons and corner use cases which are still not completely addressed by the Gremlin language. Please consider using bytecode-based requests instead when possible. The `Client` class implementation/interface is based on the Java Driver, with some restrictions. Most notably, Gremlin-Python does not yet implement the `Cluster` class. Instead, `Client` is instantiated directly. Usage is as follows: [source,python] ---- from gremlin_python.driver import client <1> client = client.Client('ws://localhost:8182/gremlin', 'g') <2> ---- <1> Import the Gremlin-Python `client` module. <2> Opens a reference to `localhost` - note that there are various configuration options that can be passed to the `Client` object upon instantiation as keyword arguments. Once a `Client` instance is ready, it is possible to issue some Gremlin: [source,python] ---- result_set = client.submit(""[1,2,3,4]"") <1> future_results = result_set.all() <2> results = future_results.result() <3> assert results == [1, 2, 3, 4] <4> future_result_set = client.submitAsync(""[1,2,3,4]"") <5> result_set = future_result_set.result() <6> result = result_set.one() <7> assert results == [1, 2, 3, 4] <8> assert result_set.done.done() <9> client.close() <10> ---- <1> Submit a script that simply returns a `List` of integers. This method blocks until the request is written to the server and a `ResultSet` is constructed. <2> Even though the `ResultSet` is constructed, it does not mean that the server has sent back the results (or even evaluated the script potentially). The `ResultSet` is just a holder that is awaiting the results from the server. The `all` method returns a `concurrent.futures.Future` that resolves to a list when it is complete. <3> Block until the the script is evaluated and results are sent back by the server. <4> Verify the result. <5> Submit the same script to the server but don't block. <6> Wait until request is written to the server and `ResultSet` is constructed. <7> Read a single result off the result stream. <8> Again, verify the result. <9> Verify that the all results have been read and stream is closed. <10> Close client and underlying pool connections. [[gremlin-python-dsl]] === Domain Specific Languages Writing a Gremlin <> (DSL) in Python simply requires direct extension of several classes: * `GraphTraversal` - which exposes the various steps used in traversal writing * `__` - which spawns anonymous traversals from steps * `GraphTraversalSource` - which spawns `GraphTraversal` instances The Social DSL based on the link:https://tinkerpop.apache.org/docs/current/images/tinkerpop-modern.png[""modern"" toy graph] might look like this: [source,python] ---- class SocialTraversal(GraphTraversal): def knows(self, person_name): return self.out(""knows"").hasLabel(""person"").has(""name"", person_name) def youngestFriendsAge(self): return self.out(""knows"").hasLabel(""person"").values(""age"").min() def createdAtLeast(self, number): return self.outE(""created"").count().is_(P.gte(number)) class __(AnonymousTraversal): graph_traversal = SocialTraversal @classmethod def knows(cls, *args): return cls.graph_traversal(None, None, Bytecode()).knows(*args) @classmethod def youngestFriendsAge(cls, *args): return cls.graph_traversal(None, None, Bytecode()).youngestFriendsAge(*args) @classmethod def createdAtLeast(cls, *args): return cls.graph_traversal(None, None, Bytecode()).createdAtLeast(*args) class SocialTraversalSource(GraphTraversalSource): def __init__(self, *args, **kwargs): super(SocialTraversalSource, self).__init__(*args, **kwargs) self.graph_traversal = SocialTraversal def persons(self, *args): traversal = self.get_graph_traversal() traversal.bytecode.add_step(""V"") traversal.bytecode.add_step(""hasLabel"", ""person"") if len(args) > 0: traversal.bytecode.add_step(""has"", ""name"", P.within(args)) return traversal ---- NOTE: The `AnonymousTraversal` class above is just an alias for `+__+` as in `+from gremlin_python.process.graph_traversal import __ as AnonymousTraversal+` Using the DSL is straightforward and just requires that the graph instance know the `SocialTraversalSource` should be used: [source,python] ---- social = Graph().traversal(SocialTraversalSource).withRemote(DriverRemoteConnection('ws://localhost:8182/gremlin','g')) social.persons(""marko"").knows(""josh"") social.persons(""marko"").youngestFriendsAge() social.persons().filter(__.createdAtLeast(2)).count() ---- === Syntactic Sugar Python supports meta-programming and operator overloading. There are three uses of these techniques in Gremlin-Python that makes traversals a bit more concise. [source,python] ---- >>> g.V().both()[1:3].toList() [v[2], v[4]] >>> g.V().both()[1].toList() [v[2]] >>> g.V().both().name.toList() ['lop', 'lop', 'lop', 'vadas', 'josh', 'josh', 'josh', 'marko', 'marko', 'marko', 'peter', 'ripple'] ---- [[gremlin-python-differences]] === Differences In situations where Python reserved words and global functions overlap with standard Gremlin steps and tokens, those bits of conflicting Gremlin get an underscore appended as a suffix: *Steps* - <>, <>, <>, <>, <>, <>, <>, <>, <>, <>, <>, <>, <>, <> *Tokens* - <> === Limitations * Traversals that return a `Set` *might* be coerced to a `List` in Python. In the case of Python, number equality is different from JVM languages which produces different `Set` results when those types are in use. When this case is detected during deserialization, the `Set` is coerced to a `List` so that traversals return consistent results within a collection across different languages. If a `Set` is needed then convert `List` results to `Set` manually. * Gremlin is capable of returning `Dictionary` results that use non-hashable keys (e.g. Dictionary as a key) and Python does not support that at a language level. Gremlin that returns such results will need to be re-written to avoid that. === Application Examples The TinkerPop source code contains a simple Python script that shows a basic example of how gremlinpython works. It can be found in GitHub link:https://github.com/apache/tinkerpop/tree/xx.yy.zz/gremlin-python/src/main/python/example.py[here] and is designed to work best with a running <> configured with the default `conf/gremlin-server.yaml` file as included with the standard release packaging. [source,shell] ---- pip install gremlinpython pip install tornado python example.py ---- anchor:gremlin-DotNet[] [[gremlin-dotnet]] == Gremlin.Net image:gremlin-dotnet-logo.png[width=371,float=right] Apache TinkerPop's Gremlin.Net implements Gremlin within the C# language. It targets .NET Standard and can therefore be used on different operating systems and with different .NET frameworks, such as .NET Framework and link:https://www.microsoft.com/net/core[.NET Core]. Since the C# syntax is very similar to that of Java, it should be very easy to switch between Gremlin-Java and Gremlin.Net. The only major syntactical difference is that all method names in Gremlin.Net use PascalCase as opposed to camelCase in Gremlin-Java in order to comply with .NET conventions. [source,powershell] nuget install Gremlin.Net === Connecting The pattern for connecting is described in <> and it basically distills down to creating a `GraphTraversalSource`. A `GraphTraversalSource` is created from the `AnonymousTraversalSource.traversal()` method where the ""g"" provided to the `DriverRemoteConnection` corresponds to the name of a `GraphTraversalSource` on the remote end. [source,csharp] ---- include::../../../gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Docs/Reference/GremlinVariantsTests.cs[tags=connecting] ---- === Common Imports There are a number of classes, functions and tokens that are typically used with Gremlin. The following imports provide most of the typical functionality required to use Gremlin: [source,csharp] ---- include::../../../gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Docs/Reference/GremlinVariantsTests.cs[tags=commonImports] ---- === Configuration The connection properties for the Gremlin.Net driver can be passed to the `GremlinServer` instance as keyword arguments: [width=""100%"",cols=""3,10,^2"",options=""header""] |========================================================= |Key |Description |Default |hostname |The hostname that the driver will connect to. |localhost |port |The port on which Gremlin Server can be reached. |8182 |enableSsl |Determines if SSL should be enabled or not. If enabled on the server then it must be enabled on the client. |false |username |The username to submit on requests that require authentication. |_none_ |password |The password to submit on requests that require authentication. |_none_ |========================================================= ==== Connection Pool It is also possible to configure the `ConnectionPool` of the Gremlin.Net driver. These configuration options can be set as properties on the `ConnectionPoolSettings` instance that can be passed to the `GremlinClient`: [width=""100%"",cols=""3,10,^2"",options=""header""] |========================================================= |Key |Description |Default |PoolSize |The size of the connection pool. |4 |MaxInProcessPerConnection |The maximum number of in-flight requests that can occur on a connection. |32 |ReconnectionAttempts |The number of attempts to get an open connection from the pool to submit a request. |4 |ReconnectionBaseDelay |The base delay used for the exponential backoff for the reconnection attempts. |1 s |========================================================= A `NoConnectionAvailableException` is thrown if all connections have reached the `MaxInProcessPerConnection` limit when a new request comes in. A `ServerUnavailableException` is thrown if no connection is available to the server to submit a request after `ReconnectionAttempts` retries. ==== Serialization The Gremlin.Net driver uses by default GraphSON 3.0 but it is also possible to use GraphSON 2.0 which can be necessary when the server does not support GraphSON 3.0 yet: [source,csharp] ---- include::../../../gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Docs/Reference/GremlinVariantsTests.cs[tags=serialization] ---- === Traversal Strategies In order to add and remove traversal strategies from a traversal source, Gremlin.Net has an `AbstractTraversalStrategy` class along with a collection of subclasses that mirror the standard Gremlin-Java strategies. [source,csharp] ---- include::../../../gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Docs/Reference/GremlinVariantsTests.cs[tags=traversalStrategies] ---- NOTE: Many of the TraversalStrategy classes in Gremlin.Net are proxies to the respective strategy on Apache TinkerPop’s JVM-based Gremlin traversal machine. As such, their `Apply(ITraversal)` method does nothing. However, the strategy is encoded in the Gremlin.Net bytecode and transmitted to the Gremlin traversal machine for re-construction machine-side. === The Lambda Solution Supporting link:https://en.wikipedia.org/wiki/Anonymous_function[anonymous functions] across languages is difficult as most languages do not support lambda introspection and thus, code analysis. While Gremlin.Net doesn't support C# lambdas, it is still able to represent lambdas in other languages. When the lambda is represented in `Bytecode` its language is encoded such that the remote connection host can infer which translator and ultimate execution engine to use. [source,csharp] ---- g.V().Out().Map(Lambda.Groovy(""it.get().value('name').length()"")).Sum().ToList(); <1> g.V().Out().Map(Lambda.Python(""lambda x: len(x.get().value('name'))"")).Sum().ToList(); <2> ---- <1> `Lambda.Groovy()` can be used to create a Groovy lambda. <2> `Lambda.Python()` can be used to create a Python lambda. The `ILambda` interface returned by these two methods inherits interfaces like `IFunction` and `IPredicate` that mirror their Java counterparts which makes it possible to use lambdas with Gremlin.Net for the same steps as in Gremlin-Java. TIP: When running into situations where Groovy cannot properly discern a method signature based on the `Lambda` instance created, it will help to fully define the closure in the lambda expression - so rather than `Lambda.Groovy(""it.get().value('name'))`, prefer `Lambda.Groovy(""x -> x.get().value('name'))`. === Submitting Scripts WARNING: TinkerPop does not recommend submitting script-based requests and generally continues to support this feature for legacy reasons and corner use cases which are still not completely addressed by the Gremlin language. Please consider using bytecode-based requests instead when possible. Gremlin scripts are sent to the server from a `IGremlinClient` instance. A `IGremlinClient` is created as follows: [source,csharp] ---- include::../../../gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Docs/Reference/GremlinVariantsTests.cs[tags=submittingScripts] ---- If the remote system has authentication and SSL enabled, then the `GremlinServer` object can be configured as follows: [source,csharp] ---- include::../../../gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Docs/Reference/GremlinVariantsTests.cs[tags=submittingScriptsWithAuthentication] ---- It is also possible to initialize the `Client` to use <>: [source,csharp] ---- var gremlinServer = new GremlinServer(""localhost"", 8182); var client = new GremlinClient(gremlinServer, sessionId: Guid.NewGuid().ToString())) ---- [[gremlin-net-dsl]] === Domain Specific Languages Developing a <> (DSL) for .Net is most easily implemented using link:https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods[Extension Methods] as they don't require direct extension of classes in the TinkerPop hierarchy. Extension Method classes simply need to be constructed for the `GraphTraversal` and the `GraphTraversalSource`. Unfortunately, anonymous traversals (spawned from `+__+`) can't use the Extension Method approach as they do not work for static classes and static classes can't be extended. The only option is to re-implement the methods of `+__+` as a wrapper in the anonymous traversal for the DSL or to simply create a static class for the DSL and use the two anonymous traversals creators independently. The following example uses the latter approach as it saves a lot of boilerplate code with the minor annoyance of having a second static class to deal with when writing traversals rather than just calling `+__+` for everything. [source,csharp] ---- include::../../../gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Docs/Reference/GremlinVariantsDsl.cs[tags=dsl] ---- Note the creation of `__Social` as the Social DSL's ""extension"" to the available ways in which to spawn anonymous traversals. The use of the double underscore prefix in the name is just a convention to consider using and is not a requirement. To use the DSL, bring it into scope with the `using` directive: [source,csharp] ---- include::../../../gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Docs/Reference/GremlinVariantsDslTests.cs[tags=dslUsing] ---- and then it can be called from the application as follows: [source,csharp] ---- include::../../../gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Docs/Reference/GremlinVariantsDslTests.cs[tags=dslExamples] ---- [[gremlin-dotnet-differences]] === Differences Gremlin allows for `Map` instances to include `null` keys, but `null` keys in C# `Dictionary` instances are not allowed. It is therefore necessary to rewrite a traversal such as: [source,javascript] ---- g.V().groupCount().by('age') ---- where ""age"" is not a valid key for all vertices in a way that will remove the need for a `null` to be returned. [source,javascript] ---- g.V().has('age').groupCount().by('age') g.V().hasLabel('person').groupCount().by('age') ---- Either of the above two options accomplishes the desired goal as both prevent `groupCount()` from having to process the possibility of `null`. anchor:gremlin-dotnet-template[] [[dotnet-application-examples]] === Application Examples This link:https://docs.microsoft.com/dotnet/core/tools/custom-templates[dotnet template] helps getting started with <>. It creates a new C# console project that shows how to connect to a <> with Gremlin.Net. You can install the template with the dotnet CLI tool: [source,shell] dotnet new -i Gremlin.Net.Template After the template is installed, a new project based on this template can be installed: [source,shell] dotnet new gremlin Specify the output directory for the new project which will then also be used as the name of the created project: [source,shell] dotnet new gremlin -o MyFirstGremlinProject [[gremlin-javascript]] == Gremlin-JavaScript image:gremlin-js.png[width=130,float=right] Apache TinkerPop's Gremlin-JavaScript implements Gremlin within the JavaScript language. It targets Node.js runtime and can be used on different operating systems on any Node.js 6 or above. Since the JavaScript naming conventions are very similar to that of Java, it should be very easy to switch between Gremlin-Java and Gremlin-JavaScript. [source,bash] npm install gremlin === Connecting The pattern for connecting is described in <> and it basically distills down to creating a `GraphTraversalSource`. A `GraphTraversalSource` is created from the `AnonymousTraversalSource.traversal()` method where the ""g"" provided to the `DriverRemoteConnection` corresponds to the name of a `GraphTraversalSource` on the remote end. [source,javascript] ---- const g = traversal().withRemote(new DriverRemoteConnection('ws://localhost:8182/gremlin')); ---- Gremlin-JavaScript supports plain text SASL authentication, you can set it on the connection options. [source,javascript] ---- const authenticator = new gremlin.driver.auth.PlainTextSaslAuthenticator('myuser', 'mypassword'); const g = traversal().withRemote(new DriverRemoteConnection('ws://localhost:8182/gremlin', { authenticator }); ---- Given that I/O operations in Node.js are asynchronous by default, <> return a `Promise`: * `Traversal.toList()`: Returns a `Promise` with an `Array` as result value. * `Traversal.next()`: Returns a `Promise` with a `{ value, done }` tuple as result value, according to the link:https://github.com/tc39/proposal-async-iteration[async iterator proposal]. * `Traversal.iterate()`: Returns a `Promise` without a value. For example: [source,javascript] ---- g.V().hasLabel('person').values('name').toList() .then(names => console.log(names)); ---- When using `async` functions it is possible to `await` the promises: [source,javascript] ---- const names = await g.V().hasLabel('person').values('name').toList(); console.log(names); ---- === Common Imports There are a number of classes, functions and tokens that are typically used with Gremlin. The following imports provide most of the typical functionality required to use Gremlin: [source,javascript] ---- const gremlin = require('gremlin'); const traversal = gremlin.process.AnonymousTraversalSource.traversal; const __ = gremlin.process.statics; const DriverRemoteConnection = gremlin.driver.DriverRemoteConnection; const column = gremlin.process.column const direction = gremlin.process.direction const p = gremlin.process.P const textp = gremlin.process.TextP const pick = gremlin.process.pick const pop = gremlin.process.pop const order = gremlin.process.order const scope = gremlin.process.scope const t = gremlin.process.t ---- === Submitting Scripts WARNING: TinkerPop does not recommend submitting script-based requests and generally continues to support this feature for legacy reasons and corner use cases which are still not completely addressed by the Gremlin language. Please consider using bytecode-based requests instead when possible. It is possible to submit parametrized Gremlin scripts to the server as strings, using the `Client` class: [source,javascript] ---- const gremlin = require('gremlin'); const client = new gremlin.driver.Client('ws://localhost:8182/gremlin', { traversalSource: 'g' }); const result1 = await client.submit('g.V(vid)', { vid: 1 }); const vertex = result1.first(); const result2 = await client.submit('g.V().hasLabel(label).tail(n)', { label: 'person', n: 3 }); // ResultSet is an iterable for (const vertex of result2) { console.log(vertex.id); } ---- It is also possible to initialize the `Client` to use <>: [source,javascript] ---- const client = new gremlin.driver.Client('ws://localhost:8182/gremlin', { traversalSource: 'g', 'session': 'unique-string-id' }); ---- With this configuration, the state of variables within scripts are preserved between requests. ==== Per Request Settings Some settings can be established per request, like an override of the `scriptEvaluationTimeout` which can be helpful when it is known that particular request might need to execute longer than what the server might allow with its settings: [source,javascript] ---- const result = await client.submit('g.V().repeat(both()).times(100)', null, {""scriptEvaluationTimeout"": 60000}); ---- [[gremlin-javascript-dsl]] === Domain Specific Languages Developing Gremlin DSLs in JavaScript largely requires extension of existing core classes with use of standalone functions for anonymous traversal spawning. The pattern is demonstrated in the following example: [source,javascript] ---- class SocialTraversal extends GraphTraversal { constructor(graph, traversalStrategies, bytecode) { super(graph, traversalStrategies, bytecode); } aged(age) { return this.has('person', 'age', age); } } class SocialTraversalSource extends GraphTraversalSource { constructor(graph, traversalStrategies, bytecode) { super(graph, traversalStrategies, bytecode, SocialTraversalSource, SocialTraversal); } person(name) { return this.V().has('person', 'name', name); } } function anonymous() { return new SocialTraversal(null, null, new Bytecode()); } function aged(age) { return anonymous().aged(age); } ---- `SocialTraversal` extends the core `GraphTraversal` class and has a three argument constructor which is immediately proxied to the `GraphTraversal` constructor. New DSL steps are then added to this class using available steps to construct the underlying traversal to execute as demonstrated in the `aged()` step. The `SocialTraversal` is spawned from a `SocialTraversalSource` which is extended from `GraphTraversalSource`. Steps added here are meant to be start steps. In the above case, the `person()` start step find a ""person"" vertex to begin the traversal from. Typically, steps that are made available on a `GraphTraversal` (i.e. SocialTraversal in this example) should also be made available as spawns for anonymous traversals. The recommendation is that these steps be exposed in the module as standalone functions. In the example above, the standalone `aged()` step creates an anonymous traversal through an `anonymous()` utility function. The method for creating these standalone functions can be handled in other ways if desired. To use the DSL, simply initialize the `g` as follows: [source,javascript] ---- const g = traversal(SocialTraversalSource).withRemote(connection); g.person('marko').aged(29).values('name').toList(). then(names => console.log(names)); ---- [[gremlin-javascript-differences]] === Differences In situations where Javascript reserved words and global functions overlap with standard Gremlin steps and tokens, those bits of conflicting Gremlin get an underscore appended as a suffix: *Steps* - <>, <>, <> Gremlin allows for `Map` instances to include `null` keys, but `null` keys in Javascript have some interesting behavior as in: [source,text] ---- > var a = { null: 'something', 'b': 'else' }; > JSON.stringify(a) '{""null"":""something"",""b"":""else""}' > JSON.parse(JSON.stringify(a)) { null: 'something', b: 'else' } > a[null] 'something' > a['null'] 'something' ---- This behavior needs to be considered when using Gremlin to return such results. A typical situation where this might happen is with `group()` or `groupCount()` as in: [source,javascript] ---- g.V().groupCount().by('age') ---- where ""age"" is not a valid key for all vertices. In these cases, it will return `null` for that key and group on that. It may bet better in Javascript to filter away those vertices to avoid the return of `null` in the returned `Map`: [source,javascript] ---- g.V().has('age').groupCount().by('age') g.V().hasLabel('person').groupCount().by('age') ---- Either of the above two options accomplishes the desired goal as both prevent `groupCount()` from having to process the possibility of `null`.",16239,True,2766.7508807248105,median "*&---------------------------------------------------------------------* *& Include ZABAPGIT_OBJECT_CLAS *&---------------------------------------------------------------------* *----------------------------------------------------------------------* * CLASS lcl_object_clas DEFINITION *----------------------------------------------------------------------* * *----------------------------------------------------------------------* CLASS lcl_object_clas DEFINITION INHERITING FROM lcl_objects_program. PUBLIC SECTION. INTERFACES lif_object. ALIASES mo_files FOR lif_object~mo_files. METHODS constructor IMPORTING is_item TYPE ty_item iv_language TYPE spras. PROTECTED SECTION. METHODS deserialize_abap IMPORTING io_xml TYPE REF TO lcl_xml_input iv_package TYPE devclass RAISING lcx_exception. METHODS deserialize_docu IMPORTING io_xml TYPE REF TO lcl_xml_input RAISING lcx_exception. DATA mo_object_oriented_object_fct TYPE REF TO lif_object_oriented_object_fnc. PRIVATE SECTION. DATA mv_skip_testclass TYPE abap_bool. METHODS deserialize_tpool IMPORTING io_xml TYPE REF TO lcl_xml_input RAISING lcx_exception. METHODS deserialize_sotr IMPORTING io_xml TYPE REF TO lcl_xml_input iv_package TYPE devclass RAISING lcx_exception. METHODS serialize_xml IMPORTING io_xml TYPE REF TO lcl_xml_output RAISING lcx_exception. ENDCLASS. ""lcl_object_dtel DEFINITION *----------------------------------------------------------------------* * CLASS lcl_object_clas IMPLEMENTATION *----------------------------------------------------------------------* * *----------------------------------------------------------------------* CLASS lcl_object_clas IMPLEMENTATION. METHOD lif_object~has_changed_since. DATA: lt_includes TYPE seoincl_t. FIELD-SYMBOLS LIKE LINE OF lt_includes. lt_includes = mo_object_oriented_object_fct->get_includes( ms_item-obj_name ). LOOP AT lt_includes ASSIGNING . rv_changed = check_prog_changed_since( iv_program = iv_timestamp = iv_timestamp iv_skip_gui = abap_true ). IF rv_changed = abap_true. RETURN. ENDIF. ENDLOOP. ENDMETHOD. ""lif_object~has_changed_since METHOD lif_object~get_metadata. rs_metadata = get_metadata( ). ENDMETHOD. ""lif_object~get_metadata METHOD lif_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 = mo_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 lif_object~exists. DATA: ls_class_key TYPE seoclskey. ls_class_key-clsname = ms_item-obj_name. rv_bool = mo_object_oriented_object_fct->exists( iv_object_name = ls_class_key ). ENDMETHOD. ""lif_object~exists METHOD lif_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. ""jump METHOD lif_object~delete. DATA: ls_clskey TYPE seoclskey. ls_clskey-clsname = ms_item-obj_name. mo_object_oriented_object_fct->delete( ls_clskey ). ENDMETHOD. ""delete METHOD lif_object~serialize. DATA: lt_source TYPE seop_source_string, ls_class_key TYPE seoclskey. ls_class_key-clsname = ms_item-obj_name. IF lif_object~exists( ) = abap_false. RETURN. ENDIF. CALL FUNCTION 'SEO_BUFFER_REFRESH' EXPORTING version = seoc_version_active force = seox_true. CALL FUNCTION 'SEO_BUFFER_REFRESH' EXPORTING version = seoc_version_inactive force = seox_true. lt_source = mo_object_oriented_object_fct->serialize_abap( ls_class_key ). mo_files->add_abap( lt_source ). lt_source = mo_object_oriented_object_fct->serialize_abap( is_class_key = ls_class_key iv_type = seop_ext_class_locals_def ). IF NOT lt_source[] IS INITIAL. mo_files->add_abap( iv_extra = 'locals_def' it_abap = lt_source ). ""#EC NOTEXT ENDIF. lt_source = mo_object_oriented_object_fct->serialize_abap( is_class_key = ls_class_key iv_type = seop_ext_class_locals_imp ). IF NOT lt_source[] IS INITIAL. mo_files->add_abap( iv_extra = 'locals_imp' it_abap = lt_source ). ""#EC NOTEXT ENDIF. lt_source = mo_object_oriented_object_fct->serialize_abap( is_class_key = ls_class_key iv_type = seop_ext_class_testclasses ). mv_skip_testclass = mo_object_oriented_object_fct->get_skip_test_classes( ). IF NOT lt_source[] IS INITIAL AND mv_skip_testclass = abap_false. mo_files->add_abap( iv_extra = 'testclasses' it_abap = lt_source ). ""#EC NOTEXT ENDIF. lt_source = mo_object_oriented_object_fct->serialize_abap( is_class_key = ls_class_key iv_type = seop_ext_class_macros ). IF NOT lt_source[] IS INITIAL. mo_files->add_abap( iv_extra = 'macros' it_abap = lt_source ). ""#EC NOTEXT ENDIF. serialize_xml( io_xml ). ENDMETHOD. ""serialize METHOD serialize_xml. DATA: ls_vseoclass TYPE vseoclass, lt_tpool TYPE textpool_table, lv_object TYPE dokhl-object, lv_state TYPE dokhl-dokstate, lt_descriptions TYPE ty_seocompotx_tt, ls_clskey TYPE seoclskey, lt_sotr TYPE ty_sotr_tt, lt_lines TYPE tlinetab. ls_clskey-clsname = ms_item-obj_name. ls_vseoclass = mo_object_oriented_object_fct->get_class_properties( is_class_key = ls_clskey ). 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. IF mv_skip_testclass = abap_true. CLEAR ls_vseoclass-with_unit_tests. ENDIF. io_xml->add( iv_name = 'VSEOCLASS' ig_data = ls_vseoclass ). lt_tpool = mo_object_oriented_object_fct->read_text_pool( iv_class_name = ls_clskey-clsname iv_language = mv_language ). io_xml->add( iv_name = 'TPOOL' ig_data = add_tpool( lt_tpool ) ). IF ls_vseoclass-category = seoc_category_exception. lt_sotr = mo_object_oriented_object_fct->read_sotr( ms_item-obj_name ). IF lines( lt_sotr ) > 0. io_xml->add( iv_name = 'SOTR' ig_data = lt_sotr ). ENDIF. ENDIF. lt_lines = mo_object_oriented_object_fct->read_documentation( iv_class_name = ls_clskey-clsname iv_language = mv_language ). IF lines( lt_lines ) > 0. io_xml->add( iv_name = 'LINES' ig_data = lt_lines ). ENDIF. lt_descriptions = mo_object_oriented_object_fct->read_descriptions( ls_clskey-clsname ). IF lines( lt_descriptions ) > 0. io_xml->add( iv_name = 'DESCRIPTIONS' ig_data = lt_descriptions ). ENDIF. ENDMETHOD. ""serialize_xml METHOD lif_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. ""deserialize METHOD deserialize_sotr. ""OTR stands for Online Text Repository DATA: lt_sotr TYPE ty_sotr_tt, lt_objects TYPE sotr_objects. io_xml->read( EXPORTING iv_name = 'SOTR' CHANGING cg_data = lt_sotr ). IF lines( lt_sotr ) = 0. RETURN. ENDIF. mo_object_oriented_object_fct->create_sotr( iv_package = iv_package it_sotr = lt_sotr ). ENDMETHOD. METHOD deserialize_docu. DATA: lt_lines TYPE tlinetab, lv_object TYPE dokhl-object. io_xml->read( EXPORTING iv_name = 'LINES' CHANGING cg_data = lt_lines ). IF lt_lines[] IS INITIAL. RETURN. ENDIF. lv_object = ms_item-obj_name. mo_object_oriented_object_fct->create_documentation( it_lines = lt_lines iv_object_name = lv_object iv_language = mv_language ). ENDMETHOD. METHOD deserialize_tpool. DATA: lv_clsname TYPE seoclsname, lt_tpool_ext TYPE ty_tpool_tt, lt_tpool TYPE textpool_table. io_xml->read( EXPORTING iv_name = 'TPOOL' CHANGING cg_data = lt_tpool_ext ). lt_tpool = read_tpool( lt_tpool_ext ). IF lt_tpool[] IS INITIAL. RETURN. ENDIF. lv_clsname = ms_item-obj_name. mo_object_oriented_object_fct->insert_text_pool( iv_class_name = lv_clsname it_text_pool = lt_tpool iv_language = mv_language ). ENDMETHOD. ""deserialize_textpool METHOD deserialize_abap. 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 ty_seocompotx_tt, ls_class_key TYPE seoclskey. lt_source = mo_files->read_abap( ). lt_local_definitions = mo_files->read_abap( iv_extra = 'locals_def' iv_error = abap_false ). ""#EC NOTEXT lt_local_implementations = mo_files->read_abap( iv_extra = 'locals_imp' iv_error = abap_false ). ""#EC NOTEXT lt_local_macros = mo_files->read_abap( iv_extra = 'macros' iv_error = abap_false ). ""#EC NOTEXT lt_test_classes = mo_files->read_abap( iv_extra = 'testclasses' iv_error = abap_false ). ""#EC NOTEXT ls_class_key-clsname = ms_item-obj_name. io_xml->read( EXPORTING iv_name = 'VSEOCLASS' CHANGING cg_data = ls_vseoclass ). mo_object_oriented_object_fct->create( EXPORTING iv_package = iv_package CHANGING is_properties = ls_vseoclass ). mo_object_oriented_object_fct->generate_locals( is_key = ls_class_key iv_force = seox_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 ). mo_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 ). mo_object_oriented_object_fct->update_descriptions( is_key = ls_class_key it_descriptions = lt_descriptions ). mo_object_oriented_object_fct->add_to_activation_list( is_item = ms_item ). ENDMETHOD. ""deserialize METHOD lif_object~compare_to_remote_version. CREATE OBJECT ro_comparison_result TYPE lcl_null_comparison_result. ENDMETHOD. METHOD constructor. super->constructor( is_item = is_item iv_language = iv_language ). mo_object_oriented_object_fct = lcl_object_oriented_factory=>make( iv_object_type = ms_item-obj_type ). ENDMETHOD. ENDCLASS. ""lcl_object_CLAS IMPLEMENTATION CLASS lcl_object_oriented_class DEFINITION INHERITING FROM lcl_object_oriented_base. PUBLIC SECTION. METHODS: lif_object_oriented_object_fnc~create REDEFINITION, lif_object_oriented_object_fnc~generate_locals REDEFINITION, lif_object_oriented_object_fnc~insert_text_pool REDEFINITION, lif_object_oriented_object_fnc~create_sotr REDEFINITION, lif_object_oriented_object_fnc~get_includes REDEFINITION, lif_object_oriented_object_fnc~get_class_properties REDEFINITION, lif_object_oriented_object_fnc~read_text_pool REDEFINITION, lif_object_oriented_object_fnc~read_sotr REDEFINITION, lif_object_oriented_object_fnc~delete REDEFINITION. ENDCLASS. CLASS lcl_object_oriented_class IMPLEMENTATION. METHOD lif_object_oriented_object_fnc~create. CALL FUNCTION 'SEO_CLASS_CREATE_COMPLETE' EXPORTING devclass = iv_package overwrite = iv_overwrite CHANGING class = is_properties EXCEPTIONS existing = 1 is_interface = 2 db_error = 3 component_error = 4 no_access = 5 other = 6 OTHERS = 7. IF sy-subrc <> 0. lcx_exception=>raise( 'error from SEO_CLASS_CREATE_COMPLETE' ). ENDIF. ENDMETHOD. METHOD lif_object_oriented_object_fnc~generate_locals. CALL FUNCTION 'SEO_CLASS_GENERATE_LOCALS' EXPORTING clskey = is_key force = iv_force locals_def = it_local_definitions locals_imp = it_local_implementations locals_mac = it_local_macros locals_testclasses = it_local_test_classes EXCEPTIONS not_existing = 1 model_only = 2 locals_not_generated = 3 locals_not_initialised = 4 OTHERS = 5. IF sy-subrc <> 0. lcx_exception=>raise( 'error from generate_locals' ). ENDIF. ENDMETHOD. METHOD lif_object_oriented_object_fnc~insert_text_pool. DATA: lv_cp TYPE program. lv_cp = cl_oo_classname_service=>get_classpool_name( iv_class_name ). INSERT TEXTPOOL lv_cp FROM it_text_pool LANGUAGE iv_language STATE 'I'. IF sy-subrc <> 0. lcx_exception=>raise( 'error from INSERT TEXTPOOL' ). ENDIF. lcl_objects_activation=>add( iv_type = 'REPT' iv_name = lv_cp ). ENDMETHOD. METHOD lif_object_oriented_object_fnc~create_sotr. DATA: lt_sotr TYPE ty_sotr_tt, lt_objects TYPE sotr_objects, ls_paket TYPE sotr_pack, lv_object LIKE LINE OF lt_objects. FIELD-SYMBOLS: LIKE LINE OF lt_sotr. LOOP AT it_sotr ASSIGNING . CALL FUNCTION 'SOTR_OBJECT_GET_OBJECTS' EXPORTING object_vector = -header-objid_vec IMPORTING objects = lt_objects EXCEPTIONS object_not_found = 1 OTHERS = 2. IF sy-subrc <> 0. lcx_exception=>raise( 'error from SOTR_OBJECT_GET_OBJECTS' ). ENDIF. READ TABLE lt_objects INDEX 1 INTO lv_object. ASSERT sy-subrc = 0. ls_paket-paket = iv_package. CALL FUNCTION 'SOTR_CREATE_CONCEPT' EXPORTING paket = ls_paket crea_lan = -header-crea_lan alias_name = -header-alias_name object = lv_object entries = -entries concept_default = -header-concept EXCEPTIONS package_missing = 1 crea_lan_missing = 2 object_missing = 3 paket_does_not_exist = 4 alias_already_exist = 5 object_type_not_found = 6 langu_missing = 7 identical_context_not_allowed = 8 text_too_long = 9 error_in_update = 10 no_master_langu = 11 error_in_concept_id = 12 alias_not_allowed = 13 tadir_entry_creation_failed = 14 internal_error = 15 error_in_correction = 16 user_cancelled = 17 no_entry_found = 18 OTHERS = 19. IF sy-subrc <> 0. lcx_exception=>raise( 'error from SOTR_CREATE_CONCEPT' ). ENDIF. ENDLOOP. ENDMETHOD. METHOD lif_object_oriented_object_fnc~get_includes. * note: includes returned might not exist * method cl_oo_classname_service=>GET_ALL_CLASS_INCLUDES does not exist in 702 DATA: lv_class_name TYPE seoclsname, lt_methods TYPE seop_methods_w_include. FIELD-SYMBOLS: LIKE LINE OF lt_methods. lv_class_name = iv_object_name. APPEND cl_oo_classname_service=>get_ccdef_name( lv_class_name ) TO rt_includes. APPEND cl_oo_classname_service=>get_ccmac_name( lv_class_name ) TO rt_includes. APPEND cl_oo_classname_service=>get_ccimp_name( lv_class_name ) TO rt_includes. APPEND cl_oo_classname_service=>get_cl_name( lv_class_name ) TO rt_includes. APPEND cl_oo_classname_service=>get_ccau_name( lv_class_name ) TO rt_includes. APPEND cl_oo_classname_service=>get_pubsec_name( lv_class_name ) TO rt_includes. APPEND cl_oo_classname_service=>get_prosec_name( lv_class_name ) TO rt_includes. APPEND cl_oo_classname_service=>get_prisec_name( lv_class_name ) TO rt_includes. APPEND cl_oo_classname_service=>get_classpool_name( lv_class_name ) TO rt_includes. APPEND cl_oo_classname_service=>get_ct_name( lv_class_name ) TO rt_includes. APPEND cl_oo_classname_service=>get_cs_name( lv_class_name ) TO rt_includes. lt_methods = cl_oo_classname_service=>get_all_method_includes( lv_class_name ). LOOP AT lt_methods ASSIGNING . APPEND -incname TO rt_includes. ENDLOOP. ENDMETHOD. METHOD lif_object_oriented_object_fnc~get_class_properties. CALL FUNCTION 'SEO_CLIF_GET' EXPORTING cifkey = is_class_key version = seoc_version_active IMPORTING class = rs_class_properties EXCEPTIONS not_existing = 1 deleted = 2 model_only = 3 OTHERS = 4. IF sy-subrc = 1. RETURN. "" in case only inactive version exists ELSEIF sy-subrc <> 0. lcx_exception=>raise( 'error from seo_clif_get' ). ENDIF. ENDMETHOD. METHOD lif_object_oriented_object_fnc~read_text_pool. DATA: lv_cp TYPE program. lv_cp = cl_oo_classname_service=>get_classpool_name( iv_class_name ). READ TEXTPOOL lv_cp INTO rt_text_pool LANGUAGE iv_language. ""#EC CI_READ_REP ENDMETHOD. METHOD lif_object_oriented_object_fnc~read_sotr. DATA: lv_concept TYPE sotr_head-concept, lt_seocompodf TYPE STANDARD TABLE OF seocompodf WITH DEFAULT KEY, ls_header TYPE sotr_head, lt_entries TYPE sotr_text_tt. FIELD-SYMBOLS: LIKE LINE OF rt_sotr, LIKE LINE OF lt_seocompodf, LIKE LINE OF lt_entries. SELECT * FROM seocompodf INTO TABLE lt_seocompodf WHERE clsname = iv_object_name AND version = '1' AND exposure = '2' AND attdecltyp = '2' AND type = 'SOTR_CONC' ORDER BY PRIMARY KEY. LOOP AT lt_seocompodf ASSIGNING . lv_concept = translate( val = -attvalue from = '''' to = '' ). CALL FUNCTION 'SOTR_GET_CONCEPT' EXPORTING concept = lv_concept IMPORTING header = ls_header TABLES entries = lt_entries EXCEPTIONS no_entry_found = 1 OTHERS = 2. IF sy-subrc <> 0. CONTINUE. ENDIF. CLEAR: ls_header-paket, ls_header-crea_name, ls_header-crea_tstut, ls_header-chan_name, ls_header-chan_tstut. LOOP AT lt_entries ASSIGNING . CLEAR: -version, -crea_name, -crea_tstut, -chan_name, -chan_tstut. ENDLOOP. APPEND INITIAL LINE TO rt_sotr ASSIGNING . -header = ls_header. -entries = lt_entries. ENDLOOP. ENDMETHOD. METHOD lif_object_oriented_object_fnc~delete. CALL FUNCTION 'SEO_CLASS_DELETE_COMPLETE' EXPORTING clskey = is_deletion_key EXCEPTIONS not_existing = 1 is_interface = 2 db_error = 3 no_access = 4 other = 5 OTHERS = 6. IF sy-subrc <> 0. lcx_exception=>raise( 'Error from SEO_CLASS_DELETE_COMPLETE' ). ENDIF. ENDMETHOD. ENDCLASS. ",5456,False,1133.0471779127126,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. */ //// :doctype: book :numbered: :toc: left :icons: font :experimental: [[hbase_default_configurations]] === HBase Default Configuration The documentation below is generated using the default hbase configuration file, _hbase-default.xml_, as source. [[hbase.tmp.dir]] *`hbase.tmp.dir`*:: + .Description Temporary directory on the local filesystem. Change this setting to point to a location more permanent than '/tmp', the usual resolve for java.io.tmpdir, as the '/tmp' directory is cleared on machine restart. + .Default `${java.io.tmpdir}/hbase-${user.name}` [[hbase.rootdir]] *`hbase.rootdir`*:: + .Description The directory shared by region servers and into which HBase persists. The URL should be 'fully-qualified' to include the filesystem scheme. For example, to specify the HDFS directory '/hbase' where the HDFS instance's namenode is running at namenode.example.org on port 9000, set this value to: hdfs://namenode.example.org:9000/hbase. By default, we write to whatever ${hbase.tmp.dir} is set too -- usually /tmp -- so change this configuration or else all data will be lost on machine restart. + .Default `${hbase.tmp.dir}/hbase` [[hbase.cluster.distributed]] *`hbase.cluster.distributed`*:: + .Description The mode the cluster will be in. Possible values are false for standalone mode and true for distributed mode. If false, startup will run all HBase and ZooKeeper daemons together in the one JVM. + .Default `false` [[hbase.zookeeper.quorum]] *`hbase.zookeeper.quorum`*:: + .Description Comma separated list of servers in the ZooKeeper ensemble (This config. should have been named hbase.zookeeper.ensemble). For example, ""host1.mydomain.com,host2.mydomain.com,host3.mydomain.com"". By default this is set to localhost for local and pseudo-distributed modes of operation. For a fully-distributed setup, this should be set to a full list of ZooKeeper ensemble servers. If HBASE_MANAGES_ZK is set in hbase-env.sh this is the list of servers which hbase will start/stop ZooKeeper on as part of cluster start/stop. Client-side, we will take this list of ensemble members and put it together with the hbase.zookeeper.clientPort config. and pass it into zookeeper constructor as the connectString parameter. + .Default `localhost` [[hbase.local.dir]] *`hbase.local.dir`*:: + .Description Directory on the local filesystem to be used as a local storage. + .Default `${hbase.tmp.dir}/local/` [[hbase.master.info.port]] *`hbase.master.info.port`*:: + .Description The port for the HBase Master web UI. Set to -1 if you do not want a UI instance run. + .Default `16010` [[hbase.master.info.bindAddress]] *`hbase.master.info.bindAddress`*:: + .Description The bind address for the HBase Master web UI + .Default `0.0.0.0` [[hbase.master.logcleaner.plugins]] *`hbase.master.logcleaner.plugins`*:: + .Description A comma-separated list of BaseLogCleanerDelegate invoked by the LogsCleaner service. These WAL cleaners are called in order, so put the cleaner that prunes the most files in front. To implement your own BaseLogCleanerDelegate, just put it in HBase's classpath and add the fully qualified class name here. Always add the above default log cleaners in the list. + .Default `org.apache.hadoop.hbase.master.cleaner.TimeToLiveLogCleaner` [[hbase.master.logcleaner.ttl]] *`hbase.master.logcleaner.ttl`*:: + .Description Maximum time a WAL can stay in the .oldlogdir directory, after which it will be cleaned by a Master thread. + .Default `600000` [[hbase.master.hfilecleaner.plugins]] *`hbase.master.hfilecleaner.plugins`*:: + .Description A comma-separated list of BaseHFileCleanerDelegate invoked by the HFileCleaner service. These HFiles cleaners are called in order, so put the cleaner that prunes the most files in front. To implement your own BaseHFileCleanerDelegate, just put it in HBase's classpath and add the fully qualified class name here. Always add the above default log cleaners in the list as they will be overwritten in hbase-site.xml. + .Default `org.apache.hadoop.hbase.master.cleaner.TimeToLiveHFileCleaner` [[hbase.master.infoserver.redirect]] *`hbase.master.infoserver.redirect`*:: + .Description Whether or not the Master listens to the Master web UI port (hbase.master.info.port) and redirects requests to the web UI server shared by the Master and RegionServer. + .Default `true` [[hbase.regionserver.port]] *`hbase.regionserver.port`*:: + .Description The port the HBase RegionServer binds to. + .Default `16020` [[hbase.regionserver.info.port]] *`hbase.regionserver.info.port`*:: + .Description The port for the HBase RegionServer web UI Set to -1 if you do not want the RegionServer UI to run. + .Default `16030` [[hbase.regionserver.info.bindAddress]] *`hbase.regionserver.info.bindAddress`*:: + .Description The address for the HBase RegionServer web UI + .Default `0.0.0.0` [[hbase.regionserver.info.port.auto]] *`hbase.regionserver.info.port.auto`*:: + .Description Whether or not the Master or RegionServer UI should search for a port to bind to. Enables automatic port search if hbase.regionserver.info.port is already in use. Useful for testing, turned off by default. + .Default `false` [[hbase.regionserver.handler.count]] *`hbase.regionserver.handler.count`*:: + .Description Count of RPC Listener instances spun up on RegionServers. Same property is used by the Master for count of master handlers. + .Default `30` [[hbase.ipc.server.callqueue.handler.factor]] *`hbase.ipc.server.callqueue.handler.factor`*:: + .Description Factor to determine the number of call queues. A value of 0 means a single queue shared between all the handlers. A value of 1 means that each handler has its own queue. + .Default `0.1` [[hbase.ipc.server.callqueue.read.ratio]] *`hbase.ipc.server.callqueue.read.ratio`*:: + .Description Split the call queues into read and write queues. The specified interval (which should be between 0.0 and 1.0) will be multiplied by the number of call queues. A value of 0 indicate to not split the call queues, meaning that both read and write requests will be pushed to the same set of queues. A value lower than 0.5 means that there will be less read queues than write queues. A value of 0.5 means there will be the same number of read and write queues. A value greater than 0.5 means that there will be more read queues than write queues. A value of 1.0 means that all the queues except one are used to dispatch read requests. Example: Given the total number of call queues being 10 a read.ratio of 0 means that: the 10 queues will contain both read/write requests. a read.ratio of 0.3 means that: 3 queues will contain only read requests and 7 queues will contain only write requests. a read.ratio of 0.5 means that: 5 queues will contain only read requests and 5 queues will contain only write requests. a read.ratio of 0.8 means that: 8 queues will contain only read requests and 2 queues will contain only write requests. a read.ratio of 1 means that: 9 queues will contain only read requests and 1 queues will contain only write requests. + .Default `0` [[hbase.ipc.server.callqueue.scan.ratio]] *`hbase.ipc.server.callqueue.scan.ratio`*:: + .Description Given the number of read call queues, calculated from the total number of call queues multiplied by the callqueue.read.ratio, the scan.ratio property will split the read call queues into small-read and long-read queues. A value lower than 0.5 means that there will be less long-read queues than short-read queues. A value of 0.5 means that there will be the same number of short-read and long-read queues. A value greater than 0.5 means that there will be more long-read queues than short-read queues A value of 0 or 1 indicate to use the same set of queues for gets and scans. Example: Given the total number of read call queues being 8 a scan.ratio of 0 or 1 means that: 8 queues will contain both long and short read requests. a scan.ratio of 0.3 means that: 2 queues will contain only long-read requests and 6 queues will contain only short-read requests. a scan.ratio of 0.5 means that: 4 queues will contain only long-read requests and 4 queues will contain only short-read requests. a scan.ratio of 0.8 means that: 6 queues will contain only long-read requests and 2 queues will contain only short-read requests. + .Default `0` [[hbase.regionserver.msginterval]] *`hbase.regionserver.msginterval`*:: + .Description Interval between messages from the RegionServer to Master in milliseconds. + .Default `3000` [[hbase.regionserver.regionSplitLimit]] *`hbase.regionserver.regionSplitLimit`*:: + .Description Limit for the number of regions after which no more region splitting should take place. This is not a hard limit for the number of regions but acts as a guideline for the regionserver to stop splitting after a certain limit. Default is MAX_INT; i.e. do not block splitting. + .Default `2147483647` [[hbase.regionserver.logroll.period]] *`hbase.regionserver.logroll.period`*:: + .Description Period at which we will roll the commit log regardless of how many edits it has. + .Default `3600000` [[hbase.regionserver.logroll.errors.tolerated]] *`hbase.regionserver.logroll.errors.tolerated`*:: + .Description The number of consecutive WAL close errors we will allow before triggering a server abort. A setting of 0 will cause the region server to abort if closing the current WAL writer fails during log rolling. Even a small value (2 or 3) will allow a region server to ride over transient HDFS errors. + .Default `2` [[hbase.regionserver.hlog.reader.impl]] *`hbase.regionserver.hlog.reader.impl`*:: + .Description The WAL file reader implementation. + .Default `org.apache.hadoop.hbase.regionserver.wal.ProtobufLogReader` [[hbase.regionserver.hlog.writer.impl]] *`hbase.regionserver.hlog.writer.impl`*:: + .Description The WAL file writer implementation. + .Default `org.apache.hadoop.hbase.regionserver.wal.ProtobufLogWriter` [[hbase.master.distributed.log.replay]] *`hbase.master.distributed.log.replay`*:: + .Description Enable 'distributed log replay' as default engine splitting WAL files on server crash. This default is new in hbase 1.0. To fall back to the old mode 'distributed log splitter', set the value to 'false'. 'Disributed log replay' improves MTTR because it does not write intermediate files. 'DLR' required that 'hfile.format.version' be set to version 3 or higher. + .Default `true` [[hbase.regionserver.global.memstore.size]] *`hbase.regionserver.global.memstore.size`*:: + .Description Maximum size of all memstores in a region server before new updates are blocked and flushes are forced. Defaults to 40% of heap. Updates are blocked and flushes are forced until size of all memstores in a region server hits hbase.regionserver.global.memstore.size.lower.limit. + .Default `0.4` [[hbase.regionserver.global.memstore.size.lower.limit]] *`hbase.regionserver.global.memstore.size.lower.limit`*:: + .Description Maximum size of all memstores in a region server before flushes are forced. Defaults to 95% of hbase.regionserver.global.memstore.size. A 100% value for this value causes the minimum possible flushing to occur when updates are blocked due to memstore limiting. + .Default `0.95` [[hbase.regionserver.optionalcacheflushinterval]] *`hbase.regionserver.optionalcacheflushinterval`*:: + .Description Maximum amount of time an edit lives in memory before being automatically flushed. Default 1 hour. Set it to 0 to disable automatic flushing. + .Default `3600000` [[hbase.regionserver.dns.interface]] *`hbase.regionserver.dns.interface`*:: + .Description The name of the Network Interface from which a region server should report its IP address. + .Default `default` [[hbase.regionserver.dns.nameserver]] *`hbase.regionserver.dns.nameserver`*:: + .Description The host name or IP address of the name server (DNS) which a region server should use to determine the host name used by the master for communication and display purposes. + .Default `default` [[hbase.regionserver.region.split.policy]] *`hbase.regionserver.region.split.policy`*:: + .Description A split policy determines when a region should be split. The various other split policies that are available currently are ConstantSizeRegionSplitPolicy, DisabledRegionSplitPolicy, DelimitedKeyPrefixRegionSplitPolicy, KeyPrefixRegionSplitPolicy etc. + .Default `org.apache.hadoop.hbase.regionserver.IncreasingToUpperBoundRegionSplitPolicy` [[zookeeper.session.timeout]] *`zookeeper.session.timeout`*:: + .Description ZooKeeper session timeout in milliseconds. It is used in two different ways. First, this value is used in the ZK client that HBase uses to connect to the ensemble. It is also used by HBase when it starts a ZK server and it is passed as the 'maxSessionTimeout'. See http://hadoop.apache.org/zookeeper/docs/current/zookeeperProgrammers.html#ch_zkSessions. For example, if a HBase region server connects to a ZK ensemble that's also managed by HBase, then the session timeout will be the one specified by this configuration. But, a region server that connects to an ensemble managed with a different configuration will be subjected that ensemble's maxSessionTimeout. So, even though HBase might propose using 90 seconds, the ensemble can have a max timeout lower than this and it will take precedence. The current default that ZK ships with is 40 seconds, which is lower than HBase's. + .Default `90000` [[zookeeper.znode.parent]] *`zookeeper.znode.parent`*:: + .Description Root ZNode for HBase in ZooKeeper. All of HBase's ZooKeeper files that are configured with a relative path will go under this node. By default, all of HBase's ZooKeeper file path are configured with a relative path, so they will all go under this directory unless changed. + .Default `/hbase` [[zookeeper.znode.acl.parent]] *`zookeeper.znode.acl.parent`*:: + .Description Root ZNode for access control lists. + .Default `acl` [[hbase.zookeeper.dns.interface]] *`hbase.zookeeper.dns.interface`*:: + .Description The name of the Network Interface from which a ZooKeeper server should report its IP address. + .Default `default` [[hbase.zookeeper.dns.nameserver]] *`hbase.zookeeper.dns.nameserver`*:: + .Description The host name or IP address of the name server (DNS) which a ZooKeeper server should use to determine the host name used by the master for communication and display purposes. + .Default `default` [[hbase.zookeeper.peerport]] *`hbase.zookeeper.peerport`*:: + .Description Port used by ZooKeeper peers to talk to each other. See http://hadoop.apache.org/zookeeper/docs/r3.1.1/zookeeperStarted.html#sc_RunningReplicatedZooKeeper for more information. + .Default `2888` [[hbase.zookeeper.leaderport]] *`hbase.zookeeper.leaderport`*:: + .Description Port used by ZooKeeper for leader election. See http://hadoop.apache.org/zookeeper/docs/r3.1.1/zookeeperStarted.html#sc_RunningReplicatedZooKeeper for more information. + .Default `3888` [[hbase.zookeeper.useMulti]] *`hbase.zookeeper.useMulti`*:: + .Description Instructs HBase to make use of ZooKeeper's multi-update functionality. This allows certain ZooKeeper operations to complete more quickly and prevents some issues with rare Replication failure scenarios (see the release note of HBASE-2611 for an example). IMPORTANT: only set this to true if all ZooKeeper servers in the cluster are on version 3.4+ and will not be downgraded. ZooKeeper versions before 3.4 do not support multi-update and will not fail gracefully if multi-update is invoked (see ZOOKEEPER-1495). + .Default `true` [[hbase.config.read.zookeeper.config]] *`hbase.config.read.zookeeper.config`*:: + .Description Set to true to allow HBaseConfiguration to read the zoo.cfg file for ZooKeeper properties. Switching this to true is not recommended, since the functionality of reading ZK properties from a zoo.cfg file has been deprecated. + .Default `false` [[hbase.zookeeper.property.initLimit]] *`hbase.zookeeper.property.initLimit`*:: + .Description Property from ZooKeeper's config zoo.cfg. The number of ticks that the initial synchronization phase can take. + .Default `10` [[hbase.zookeeper.property.syncLimit]] *`hbase.zookeeper.property.syncLimit`*:: + .Description Property from ZooKeeper's config zoo.cfg. The number of ticks that can pass between sending a request and getting an acknowledgment. + .Default `5` [[hbase.zookeeper.property.dataDir]] *`hbase.zookeeper.property.dataDir`*:: + .Description Property from ZooKeeper's config zoo.cfg. The directory where the snapshot is stored. + .Default `${hbase.tmp.dir}/zookeeper` [[hbase.zookeeper.property.clientPort]] *`hbase.zookeeper.property.clientPort`*:: + .Description Property from ZooKeeper's config zoo.cfg. The port at which the clients will connect. + .Default `2181` [[hbase.zookeeper.property.maxClientCnxns]] *`hbase.zookeeper.property.maxClientCnxns`*:: + .Description Property from ZooKeeper's config zoo.cfg. Limit on number of concurrent connections (at the socket level) that a single client, identified by IP address, may make to a single member of the ZooKeeper ensemble. Set high to avoid zk connection issues running standalone and pseudo-distributed. + .Default `300` [[hbase.client.write.buffer]] *`hbase.client.write.buffer`*:: + .Description Default size of the HTable client write buffer in bytes. A bigger buffer takes more memory -- on both the client and server side since server instantiates the passed write buffer to process it -- but a larger buffer size reduces the number of RPCs made. For an estimate of server-side memory-used, evaluate hbase.client.write.buffer * hbase.regionserver.handler.count + .Default `2097152` [[hbase.client.pause]] *`hbase.client.pause`*:: + .Description General client pause value. Used mostly as value to wait before running a retry of a failed get, region lookup, etc. See hbase.client.retries.number for description of how we backoff from this initial pause amount and how this pause works w/ retries. + .Default `100` [[hbase.client.retries.number]] *`hbase.client.retries.number`*:: + .Description Maximum retries. Used as maximum for all retryable operations such as the getting of a cell's value, starting a row update, etc. Retry interval is a rough function based on hbase.client.pause. At first we retry at this interval but then with backoff, we pretty quickly reach retrying every ten seconds. See HConstants#RETRY_BACKOFF for how the backup ramps up. Change this setting and hbase.client.pause to suit your workload. + .Default `35` [[hbase.client.max.total.tasks]] *`hbase.client.max.total.tasks`*:: + .Description The maximum number of concurrent tasks a single HTable instance will send to the cluster. + .Default `100` [[hbase.client.max.perserver.tasks]] *`hbase.client.max.perserver.tasks`*:: + .Description The maximum number of concurrent tasks a single HTable instance will send to a single region server. + .Default `5` [[hbase.client.max.perregion.tasks]] *`hbase.client.max.perregion.tasks`*:: + .Description The maximum number of concurrent connections the client will maintain to a single Region. That is, if there is already hbase.client.max.perregion.tasks writes in progress for this region, new puts won't be sent to this region until some writes finishes. + .Default `1` [[hbase.client.scanner.caching]] *`hbase.client.scanner.caching`*:: + .Description Number of rows that will be fetched when calling next on a scanner if it is not served from (local, client) memory. Higher caching values will enable faster scanners but will eat up more memory and some calls of next may take longer and longer times when the cache is empty. Do not set this value such that the time between invocations is greater than the scanner timeout; i.e. hbase.client.scanner.timeout.period + .Default `100` [[hbase.client.keyvalue.maxsize]] *`hbase.client.keyvalue.maxsize`*:: + .Description Specifies the combined maximum allowed size of a KeyValue instance. This is to set an upper boundary for a single entry saved in a storage file. Since they cannot be split it helps avoiding that a region cannot be split any further because the data is too large. It seems wise to set this to a fraction of the maximum region size. Setting it to zero or less disables the check. + .Default `10485760` [[hbase.client.scanner.timeout.period]] *`hbase.client.scanner.timeout.period`*:: + .Description Client scanner lease period in milliseconds. + .Default `60000` [[hbase.client.localityCheck.threadPoolSize]] *`hbase.client.localityCheck.threadPoolSize`*:: + .Description + .Default `2` [[hbase.bulkload.retries.number]] *`hbase.bulkload.retries.number`*:: + .Description Maximum retries. This is maximum number of iterations to atomic bulk loads are attempted in the face of splitting operations 0 means never give up. + .Default `10` [[hbase.balancer.period ]] *`hbase.balancer.period `*:: + .Description Period at which the region balancer runs in the Master. + .Default `300000` [[hbase.regions.slop]] *`hbase.regions.slop`*:: + .Description Rebalance if any regionserver has average + (average * slop) regions. + .Default `0.2` [[hbase.server.thread.wakefrequency]] *`hbase.server.thread.wakefrequency`*:: + .Description Time to sleep in between searches for work (in milliseconds). Used as sleep interval by service threads such as log roller. + .Default `10000` [[hbase.server.versionfile.writeattempts]] *`hbase.server.versionfile.writeattempts`*:: + .Description How many time to retry attempting to write a version file before just aborting. Each attempt is seperated by the hbase.server.thread.wakefrequency milliseconds. + .Default `3` [[hbase.hregion.memstore.flush.size]] *`hbase.hregion.memstore.flush.size`*:: + .Description Memstore will be flushed to disk if size of the memstore exceeds this number of bytes. Value is checked by a thread that runs every hbase.server.thread.wakefrequency. + .Default `134217728` [[hbase.hregion.percolumnfamilyflush.size.lower.bound]] *`hbase.hregion.percolumnfamilyflush.size.lower.bound`*:: + .Description If FlushLargeStoresPolicy is used, then every time that we hit the total memstore limit, we find out all the column families whose memstores exceed this value, and only flush them, while retaining the others whose memstores are lower than this limit. If none of the families have their memstore size more than this, all the memstores will be flushed (just as usual). This value should be less than half of the total memstore threshold (hbase.hregion.memstore.flush.size). + .Default `16777216` [[hbase.hregion.preclose.flush.size]] *`hbase.hregion.preclose.flush.size`*:: + .Description If the memstores in a region are this size or larger when we go to close, run a ""pre-flush"" to clear out memstores before we put up the region closed flag and take the region offline. On close, a flush is run under the close flag to empty memory. During this time the region is offline and we are not taking on any writes. If the memstore content is large, this flush could take a long time to complete. The preflush is meant to clean out the bulk of the memstore before putting up the close flag and taking the region offline so the flush that runs under the close flag has little to do. + .Default `5242880` [[hbase.hregion.memstore.block.multiplier]] *`hbase.hregion.memstore.block.multiplier`*:: + .Description Block updates if memstore has hbase.hregion.memstore.block.multiplier times hbase.hregion.memstore.flush.size bytes. Useful preventing runaway memstore during spikes in update traffic. Without an upper-bound, memstore fills such that when it flushes the resultant flush files take a long time to compact or split, or worse, we OOME. + .Default `4` [[hbase.hregion.memstore.mslab.enabled]] *`hbase.hregion.memstore.mslab.enabled`*:: + .Description Enables the MemStore-Local Allocation Buffer, a feature which works to prevent heap fragmentation under heavy write loads. This can reduce the frequency of stop-the-world GC pauses on large heaps. + .Default `true` [[hbase.hregion.max.filesize]] *`hbase.hregion.max.filesize`*:: + .Description Maximum HFile size. If the sum of the sizes of a region's HFiles has grown to exceed this value, the region is split in two. + .Default `10737418240` [[hbase.hregion.majorcompaction]] *`hbase.hregion.majorcompaction`*:: + .Description Time between major compactions, expressed in milliseconds. Set to 0 to disable time-based automatic major compactions. User-requested and size-based major compactions will still run. This value is multiplied by hbase.hregion.majorcompaction.jitter to cause compaction to start at a somewhat-random time during a given window of time. The default value is 7 days, expressed in milliseconds. If major compactions are causing disruption in your environment, you can configure them to run at off-peak times for your deployment, or disable time-based major compactions by setting this parameter to 0, and run major compactions in a cron job or by another external mechanism. + .Default `604800000` [[hbase.hregion.majorcompaction.jitter]] *`hbase.hregion.majorcompaction.jitter`*:: + .Description A multiplier applied to hbase.hregion.majorcompaction to cause compaction to occur a given amount of time either side of hbase.hregion.majorcompaction. The smaller the number, the closer the compactions will happen to the hbase.hregion.majorcompaction interval. + .Default `0.50` [[hbase.hstore.compactionThreshold]] *`hbase.hstore.compactionThreshold`*:: + .Description If more than this number of StoreFiles exist in any one Store (one StoreFile is written per flush of MemStore), a compaction is run to rewrite all StoreFiles into a single StoreFile. Larger values delay compaction, but when compaction does occur, it takes longer to complete. + .Default `3` [[hbase.hstore.flusher.count]] *`hbase.hstore.flusher.count`*:: + .Description The number of flush threads. With fewer threads, the MemStore flushes will be queued. With more threads, the flushes will be executed in parallel, increasing the load on HDFS, and potentially causing more compactions. + .Default `2` [[hbase.hstore.blockingStoreFiles]] *`hbase.hstore.blockingStoreFiles`*:: + .Description If more than this number of StoreFiles exist in any one Store (one StoreFile is written per flush of MemStore), updates are blocked for this region until a compaction is completed, or until hbase.hstore.blockingWaitTime has been exceeded. + .Default `10` [[hbase.hstore.blockingWaitTime]] *`hbase.hstore.blockingWaitTime`*:: + .Description The time for which a region will block updates after reaching the StoreFile limit defined by hbase.hstore.blockingStoreFiles. After this time has elapsed, the region will stop blocking updates even if a compaction has not been completed. + .Default `90000` [[hbase.hstore.compaction.min]] *`hbase.hstore.compaction.min`*:: + .Description The minimum number of StoreFiles which must be eligible for compaction before compaction can run. The goal of tuning hbase.hstore.compaction.min is to avoid ending up with too many tiny StoreFiles to compact. Setting this value to 2 would cause a minor compaction each time you have two StoreFiles in a Store, and this is probably not appropriate. If you set this value too high, all the other values will need to be adjusted accordingly. For most cases, the default value is appropriate. In previous versions of HBase, the parameter hbase.hstore.compaction.min was named hbase.hstore.compactionThreshold. + .Default `3` [[hbase.hstore.compaction.max]] *`hbase.hstore.compaction.max`*:: + .Description The maximum number of StoreFiles which will be selected for a single minor compaction, regardless of the number of eligible StoreFiles. Effectively, the value of hbase.hstore.compaction.max controls the length of time it takes a single compaction to complete. Setting it larger means that more StoreFiles are included in a compaction. For most cases, the default value is appropriate. + .Default `10` [[hbase.hstore.compaction.min.size]] *`hbase.hstore.compaction.min.size`*:: + .Description A StoreFile smaller than this size will always be eligible for minor compaction. HFiles this size or larger are evaluated by hbase.hstore.compaction.ratio to determine if they are eligible. Because this limit represents the ""automatic include""limit for all StoreFiles smaller than this value, this value may need to be reduced in write-heavy environments where many StoreFiles in the 1-2 MB range are being flushed, because every StoreFile will be targeted for compaction and the resulting StoreFiles may still be under the minimum size and require further compaction. If this parameter is lowered, the ratio check is triggered more quickly. This addressed some issues seen in earlier versions of HBase but changing this parameter is no longer necessary in most situations. Default: 128 MB expressed in bytes. + .Default `134217728` [[hbase.hstore.compaction.max.size]] *`hbase.hstore.compaction.max.size`*:: + .Description A StoreFile larger than this size will be excluded from compaction. The effect of raising hbase.hstore.compaction.max.size is fewer, larger StoreFiles that do not get compacted often. If you feel that compaction is happening too often without much benefit, you can try raising this value. Default: the value of LONG.MAX_VALUE, expressed in bytes. + .Default `9223372036854775807` [[hbase.hstore.compaction.ratio]] *`hbase.hstore.compaction.ratio`*:: + .Description For minor compaction, this ratio is used to determine whether a given StoreFile which is larger than hbase.hstore.compaction.min.size is eligible for compaction. Its effect is to limit compaction of large StoreFiles. The value of hbase.hstore.compaction.ratio is expressed as a floating-point decimal. A large ratio, such as 10, will produce a single giant StoreFile. Conversely, a low value, such as .25, will produce behavior similar to the BigTable compaction algorithm, producing four StoreFiles. A moderate value of between 1.0 and 1.4 is recommended. When tuning this value, you are balancing write costs with read costs. Raising the value (to something like 1.4) will have more write costs, because you will compact larger StoreFiles. However, during reads, HBase will need to seek through fewer StoreFiles to accomplish the read. Consider this approach if you cannot take advantage of Bloom filters. Otherwise, you can lower this value to something like 1.0 to reduce the background cost of writes, and use Bloom filters to control the number of StoreFiles touched during reads. For most cases, the default value is appropriate. + .Default `1.2F` [[hbase.hstore.compaction.ratio.offpeak]] *`hbase.hstore.compaction.ratio.offpeak`*:: + .Description Allows you to set a different (by default, more aggressive) ratio for determining whether larger StoreFiles are included in compactions during off-peak hours. Works in the same way as hbase.hstore.compaction.ratio. Only applies if hbase.offpeak.start.hour and hbase.offpeak.end.hour are also enabled. + .Default `5.0F` [[hbase.hstore.time.to.purge.deletes]] *`hbase.hstore.time.to.purge.deletes`*:: + .Description The amount of time to delay purging of delete markers with future timestamps. If unset, or set to 0, all delete markers, including those with future timestamps, are purged during the next major compaction. Otherwise, a delete marker is kept until the major compaction which occurs after the marker's timestamp plus the value of this setting, in milliseconds. + .Default `0` [[hbase.offpeak.start.hour]] *`hbase.offpeak.start.hour`*:: + .Description The start of off-peak hours, expressed as an integer between 0 and 23, inclusive. Set to -1 to disable off-peak. + .Default `-1` [[hbase.offpeak.end.hour]] *`hbase.offpeak.end.hour`*:: + .Description The end of off-peak hours, expressed as an integer between 0 and 23, inclusive. Set to -1 to disable off-peak. + .Default `-1` [[hbase.regionserver.thread.compaction.throttle]] *`hbase.regionserver.thread.compaction.throttle`*:: + .Description There are two different thread pools for compactions, one for large compactions and the other for small compactions. This helps to keep compaction of lean tables (such as hbase:meta) fast. If a compaction is larger than this threshold, it goes into the large compaction pool. In most cases, the default value is appropriate. Default: 2 x hbase.hstore.compaction.max x hbase.hregion.memstore.flush.size (which defaults to 128MB). The value field assumes that the value of hbase.hregion.memstore.flush.size is unchanged from the default. + .Default `2684354560` [[hbase.hstore.compaction.kv.max]] *`hbase.hstore.compaction.kv.max`*:: + .Description The maximum number of KeyValues to read and then write in a batch when flushing or compacting. Set this lower if you have big KeyValues and problems with Out Of Memory Exceptions Set this higher if you have wide, small rows. + .Default `10` [[hbase.storescanner.parallel.seek.enable]] *`hbase.storescanner.parallel.seek.enable`*:: + .Description Enables StoreFileScanner parallel-seeking in StoreScanner, a feature which can reduce response latency under special conditions. + .Default `false` [[hbase.storescanner.parallel.seek.threads]] *`hbase.storescanner.parallel.seek.threads`*:: + .Description The default thread pool size if parallel-seeking feature enabled. + .Default `10` [[hfile.block.cache.size]] *`hfile.block.cache.size`*:: + .Description Percentage of maximum heap (-Xmx setting) to allocate to block cache used by a StoreFile. Default of 0.4 means allocate 40%. Set to 0 to disable but it's not recommended; you need at least enough cache to hold the storefile indices. + .Default `0.4` [[hfile.block.index.cacheonwrite]] *`hfile.block.index.cacheonwrite`*:: + .Description This allows to put non-root multi-level index blocks into the block cache at the time the index is being written. + .Default `false` [[hfile.index.block.max.size]] *`hfile.index.block.max.size`*:: + .Description When the size of a leaf-level, intermediate-level, or root-level index block in a multi-level block index grows to this size, the block is written out and a new block is started. + .Default `131072` [[hbase.bucketcache.ioengine]] *`hbase.bucketcache.ioengine`*:: + .Description Where to store the contents of the bucketcache. One of: onheap, offheap, or file. If a file, set it to file:PATH_TO_FILE. See https://hbase.apache.org/apidocs/org/apache/hadoop/hbase/io/hfile/CacheConfig.html for more information. + .Default `` [[hbase.bucketcache.combinedcache.enabled]] *`hbase.bucketcache.combinedcache.enabled`*:: + .Description Whether or not the bucketcache is used in league with the LRU on-heap block cache. In this mode, indices and blooms are kept in the LRU blockcache and the data blocks are kept in the bucketcache. + .Default `true` [[hbase.bucketcache.size]] *`hbase.bucketcache.size`*:: + .Description Used along with bucket cache, this is a float that EITHER represents a percentage of total heap memory size to give to the cache (if < 1.0) OR, it is the capacity in megabytes of the cache. + .Default `0` when specified as a float [[hbase.bucketcache.bucket.sizes]] *`hbase.bucketcache.bucket.sizes`*:: + .Description A comma-separated list of sizes for buckets for the bucketcache if you use multiple sizes. Should be a list of block sizes in order from smallest to largest. The sizes you use will depend on your data access patterns. + .Default `` [[hfile.format.version]] *`hfile.format.version`*:: + .Description The HFile format version to use for new files. Version 3 adds support for tags in hfiles (See http://hbase.apache.org/book.html#hbase.tags). Distributed Log Replay requires that tags are enabled. Also see the configuration 'hbase.replication.rpc.codec'. + .Default `3` [[hfile.block.bloom.cacheonwrite]] *`hfile.block.bloom.cacheonwrite`*:: + .Description Enables cache-on-write for inline blocks of a compound Bloom filter. + .Default `false` [[io.storefile.bloom.block.size]] *`io.storefile.bloom.block.size`*:: + .Description The size in bytes of a single block (""chunk"") of a compound Bloom filter. This size is approximate, because Bloom blocks can only be inserted at data block boundaries, and the number of keys per data block varies. + .Default `131072` [[hbase.rs.cacheblocksonwrite]] *`hbase.rs.cacheblocksonwrite`*:: + .Description Whether an HFile block should be added to the block cache when the block is finished. + .Default `false` [[hbase.rpc.timeout]] *`hbase.rpc.timeout`*:: + .Description This is for the RPC layer to define how long HBase client applications take for a remote call to time out. It uses pings to check connections but will eventually throw a TimeoutException. + .Default `60000` [[hbase.rpc.shortoperation.timeout]] *`hbase.rpc.shortoperation.timeout`*:: + .Description This is another version of ""hbase.rpc.timeout"". For those RPC operation within cluster, we rely on this configuration to set a short timeout limitation for short operation. For example, short rpc timeout for region server's trying to report to active master can benefit quicker master failover process. + .Default `10000` [[hbase.ipc.client.tcpnodelay]] *`hbase.ipc.client.tcpnodelay`*:: + .Description Set no delay on rpc socket connections. See http://docs.oracle.com/javase/1.5.0/docs/api/java/net/Socket.html#getTcpNoDelay() + .Default `true` [[hbase.master.keytab.file]] *`hbase.master.keytab.file`*:: + .Description Full path to the kerberos keytab file to use for logging in the configured HMaster server principal. + .Default `` [[hbase.master.kerberos.principal]] *`hbase.master.kerberos.principal`*:: + .Description Ex. ""hbase/_HOST@EXAMPLE.COM"". The kerberos principal name that should be used to run the HMaster process. The principal name should be in the form: user/hostname@DOMAIN. If ""_HOST"" is used as the hostname portion, it will be replaced with the actual hostname of the running instance. + .Default `` [[hbase.regionserver.keytab.file]] *`hbase.regionserver.keytab.file`*:: + .Description Full path to the kerberos keytab file to use for logging in the configured HRegionServer server principal. + .Default `` [[hbase.regionserver.kerberos.principal]] *`hbase.regionserver.kerberos.principal`*:: + .Description Ex. ""hbase/_HOST@EXAMPLE.COM"". The kerberos principal name that should be used to run the HRegionServer process. The principal name should be in the form: user/hostname@DOMAIN. If ""_HOST"" is used as the hostname portion, it will be replaced with the actual hostname of the running instance. An entry for this principal must exist in the file specified in hbase.regionserver.keytab.file + .Default `` [[hadoop.policy.file]] *`hadoop.policy.file`*:: + .Description The policy configuration file used by RPC servers to make authorization decisions on client requests. Only used when HBase security is enabled. + .Default `hbase-policy.xml` [[hbase.superuser]] *`hbase.superuser`*:: + .Description List of users or groups (comma-separated), who are allowed full privileges, regardless of stored ACLs, across the cluster. Only used when HBase security is enabled. + .Default `` [[hbase.auth.key.update.interval]] *`hbase.auth.key.update.interval`*:: + .Description The update interval for master key for authentication tokens in servers in milliseconds. Only used when HBase security is enabled. + .Default `86400000` [[hbase.auth.token.max.lifetime]] *`hbase.auth.token.max.lifetime`*:: + .Description The maximum lifetime in milliseconds after which an authentication token expires. Only used when HBase security is enabled. + .Default `604800000` [[hbase.ipc.client.fallback-to-simple-auth-allowed]] *`hbase.ipc.client.fallback-to-simple-auth-allowed`*:: + .Description When a client is configured to attempt a secure connection, but attempts to connect to an insecure server, that server may instruct the client to switch to SASL SIMPLE (unsecure) authentication. This setting controls whether or not the client will accept this instruction from the server. When false (the default), the client will not allow the fallback to SIMPLE authentication, and will abort the connection. + .Default `false` [[hbase.display.keys]] *`hbase.display.keys`*:: + .Description When this is set to true the webUI and such will display all start/end keys as part of the table details, region names, etc. When this is set to false, the keys are hidden. + .Default `true` [[hbase.coprocessor.region.classes]] *`hbase.coprocessor.region.classes`*:: + .Description A comma-separated list of Coprocessors that are loaded by default on all tables. For any override coprocessor method, these classes will be called in order. After implementing your own Coprocessor, just put it in HBase's classpath and add the fully qualified class name here. A coprocessor can also be loaded on demand by setting HTableDescriptor. + .Default `` [[hbase.rest.port]] *`hbase.rest.port`*:: + .Description The port for the HBase REST server. + .Default `8080` [[hbase.rest.readonly]] *`hbase.rest.readonly`*:: + .Description Defines the mode the REST server will be started in. Possible values are: false: All HTTP methods are permitted - GET/PUT/POST/DELETE. true: Only the GET method is permitted. + .Default `false` [[hbase.rest.threads.max]] *`hbase.rest.threads.max`*:: + .Description The maximum number of threads of the REST server thread pool. Threads in the pool are reused to process REST requests. This controls the maximum number of requests processed concurrently. It may help to control the memory used by the REST server to avoid OOM issues. If the thread pool is full, incoming requests will be queued up and wait for some free threads. + .Default `100` [[hbase.rest.threads.min]] *`hbase.rest.threads.min`*:: + .Description The minimum number of threads of the REST server thread pool. The thread pool always has at least these number of threads so the REST server is ready to serve incoming requests. + .Default `2` [[hbase.rest.support.proxyuser]] *`hbase.rest.support.proxyuser`*:: + .Description Enables running the REST server to support proxy-user mode. + .Default `false` [[hbase.defaults.for.version.skip]] *`hbase.defaults.for.version.skip`*:: + .Description Set to true to skip the 'hbase.defaults.for.version' check. Setting this to true can be useful in contexts other than the other side of a maven generation; i.e. running in an ide. You'll want to set this boolean to true to avoid seeing the RuntimException complaint: ""hbase-default.xml file seems to be for and old version of HBase (\\${hbase.version}), this version is X.X.X-SNAPSHOT"" + .Default `false` [[hbase.coprocessor.master.classes]] *`hbase.coprocessor.master.classes`*:: + .Description A comma-separated list of org.apache.hadoop.hbase.coprocessor.MasterObserver coprocessors that are loaded by default on the active HMaster process. For any implemented coprocessor methods, the listed classes will be called in order. After implementing your own MasterObserver, just put it in HBase's classpath and add the fully qualified class name here. + .Default `` [[hbase.coprocessor.abortonerror]] *`hbase.coprocessor.abortonerror`*:: + .Description Set to true to cause the hosting server (master or regionserver) to abort if a coprocessor fails to load, fails to initialize, or throws an unexpected Throwable object. Setting this to false will allow the server to continue execution but the system wide state of the coprocessor in question will become inconsistent as it will be properly executing in only a subset of servers, so this is most useful for debugging only. + .Default `true` [[hbase.online.schema.update.enable]] *`hbase.online.schema.update.enable`*:: + .Description Set true to enable online schema changes. + .Default `true` [[hbase.table.lock.enable]] *`hbase.table.lock.enable`*:: + .Description Set to true to enable locking the table in zookeeper for schema change operations. Table locking from master prevents concurrent schema modifications to corrupt table state. + .Default `true` [[hbase.table.max.rowsize]] *`hbase.table.max.rowsize`*:: + .Description Maximum size of single row in bytes (default is 1 Gb) for Get'ting or Scan'ning without in-row scan flag set. If row size exceeds this limit RowTooBigException is thrown to client. + .Default `1073741824` [[hbase.thrift.minWorkerThreads]] *`hbase.thrift.minWorkerThreads`*:: + .Description The ""core size"" of the thread pool. New threads are created on every connection until this many threads are created. + .Default `16` [[hbase.thrift.maxWorkerThreads]] *`hbase.thrift.maxWorkerThreads`*:: + .Description The maximum size of the thread pool. When the pending request queue overflows, new threads are created until their number reaches this number. After that, the server starts dropping connections. + .Default `1000` [[hbase.thrift.maxQueuedRequests]] *`hbase.thrift.maxQueuedRequests`*:: + .Description The maximum number of pending Thrift connections waiting in the queue. If there are no idle threads in the pool, the server queues requests. Only when the queue overflows, new threads are added, up to hbase.thrift.maxQueuedRequests threads. + .Default `1000` [[hbase.regionserver.thrift.framed]] *`hbase.regionserver.thrift.framed`*:: + .Description Use Thrift TFramedTransport on the server side. This is the recommended transport for thrift servers and requires a similar setting on the client side. Changing this to false will select the default transport, vulnerable to DoS when malformed requests are issued due to THRIFT-601. + .Default `false` [[hbase.regionserver.thrift.framed.max_frame_size_in_mb]] *`hbase.regionserver.thrift.framed.max_frame_size_in_mb`*:: + .Description Default frame size when using framed transport + .Default `2` [[hbase.regionserver.thrift.compact]] *`hbase.regionserver.thrift.compact`*:: + .Description Use Thrift TCompactProtocol binary serialization protocol. + .Default `false` [[hbase.data.umask.enable]] *`hbase.data.umask.enable`*:: + .Description Enable, if true, that file permissions should be assigned to the files written by the regionserver + .Default `false` [[hbase.data.umask]] *`hbase.data.umask`*:: + .Description File permissions that should be used to write data files when hbase.data.umask.enable is true + .Default `000` [[hbase.snapshot.enabled]] *`hbase.snapshot.enabled`*:: + .Description Set to true to allow snapshots to be taken / restored / cloned. + .Default `true` [[hbase.snapshot.restore.take.failsafe.snapshot]] *`hbase.snapshot.restore.take.failsafe.snapshot`*:: + .Description Set to true to take a snapshot before the restore operation. The snapshot taken will be used in case of failure, to restore the previous state. At the end of the restore operation this snapshot will be deleted + .Default `true` [[hbase.snapshot.restore.failsafe.name]] *`hbase.snapshot.restore.failsafe.name`*:: + .Description Name of the failsafe snapshot taken by the restore operation. You can use the {snapshot.name}, {table.name} and {restore.timestamp} variables to create a name based on what you are restoring. + .Default `hbase-failsafe-{snapshot.name}-{restore.timestamp}` [[hbase.server.compactchecker.interval.multiplier]] *`hbase.server.compactchecker.interval.multiplier`*:: + .Description The number that determines how often we scan to see if compaction is necessary. Normally, compactions are done after some events (such as memstore flush), but if region didn't receive a lot of writes for some time, or due to different compaction policies, it may be necessary to check it periodically. The interval between checks is hbase.server.compactchecker.interval.multiplier multiplied by hbase.server.thread.wakefrequency. + .Default `1000` [[hbase.lease.recovery.timeout]] *`hbase.lease.recovery.timeout`*:: + .Description How long we wait on dfs lease recovery in total before giving up. + .Default `900000` [[hbase.lease.recovery.dfs.timeout]] *`hbase.lease.recovery.dfs.timeout`*:: + .Description How long between dfs recover lease invocations. Should be larger than the sum of the time it takes for the namenode to issue a block recovery command as part of datanode; dfs.heartbeat.interval and the time it takes for the primary datanode, performing block recovery to timeout on a dead datanode; usually dfs.client.socket-timeout. See the end of HBASE-8389 for more. + .Default `64000` [[hbase.column.max.version]] *`hbase.column.max.version`*:: + .Description New column family descriptors will use this value as the default number of versions to keep. + .Default `1` [[hbase.dfs.client.read.shortcircuit.buffer.size]] *`hbase.dfs.client.read.shortcircuit.buffer.size`*:: + .Description If the DFSClient configuration dfs.client.read.shortcircuit.buffer.size is unset, we will use what is configured here as the short circuit read default direct byte buffer size. DFSClient native default is 1MB; HBase keeps its HDFS files open so number of file blocks * 1MB soon starts to add up and threaten OOME because of a shortage of direct memory. So, we set it down from the default. Make it > the default hbase block size set in the HColumnDescriptor which is usually 64k. + .Default `131072` [[hbase.regionserver.checksum.verify]] *`hbase.regionserver.checksum.verify`*:: + .Description If set to true (the default), HBase verifies the checksums for hfile blocks. HBase writes checksums inline with the data when it writes out hfiles. HDFS (as of this writing) writes checksums to a separate file than the data file necessitating extra seeks. Setting this flag saves some on i/o. Checksum verification by HDFS will be internally disabled on hfile streams when this flag is set. If the hbase-checksum verification fails, we will switch back to using HDFS checksums (so do not disable HDFS checksums! And besides this feature applies to hfiles only, not to WALs). If this parameter is set to false, then hbase will not verify any checksums, instead it will depend on checksum verification being done in the HDFS client. + .Default `true` [[hbase.hstore.bytes.per.checksum]] *`hbase.hstore.bytes.per.checksum`*:: + .Description Number of bytes in a newly created checksum chunk for HBase-level checksums in hfile blocks. + .Default `16384` [[hbase.hstore.checksum.algorithm]] *`hbase.hstore.checksum.algorithm`*:: + .Description Name of an algorithm that is used to compute checksums. Possible values are NULL, CRC32, CRC32C. + .Default `CRC32` [[hbase.status.published]] *`hbase.status.published`*:: + .Description This setting activates the publication by the master of the status of the region server. When a region server dies and its recovery starts, the master will push this information to the client application, to let them cut the connection immediately instead of waiting for a timeout. + .Default `false` [[hbase.status.publisher.class]] *`hbase.status.publisher.class`*:: + .Description Implementation of the status publication with a multicast message. + .Default `org.apache.hadoop.hbase.master.ClusterStatusPublisher$MulticastPublisher` [[hbase.status.listener.class]] *`hbase.status.listener.class`*:: + .Description Implementation of the status listener with a multicast message. + .Default `org.apache.hadoop.hbase.client.ClusterStatusListener$MulticastListener` [[hbase.status.multicast.address.ip]] *`hbase.status.multicast.address.ip`*:: + .Description Multicast address to use for the status publication by multicast. + .Default `226.1.1.3` [[hbase.status.multicast.address.port]] *`hbase.status.multicast.address.port`*:: + .Description Multicast port to use for the status publication by multicast. + .Default `16100` [[hbase.dynamic.jars.dir]] *`hbase.dynamic.jars.dir`*:: + .Description The directory from which the custom filter/co-processor jars can be loaded dynamically by the region server without the need to restart. However, an already loaded filter/co-processor class would not be un-loaded. See HBASE-1936 for more details. + .Default `${hbase.rootdir}/lib` [[hbase.security.authentication]] *`hbase.security.authentication`*:: + .Description Controls whether or not secure authentication is enabled for HBase. Possible values are 'simple' (no authentication), and 'kerberos'. + .Default `simple` [[hbase.rest.filter.classes]] *`hbase.rest.filter.classes`*:: + .Description Servlet filters for REST service. + .Default `org.apache.hadoop.hbase.rest.filter.GzipFilter` [[hbase.master.loadbalancer.class]] *`hbase.master.loadbalancer.class`*:: + .Description Class used to execute the regions balancing when the period occurs. See the class comment for more on how it works http://hbase.apache.org/devapidocs/org/apache/hadoop/hbase/master/balancer/StochasticLoadBalancer.html It replaces the DefaultLoadBalancer as the default (since renamed as the SimpleLoadBalancer). + .Default `org.apache.hadoop.hbase.master.balancer.StochasticLoadBalancer` [[hbase.security.exec.permission.checks]] *`hbase.security.exec.permission.checks`*:: + .Description If this setting is enabled and ACL based access control is active (the AccessController coprocessor is installed either as a system coprocessor or on a table as a table coprocessor) then you must grant all relevant users EXEC privilege if they require the ability to execute coprocessor endpoint calls. EXEC privilege, like any other permission, can be granted globally to a user, or to a user on a per table or per namespace basis. For more information on coprocessor endpoints, see the coprocessor section of the HBase online manual. For more information on granting or revoking permissions using the AccessController, see the security section of the HBase online manual. + .Default `false` [[hbase.procedure.regionserver.classes]] *`hbase.procedure.regionserver.classes`*:: + .Description A comma-separated list of org.apache.hadoop.hbase.procedure.RegionServerProcedureManager procedure managers that are loaded by default on the active HRegionServer process. The lifecycle methods (init/start/stop) will be called by the active HRegionServer process to perform the specific globally barriered procedure. After implementing your own RegionServerProcedureManager, just put it in HBase's classpath and add the fully qualified class name here. + .Default `` [[hbase.procedure.master.classes]] *`hbase.procedure.master.classes`*:: + .Description A comma-separated list of org.apache.hadoop.hbase.procedure.MasterProcedureManager procedure managers that are loaded by default on the active HMaster process. A procedure is identified by its signature and users can use the signature and an instant name to trigger an execution of a globally barriered procedure. After implementing your own MasterProcedureManager, just put it in HBase's classpath and add the fully qualified class name here. + .Default `` [[hbase.coordinated.state.manager.class]] *`hbase.coordinated.state.manager.class`*:: + .Description Fully qualified name of class implementing coordinated state manager. + .Default `org.apache.hadoop.hbase.coordination.ZkCoordinatedStateManager` [[hbase.regionserver.storefile.refresh.period]] *`hbase.regionserver.storefile.refresh.period`*:: + .Description The period (in milliseconds) for refreshing the store files for the secondary regions. 0 means this feature is disabled. Secondary regions sees new files (from flushes and compactions) from primary once the secondary region refreshes the list of files in the region (there is no notification mechanism). But too frequent refreshes might cause extra Namenode pressure. If the files cannot be refreshed for longer than HFile TTL (hbase.master.hfilecleaner.ttl) the requests are rejected. Configuring HFile TTL to a larger value is also recommended with this setting. + .Default `0` [[hbase.region.replica.replication.enabled]] *`hbase.region.replica.replication.enabled`*:: + .Description Whether asynchronous WAL replication to the secondary region replicas is enabled or not. If this is enabled, a replication peer named ""region_replica_replication"" will be created which will tail the logs and replicate the mutatations to region replicas for tables that have region replication > 1. If this is enabled once, disabling this replication also requires disabling the replication peer using shell or ReplicationAdmin java class. Replication to secondary region replicas works over standard inter-cluster replication. So replication, if disabled explicitly, also has to be enabled by setting ""hbase.replication"" to true for this feature to work. + .Default `false` [[hbase.http.filter.initializers]] *`hbase.http.filter.initializers`*:: + .Description A comma separated list of class names. Each class in the list must extend org.apache.hadoop.hbase.http.FilterInitializer. The corresponding Filter will be initialized. Then, the Filter will be applied to all user facing jsp and servlet web pages. The ordering of the list defines the ordering of the filters. The default StaticUserWebFilter add a user principal as defined by the hbase.http.staticuser.user property. + .Default `org.apache.hadoop.hbase.http.lib.StaticUserWebFilter` [[hbase.security.visibility.mutations.checkauths]] *`hbase.security.visibility.mutations.checkauths`*:: + .Description This property if enabled, will check whether the labels in the visibility expression are associated with the user issuing the mutation + .Default `false` [[hbase.http.max.threads]] *`hbase.http.max.threads`*:: + .Description The maximum number of threads that the HTTP Server will create in its ThreadPool. + .Default `10` [[hbase.replication.rpc.codec]] *`hbase.replication.rpc.codec`*:: + .Description The codec that is to be used when replication is enabled so that the tags are also replicated. This is used along with HFileV3 which supports tags in them. If tags are not used or if the hfile version used is HFileV2 then KeyValueCodec can be used as the replication codec. Note that using KeyValueCodecWithTags for replication when there are no tags causes no harm. + .Default `org.apache.hadoop.hbase.codec.KeyValueCodecWithTags` [[hbase.http.staticuser.user]] *`hbase.http.staticuser.user`*:: + .Description The user name to filter as, on static web filters while rendering content. An example use is the HDFS web UI (user to be used for browsing files). + .Default `dr.stack` [[hbase.regionserver.handler.abort.on.error.percent]] *`hbase.regionserver.handler.abort.on.error.percent`*:: + .Description The percent of region server RPC threads failed to abort RS. -1 Disable aborting; 0 Abort if even a single handler has died; 0.x Abort only when this percent of handlers have died; 1 Abort only all of the handers have died. + .Default `0.5` [[hbase.master.cleaner.snapshot.interval]] *`hbase.master.cleaner.snapshot.interval`*:: + .Description Snapshot Cleanup chore interval in milliseconds. The cleanup thread keeps running at this interval to find all snapshots that are expired based on TTL and delete them. + .Default `1800000` [[hbase.master.snapshot.ttl]] *`hbase.master.snapshot.ttl`*:: + .Description Default Snapshot TTL to be considered when the user does not specify TTL while creating snapshot. Default value 0 indicates FOREVERE - snapshot should not be automatically deleted until it is manually deleted + .Default `0` [[hbase.master.regions.recovery.check.interval]] *`hbase.master.regions.recovery.check.interval`*:: + .Description Regions Recovery Chore interval in milliseconds. This chore keeps running at this interval to find all regions with configurable max store file ref count and reopens them. + .Default `1200000` [[hbase.regions.recovery.store.file.ref.count]] *`hbase.regions.recovery.store.file.ref.count`*:: + .Description Very large number of ref count on a compacted store file indicates that it is a ref leak on that object(compacted store file). Such files can not be removed after it is invalidated via compaction. Only way to recover in such scenario is to reopen the region which can release all resources, like the refcount, leases, etc. This config represents Store files Ref Count threshold value considered for reopening regions. Any region with compacted store files ref count > this value would be eligible for reopening by master. Here, we get the max refCount among all refCounts on all compacted away store files that belong to a particular region. Default value -1 indicates this feature is turned off. Only positive integer value should be provided to enable this feature. + .Default `-1` [[hbase.rpc.rows.size.threshold.reject]] *`hbase.rpc.rows.size.threshold.reject`*:: + .Description If value is true, RegionServer will abort batch requests of Put/Delete with number of rows in a batch operation exceeding threshold defined by value of config: hbase.rpc.rows.warning.threshold. The default value is false and hence, by default, only warning will be logged. This config should be turned on to prevent RegionServer from serving very large batch size of rows and this way we can improve CPU usages by discarding too large batch request. + .Default `false` [[hbase.regionserver.slowlog.ringbuffer.size]] *`hbase.regionserver.slowlog.ringbuffer.size`*:: + .Description Default size of ringbuffer to be maintained by each RegionServer in order to store online slowlog responses. This is an in-memory ring buffer of requests that were judged to be too slow in addition to the responseTooSlow logging. The in-memory representation would be complete. For more details, please look into Doc Section: <> + .Default `256` [[hbase.regionserver.slowlog.buffer.enabled]] *`hbase.regionserver.slowlog.buffer.enabled`*:: + .Description Indicates whether RegionServers have ring buffer running for storing Online Slow logs in FIFO manner with limited entries. The size of the ring buffer is indicated by config: hbase.regionserver.slowlog.ringbuffer.size The default value is false, turn this on and get latest slowlog responses with complete data. For more details, please look into Doc Section: <> + .Default `false` [[hbase.regionserver.slowlog.systable.enabled]] *`hbase.regionserver.slowlog.systable.enabled`*:: + .Description Should be enabled only if hbase.regionserver.slowlog.buffer.enabled is enabled. If enabled (true), all slow/large RPC logs would be persisted to system table hbase:slowlog (in addition to in-memory ring buffer at each RegionServer). The records are stored in increasing order of time. Operators can scan the table with various combination of ColumnValueFilter and time range. More details are provided in the doc section: ""Get Slow/Large Response Logs from System table hbase:slowlog"" + .Default `false` [[hbase.master.balancer.decision.buffer.enabled]] *`hbase.master.balancer.decision.buffer.enabled`*:: + .Description Indicates whether active HMaster has ring buffer running for storing balancer decisions in FIFO manner with limited entries. The size of the ring buffer is indicated by config: hbase.master.balancer.decision.queue.size + .Default `false` ",16319,True,3116.8053955582127,median "----------------------------------------------------------------------- -- AWA.Events.Models -- AWA.Events.Models ----------------------------------------------------------------------- -- File generated by ada-gen DO NOT MODIFY -- Template used: templates/model/package-body.xhtml -- Ada Generator: https://ada-gen.googlecode.com/svn/trunk Revision 1095 ----------------------------------------------------------------------- -- Copyright (C) 2019 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the ""License""); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an ""AS IS"" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Beans.Objects.Time; package body AWA.Events.Models is use type ADO.Objects.Object_Record_Access; use type ADO.Objects.Object_Ref; pragma Warnings (Off, ""formal parameter * is not referenced""); function Message_Type_Key (Id : in ADO.Identifier) return ADO.Objects.Object_Key is Result : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => MESSAGE_TYPE_DEF'Access); begin ADO.Objects.Set_Value (Result, Id); return Result; end Message_Type_Key; function Message_Type_Key (Id : in String) return ADO.Objects.Object_Key is Result : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => MESSAGE_TYPE_DEF'Access); begin ADO.Objects.Set_Value (Result, Id); return Result; end Message_Type_Key; function ""="" (Left, Right : Message_Type_Ref'Class) return Boolean is begin return ADO.Objects.Object_Ref'Class (Left) = ADO.Objects.Object_Ref'Class (Right); end ""=""; procedure Set_Field (Object : in out Message_Type_Ref'Class; Impl : out Message_Type_Access) is Result : ADO.Objects.Object_Record_Access; begin Object.Prepare_Modify (Result); Impl := Message_Type_Impl (Result.all)'Access; end Set_Field; -- Internal method to allocate the Object_Record instance procedure Allocate (Object : in out Message_Type_Ref) is Impl : Message_Type_Access; begin Impl := new Message_Type_Impl; ADO.Objects.Set_Object (Object, Impl.all'Access); end Allocate; -- ---------------------------------------- -- Data object: Message_Type -- ---------------------------------------- procedure Set_Id (Object : in out Message_Type_Ref; Value : in ADO.Identifier) is Impl : Message_Type_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Key_Value (Impl.all, 1, Value); end Set_Id; function Get_Id (Object : in Message_Type_Ref) return ADO.Identifier is Impl : constant Message_Type_Access := Message_Type_Impl (Object.Get_Object.all)'Access; begin return Impl.Get_Key_Value; end Get_Id; procedure Set_Name (Object : in out Message_Type_Ref; Value : in String) is Impl : Message_Type_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_String (Impl.all, 2, Impl.Name, Value); end Set_Name; procedure Set_Name (Object : in out Message_Type_Ref; Value : in Ada.Strings.Unbounded.Unbounded_String) is Impl : Message_Type_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Unbounded_String (Impl.all, 2, Impl.Name, Value); end Set_Name; function Get_Name (Object : in Message_Type_Ref) return String is begin return Ada.Strings.Unbounded.To_String (Object.Get_Name); end Get_Name; function Get_Name (Object : in Message_Type_Ref) return Ada.Strings.Unbounded.Unbounded_String is Impl : constant Message_Type_Access := Message_Type_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Name; end Get_Name; -- Copy of the object. procedure Copy (Object : in Message_Type_Ref; Into : in out Message_Type_Ref) is Result : Message_Type_Ref; begin if not Object.Is_Null then declare Impl : constant Message_Type_Access := Message_Type_Impl (Object.Get_Load_Object.all)'Access; Copy : constant Message_Type_Access := new Message_Type_Impl; begin ADO.Objects.Set_Object (Result, Copy.all'Access); Copy.Copy (Impl.all); Copy.Name := Impl.Name; end; end if; Into := Result; end Copy; procedure Find (Object : in out Message_Type_Ref; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean) is Impl : constant Message_Type_Access := new Message_Type_Impl; begin Impl.Find (Session, Query, Found); if Found then ADO.Objects.Set_Object (Object, Impl.all'Access); else ADO.Objects.Set_Object (Object, null); Destroy (Impl); end if; end Find; procedure Load (Object : in out Message_Type_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier) is Impl : constant Message_Type_Access := new Message_Type_Impl; Found : Boolean; Query : ADO.SQL.Query; begin Query.Bind_Param (Position => 1, Value => Id); Query.Set_Filter (""id = ?""); Impl.Find (Session, Query, Found); if not Found then Destroy (Impl); raise ADO.Objects.NOT_FOUND; end if; ADO.Objects.Set_Object (Object, Impl.all'Access); end Load; procedure Load (Object : in out Message_Type_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier; Found : out Boolean) is Impl : constant Message_Type_Access := new Message_Type_Impl; Query : ADO.SQL.Query; begin Query.Bind_Param (Position => 1, Value => Id); Query.Set_Filter (""id = ?""); Impl.Find (Session, Query, Found); if not Found then Destroy (Impl); else ADO.Objects.Set_Object (Object, Impl.all'Access); end if; end Load; procedure Save (Object : in out Message_Type_Ref; Session : in out ADO.Sessions.Master_Session'Class) is Impl : ADO.Objects.Object_Record_Access := Object.Get_Object; begin if Impl = null then Impl := new Message_Type_Impl; ADO.Objects.Set_Object (Object, Impl); end if; if not ADO.Objects.Is_Created (Impl.all) then Impl.Create (Session); else Impl.Save (Session); end if; end Save; procedure Delete (Object : in out Message_Type_Ref; Session : in out ADO.Sessions.Master_Session'Class) is Impl : constant ADO.Objects.Object_Record_Access := Object.Get_Object; begin if Impl /= null then Impl.Delete (Session); end if; end Delete; -- -------------------- -- Free the object -- -------------------- procedure Destroy (Object : access Message_Type_Impl) is type Message_Type_Impl_Ptr is access all Message_Type_Impl; procedure Unchecked_Free is new Ada.Unchecked_Deallocation (Message_Type_Impl, Message_Type_Impl_Ptr); pragma Warnings (Off, ""*redundant conversion*""); Ptr : Message_Type_Impl_Ptr := Message_Type_Impl (Object.all)'Access; pragma Warnings (On, ""*redundant conversion*""); begin Unchecked_Free (Ptr); end Destroy; procedure Find (Object : in out Message_Type_Impl; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean) is Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query, MESSAGE_TYPE_DEF'Access); begin Stmt.Execute; if Stmt.Has_Elements then Object.Load (Stmt, Session); Stmt.Next; Found := not Stmt.Has_Elements; else Found := False; end if; end Find; overriding procedure Load (Object : in out Message_Type_Impl; Session : in out ADO.Sessions.Session'Class) is Found : Boolean; Query : ADO.SQL.Query; Id : constant ADO.Identifier := Object.Get_Key_Value; begin Query.Bind_Param (Position => 1, Value => Id); Query.Set_Filter (""id = ?""); Object.Find (Session, Query, Found); if not Found then raise ADO.Objects.NOT_FOUND; end if; end Load; procedure Save (Object : in out Message_Type_Impl; Session : in out ADO.Sessions.Master_Session'Class) is Stmt : ADO.Statements.Update_Statement := Session.Create_Statement (MESSAGE_TYPE_DEF'Access); begin if Object.Is_Modified (1) then Stmt.Save_Field (Name => COL_0_1_NAME, -- id Value => Object.Get_Key); Object.Clear_Modified (1); end if; if Object.Is_Modified (2) then Stmt.Save_Field (Name => COL_1_1_NAME, -- name Value => Object.Name); Object.Clear_Modified (2); end if; if Stmt.Has_Save_Fields then Stmt.Set_Filter (Filter => ""id = ?""); Stmt.Add_Param (Value => Object.Get_Key); declare Result : Integer; begin Stmt.Execute (Result); if Result /= 1 then if Result /= 0 then raise ADO.Objects.UPDATE_ERROR; end if; end if; end; end if; end Save; procedure Create (Object : in out Message_Type_Impl; Session : in out ADO.Sessions.Master_Session'Class) is Query : ADO.Statements.Insert_Statement := Session.Create_Statement (MESSAGE_TYPE_DEF'Access); Result : Integer; begin Session.Allocate (Id => Object); Query.Save_Field (Name => COL_0_1_NAME, -- id Value => Object.Get_Key); Query.Save_Field (Name => COL_1_1_NAME, -- name Value => Object.Name); Query.Execute (Result); if Result /= 1 then raise ADO.Objects.INSERT_ERROR; end if; ADO.Objects.Set_Created (Object); end Create; procedure Delete (Object : in out Message_Type_Impl; Session : in out ADO.Sessions.Master_Session'Class) is Stmt : ADO.Statements.Delete_Statement := Session.Create_Statement (MESSAGE_TYPE_DEF'Access); begin Stmt.Set_Filter (Filter => ""id = ?""); Stmt.Add_Param (Value => Object.Get_Key); Stmt.Execute; end Delete; -- ------------------------------ -- Get the bean attribute identified by the name. -- ------------------------------ overriding function Get_Value (From : in Message_Type_Ref; Name : in String) return Util.Beans.Objects.Object is Obj : ADO.Objects.Object_Record_Access; Impl : access Message_Type_Impl; begin if From.Is_Null then return Util.Beans.Objects.Null_Object; end if; Obj := From.Get_Load_Object; Impl := Message_Type_Impl (Obj.all)'Access; if Name = ""id"" then return ADO.Objects.To_Object (Impl.Get_Key); elsif Name = ""name"" then return Util.Beans.Objects.To_Object (Impl.Name); end if; return Util.Beans.Objects.Null_Object; end Get_Value; procedure List (Object : in out Message_Type_Vector; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class) is Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query, MESSAGE_TYPE_DEF'Access); begin Stmt.Execute; Message_Type_Vectors.Clear (Object); while Stmt.Has_Elements loop declare Item : Message_Type_Ref; Impl : constant Message_Type_Access := new Message_Type_Impl; begin Impl.Load (Stmt, Session); ADO.Objects.Set_Object (Item, Impl.all'Access); Object.Append (Item); end; Stmt.Next; end loop; end List; -- ------------------------------ -- Load the object from current iterator position -- ------------------------------ procedure Load (Object : in out Message_Type_Impl; Stmt : in out ADO.Statements.Query_Statement'Class; Session : in out ADO.Sessions.Session'Class) is pragma Unreferenced (Session); begin Object.Set_Key_Value (Stmt.Get_Identifier (0)); Object.Name := Stmt.Get_Unbounded_String (1); ADO.Objects.Set_Created (Object); end Load; function Queue_Key (Id : in ADO.Identifier) return ADO.Objects.Object_Key is Result : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => QUEUE_DEF'Access); begin ADO.Objects.Set_Value (Result, Id); return Result; end Queue_Key; function Queue_Key (Id : in String) return ADO.Objects.Object_Key is Result : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => QUEUE_DEF'Access); begin ADO.Objects.Set_Value (Result, Id); return Result; end Queue_Key; function ""="" (Left, Right : Queue_Ref'Class) return Boolean is begin return ADO.Objects.Object_Ref'Class (Left) = ADO.Objects.Object_Ref'Class (Right); end ""=""; procedure Set_Field (Object : in out Queue_Ref'Class; Impl : out Queue_Access) is Result : ADO.Objects.Object_Record_Access; begin Object.Prepare_Modify (Result); Impl := Queue_Impl (Result.all)'Access; end Set_Field; -- Internal method to allocate the Object_Record instance procedure Allocate (Object : in out Queue_Ref) is Impl : Queue_Access; begin Impl := new Queue_Impl; Impl.Server_Id := 0; ADO.Objects.Set_Object (Object, Impl.all'Access); end Allocate; -- ---------------------------------------- -- Data object: Queue -- ---------------------------------------- procedure Set_Id (Object : in out Queue_Ref; Value : in ADO.Identifier) is Impl : Queue_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Key_Value (Impl.all, 1, Value); end Set_Id; function Get_Id (Object : in Queue_Ref) return ADO.Identifier is Impl : constant Queue_Access := Queue_Impl (Object.Get_Object.all)'Access; begin return Impl.Get_Key_Value; end Get_Id; procedure Set_Server_Id (Object : in out Queue_Ref; Value : in Integer) is Impl : Queue_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Integer (Impl.all, 2, Impl.Server_Id, Value); end Set_Server_Id; function Get_Server_Id (Object : in Queue_Ref) return Integer is Impl : constant Queue_Access := Queue_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Server_Id; end Get_Server_Id; procedure Set_Name (Object : in out Queue_Ref; Value : in String) is Impl : Queue_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_String (Impl.all, 3, Impl.Name, Value); end Set_Name; procedure Set_Name (Object : in out Queue_Ref; Value : in Ada.Strings.Unbounded.Unbounded_String) is Impl : Queue_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Unbounded_String (Impl.all, 3, Impl.Name, Value); end Set_Name; function Get_Name (Object : in Queue_Ref) return String is begin return Ada.Strings.Unbounded.To_String (Object.Get_Name); end Get_Name; function Get_Name (Object : in Queue_Ref) return Ada.Strings.Unbounded.Unbounded_String is Impl : constant Queue_Access := Queue_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Name; end Get_Name; -- Copy of the object. procedure Copy (Object : in Queue_Ref; Into : in out Queue_Ref) is Result : Queue_Ref; begin if not Object.Is_Null then declare Impl : constant Queue_Access := Queue_Impl (Object.Get_Load_Object.all)'Access; Copy : constant Queue_Access := new Queue_Impl; begin ADO.Objects.Set_Object (Result, Copy.all'Access); Copy.Copy (Impl.all); Copy.Server_Id := Impl.Server_Id; Copy.Name := Impl.Name; end; end if; Into := Result; end Copy; procedure Find (Object : in out Queue_Ref; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean) is Impl : constant Queue_Access := new Queue_Impl; begin Impl.Find (Session, Query, Found); if Found then ADO.Objects.Set_Object (Object, Impl.all'Access); else ADO.Objects.Set_Object (Object, null); Destroy (Impl); end if; end Find; procedure Load (Object : in out Queue_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier) is Impl : constant Queue_Access := new Queue_Impl; Found : Boolean; Query : ADO.SQL.Query; begin Query.Bind_Param (Position => 1, Value => Id); Query.Set_Filter (""id = ?""); Impl.Find (Session, Query, Found); if not Found then Destroy (Impl); raise ADO.Objects.NOT_FOUND; end if; ADO.Objects.Set_Object (Object, Impl.all'Access); end Load; procedure Load (Object : in out Queue_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier; Found : out Boolean) is Impl : constant Queue_Access := new Queue_Impl; Query : ADO.SQL.Query; begin Query.Bind_Param (Position => 1, Value => Id); Query.Set_Filter (""id = ?""); Impl.Find (Session, Query, Found); if not Found then Destroy (Impl); else ADO.Objects.Set_Object (Object, Impl.all'Access); end if; end Load; procedure Save (Object : in out Queue_Ref; Session : in out ADO.Sessions.Master_Session'Class) is Impl : ADO.Objects.Object_Record_Access := Object.Get_Object; begin if Impl = null then Impl := new Queue_Impl; ADO.Objects.Set_Object (Object, Impl); end if; if not ADO.Objects.Is_Created (Impl.all) then Impl.Create (Session); else Impl.Save (Session); end if; end Save; procedure Delete (Object : in out Queue_Ref; Session : in out ADO.Sessions.Master_Session'Class) is Impl : constant ADO.Objects.Object_Record_Access := Object.Get_Object; begin if Impl /= null then Impl.Delete (Session); end if; end Delete; -- -------------------- -- Free the object -- -------------------- procedure Destroy (Object : access Queue_Impl) is type Queue_Impl_Ptr is access all Queue_Impl; procedure Unchecked_Free is new Ada.Unchecked_Deallocation (Queue_Impl, Queue_Impl_Ptr); pragma Warnings (Off, ""*redundant conversion*""); Ptr : Queue_Impl_Ptr := Queue_Impl (Object.all)'Access; pragma Warnings (On, ""*redundant conversion*""); begin Unchecked_Free (Ptr); end Destroy; procedure Find (Object : in out Queue_Impl; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean) is Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query, QUEUE_DEF'Access); begin Stmt.Execute; if Stmt.Has_Elements then Object.Load (Stmt, Session); Stmt.Next; Found := not Stmt.Has_Elements; else Found := False; end if; end Find; overriding procedure Load (Object : in out Queue_Impl; Session : in out ADO.Sessions.Session'Class) is Found : Boolean; Query : ADO.SQL.Query; Id : constant ADO.Identifier := Object.Get_Key_Value; begin Query.Bind_Param (Position => 1, Value => Id); Query.Set_Filter (""id = ?""); Object.Find (Session, Query, Found); if not Found then raise ADO.Objects.NOT_FOUND; end if; end Load; procedure Save (Object : in out Queue_Impl; Session : in out ADO.Sessions.Master_Session'Class) is Stmt : ADO.Statements.Update_Statement := Session.Create_Statement (QUEUE_DEF'Access); begin if Object.Is_Modified (1) then Stmt.Save_Field (Name => COL_0_2_NAME, -- id Value => Object.Get_Key); Object.Clear_Modified (1); end if; if Object.Is_Modified (2) then Stmt.Save_Field (Name => COL_1_2_NAME, -- server_id Value => Object.Server_Id); Object.Clear_Modified (2); end if; if Object.Is_Modified (3) then Stmt.Save_Field (Name => COL_2_2_NAME, -- name Value => Object.Name); Object.Clear_Modified (3); end if; if Stmt.Has_Save_Fields then Stmt.Set_Filter (Filter => ""id = ?""); Stmt.Add_Param (Value => Object.Get_Key); declare Result : Integer; begin Stmt.Execute (Result); if Result /= 1 then if Result /= 0 then raise ADO.Objects.UPDATE_ERROR; end if; end if; end; end if; end Save; procedure Create (Object : in out Queue_Impl; Session : in out ADO.Sessions.Master_Session'Class) is Query : ADO.Statements.Insert_Statement := Session.Create_Statement (QUEUE_DEF'Access); Result : Integer; begin Session.Allocate (Id => Object); Query.Save_Field (Name => COL_0_2_NAME, -- id Value => Object.Get_Key); Query.Save_Field (Name => COL_1_2_NAME, -- server_id Value => Object.Server_Id); Query.Save_Field (Name => COL_2_2_NAME, -- name Value => Object.Name); Query.Execute (Result); if Result /= 1 then raise ADO.Objects.INSERT_ERROR; end if; ADO.Objects.Set_Created (Object); end Create; procedure Delete (Object : in out Queue_Impl; Session : in out ADO.Sessions.Master_Session'Class) is Stmt : ADO.Statements.Delete_Statement := Session.Create_Statement (QUEUE_DEF'Access); begin Stmt.Set_Filter (Filter => ""id = ?""); Stmt.Add_Param (Value => Object.Get_Key); Stmt.Execute; end Delete; -- ------------------------------ -- Get the bean attribute identified by the name. -- ------------------------------ overriding function Get_Value (From : in Queue_Ref; Name : in String) return Util.Beans.Objects.Object is Obj : ADO.Objects.Object_Record_Access; Impl : access Queue_Impl; begin if From.Is_Null then return Util.Beans.Objects.Null_Object; end if; Obj := From.Get_Load_Object; Impl := Queue_Impl (Obj.all)'Access; if Name = ""id"" then return ADO.Objects.To_Object (Impl.Get_Key); elsif Name = ""server_id"" then return Util.Beans.Objects.To_Object (Long_Long_Integer (Impl.Server_Id)); elsif Name = ""name"" then return Util.Beans.Objects.To_Object (Impl.Name); end if; return Util.Beans.Objects.Null_Object; end Get_Value; -- ------------------------------ -- Load the object from current iterator position -- ------------------------------ procedure Load (Object : in out Queue_Impl; Stmt : in out ADO.Statements.Query_Statement'Class; Session : in out ADO.Sessions.Session'Class) is pragma Unreferenced (Session); begin Object.Set_Key_Value (Stmt.Get_Identifier (0)); Object.Server_Id := Stmt.Get_Integer (1); Object.Name := Stmt.Get_Unbounded_String (2); ADO.Objects.Set_Created (Object); end Load; function Message_Key (Id : in ADO.Identifier) return ADO.Objects.Object_Key is Result : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => MESSAGE_DEF'Access); begin ADO.Objects.Set_Value (Result, Id); return Result; end Message_Key; function Message_Key (Id : in String) return ADO.Objects.Object_Key is Result : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => MESSAGE_DEF'Access); begin ADO.Objects.Set_Value (Result, Id); return Result; end Message_Key; function ""="" (Left, Right : Message_Ref'Class) return Boolean is begin return ADO.Objects.Object_Ref'Class (Left) = ADO.Objects.Object_Ref'Class (Right); end ""=""; procedure Set_Field (Object : in out Message_Ref'Class; Impl : out Message_Access) is Result : ADO.Objects.Object_Record_Access; begin Object.Prepare_Modify (Result); Impl := Message_Impl (Result.all)'Access; end Set_Field; -- Internal method to allocate the Object_Record instance procedure Allocate (Object : in out Message_Ref) is Impl : Message_Access; begin Impl := new Message_Impl; Impl.Create_Date := ADO.DEFAULT_TIME; Impl.Priority := 0; Impl.Count := 0; Impl.Server_Id := 0; Impl.Task_Id := 0; Impl.Status := AWA.Events.Models.Message_Status_Type'First; Impl.Processing_Date.Is_Null := True; Impl.Version := 0; Impl.Entity_Id := ADO.NO_IDENTIFIER; Impl.Entity_Type := 0; Impl.Finish_Date.Is_Null := True; ADO.Objects.Set_Object (Object, Impl.all'Access); end Allocate; -- ---------------------------------------- -- Data object: Message -- ---------------------------------------- procedure Set_Id (Object : in out Message_Ref; Value : in ADO.Identifier) is Impl : Message_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Key_Value (Impl.all, 1, Value); end Set_Id; function Get_Id (Object : in Message_Ref) return ADO.Identifier is Impl : constant Message_Access := Message_Impl (Object.Get_Object.all)'Access; begin return Impl.Get_Key_Value; end Get_Id; procedure Set_Create_Date (Object : in out Message_Ref; Value : in Ada.Calendar.Time) is Impl : Message_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Time (Impl.all, 2, Impl.Create_Date, Value); end Set_Create_Date; function Get_Create_Date (Object : in Message_Ref) return Ada.Calendar.Time is Impl : constant Message_Access := Message_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Create_Date; end Get_Create_Date; procedure Set_Priority (Object : in out Message_Ref; Value : in Integer) is Impl : Message_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Integer (Impl.all, 3, Impl.Priority, Value); end Set_Priority; function Get_Priority (Object : in Message_Ref) return Integer is Impl : constant Message_Access := Message_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Priority; end Get_Priority; procedure Set_Count (Object : in out Message_Ref; Value : in Integer) is Impl : Message_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Integer (Impl.all, 4, Impl.Count, Value); end Set_Count; function Get_Count (Object : in Message_Ref) return Integer is Impl : constant Message_Access := Message_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Count; end Get_Count; procedure Set_Parameters (Object : in out Message_Ref; Value : in String) is Impl : Message_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_String (Impl.all, 5, Impl.Parameters, Value); end Set_Parameters; procedure Set_Parameters (Object : in out Message_Ref; Value : in Ada.Strings.Unbounded.Unbounded_String) is Impl : Message_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Unbounded_String (Impl.all, 5, Impl.Parameters, Value); end Set_Parameters; function Get_Parameters (Object : in Message_Ref) return String is begin return Ada.Strings.Unbounded.To_String (Object.Get_Parameters); end Get_Parameters; function Get_Parameters (Object : in Message_Ref) return Ada.Strings.Unbounded.Unbounded_String is Impl : constant Message_Access := Message_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Parameters; end Get_Parameters; procedure Set_Server_Id (Object : in out Message_Ref; Value : in Integer) is Impl : Message_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Integer (Impl.all, 6, Impl.Server_Id, Value); end Set_Server_Id; function Get_Server_Id (Object : in Message_Ref) return Integer is Impl : constant Message_Access := Message_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Server_Id; end Get_Server_Id; procedure Set_Task_Id (Object : in out Message_Ref; Value : in Integer) is Impl : Message_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Integer (Impl.all, 7, Impl.Task_Id, Value); end Set_Task_Id; function Get_Task_Id (Object : in Message_Ref) return Integer is Impl : constant Message_Access := Message_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Task_Id; end Get_Task_Id; procedure Set_Status (Object : in out Message_Ref; Value : in AWA.Events.Models.Message_Status_Type) is procedure Set_Field_Enum is new ADO.Objects.Set_Field_Operation (Message_Status_Type); Impl : Message_Access; begin Set_Field (Object, Impl); Set_Field_Enum (Impl.all, 8, Impl.Status, Value); end Set_Status; function Get_Status (Object : in Message_Ref) return AWA.Events.Models.Message_Status_Type is Impl : constant Message_Access := Message_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Status; end Get_Status; procedure Set_Processing_Date (Object : in out Message_Ref; Value : in ADO.Nullable_Time) is Impl : Message_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Time (Impl.all, 9, Impl.Processing_Date, Value); end Set_Processing_Date; function Get_Processing_Date (Object : in Message_Ref) return ADO.Nullable_Time is Impl : constant Message_Access := Message_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Processing_Date; end Get_Processing_Date; function Get_Version (Object : in Message_Ref) return Integer is Impl : constant Message_Access := Message_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Version; end Get_Version; procedure Set_Entity_Id (Object : in out Message_Ref; Value : in ADO.Identifier) is Impl : Message_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Identifier (Impl.all, 11, Impl.Entity_Id, Value); end Set_Entity_Id; function Get_Entity_Id (Object : in Message_Ref) return ADO.Identifier is Impl : constant Message_Access := Message_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Entity_Id; end Get_Entity_Id; procedure Set_Entity_Type (Object : in out Message_Ref; Value : in ADO.Entity_Type) is Impl : Message_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Entity_Type (Impl.all, 12, Impl.Entity_Type, Value); end Set_Entity_Type; function Get_Entity_Type (Object : in Message_Ref) return ADO.Entity_Type is Impl : constant Message_Access := Message_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Entity_Type; end Get_Entity_Type; procedure Set_Finish_Date (Object : in out Message_Ref; Value : in ADO.Nullable_Time) is Impl : Message_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Time (Impl.all, 13, Impl.Finish_Date, Value); end Set_Finish_Date; function Get_Finish_Date (Object : in Message_Ref) return ADO.Nullable_Time is Impl : constant Message_Access := Message_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Finish_Date; end Get_Finish_Date; procedure Set_Queue (Object : in out Message_Ref; Value : in AWA.Events.Models.Queue_Ref'Class) is Impl : Message_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Object (Impl.all, 14, Impl.Queue, Value); end Set_Queue; function Get_Queue (Object : in Message_Ref) return AWA.Events.Models.Queue_Ref'Class is Impl : constant Message_Access := Message_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Queue; end Get_Queue; procedure Set_Message_Type (Object : in out Message_Ref; Value : in AWA.Events.Models.Message_Type_Ref'Class) is Impl : Message_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Object (Impl.all, 15, Impl.Message_Type, Value); end Set_Message_Type; function Get_Message_Type (Object : in Message_Ref) return AWA.Events.Models.Message_Type_Ref'Class is Impl : constant Message_Access := Message_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Message_Type; end Get_Message_Type; procedure Set_User (Object : in out Message_Ref; Value : in AWA.Users.Models.User_Ref'Class) is Impl : Message_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Object (Impl.all, 16, Impl.User, Value); end Set_User; function Get_User (Object : in Message_Ref) return AWA.Users.Models.User_Ref'Class is Impl : constant Message_Access := Message_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.User; end Get_User; procedure Set_Session (Object : in out Message_Ref; Value : in AWA.Users.Models.Session_Ref'Class) is Impl : Message_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Object (Impl.all, 17, Impl.Session, Value); end Set_Session; function Get_Session (Object : in Message_Ref) return AWA.Users.Models.Session_Ref'Class is Impl : constant Message_Access := Message_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Session; end Get_Session; -- Copy of the object. procedure Copy (Object : in Message_Ref; Into : in out Message_Ref) is Result : Message_Ref; begin if not Object.Is_Null then declare Impl : constant Message_Access := Message_Impl (Object.Get_Load_Object.all)'Access; Copy : constant Message_Access := new Message_Impl; begin ADO.Objects.Set_Object (Result, Copy.all'Access); Copy.Copy (Impl.all); Copy.Create_Date := Impl.Create_Date; Copy.Priority := Impl.Priority; Copy.Count := Impl.Count; Copy.Parameters := Impl.Parameters; Copy.Server_Id := Impl.Server_Id; Copy.Task_Id := Impl.Task_Id; Copy.Status := Impl.Status; Copy.Processing_Date := Impl.Processing_Date; Copy.Version := Impl.Version; Copy.Entity_Id := Impl.Entity_Id; Copy.Entity_Type := Impl.Entity_Type; Copy.Finish_Date := Impl.Finish_Date; Copy.Queue := Impl.Queue; Copy.Message_Type := Impl.Message_Type; Copy.User := Impl.User; Copy.Session := Impl.Session; end; end if; Into := Result; end Copy; procedure Find (Object : in out Message_Ref; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean) is Impl : constant Message_Access := new Message_Impl; begin Impl.Find (Session, Query, Found); if Found then ADO.Objects.Set_Object (Object, Impl.all'Access); else ADO.Objects.Set_Object (Object, null); Destroy (Impl); end if; end Find; procedure Load (Object : in out Message_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier) is Impl : constant Message_Access := new Message_Impl; Found : Boolean; Query : ADO.SQL.Query; begin Query.Bind_Param (Position => 1, Value => Id); Query.Set_Filter (""id = ?""); Impl.Find (Session, Query, Found); if not Found then Destroy (Impl); raise ADO.Objects.NOT_FOUND; end if; ADO.Objects.Set_Object (Object, Impl.all'Access); end Load; procedure Load (Object : in out Message_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier; Found : out Boolean) is Impl : constant Message_Access := new Message_Impl; Query : ADO.SQL.Query; begin Query.Bind_Param (Position => 1, Value => Id); Query.Set_Filter (""id = ?""); Impl.Find (Session, Query, Found); if not Found then Destroy (Impl); else ADO.Objects.Set_Object (Object, Impl.all'Access); end if; end Load; procedure Save (Object : in out Message_Ref; Session : in out ADO.Sessions.Master_Session'Class) is Impl : ADO.Objects.Object_Record_Access := Object.Get_Object; begin if Impl = null then Impl := new Message_Impl; ADO.Objects.Set_Object (Object, Impl); end if; if not ADO.Objects.Is_Created (Impl.all) then Impl.Create (Session); else Impl.Save (Session); end if; end Save; procedure Delete (Object : in out Message_Ref; Session : in out ADO.Sessions.Master_Session'Class) is Impl : constant ADO.Objects.Object_Record_Access := Object.Get_Object; begin if Impl /= null then Impl.Delete (Session); end if; end Delete; -- -------------------- -- Free the object -- -------------------- procedure Destroy (Object : access Message_Impl) is type Message_Impl_Ptr is access all Message_Impl; procedure Unchecked_Free is new Ada.Unchecked_Deallocation (Message_Impl, Message_Impl_Ptr); pragma Warnings (Off, ""*redundant conversion*""); Ptr : Message_Impl_Ptr := Message_Impl (Object.all)'Access; pragma Warnings (On, ""*redundant conversion*""); begin Unchecked_Free (Ptr); end Destroy; procedure Find (Object : in out Message_Impl; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean) is Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query, MESSAGE_DEF'Access); begin Stmt.Execute; if Stmt.Has_Elements then Object.Load (Stmt, Session); Stmt.Next; Found := not Stmt.Has_Elements; else Found := False; end if; end Find; overriding procedure Load (Object : in out Message_Impl; Session : in out ADO.Sessions.Session'Class) is Found : Boolean; Query : ADO.SQL.Query; Id : constant ADO.Identifier := Object.Get_Key_Value; begin Query.Bind_Param (Position => 1, Value => Id); Query.Set_Filter (""id = ?""); Object.Find (Session, Query, Found); if not Found then raise ADO.Objects.NOT_FOUND; end if; end Load; procedure Save (Object : in out Message_Impl; Session : in out ADO.Sessions.Master_Session'Class) is Stmt : ADO.Statements.Update_Statement := Session.Create_Statement (MESSAGE_DEF'Access); begin if Object.Is_Modified (1) then Stmt.Save_Field (Name => COL_0_3_NAME, -- id Value => Object.Get_Key); Object.Clear_Modified (1); end if; if Object.Is_Modified (2) then Stmt.Save_Field (Name => COL_1_3_NAME, -- create_date Value => Object.Create_Date); Object.Clear_Modified (2); end if; if Object.Is_Modified (3) then Stmt.Save_Field (Name => COL_2_3_NAME, -- priority Value => Object.Priority); Object.Clear_Modified (3); end if; if Object.Is_Modified (4) then Stmt.Save_Field (Name => COL_3_3_NAME, -- count Value => Object.Count); Object.Clear_Modified (4); end if; if Object.Is_Modified (5) then Stmt.Save_Field (Name => COL_4_3_NAME, -- parameters Value => Object.Parameters); Object.Clear_Modified (5); end if; if Object.Is_Modified (6) then Stmt.Save_Field (Name => COL_5_3_NAME, -- server_id Value => Object.Server_Id); Object.Clear_Modified (6); end if; if Object.Is_Modified (7) then Stmt.Save_Field (Name => COL_6_3_NAME, -- task_id Value => Object.Task_Id); Object.Clear_Modified (7); end if; if Object.Is_Modified (8) then Stmt.Save_Field (Name => COL_7_3_NAME, -- status Value => Integer (Message_Status_Type'Pos (Object.Status))); Object.Clear_Modified (8); end if; if Object.Is_Modified (9) then Stmt.Save_Field (Name => COL_8_3_NAME, -- processing_date Value => Object.Processing_Date); Object.Clear_Modified (9); end if; if Object.Is_Modified (11) then Stmt.Save_Field (Name => COL_10_3_NAME, -- entity_id Value => Object.Entity_Id); Object.Clear_Modified (11); end if; if Object.Is_Modified (12) then Stmt.Save_Field (Name => COL_11_3_NAME, -- entity_type Value => Object.Entity_Type); Object.Clear_Modified (12); end if; if Object.Is_Modified (13) then Stmt.Save_Field (Name => COL_12_3_NAME, -- finish_date Value => Object.Finish_Date); Object.Clear_Modified (13); end if; if Object.Is_Modified (14) then Stmt.Save_Field (Name => COL_13_3_NAME, -- queue_id Value => Object.Queue); Object.Clear_Modified (14); end if; if Object.Is_Modified (15) then Stmt.Save_Field (Name => COL_14_3_NAME, -- message_type_id Value => Object.Message_Type); Object.Clear_Modified (15); end if; if Object.Is_Modified (16) then Stmt.Save_Field (Name => COL_15_3_NAME, -- user_id Value => Object.User); Object.Clear_Modified (16); end if; if Object.Is_Modified (17) then Stmt.Save_Field (Name => COL_16_3_NAME, -- session_id Value => Object.Session); Object.Clear_Modified (17); end if; if Stmt.Has_Save_Fields then Object.Version := Object.Version + 1; Stmt.Save_Field (Name => ""version"", Value => Object.Version); Stmt.Set_Filter (Filter => ""id = ? and version = ?""); Stmt.Add_Param (Value => Object.Get_Key); Stmt.Add_Param (Value => Object.Version - 1); declare Result : Integer; begin Stmt.Execute (Result); if Result /= 1 then if Result /= 0 then raise ADO.Objects.UPDATE_ERROR; else raise ADO.Objects.LAZY_LOCK; end if; end if; end; end if; end Save; procedure Create (Object : in out Message_Impl; Session : in out ADO.Sessions.Master_Session'Class) is Query : ADO.Statements.Insert_Statement := Session.Create_Statement (MESSAGE_DEF'Access); Result : Integer; begin Object.Version := 1; Session.Allocate (Id => Object); Query.Save_Field (Name => COL_0_3_NAME, -- id Value => Object.Get_Key); Query.Save_Field (Name => COL_1_3_NAME, -- create_date Value => Object.Create_Date); Query.Save_Field (Name => COL_2_3_NAME, -- priority Value => Object.Priority); Query.Save_Field (Name => COL_3_3_NAME, -- count Value => Object.Count); Query.Save_Field (Name => COL_4_3_NAME, -- parameters Value => Object.Parameters); Query.Save_Field (Name => COL_5_3_NAME, -- server_id Value => Object.Server_Id); Query.Save_Field (Name => COL_6_3_NAME, -- task_id Value => Object.Task_Id); Query.Save_Field (Name => COL_7_3_NAME, -- status Value => Integer (Message_Status_Type'Pos (Object.Status))); Query.Save_Field (Name => COL_8_3_NAME, -- processing_date Value => Object.Processing_Date); Query.Save_Field (Name => COL_9_3_NAME, -- version Value => Object.Version); Query.Save_Field (Name => COL_10_3_NAME, -- entity_id Value => Object.Entity_Id); Query.Save_Field (Name => COL_11_3_NAME, -- entity_type Value => Object.Entity_Type); Query.Save_Field (Name => COL_12_3_NAME, -- finish_date Value => Object.Finish_Date); Query.Save_Field (Name => COL_13_3_NAME, -- queue_id Value => Object.Queue); Query.Save_Field (Name => COL_14_3_NAME, -- message_type_id Value => Object.Message_Type); Query.Save_Field (Name => COL_15_3_NAME, -- user_id Value => Object.User); Query.Save_Field (Name => COL_16_3_NAME, -- session_id Value => Object.Session); Query.Execute (Result); if Result /= 1 then raise ADO.Objects.INSERT_ERROR; end if; ADO.Objects.Set_Created (Object); end Create; procedure Delete (Object : in out Message_Impl; Session : in out ADO.Sessions.Master_Session'Class) is Stmt : ADO.Statements.Delete_Statement := Session.Create_Statement (MESSAGE_DEF'Access); begin Stmt.Set_Filter (Filter => ""id = ?""); Stmt.Add_Param (Value => Object.Get_Key); Stmt.Execute; end Delete; -- ------------------------------ -- Get the bean attribute identified by the name. -- ------------------------------ overriding function Get_Value (From : in Message_Ref; Name : in String) return Util.Beans.Objects.Object is Obj : ADO.Objects.Object_Record_Access; Impl : access Message_Impl; begin if From.Is_Null then return Util.Beans.Objects.Null_Object; end if; Obj := From.Get_Load_Object; Impl := Message_Impl (Obj.all)'Access; if Name = ""id"" then return ADO.Objects.To_Object (Impl.Get_Key); elsif Name = ""create_date"" then return Util.Beans.Objects.Time.To_Object (Impl.Create_Date); elsif Name = ""priority"" then return Util.Beans.Objects.To_Object (Long_Long_Integer (Impl.Priority)); elsif Name = ""count"" then return Util.Beans.Objects.To_Object (Long_Long_Integer (Impl.Count)); elsif Name = ""parameters"" then return Util.Beans.Objects.To_Object (Impl.Parameters); elsif Name = ""server_id"" then return Util.Beans.Objects.To_Object (Long_Long_Integer (Impl.Server_Id)); elsif Name = ""task_id"" then return Util.Beans.Objects.To_Object (Long_Long_Integer (Impl.Task_Id)); elsif Name = ""status"" then return AWA.Events.Models.Message_Status_Type_Objects.To_Object (Impl.Status); elsif Name = ""processing_date"" then if Impl.Processing_Date.Is_Null then return Util.Beans.Objects.Null_Object; else return Util.Beans.Objects.Time.To_Object (Impl.Processing_Date.Value); end if; elsif Name = ""entity_id"" then return Util.Beans.Objects.To_Object (Long_Long_Integer (Impl.Entity_Id)); elsif Name = ""entity_type"" then return Util.Beans.Objects.To_Object (Long_Long_Integer (Impl.Entity_Type)); elsif Name = ""finish_date"" then if Impl.Finish_Date.Is_Null then return Util.Beans.Objects.Null_Object; else return Util.Beans.Objects.Time.To_Object (Impl.Finish_Date.Value); end if; end if; return Util.Beans.Objects.Null_Object; end Get_Value; procedure List (Object : in out Message_Vector; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class) is Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query, MESSAGE_DEF'Access); begin Stmt.Execute; Message_Vectors.Clear (Object); while Stmt.Has_Elements loop declare Item : Message_Ref; Impl : constant Message_Access := new Message_Impl; begin Impl.Load (Stmt, Session); ADO.Objects.Set_Object (Item, Impl.all'Access); Object.Append (Item); end; Stmt.Next; end loop; end List; -- ------------------------------ -- Load the object from current iterator position -- ------------------------------ procedure Load (Object : in out Message_Impl; Stmt : in out ADO.Statements.Query_Statement'Class; Session : in out ADO.Sessions.Session'Class) is begin Object.Set_Key_Value (Stmt.Get_Identifier (0)); Object.Create_Date := Stmt.Get_Time (1); Object.Priority := Stmt.Get_Integer (2); Object.Count := Stmt.Get_Integer (3); Object.Parameters := Stmt.Get_Unbounded_String (4); Object.Server_Id := Stmt.Get_Integer (5); Object.Task_Id := Stmt.Get_Integer (6); Object.Status := Message_Status_Type'Val (Stmt.Get_Integer (7)); Object.Processing_Date := Stmt.Get_Nullable_Time (8); Object.Entity_Id := Stmt.Get_Identifier (10); Object.Entity_Type := ADO.Entity_Type (Stmt.Get_Integer (11)); Object.Finish_Date := Stmt.Get_Nullable_Time (12); if not Stmt.Is_Null (13) then Object.Queue.Set_Key_Value (Stmt.Get_Identifier (13), Session); end if; if not Stmt.Is_Null (14) then Object.Message_Type.Set_Key_Value (Stmt.Get_Identifier (14), Session); end if; if not Stmt.Is_Null (15) then Object.User.Set_Key_Value (Stmt.Get_Identifier (15), Session); end if; if not Stmt.Is_Null (16) then Object.Session.Set_Key_Value (Stmt.Get_Identifier (16), Session); end if; Object.Version := Stmt.Get_Integer (9); ADO.Objects.Set_Created (Object); end Load; end AWA.Events.Models; ",12252,True,3450.1351180166625,median "CLASS zcl_abapgit_objects_generic DEFINITION PUBLIC CREATE PUBLIC . PUBLIC SECTION. METHODS constructor IMPORTING !is_item TYPE zif_abapgit_definitions=>ty_item RAISING zcx_abapgit_exception . METHODS delete RAISING zcx_abapgit_exception . METHODS deserialize IMPORTING !iv_package TYPE devclass !io_xml TYPE REF TO zif_abapgit_xml_input RAISING zcx_abapgit_exception . METHODS exists RETURNING VALUE(rv_bool) TYPE abap_bool RAISING zcx_abapgit_exception . METHODS serialize IMPORTING !io_xml TYPE REF TO zif_abapgit_xml_output RAISING zcx_abapgit_exception . PROTECTED SECTION. TYPES: BEGIN OF ty_s_objkey, num TYPE n LENGTH 3, value TYPE c LENGTH 128, END OF ty_s_objkey . TYPES: ty_t_objkey TYPE SORTED TABLE OF ty_s_objkey WITH UNIQUE KEY num . DATA ms_object_header TYPE objh . DATA: mt_object_table TYPE STANDARD TABLE OF objsl WITH DEFAULT KEY . DATA: mt_object_method TYPE STANDARD TABLE OF objm WITH DEFAULT KEY . DATA ms_item TYPE zif_abapgit_definitions=>ty_item . METHODS after_import . METHODS before_export . METHODS corr_insert IMPORTING !iv_package TYPE devclass RAISING zcx_abapgit_exception . METHODS deserialize_data IMPORTING !io_xml TYPE REF TO zif_abapgit_xml_input RAISING zcx_abapgit_exception . METHODS distribute_name_to_components IMPORTING !it_key_component TYPE ddfields CHANGING !ct_objkey TYPE ty_t_objkey !cs_objkey TYPE ty_s_objkey !cv_non_value_pos TYPE numc3 . METHODS get_key_fields IMPORTING !iv_table TYPE objsl-tobj_name RETURNING VALUE(rt_keys) TYPE ddfields RAISING zcx_abapgit_exception . METHODS get_primary_table RETURNING VALUE(rv_table) TYPE objsl-tobj_name RAISING zcx_abapgit_exception . METHODS get_where_clause IMPORTING !iv_tobj_name TYPE objsl-tobj_name RETURNING VALUE(rv_where) TYPE string RAISING zcx_abapgit_exception . METHODS serialize_data IMPORTING !io_xml TYPE REF TO zif_abapgit_xml_output RAISING zcx_abapgit_exception . METHODS split_value_to_keys IMPORTING !it_key_component TYPE ddfields CHANGING !ct_objkey TYPE ty_t_objkey !cs_objkey TYPE ty_s_objkey !cv_non_value_pos TYPE numc3 . METHODS validate IMPORTING !io_xml TYPE REF TO zif_abapgit_xml_input RAISING zcx_abapgit_exception . PRIVATE SECTION. ENDCLASS. CLASS zcl_abapgit_objects_generic IMPLEMENTATION. METHOD after_import. DATA: lt_cts_object_entry TYPE STANDARD TABLE OF e071 WITH DEFAULT KEY, ls_cts_object_entry LIKE LINE OF lt_cts_object_entry, lt_cts_key TYPE STANDARD TABLE OF e071k WITH DEFAULT KEY. FIELD-SYMBOLS LIKE LINE OF mt_object_method. ls_cts_object_entry-pgmid = seok_pgmid_r3tr. ls_cts_object_entry-object = ms_item-obj_type. ls_cts_object_entry-obj_name = ms_item-obj_name. INSERT ls_cts_object_entry INTO TABLE lt_cts_object_entry. READ TABLE mt_object_method ASSIGNING WITH KEY objectname = ms_item-obj_type objecttype = 'L' method = 'AFTER_IMP'. IF sy-subrc = 0. * client is actually optional for most AIM, but let's supply it and hope * that those client-independent-ones just ignore it CALL FUNCTION -methodname EXPORTING iv_tarclient = sy-mandt iv_is_upgrade = abap_false TABLES tt_e071 = lt_cts_object_entry tt_e071k = lt_cts_key. ENDIF. ENDMETHOD. METHOD before_export. DATA: lt_cts_object_entry TYPE STANDARD TABLE OF e071 WITH DEFAULT KEY, ls_cts_object_entry LIKE LINE OF lt_cts_object_entry, lt_cts_key TYPE STANDARD TABLE OF e071k WITH DEFAULT KEY, lv_client TYPE trclient. FIELD-SYMBOLS LIKE LINE OF mt_object_method. READ TABLE mt_object_method ASSIGNING WITH KEY objectname = ms_item-obj_type objecttype = 'L' method = 'BEFORE_EXP'. IF sy-subrc = 0. lv_client = sy-mandt. ls_cts_object_entry-pgmid = seok_pgmid_r3tr. ls_cts_object_entry-object = ms_item-obj_type. ls_cts_object_entry-obj_name = ms_item-obj_name. INSERT ls_cts_object_entry INTO TABLE lt_cts_object_entry. CALL FUNCTION -methodname EXPORTING iv_client = lv_client TABLES tt_e071 = lt_cts_object_entry tt_e071k = lt_cts_key. ENDIF. ENDMETHOD. METHOD constructor. CONSTANTS lc_logical_transport_object TYPE c LENGTH 1 VALUE 'L'. SELECT SINGLE * FROM objh INTO ms_object_header WHERE objectname = is_item-obj_type AND objecttype = lc_logical_transport_object. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'Not found in OBJH, or not supported' ). ENDIF. * object tables SELECT * FROM objsl INTO CORRESPONDING FIELDS OF TABLE mt_object_table WHERE objectname = is_item-obj_type AND objecttype = lc_logical_transport_object AND tobject = 'TABU' ORDER BY PRIMARY KEY. IF mt_object_table IS INITIAL. zcx_abapgit_exception=>raise( |Obviously corrupted object-type { is_item-obj_type }: No tables defined| ). ENDIF. * only unique tables SORT mt_object_table BY tobj_name ASCENDING. DELETE ADJACENT DUPLICATES FROM mt_object_table COMPARING tobj_name. * object methods SELECT * FROM objm INTO TABLE mt_object_method WHERE objectname = is_item-obj_type AND objecttype = lc_logical_transport_object ORDER BY PRIMARY KEY. ms_item = is_item. ENDMETHOD. METHOD corr_insert. * this will also insert into TADIR CALL FUNCTION 'RS_CORR_INSERT' EXPORTING object = ms_item-obj_name object_class = ms_item-obj_type mode = 'I' global_lock = abap_true devclass = iv_package master_language = sy-langu suppress_dialog = abap_true EXCEPTIONS cancelled = 1 permission_failure = 2 unknown_objectclass = 3 OTHERS = 4. IF sy-subrc <> 0. zcx_abapgit_exception=>raise_t100( ). ENDIF. ENDMETHOD. METHOD delete. DATA: lv_where TYPE string, lv_primary TYPE objsl-tobj_name. FIELD-SYMBOLS LIKE LINE OF mt_object_table. lv_primary = get_primary_table( ). LOOP AT mt_object_table ASSIGNING . lv_where = get_where_clause( -tobj_name ). ASSERT NOT lv_where IS INITIAL. DELETE FROM (-tobj_name) WHERE (lv_where). IF -tobj_name = lv_primary. ASSERT sy-dbcnt <= 1. ""Just to be on the very safe side ENDIF. ENDLOOP. ENDMETHOD. METHOD deserialize. validate( io_xml ). delete( ). deserialize_data( io_xml ). after_import( ). corr_insert( iv_package ). ENDMETHOD. METHOD deserialize_data. DATA: lr_ref TYPE REF TO data. FIELD-SYMBOLS: TYPE STANDARD TABLE, LIKE LINE OF mt_object_table. LOOP AT mt_object_table ASSIGNING . CREATE DATA lr_ref TYPE STANDARD TABLE OF (-tobj_name). ASSIGN lr_ref->* TO . io_xml->read( EXPORTING iv_name = -tobj_name CHANGING cg_data = ). INSERT (-tobj_name) FROM TABLE . IF sy-subrc <> 0. zcx_abapgit_exception=>raise( |Error inserting data, { -tobj_name }| ). ENDIF. ENDLOOP. ENDMETHOD. METHOD distribute_name_to_components. DATA: lt_key_component_uncovered LIKE it_key_component, ls_key_component_uncovered LIKE LINE OF lt_key_component_uncovered, ls_objkey_sub LIKE cs_objkey, lv_objkey_sub_pos TYPE i, lv_remaining_length TYPE i, lv_count_components_covered LIKE ls_objkey_sub-num. DATA lv_len LIKE ls_key_component_uncovered-leng. lt_key_component_uncovered = it_key_component. ls_objkey_sub-num = cs_objkey-num. lv_objkey_sub_pos = 0. * we want to fill the atribute values which are not covered by explicit key components yet lv_count_components_covered = ls_objkey_sub-num - 1. DO lv_count_components_covered TIMES. DELETE lt_key_component_uncovered INDEX 1. ENDDO. LOOP AT lt_key_component_uncovered INTO ls_key_component_uncovered. CLEAR ls_objkey_sub-value. * Some datatype used in the key might exceed the total remaining characters length (e. g. SICF) TRY. lv_remaining_length = strlen( |{ substring( val = cs_objkey-value off = lv_objkey_sub_pos ) }| ). CATCH cx_sy_range_out_of_bounds. lv_remaining_length = 0. RETURN. "">>>>>>>>>>>>>>>>>>>>>>>>>>> ENDTRY. IF ls_key_component_uncovered-leng <= lv_remaining_length. lv_len = ls_key_component_uncovered-leng. ELSE. lv_len = lv_remaining_length. ENDIF. ls_objkey_sub-value = |{ substring( val = cs_objkey-value off = lv_objkey_sub_pos len = lv_len ) }|. ls_objkey_sub-num = cv_non_value_pos. INSERT ls_objkey_sub INTO TABLE ct_objkey. lv_objkey_sub_pos = lv_objkey_sub_pos + ls_key_component_uncovered-leng. cv_non_value_pos = cv_non_value_pos + 1. CLEAR ls_objkey_sub. IF lv_objkey_sub_pos = strlen( cs_objkey-value ). cs_objkey-num = cv_non_value_pos. EXIT. ""end splitting - all characters captured ENDIF. ENDLOOP. ENDMETHOD. METHOD exists. DATA: lv_where_clause TYPE string, lv_primary TYPE objsl-tobj_name, lr_table_line TYPE REF TO data. FIELD-SYMBOLS: TYPE any. lv_primary = get_primary_table( ). lv_where_clause = get_where_clause( lv_primary ). CREATE DATA lr_table_line TYPE (lv_primary). ASSIGN lr_table_line->* TO . SELECT SINGLE * FROM (lv_primary) INTO WHERE (lv_where_clause). rv_bool = boolc( sy-dbcnt > 0 ). ENDMETHOD. METHOD get_key_fields. DATA: lv_table TYPE ddobjname. lv_table = iv_table. CALL FUNCTION 'DDIF_NAMETAB_GET' EXPORTING tabname = lv_table TABLES dfies_tab = rt_keys EXCEPTIONS not_found = 1 OTHERS = 2. IF sy-subrc <> 0. zcx_abapgit_exception=>raise_t100( ). ENDIF. DELETE rt_keys WHERE keyflag = abap_false. ENDMETHOD. METHOD get_primary_table. DATA: ls_object_table LIKE LINE OF mt_object_table. READ TABLE mt_object_table INTO ls_object_table WITH KEY prim_table = abap_true. IF sy-subrc <> 0. * Fallback. For some objects, no primary table is explicitly flagged * The, the one with only one key field shall be chosen READ TABLE mt_object_table INTO ls_object_table WITH KEY tobjkey = '/&'. ""#EC CI_SUBRC ENDIF. IF ls_object_table IS INITIAL. zcx_abapgit_exception=>raise( |Object { ms_item-obj_type } has got no defined primary table| ). ENDIF. rv_table = ls_object_table-tobj_name. ENDMETHOD. METHOD get_where_clause. DATA: lv_objkey_pos TYPE i, lv_next_objkey_pos TYPE i, lv_value_pos TYPE i, lv_objkey_length TYPE i, lt_objkey TYPE ty_t_objkey, ls_objkey LIKE LINE OF lt_objkey, lv_non_value_pos TYPE numc3, lt_key_fields TYPE ddfields. DATA: lv_is_asterix TYPE abap_bool, lv_where_statement TYPE string, lv_key_pos TYPE i, lv_value128 TYPE string. FIELD-SYMBOLS LIKE LINE OF mt_object_table. FIELD-SYMBOLS LIKE LINE OF lt_key_fields. READ TABLE mt_object_table ASSIGNING WITH KEY tobj_name = iv_tobj_name. ASSERT sy-subrc = 0. lt_key_fields = get_key_fields( iv_tobj_name ). * analyze the object key and compose the key (table) CLEAR lt_objkey. CLEAR ls_objkey. lv_objkey_pos = 0. lv_non_value_pos = 1. lv_value_pos = 0. lv_objkey_length = strlen( -tobjkey ). WHILE lv_objkey_pos <= lv_objkey_length. ls_objkey-num = lv_non_value_pos. * command IF -tobjkey+lv_objkey_pos(1) = '/'. IF NOT ls_objkey-value IS INITIAL. * We reached the end of a key-definition. * this key part may address multiple fields. * E. g. six characters may address one boolean field and a five-digit version field. * Thus, we need to analyze the remaining key components which have not been covered yet. split_value_to_keys( EXPORTING it_key_component = lt_key_fields CHANGING ct_objkey = lt_objkey cs_objkey = ls_objkey cv_non_value_pos = lv_non_value_pos ). ENDIF. lv_next_objkey_pos = lv_objkey_pos + 1. * '*' means all further key values IF -tobjkey+lv_next_objkey_pos(1) = '*'. ls_objkey-value = '*'. INSERT ls_objkey INTO TABLE lt_objkey. CLEAR ls_objkey. lv_non_value_pos = lv_non_value_pos + 1. lv_objkey_pos = lv_objkey_pos + 1. * object name ELSEIF -tobjkey+lv_next_objkey_pos(1) = '&'. ""TODO ls_objkey-value = ms_item-obj_name. * The object name might comprise multiple key components (e. g. WDCC) * This string needs to be split distribute_name_to_components( EXPORTING it_key_component = lt_key_fields CHANGING ct_objkey = lt_objkey cs_objkey = ls_objkey cv_non_value_pos = lv_non_value_pos ). CLEAR ls_objkey. lv_objkey_pos = lv_objkey_pos + 1. * language ELSEIF -tobjkey+lv_next_objkey_pos(1) = 'L'. ls_objkey-value = sy-langu. INSERT ls_objkey INTO TABLE lt_objkey. CLEAR ls_objkey. lv_non_value_pos = lv_non_value_pos + 1. lv_objkey_pos = lv_objkey_pos + 1. * Client ELSEIF -tobjkey+lv_next_objkey_pos(1) = 'C'. ls_objkey-value = sy-mandt. INSERT ls_objkey INTO TABLE lt_objkey. CLEAR ls_objkey. lv_non_value_pos = lv_non_value_pos + 1. lv_objkey_pos = lv_objkey_pos + 1. ENDIF. lv_value_pos = 0. * value ELSE. ls_objkey-value+lv_value_pos(1) = -tobjkey+lv_objkey_pos(1). lv_value_pos = lv_value_pos + 1. ENDIF. lv_objkey_pos = lv_objkey_pos + 1. ENDWHILE. * Similarly to that, fixed values might be supplied in the object key which actually make up key components IF NOT ls_objkey-value IS INITIAL. split_value_to_keys( EXPORTING it_key_component = lt_key_fields CHANGING ct_objkey = lt_objkey cs_objkey = ls_objkey cv_non_value_pos = lv_non_value_pos ). ENDIF. * compose the where clause lv_is_asterix = abap_false. lv_key_pos = 1. LOOP AT lt_key_fields ASSIGNING . READ TABLE lt_objkey INTO ls_objkey WITH TABLE KEY num = lv_key_pos. IF sy-subrc <> 0 OR -fieldname = 'LANGU'. CLEAR ls_objkey. lv_key_pos = lv_key_pos + 1. CONTINUE. ENDIF. IF ls_objkey-value = '*'. lv_is_asterix = abap_true. ENDIF. IF lv_is_asterix = abap_true. CONTINUE. ENDIF. IF NOT lv_where_statement IS INITIAL. CONCATENATE lv_where_statement 'AND' INTO lv_where_statement SEPARATED BY space. ENDIF. lv_value128 = cl_abap_dyn_prg=>quote( ls_objkey-value ). CONCATENATE lv_where_statement -fieldname '=' lv_value128 INTO lv_where_statement SEPARATED BY space. lv_key_pos = lv_key_pos + 1. ENDLOOP. rv_where = condense( lv_where_statement ). ENDMETHOD. METHOD serialize. before_export( ). serialize_data( io_xml ). ENDMETHOD. METHOD serialize_data. DATA: lr_ref TYPE REF TO data, lv_where TYPE string. FIELD-SYMBOLS: TYPE STANDARD TABLE, LIKE LINE OF mt_object_table. LOOP AT mt_object_table ASSIGNING . CREATE DATA lr_ref TYPE STANDARD TABLE OF (-tobj_name). ASSIGN lr_ref->* TO . lv_where = get_where_clause( -tobj_name ). SELECT * FROM (-tobj_name) INTO TABLE WHERE (lv_where) ORDER BY PRIMARY KEY. io_xml->add( iv_name = -tobj_name ig_data = ). ENDLOOP. ENDMETHOD. METHOD split_value_to_keys. DATA: lt_key_component_uncovered LIKE it_key_component, ls_dummy LIKE LINE OF ct_objkey, ls_key_component_uncovered LIKE LINE OF lt_key_component_uncovered, ls_objkey_sub LIKE cs_objkey, lv_objkey_sub_pos TYPE i. lt_key_component_uncovered = it_key_component. * we want to fill the atribute values which are not covered by explicit key components yet LOOP AT ct_objkey INTO ls_dummy. DELETE lt_key_component_uncovered INDEX 1. ENDLOOP. ls_objkey_sub-num = cs_objkey-num. lv_objkey_sub_pos = 0. LOOP AT lt_key_component_uncovered INTO ls_key_component_uncovered. CLEAR ls_objkey_sub-value. ls_objkey_sub-value = cs_objkey-value+lv_objkey_sub_pos(ls_key_component_uncovered-leng). ls_objkey_sub-num = cv_non_value_pos. INSERT ls_objkey_sub INTO TABLE ct_objkey. lv_objkey_sub_pos = lv_objkey_sub_pos + ls_key_component_uncovered-leng. cv_non_value_pos = cv_non_value_pos + 1. CLEAR ls_objkey_sub. IF lv_objkey_sub_pos = strlen( cs_objkey-value ). cs_objkey-num = cv_non_value_pos. EXIT. ""end splitting - all characters captured ENDIF. ENDLOOP. ENDMETHOD. METHOD validate. DATA: lv_where TYPE string, lv_primary TYPE objsl-tobj_name, lr_ref TYPE REF TO data. FIELD-SYMBOLS: TYPE STANDARD TABLE. lv_primary = get_primary_table( ). CREATE DATA lr_ref TYPE STANDARD TABLE OF (lv_primary). ASSIGN lr_ref->* TO . io_xml->read( EXPORTING iv_name = lv_primary CHANGING cg_data = ). IF lines( ) = 0. zcx_abapgit_exception=>raise( |Primary table { lv_primary } not found in imported container| ). ELSEIF lines( ) <> 1. zcx_abapgit_exception=>raise( |Primary table { lv_primary } contains more than one instance!| ). ENDIF. lv_where = get_where_clause( lv_primary ). * validate that max one local instance was affected by the import SELECT COUNT(*) FROM (lv_primary) WHERE (lv_where). IF sy-dbcnt > 1. zcx_abapgit_exception=>raise( |More than one instance exists locally in primary table { lv_primary }| ). ENDIF. ENDMETHOD. ENDCLASS. ",5084,False,1107.9472436946382,median "-- This spec has been automatically generated from STM32L5x2.svd pragma Restrictions (No_Elaboration_Code); pragma Ada_2012; pragma Style_Checks (Off); with HAL; with System; package STM32_SVD.DMAMUX is pragma Preelaborate; --------------- -- Registers -- --------------- subtype C0CR_DMAREQ_ID_Field is HAL.UInt7; subtype C0CR_SPOL_Field is HAL.UInt2; subtype C0CR_NBREQ_Field is HAL.UInt5; subtype C0CR_SYNC_ID_Field is HAL.UInt5; -- DMA Multiplexer Channel 0 Control register type C0CR_Register is record -- DMA Request ID DMAREQ_ID : C0CR_DMAREQ_ID_Field := 16#0#; -- unspecified Reserved_7_7 : HAL.Bit := 16#0#; -- Synchronization Overrun Interrupt Enable SOIE : Boolean := False; -- Event Generation Enable EGE : Boolean := False; -- unspecified Reserved_10_15 : HAL.UInt6 := 16#0#; -- Synchronization enable SE : Boolean := False; -- Sync polarity SPOL : C0CR_SPOL_Field := 16#0#; -- Nb request NBREQ : C0CR_NBREQ_Field := 16#0#; -- SYNC_ID SYNC_ID : C0CR_SYNC_ID_Field := 16#0#; -- unspecified Reserved_29_31 : HAL.UInt3 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for C0CR_Register use record DMAREQ_ID at 0 range 0 .. 6; Reserved_7_7 at 0 range 7 .. 7; SOIE at 0 range 8 .. 8; EGE at 0 range 9 .. 9; Reserved_10_15 at 0 range 10 .. 15; SE at 0 range 16 .. 16; SPOL at 0 range 17 .. 18; NBREQ at 0 range 19 .. 23; SYNC_ID at 0 range 24 .. 28; Reserved_29_31 at 0 range 29 .. 31; end record; subtype C1CR_DMAREQ_ID_Field is HAL.UInt7; subtype C1CR_SPOL_Field is HAL.UInt2; subtype C1CR_NBREQ_Field is HAL.UInt5; subtype C1CR_SYNC_ID_Field is HAL.UInt5; -- DMA Multiplexer Channel 1 Control register type C1CR_Register is record -- DMA Request ID DMAREQ_ID : C1CR_DMAREQ_ID_Field := 16#0#; -- unspecified Reserved_7_7 : HAL.Bit := 16#0#; -- Synchronization Overrun Interrupt Enable SOIE : Boolean := False; -- Event Generation Enable EGE : Boolean := False; -- unspecified Reserved_10_15 : HAL.UInt6 := 16#0#; -- Synchronization enable SE : Boolean := False; -- Sync polarity SPOL : C1CR_SPOL_Field := 16#0#; -- Nb request NBREQ : C1CR_NBREQ_Field := 16#0#; -- SYNC_ID SYNC_ID : C1CR_SYNC_ID_Field := 16#0#; -- unspecified Reserved_29_31 : HAL.UInt3 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for C1CR_Register use record DMAREQ_ID at 0 range 0 .. 6; Reserved_7_7 at 0 range 7 .. 7; SOIE at 0 range 8 .. 8; EGE at 0 range 9 .. 9; Reserved_10_15 at 0 range 10 .. 15; SE at 0 range 16 .. 16; SPOL at 0 range 17 .. 18; NBREQ at 0 range 19 .. 23; SYNC_ID at 0 range 24 .. 28; Reserved_29_31 at 0 range 29 .. 31; end record; subtype C2CR_DMAREQ_ID_Field is HAL.UInt7; subtype C2CR_SPOL_Field is HAL.UInt2; subtype C2CR_NBREQ_Field is HAL.UInt5; subtype C2CR_SYNC_ID_Field is HAL.UInt5; -- DMA Multiplexer Channel 2 Control register type C2CR_Register is record -- DMA Request ID DMAREQ_ID : C2CR_DMAREQ_ID_Field := 16#0#; -- unspecified Reserved_7_7 : HAL.Bit := 16#0#; -- Synchronization Overrun Interrupt Enable SOIE : Boolean := False; -- Event Generation Enable EGE : Boolean := False; -- unspecified Reserved_10_15 : HAL.UInt6 := 16#0#; -- Synchronization enable SE : Boolean := False; -- Sync polarity SPOL : C2CR_SPOL_Field := 16#0#; -- Nb request NBREQ : C2CR_NBREQ_Field := 16#0#; -- SYNC_ID SYNC_ID : C2CR_SYNC_ID_Field := 16#0#; -- unspecified Reserved_29_31 : HAL.UInt3 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for C2CR_Register use record DMAREQ_ID at 0 range 0 .. 6; Reserved_7_7 at 0 range 7 .. 7; SOIE at 0 range 8 .. 8; EGE at 0 range 9 .. 9; Reserved_10_15 at 0 range 10 .. 15; SE at 0 range 16 .. 16; SPOL at 0 range 17 .. 18; NBREQ at 0 range 19 .. 23; SYNC_ID at 0 range 24 .. 28; Reserved_29_31 at 0 range 29 .. 31; end record; subtype C3CR_DMAREQ_ID_Field is HAL.UInt7; subtype C3CR_SPOL_Field is HAL.UInt2; subtype C3CR_NBREQ_Field is HAL.UInt5; subtype C3CR_SYNC_ID_Field is HAL.UInt5; -- DMA Multiplexer Channel 3 Control register type C3CR_Register is record -- DMA Request ID DMAREQ_ID : C3CR_DMAREQ_ID_Field := 16#0#; -- unspecified Reserved_7_7 : HAL.Bit := 16#0#; -- Synchronization Overrun Interrupt Enable SOIE : Boolean := False; -- Event Generation Enable EGE : Boolean := False; -- unspecified Reserved_10_15 : HAL.UInt6 := 16#0#; -- Synchronization enable SE : Boolean := False; -- Sync polarity SPOL : C3CR_SPOL_Field := 16#0#; -- Nb request NBREQ : C3CR_NBREQ_Field := 16#0#; -- SYNC_ID SYNC_ID : C3CR_SYNC_ID_Field := 16#0#; -- unspecified Reserved_29_31 : HAL.UInt3 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for C3CR_Register use record DMAREQ_ID at 0 range 0 .. 6; Reserved_7_7 at 0 range 7 .. 7; SOIE at 0 range 8 .. 8; EGE at 0 range 9 .. 9; Reserved_10_15 at 0 range 10 .. 15; SE at 0 range 16 .. 16; SPOL at 0 range 17 .. 18; NBREQ at 0 range 19 .. 23; SYNC_ID at 0 range 24 .. 28; Reserved_29_31 at 0 range 29 .. 31; end record; subtype C4CR_DMAREQ_ID_Field is HAL.UInt7; subtype C4CR_SPOL_Field is HAL.UInt2; subtype C4CR_NBREQ_Field is HAL.UInt5; subtype C4CR_SYNC_ID_Field is HAL.UInt5; -- DMA Multiplexer Channel 4 Control register type C4CR_Register is record -- DMA Request ID DMAREQ_ID : C4CR_DMAREQ_ID_Field := 16#0#; -- unspecified Reserved_7_7 : HAL.Bit := 16#0#; -- Synchronization Overrun Interrupt Enable SOIE : Boolean := False; -- Event Generation Enable EGE : Boolean := False; -- unspecified Reserved_10_15 : HAL.UInt6 := 16#0#; -- Synchronization enable SE : Boolean := False; -- Sync polarity SPOL : C4CR_SPOL_Field := 16#0#; -- Nb request NBREQ : C4CR_NBREQ_Field := 16#0#; -- SYNC_ID SYNC_ID : C4CR_SYNC_ID_Field := 16#0#; -- unspecified Reserved_29_31 : HAL.UInt3 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for C4CR_Register use record DMAREQ_ID at 0 range 0 .. 6; Reserved_7_7 at 0 range 7 .. 7; SOIE at 0 range 8 .. 8; EGE at 0 range 9 .. 9; Reserved_10_15 at 0 range 10 .. 15; SE at 0 range 16 .. 16; SPOL at 0 range 17 .. 18; NBREQ at 0 range 19 .. 23; SYNC_ID at 0 range 24 .. 28; Reserved_29_31 at 0 range 29 .. 31; end record; subtype C5CR_DMAREQ_ID_Field is HAL.UInt7; subtype C5CR_SPOL_Field is HAL.UInt2; subtype C5CR_NBREQ_Field is HAL.UInt5; subtype C5CR_SYNC_ID_Field is HAL.UInt5; -- DMA Multiplexer Channel 5 Control register type C5CR_Register is record -- DMA Request ID DMAREQ_ID : C5CR_DMAREQ_ID_Field := 16#0#; -- unspecified Reserved_7_7 : HAL.Bit := 16#0#; -- Synchronization Overrun Interrupt Enable OIE : Boolean := False; -- Event Generation Enable EGE : Boolean := False; -- unspecified Reserved_10_15 : HAL.UInt6 := 16#0#; -- Synchronization enable SE : Boolean := False; -- Sync polarity SPOL : C5CR_SPOL_Field := 16#0#; -- Nb request NBREQ : C5CR_NBREQ_Field := 16#0#; -- SYNC_ID SYNC_ID : C5CR_SYNC_ID_Field := 16#0#; -- unspecified Reserved_29_31 : HAL.UInt3 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for C5CR_Register use record DMAREQ_ID at 0 range 0 .. 6; Reserved_7_7 at 0 range 7 .. 7; OIE at 0 range 8 .. 8; EGE at 0 range 9 .. 9; Reserved_10_15 at 0 range 10 .. 15; SE at 0 range 16 .. 16; SPOL at 0 range 17 .. 18; NBREQ at 0 range 19 .. 23; SYNC_ID at 0 range 24 .. 28; Reserved_29_31 at 0 range 29 .. 31; end record; subtype C6CR_DMAREQ_ID_Field is HAL.UInt7; subtype C6CR_SPOL_Field is HAL.UInt2; subtype C6CR_NBREQ_Field is HAL.UInt5; subtype C6CR_SYNC_ID_Field is HAL.UInt5; -- DMA Multiplexer Channel 6 Control register type C6CR_Register is record -- DMA Request ID DMAREQ_ID : C6CR_DMAREQ_ID_Field := 16#0#; -- unspecified Reserved_7_7 : HAL.Bit := 16#0#; -- Synchronization Overrun Interrupt Enable SOIE : Boolean := False; -- Event Generation Enable EGE : Boolean := False; -- unspecified Reserved_10_15 : HAL.UInt6 := 16#0#; -- Synchronization enable SE : Boolean := False; -- Sync polarity SPOL : C6CR_SPOL_Field := 16#0#; -- Nb request NBREQ : C6CR_NBREQ_Field := 16#0#; -- SYNC_ID SYNC_ID : C6CR_SYNC_ID_Field := 16#0#; -- unspecified Reserved_29_31 : HAL.UInt3 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for C6CR_Register use record DMAREQ_ID at 0 range 0 .. 6; Reserved_7_7 at 0 range 7 .. 7; SOIE at 0 range 8 .. 8; EGE at 0 range 9 .. 9; Reserved_10_15 at 0 range 10 .. 15; SE at 0 range 16 .. 16; SPOL at 0 range 17 .. 18; NBREQ at 0 range 19 .. 23; SYNC_ID at 0 range 24 .. 28; Reserved_29_31 at 0 range 29 .. 31; end record; subtype C7CR_DMAREQ_ID_Field is HAL.UInt7; subtype C7CR_SPOL_Field is HAL.UInt2; subtype C7CR_NBREQ_Field is HAL.UInt5; subtype C7CR_SYNC_ID_Field is HAL.UInt5; -- DMA Multiplexer Channel 7 Control register type C7CR_Register is record -- DMA Request ID DMAREQ_ID : C7CR_DMAREQ_ID_Field := 16#0#; -- unspecified Reserved_7_7 : HAL.Bit := 16#0#; -- Synchronization Overrun Interrupt Enable SOIE : Boolean := False; -- Event Generation Enable EGE : Boolean := False; -- unspecified Reserved_10_15 : HAL.UInt6 := 16#0#; -- Synchronization enable SE : Boolean := False; -- Sync polarity SPOL : C7CR_SPOL_Field := 16#0#; -- Nb request NBREQ : C7CR_NBREQ_Field := 16#0#; -- SYNC_ID SYNC_ID : C7CR_SYNC_ID_Field := 16#0#; -- unspecified Reserved_29_31 : HAL.UInt3 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for C7CR_Register use record DMAREQ_ID at 0 range 0 .. 6; Reserved_7_7 at 0 range 7 .. 7; SOIE at 0 range 8 .. 8; EGE at 0 range 9 .. 9; Reserved_10_15 at 0 range 10 .. 15; SE at 0 range 16 .. 16; SPOL at 0 range 17 .. 18; NBREQ at 0 range 19 .. 23; SYNC_ID at 0 range 24 .. 28; Reserved_29_31 at 0 range 29 .. 31; end record; subtype C8CR_DMAREQ_ID_Field is HAL.UInt7; subtype C8CR_SPOL_Field is HAL.UInt2; subtype C8CR_NBREQ_Field is HAL.UInt5; subtype C8CR_SYNC_ID_Field is HAL.UInt5; -- DMA Multiplexer Channel 8 Control register type C8CR_Register is record -- DMA Request ID DMAREQ_ID : C8CR_DMAREQ_ID_Field := 16#0#; -- unspecified Reserved_7_7 : HAL.Bit := 16#0#; -- Synchronization Overrun Interrupt Enable SOIE : Boolean := False; -- Event Generation Enable EGE : Boolean := False; -- unspecified Reserved_10_15 : HAL.UInt6 := 16#0#; -- Synchronization enable SE : Boolean := False; -- Sync polarity SPOL : C8CR_SPOL_Field := 16#0#; -- Nb request NBREQ : C8CR_NBREQ_Field := 16#0#; -- SYNC_ID SYNC_ID : C8CR_SYNC_ID_Field := 16#0#; -- unspecified Reserved_29_31 : HAL.UInt3 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for C8CR_Register use record DMAREQ_ID at 0 range 0 .. 6; Reserved_7_7 at 0 range 7 .. 7; SOIE at 0 range 8 .. 8; EGE at 0 range 9 .. 9; Reserved_10_15 at 0 range 10 .. 15; SE at 0 range 16 .. 16; SPOL at 0 range 17 .. 18; NBREQ at 0 range 19 .. 23; SYNC_ID at 0 range 24 .. 28; Reserved_29_31 at 0 range 29 .. 31; end record; subtype C9CR_DMAREQ_ID_Field is HAL.UInt7; subtype C9CR_SPOL_Field is HAL.UInt2; subtype C9CR_NBREQ_Field is HAL.UInt5; subtype C9CR_SYNC_ID_Field is HAL.UInt5; -- DMA Multiplexer Channel 9 Control register type C9CR_Register is record -- DMA Request ID DMAREQ_ID : C9CR_DMAREQ_ID_Field := 16#0#; -- unspecified Reserved_7_7 : HAL.Bit := 16#0#; -- Synchronization Overrun Interrupt Enable SOIE : Boolean := False; -- Event Generation Enable EGE : Boolean := False; -- unspecified Reserved_10_15 : HAL.UInt6 := 16#0#; -- Synchronization enable SE : Boolean := False; -- Sync polarity SPOL : C9CR_SPOL_Field := 16#0#; -- Nb request NBREQ : C9CR_NBREQ_Field := 16#0#; -- SYNC_ID SYNC_ID : C9CR_SYNC_ID_Field := 16#0#; -- unspecified Reserved_29_31 : HAL.UInt3 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for C9CR_Register use record DMAREQ_ID at 0 range 0 .. 6; Reserved_7_7 at 0 range 7 .. 7; SOIE at 0 range 8 .. 8; EGE at 0 range 9 .. 9; Reserved_10_15 at 0 range 10 .. 15; SE at 0 range 16 .. 16; SPOL at 0 range 17 .. 18; NBREQ at 0 range 19 .. 23; SYNC_ID at 0 range 24 .. 28; Reserved_29_31 at 0 range 29 .. 31; end record; subtype C10CR_DMAREQ_ID_Field is HAL.UInt7; subtype C10CR_SPOL_Field is HAL.UInt2; subtype C10CR_NBREQ_Field is HAL.UInt5; subtype C10CR_SYNC_ID_Field is HAL.UInt5; -- DMA Multiplexer Channel 10 Control register type C10CR_Register is record -- DMA Request ID DMAREQ_ID : C10CR_DMAREQ_ID_Field := 16#0#; -- unspecified Reserved_7_7 : HAL.Bit := 16#0#; -- Synchronization Overrun Interrupt Enable SOIE : Boolean := False; -- Event Generation Enable EGE : Boolean := False; -- unspecified Reserved_10_15 : HAL.UInt6 := 16#0#; -- Synchronization enable SE : Boolean := False; -- Sync polarity SPOL : C10CR_SPOL_Field := 16#0#; -- Nb request NBREQ : C10CR_NBREQ_Field := 16#0#; -- SYNC_ID SYNC_ID : C10CR_SYNC_ID_Field := 16#0#; -- unspecified Reserved_29_31 : HAL.UInt3 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for C10CR_Register use record DMAREQ_ID at 0 range 0 .. 6; Reserved_7_7 at 0 range 7 .. 7; SOIE at 0 range 8 .. 8; EGE at 0 range 9 .. 9; Reserved_10_15 at 0 range 10 .. 15; SE at 0 range 16 .. 16; SPOL at 0 range 17 .. 18; NBREQ at 0 range 19 .. 23; SYNC_ID at 0 range 24 .. 28; Reserved_29_31 at 0 range 29 .. 31; end record; subtype C11CR_DMAREQ_ID_Field is HAL.UInt7; subtype C11CR_SPOL_Field is HAL.UInt2; subtype C11CR_NBREQ_Field is HAL.UInt5; subtype C11CR_SYNC_ID_Field is HAL.UInt5; -- DMA Multiplexer Channel 11 Control register type C11CR_Register is record -- DMA Request ID DMAREQ_ID : C11CR_DMAREQ_ID_Field := 16#0#; -- unspecified Reserved_7_7 : HAL.Bit := 16#0#; -- Synchronization Overrun Interrupt Enable SOIE : Boolean := False; -- Event Generation Enable EGE : Boolean := False; -- unspecified Reserved_10_15 : HAL.UInt6 := 16#0#; -- Synchronization enable SE : Boolean := False; -- Sync polarity SPOL : C11CR_SPOL_Field := 16#0#; -- Nb request NBREQ : C11CR_NBREQ_Field := 16#0#; -- SYNC_ID SYNC_ID : C11CR_SYNC_ID_Field := 16#0#; -- unspecified Reserved_29_31 : HAL.UInt3 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for C11CR_Register use record DMAREQ_ID at 0 range 0 .. 6; Reserved_7_7 at 0 range 7 .. 7; SOIE at 0 range 8 .. 8; EGE at 0 range 9 .. 9; Reserved_10_15 at 0 range 10 .. 15; SE at 0 range 16 .. 16; SPOL at 0 range 17 .. 18; NBREQ at 0 range 19 .. 23; SYNC_ID at 0 range 24 .. 28; Reserved_29_31 at 0 range 29 .. 31; end record; subtype C12CR_DMAREQ_ID_Field is HAL.UInt7; subtype C12CR_SPOL_Field is HAL.UInt2; subtype C12CR_NBREQ_Field is HAL.UInt5; subtype C12CR_SYNC_ID_Field is HAL.UInt5; -- DMA Multiplexer Channel 12 Control register type C12CR_Register is record -- DMA Request ID DMAREQ_ID : C12CR_DMAREQ_ID_Field := 16#0#; -- unspecified Reserved_7_7 : HAL.Bit := 16#0#; -- Synchronization Overrun Interrupt Enable SOIE : Boolean := False; -- Event Generation Enable EGE : Boolean := False; -- unspecified Reserved_10_15 : HAL.UInt6 := 16#0#; -- Synchronization enable SE : Boolean := False; -- Sync polarity SPOL : C12CR_SPOL_Field := 16#0#; -- Nb request NBREQ : C12CR_NBREQ_Field := 16#0#; -- SYNC_ID SYNC_ID : C12CR_SYNC_ID_Field := 16#0#; -- unspecified Reserved_29_31 : HAL.UInt3 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for C12CR_Register use record DMAREQ_ID at 0 range 0 .. 6; Reserved_7_7 at 0 range 7 .. 7; SOIE at 0 range 8 .. 8; EGE at 0 range 9 .. 9; Reserved_10_15 at 0 range 10 .. 15; SE at 0 range 16 .. 16; SPOL at 0 range 17 .. 18; NBREQ at 0 range 19 .. 23; SYNC_ID at 0 range 24 .. 28; Reserved_29_31 at 0 range 29 .. 31; end record; subtype C13CR_DMAREQ_ID_Field is HAL.UInt7; subtype C13CR_SPOL_Field is HAL.UInt2; subtype C13CR_NBREQ_Field is HAL.UInt5; subtype C13CR_SYNC_ID_Field is HAL.UInt5; -- DMA Multiplexer Channel 13 Control register type C13CR_Register is record -- DMA Request ID DMAREQ_ID : C13CR_DMAREQ_ID_Field := 16#0#; -- unspecified Reserved_7_7 : HAL.Bit := 16#0#; -- Synchronization Overrun Interrupt Enable SOIE : Boolean := False; -- Event Generation Enable EGE : Boolean := False; -- unspecified Reserved_10_15 : HAL.UInt6 := 16#0#; -- Synchronization enable SE : Boolean := False; -- Sync polarity SPOL : C13CR_SPOL_Field := 16#0#; -- Nb request NBREQ : C13CR_NBREQ_Field := 16#0#; -- SYNC_ID SYNC_ID : C13CR_SYNC_ID_Field := 16#0#; -- unspecified Reserved_29_31 : HAL.UInt3 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for C13CR_Register use record DMAREQ_ID at 0 range 0 .. 6; Reserved_7_7 at 0 range 7 .. 7; SOIE at 0 range 8 .. 8; EGE at 0 range 9 .. 9; Reserved_10_15 at 0 range 10 .. 15; SE at 0 range 16 .. 16; SPOL at 0 range 17 .. 18; NBREQ at 0 range 19 .. 23; SYNC_ID at 0 range 24 .. 28; Reserved_29_31 at 0 range 29 .. 31; end record; -- CSR_SOF array type CSR_SOF_Field_Array is array (0 .. 15) of Boolean with Component_Size => 1, Size => 16; -- Type definition for CSR_SOF type CSR_SOF_Field (As_Array : Boolean := False) is record case As_Array is when False => -- SOF as a value Val : HAL.UInt16; when True => -- SOF as an array Arr : CSR_SOF_Field_Array; end case; end record with Unchecked_Union, Size => 16; for CSR_SOF_Field use record Val at 0 range 0 .. 15; Arr at 0 range 0 .. 15; end record; -- DMA Multiplexer Channel Status register type CSR_Register is record -- Synchronization Overrun Flag 0 SOF : CSR_SOF_Field := (As_Array => False, Val => 16#0#); -- unspecified Reserved_16_31 : HAL.UInt16 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for CSR_Register use record SOF at 0 range 0 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; -- CCFR_CSOF array type CCFR_CSOF_Field_Array is array (0 .. 15) of Boolean with Component_Size => 1, Size => 16; -- Type definition for CCFR_CSOF type CCFR_CSOF_Field (As_Array : Boolean := False) is record case As_Array is when False => -- CSOF as a value Val : HAL.UInt16; when True => -- CSOF as an array Arr : CCFR_CSOF_Field_Array; end case; end record with Unchecked_Union, Size => 16; for CCFR_CSOF_Field use record Val at 0 range 0 .. 15; Arr at 0 range 0 .. 15; end record; -- DMA Channel Clear Flag Register type CCFR_Register is record -- Synchronization Clear Overrun Flag 0 CSOF : CCFR_CSOF_Field := (As_Array => False, Val => 16#0#); -- unspecified Reserved_16_31 : HAL.UInt16 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for CCFR_Register use record CSOF at 0 range 0 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; subtype RG0CR_SIG_ID_Field is HAL.UInt5; subtype RG0CR_GPOL_Field is HAL.UInt2; subtype RG0CR_GNBREQ_Field is HAL.UInt5; -- DMA Request Generator 0 Control Register type RG0CR_Register is record -- Signal ID SIG_ID : RG0CR_SIG_ID_Field := 16#0#; -- unspecified Reserved_5_7 : HAL.UInt3 := 16#0#; -- Overrun Interrupt Enable OIE : Boolean := False; -- unspecified Reserved_9_15 : HAL.UInt7 := 16#0#; -- Generation Enable GE : Boolean := False; -- Generation Polarity GPOL : RG0CR_GPOL_Field := 16#0#; -- Number of Request GNBREQ : RG0CR_GNBREQ_Field := 16#0#; -- unspecified Reserved_24_31 : HAL.UInt8 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for RG0CR_Register use record SIG_ID at 0 range 0 .. 4; Reserved_5_7 at 0 range 5 .. 7; OIE at 0 range 8 .. 8; Reserved_9_15 at 0 range 9 .. 15; GE at 0 range 16 .. 16; GPOL at 0 range 17 .. 18; GNBREQ at 0 range 19 .. 23; Reserved_24_31 at 0 range 24 .. 31; end record; subtype RG1CR_SIG_ID_Field is HAL.UInt5; subtype RG1CR_GPOL_Field is HAL.UInt2; subtype RG1CR_GNBREQ_Field is HAL.UInt5; -- DMA Request Generator 1 Control Register type RG1CR_Register is record -- Signal ID SIG_ID : RG1CR_SIG_ID_Field := 16#0#; -- unspecified Reserved_5_7 : HAL.UInt3 := 16#0#; -- Overrun Interrupt Enable OIE : Boolean := False; -- unspecified Reserved_9_15 : HAL.UInt7 := 16#0#; -- Generation Enable GE : Boolean := False; -- Generation Polarity GPOL : RG1CR_GPOL_Field := 16#0#; -- Number of Request GNBREQ : RG1CR_GNBREQ_Field := 16#0#; -- unspecified Reserved_24_31 : HAL.UInt8 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for RG1CR_Register use record SIG_ID at 0 range 0 .. 4; Reserved_5_7 at 0 range 5 .. 7; OIE at 0 range 8 .. 8; Reserved_9_15 at 0 range 9 .. 15; GE at 0 range 16 .. 16; GPOL at 0 range 17 .. 18; GNBREQ at 0 range 19 .. 23; Reserved_24_31 at 0 range 24 .. 31; end record; subtype RG2CR_SIG_ID_Field is HAL.UInt5; subtype RG2CR_GPOL_Field is HAL.UInt2; subtype RG2CR_GNBREQ_Field is HAL.UInt5; -- DMA Request Generator 2 Control Register type RG2CR_Register is record -- Signal ID SIG_ID : RG2CR_SIG_ID_Field := 16#0#; -- unspecified Reserved_5_7 : HAL.UInt3 := 16#0#; -- Overrun Interrupt Enable OIE : Boolean := False; -- unspecified Reserved_9_15 : HAL.UInt7 := 16#0#; -- Generation Enable GE : Boolean := False; -- Generation Polarity GPOL : RG2CR_GPOL_Field := 16#0#; -- Number of Request GNBREQ : RG2CR_GNBREQ_Field := 16#0#; -- unspecified Reserved_24_31 : HAL.UInt8 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for RG2CR_Register use record SIG_ID at 0 range 0 .. 4; Reserved_5_7 at 0 range 5 .. 7; OIE at 0 range 8 .. 8; Reserved_9_15 at 0 range 9 .. 15; GE at 0 range 16 .. 16; GPOL at 0 range 17 .. 18; GNBREQ at 0 range 19 .. 23; Reserved_24_31 at 0 range 24 .. 31; end record; subtype RG3CR_SIG_ID_Field is HAL.UInt5; subtype RG3CR_GPOL_Field is HAL.UInt2; subtype RG3CR_GNBREQ_Field is HAL.UInt5; -- DMA Request Generator 3 Control Register type RG3CR_Register is record -- Signal ID SIG_ID : RG3CR_SIG_ID_Field := 16#0#; -- unspecified Reserved_5_7 : HAL.UInt3 := 16#0#; -- Overrun Interrupt Enable OIE : Boolean := False; -- unspecified Reserved_9_15 : HAL.UInt7 := 16#0#; -- Generation Enable GE : Boolean := False; -- Generation Polarity GPOL : RG3CR_GPOL_Field := 16#0#; -- Number of Request GNBREQ : RG3CR_GNBREQ_Field := 16#0#; -- unspecified Reserved_24_31 : HAL.UInt8 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for RG3CR_Register use record SIG_ID at 0 range 0 .. 4; Reserved_5_7 at 0 range 5 .. 7; OIE at 0 range 8 .. 8; Reserved_9_15 at 0 range 9 .. 15; GE at 0 range 16 .. 16; GPOL at 0 range 17 .. 18; GNBREQ at 0 range 19 .. 23; Reserved_24_31 at 0 range 24 .. 31; end record; subtype C14CR_DMAREQ_ID_Field is HAL.UInt7; subtype C14CR_SPOL_Field is HAL.UInt2; subtype C14CR_NBREQ_Field is HAL.UInt5; subtype C14CR_SYNC_ID_Field is HAL.UInt5; -- DMA Multiplexer Channel 10 Control register type C14CR_Register is record -- DMA request identification DMAREQ_ID : C14CR_DMAREQ_ID_Field := 16#0#; -- unspecified Reserved_7_7 : HAL.Bit := 16#0#; -- Synchronization overrun interrupt enable SOIE : Boolean := False; -- Event generation enable EGE : Boolean := False; -- unspecified Reserved_10_15 : HAL.UInt6 := 16#0#; -- Synchronization enable SE : Boolean := False; -- Synchronization polarity SPOL : C14CR_SPOL_Field := 16#0#; -- Number of DMA requests minus 1 to forward NBREQ : C14CR_NBREQ_Field := 16#0#; -- Synchronization identification SYNC_ID : C14CR_SYNC_ID_Field := 16#0#; -- unspecified Reserved_29_31 : HAL.UInt3 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for C14CR_Register use record DMAREQ_ID at 0 range 0 .. 6; Reserved_7_7 at 0 range 7 .. 7; SOIE at 0 range 8 .. 8; EGE at 0 range 9 .. 9; Reserved_10_15 at 0 range 10 .. 15; SE at 0 range 16 .. 16; SPOL at 0 range 17 .. 18; NBREQ at 0 range 19 .. 23; SYNC_ID at 0 range 24 .. 28; Reserved_29_31 at 0 range 29 .. 31; end record; subtype C15CR_DMAREQ_ID_Field is HAL.UInt7; subtype C15CR_SPOL_Field is HAL.UInt2; subtype C15CR_NBREQ_Field is HAL.UInt5; subtype C15CR_SYNC_ID_Field is HAL.UInt5; -- DMA Multiplexer Channel 10 Control register type C15CR_Register is record -- DMA request identification DMAREQ_ID : C15CR_DMAREQ_ID_Field := 16#0#; -- unspecified Reserved_7_7 : HAL.Bit := 16#0#; -- Synchronization overrun interrupt enable SOIE : Boolean := False; -- Event generation enable EGE : Boolean := False; -- unspecified Reserved_10_15 : HAL.UInt6 := 16#0#; -- Synchronization enable SE : Boolean := False; -- Synchronization polarity SPOL : C15CR_SPOL_Field := 16#0#; -- Number of DMA requests minus 1 to forward NBREQ : C15CR_NBREQ_Field := 16#0#; -- Synchronization identification SYNC_ID : C15CR_SYNC_ID_Field := 16#0#; -- unspecified Reserved_29_31 : HAL.UInt3 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for C15CR_Register use record DMAREQ_ID at 0 range 0 .. 6; Reserved_7_7 at 0 range 7 .. 7; SOIE at 0 range 8 .. 8; EGE at 0 range 9 .. 9; Reserved_10_15 at 0 range 10 .. 15; SE at 0 range 16 .. 16; SPOL at 0 range 17 .. 18; NBREQ at 0 range 19 .. 23; SYNC_ID at 0 range 24 .. 28; Reserved_29_31 at 0 range 29 .. 31; end record; -- RGSR_OF array type RGSR_OF_Field_Array is array (0 .. 3) of Boolean with Component_Size => 1, Size => 4; -- Type definition for RGSR_OF type RGSR_OF_Field (As_Array : Boolean := False) is record case As_Array is when False => -- OF as a value Val : HAL.UInt4; when True => -- OF as an array Arr : RGSR_OF_Field_Array; end case; end record with Unchecked_Union, Size => 4; for RGSR_OF_Field use record Val at 0 range 0 .. 3; Arr at 0 range 0 .. 3; end record; -- DMA Request Generator Status Register type RGSR_Register is record -- Read-only. Generator Overrun Flag 0 OF_k : RGSR_OF_Field; -- unspecified Reserved_4_31 : HAL.UInt28; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for RGSR_Register use record OF_k at 0 range 0 .. 3; Reserved_4_31 at 0 range 4 .. 31; end record; -- RGCFR_CSOF array type RGCFR_CSOF_Field_Array is array (0 .. 3) of Boolean with Component_Size => 1, Size => 4; -- Type definition for RGCFR_CSOF type RGCFR_CSOF_Field (As_Array : Boolean := False) is record case As_Array is when False => -- CSOF as a value Val : HAL.UInt4; when True => -- CSOF as an array Arr : RGCFR_CSOF_Field_Array; end case; end record with Unchecked_Union, Size => 4; for RGCFR_CSOF_Field use record Val at 0 range 0 .. 3; Arr at 0 range 0 .. 3; end record; -- DMA Request Generator Clear Flag Register type RGCFR_Register is record -- Generator Clear Overrun Flag 0 CSOF : RGCFR_CSOF_Field := (As_Array => False, Val => 16#0#); -- unspecified Reserved_4_31 : HAL.UInt28 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for RGCFR_Register use record CSOF at 0 range 0 .. 3; Reserved_4_31 at 0 range 4 .. 31; end record; ----------------- -- Peripherals -- ----------------- -- Direct memory access Multiplexer type DMAMUX_Peripheral is record -- DMA Multiplexer Channel 0 Control register C0CR : aliased C0CR_Register; -- DMA Multiplexer Channel 1 Control register C1CR : aliased C1CR_Register; -- DMA Multiplexer Channel 2 Control register C2CR : aliased C2CR_Register; -- DMA Multiplexer Channel 3 Control register C3CR : aliased C3CR_Register; -- DMA Multiplexer Channel 4 Control register C4CR : aliased C4CR_Register; -- DMA Multiplexer Channel 5 Control register C5CR : aliased C5CR_Register; -- DMA Multiplexer Channel 6 Control register C6CR : aliased C6CR_Register; -- DMA Multiplexer Channel 7 Control register C7CR : aliased C7CR_Register; -- DMA Multiplexer Channel 8 Control register C8CR : aliased C8CR_Register; -- DMA Multiplexer Channel 9 Control register C9CR : aliased C9CR_Register; -- DMA Multiplexer Channel 10 Control register C10CR : aliased C10CR_Register; -- DMA Multiplexer Channel 11 Control register C11CR : aliased C11CR_Register; -- DMA Multiplexer Channel 12 Control register C12CR : aliased C12CR_Register; -- DMA Multiplexer Channel 13 Control register C13CR : aliased C13CR_Register; -- DMA Multiplexer Channel Status register CSR : aliased CSR_Register; -- DMA Channel Clear Flag Register CCFR : aliased CCFR_Register; -- DMA Request Generator 0 Control Register RG0CR : aliased RG0CR_Register; -- DMA Request Generator 1 Control Register RG1CR : aliased RG1CR_Register; -- DMA Request Generator 2 Control Register RG2CR : aliased RG2CR_Register; -- DMA Request Generator 3 Control Register RG3CR : aliased RG3CR_Register; -- DMA Multiplexer Channel 10 Control register C14CR : aliased C14CR_Register; -- DMA Multiplexer Channel 10 Control register C15CR : aliased C15CR_Register; -- DMA Request Generator Status Register RGSR : aliased RGSR_Register; -- DMA Request Generator Clear Flag Register RGCFR : aliased RGCFR_Register; end record with Volatile; for DMAMUX_Peripheral use record C0CR at 16#0# range 0 .. 31; C1CR at 16#4# range 0 .. 31; C2CR at 16#8# range 0 .. 31; C3CR at 16#C# range 0 .. 31; C4CR at 16#10# range 0 .. 31; C5CR at 16#14# range 0 .. 31; C6CR at 16#18# range 0 .. 31; C7CR at 16#1C# range 0 .. 31; C8CR at 16#20# range 0 .. 31; C9CR at 16#24# range 0 .. 31; C10CR at 16#28# range 0 .. 31; C11CR at 16#2C# range 0 .. 31; C12CR at 16#30# range 0 .. 31; C13CR at 16#34# range 0 .. 31; CSR at 16#80# range 0 .. 31; CCFR at 16#84# range 0 .. 31; RG0CR at 16#100# range 0 .. 31; RG1CR at 16#104# range 0 .. 31; RG2CR at 16#108# range 0 .. 31; RG3CR at 16#10C# range 0 .. 31; C14CR at 16#138# range 0 .. 31; C15CR at 16#13C# range 0 .. 31; RGSR at 16#140# range 0 .. 31; RGCFR at 16#144# range 0 .. 31; end record; -- Direct memory access Multiplexer DMAMUX1_Periph : aliased DMAMUX_Peripheral with Import, Address => System'To_Address (16#40020800#); -- Direct memory access Multiplexer SEC_DMAMUX1_Periph : aliased DMAMUX_Peripheral with Import, Address => System'To_Address (16#50020800#); end STM32_SVD.DMAMUX; ",12534,True,3759.7770096518198,median "= Salesforce Component :doctitle: Salesforce :shortname: salesforce :artifactid: camel-salesforce :description: Communicate with Salesforce using Java DTOs. :since: 2.12 :supportlevel: Stable :component-header: Both producer and consumer are supported //Manually maintained attributes :camel-spring-boot-name: salesforce *Since Camel {since}* *{component-header}* This component supports producer and consumer endpoints to communicate with Salesforce using Java DTOs. There is a companion <> that generates these DTOs. [NOTE] ==== Developers wishing to contribute to the component are instructed to look at the https://github.com/apache/camel/tree/main/components/camel-salesforce/camel-salesforce-component/README.md[README.md] file on instructions on how to get started and setup your environment for running integration tests. ==== == Getting Started Follow these steps to get started with the Salesforce component. . *Create a salesforce org*. If you don't already have access to a salesforce org, you can create a https://developer.salesforce.com/signup[free developer org]. . *Create a Connected App*. In salesforce, go to Setup > Apps > App Manager, then click on *New Connected App*. Make sure to check *Enable OAuth Settings* and include relevant OAuth Scopes, including the scope called *Perform requests at any time*. Click *Save*. . *Get the Consumer Key and Consumer Secret*. You'll need these to configure salesforce authentication. View your new connected app, then copy the key and secret and save in a safe place. . *Add Maven depdendency*. + [source,xml] ---- org.apache.camel camel-salesforce ---- Spring Boot users should use the starter instead. + [source,xml] ---- org.apache.camel.springboot camel-salesforce-starter ---- . *Generate DTOs*. Optionally, generate Java DTOs to represent your salesforce objects. This step isn't a hard requirement per se, but most use cases will benefit from the type safety and auto-completion. Use the <> to generate DTOs for the salesforce objects you'll be working with. . *Configure authentication*. Using the OAuth key and secret you generated previously, configure salesforce <>. . *Create routes*. Starting creating routes that interact with salesforce! // component-configure options: START // component-configure options: END // component options: START include::partial$component-configure-options.adoc[] include::partial$component-endpoint-options.adoc[] // component options: END // endpoint options: START // endpoint options: END // component headers: START include::partial$component-endpoint-headers.adoc[] // component headers: END == Authenticating to Salesforce [[AuthenticatingToSalesforce]] The component supports three OAuth authentication flows: * https://help.salesforce.com/articleView?id=remoteaccess_oauth_username_password_flow.htm[OAuth 2.0 Username-Password Flow] * https://help.salesforce.com/articleView?id=remoteaccess_oauth_refresh_token_flow.htm[OAuth 2.0 Refresh Token Flow] * https://help.salesforce.com/articleView?id=remoteaccess_oauth_jwt_flow.htm[OAuth 2.0 JWT Bearer Token Flow] For each of the flows, different sets of properties needs to be set: .Properties to set for each authentication flow |=== | Property | Where to find it on Salesforce | Flow | clientId | Connected App, Consumer Key | All flows | clientSecret | Connected App, Consumer Secret | Username-Password, Refresh Token | userName | Salesforce user username | Username-Password, JWT Bearer Token | password | Salesforce user password | Username-Password | refreshToken | From OAuth flow callback | Refresh Token | keystore | Connected App, Digital Certificate | JWT Bearer Token |=== The component auto determines what flow you're trying to configure. In order to be explicit, set the `authenticationType` property. [NOTE] ==== Using Username-Password Flow in production is not encouraged. ==== [NOTE] ==== The certificate used in JWT Bearer Token Flow can be a self-signed certificate. The KeyStore holding the certificate and the private key must contain only single certificate-private key entry. ==== == General Usage === URI format When used as a consumer, receiving streaming events, the URI scheme is: ---- salesforce:topic?options ---- When used as a producer, invoking the Salesforce REST APIs, the URI scheme is: ---- salesforce:operationName?options ---- As a general example on using the operations in this salesforce component, the following producer endpoint uses the upsertSObject API, with the sObjectIdName parameter specifying 'Name' as the external id field. The request message body should be an SObject DTO generated using the maven plugin. [source,java] ---- ...to(""salesforce:upsertSObject?sObjectIdName=Name"")... ---- === Passing in Salesforce headers and fetching Salesforce response headers There is support to pass https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/headers.htm[Salesforce headers] via inbound message headers, header names that start with `Sforce` or `x-sfdc` on the Camel message will be passed on in the request, and response headers that start with `Sforce` will be present in the outbound message headers. For example to fetch API limits you can specify: [source,java] ---- // in your Camel route set the header before Salesforce endpoint //... .setHeader(""Sforce-Limit-Info"", constant(""api-usage"")) .to(""salesforce:getGlobalObjects"") .to(myProcessor); // myProcessor will receive `Sforce-Limit-Info` header on the outbound // message class MyProcessor implements Processor { public void process(Exchange exchange) throws Exception { Message in = exchange.getIn(); String apiLimits = in.getHeader(""Sforce-Limit-Info"", String.class); } } ---- In addition, HTTP response status code and text are available as headers `Exchange.HTTP_RESPONSE_CODE` and `Exchange.HTTP_RESPONSE_TEXT`. === Sending null values to salesforce By default, SObject fields with null values are not sent to salesforce. In order to send null values to salesforce, use the `fieldsToNull` property, as follows: [source,java] ---- accountSObject.getFieldsToNull().add(""Site""); ---- == Supported Salesforce APIs Camel supports the following Salesforce APIs: * <> * <> * <> * <> * <> * <> [[RESTAPI]] === REST API The following operations are supported: * <> - Gets supported Salesforce REST API versions. * <> - Gets available Salesforce REST Resource endpoints. * <> - Lists information about limits in your org. * <> - Gets the most recently accessed items that were viewed or referenced by the current user. * <> - Gets metadata for all available SObject types. * <> - Gets basic metadata for a specific SObject type. * <> - Gets comprehensive metadata for a specific SObject type. * <> - Gets an SObject. * <> - Gets an SObject using an External Id (user defined) field. * <> - Retrieves the specified blob field from an individual record. * <> - Creates an SObject. * <> - Updates an SObject. * <> - Deletes an SObject. * <> - Inserts or updates an SObject using an External Id. * <> - Deletes an SObject using an External Id. * <> - Runs a Salesforce SOQL query. * <> - Retrieves more results (in case of large number of results) using result link returned from the 'query' API. * <> - Runs a SOQL query. Unlike the query operation, queryAll returns records that are deleted because of a merge or delete. queryAll also returns information about archived task and event records. * <> - Runs a Salesforce SOSL query. * <> - Executes a user defined APEX REST API call. * <> - Submits a record or records (batch) for approval process. * <> - Fetches a list of all approval processes. * <> - Executes up to 25 REST API requests in a single call. You can use the output of one request as the input to a subsequent request. * <> - Creates up to 200 records with parent-child relationships (up to 5 levels) in one go. * <> - Executes up to 25 sub-requests in a single request. * <> - Retrieves one or more records of the same object type. * <> - Creates up to 200 records. * <> - Update up to 200 records. * <> - Creates or updates up to 200 records based on an External Id field. * <> - Deletes up to 200 records. Unless otherwise specified, DTO types for the following options are from `org.apache.camel.component.salesforce.api.dto` or one if its sub-packages. [[getVersions]] ==== Versions `getVersions` Lists summary information about each Salesforce version currently available, including the version, label, and a link to each version's root. *Output* Type: `List` [[getResources]] ==== Resources by Version `getResources` Lists available resources for the current API version, including resource name and URI. *Output* Type: `Map` [[limits]] ==== Limits `limits` Lists information about limits in your org. For each limit, this resource returns the maximum allocation and the remaining allocation based on usage. *Output* Type: `Limits` *Additional Usage Information* With `salesforce:limits` operation you can fetch of API limits from Salesforce and then act upon that data received. The result of `salesforce:limits` operation is mapped to `org.apache.camel.component.salesforce.api.dto.Limits` class and can be used in a custom processors or expressions. For instance, consider that you need to limit the API usage of Salesforce so that 10% of daily API requests is left for other routes. The body of output message contains an instance of `org.apache.camel.component.salesforce.api.dto.Limits` object that can be used in conjunction with Content Based Router and Content Based Router and xref:languages:spel-language.adoc[Spring Expression Language (SpEL)] to choose when to perform queries. Notice how multiplying `1.0` with the integer value held in `body.dailyApiRequests.remaining` makes the expression evaluate as with floating point arithmetic, without it - it would end up making integral division which would result with either `0` (some API limits consumed) or `1` (no API limits consumed). [source,java] ---- from(""direct:querySalesforce"") .to(""salesforce:limits"") .choice() .when(spel(""#{1.0 * body.dailyApiRequests.remaining / body.dailyApiRequests.max < 0.1}"")) .to(""salesforce:query?..."") .otherwise() .setBody(constant(""Used up Salesforce API limits, leaving 10% for critical routes"")) .endChoice() ---- [[recent]] ==== Recently Viewed Items `recent` Gets the most recently accessed items that were viewed or referenced by the current user. Salesforce stores information about record views in the interface and uses it to generate a list of recently viewed and referenced records, such as in the sidebar and for the auto-complete options in search. |=== | Parameter | Type | Description | Default | Required | `limit` | `int` | An optional limit that specifies the maximum number of records to be returned. If this parameter is not specified, the default maximum number of records returned is the maximum number of entries in RecentlyViewed, which is 200 records per object. | | |=== *Output* Type: `List` *Additional Usage Information* To fetch the recent items use `salesforce:recent` operation. This operation returns an `java.util.List` of `org.apache.camel.component.salesforce.api.dto.RecentItem` objects (`List`) that in turn contain the `Id`, `Name` and `Attributes` (with `type` and `url` properties). You can limit the number of returned items by specifying `limit` parameter set to maximum number of records to return. For example: [source,java] ---- from(""direct:fetchRecentItems"") to(""salesforce:recent"") .split().body() .log(""${body.name} at ${body.attributes.url}""); ---- [[getGlobalObjects]] ==== Describe Global `getGlobalObjects` Lists the available objects and their metadata for your organization’s data. In addition, it provides the organization encoding, as well as the maximum batch size permitted in queries. *Output* Type: `GlobalObjects` [[getBasicInfo]] ==== sObject Basic Information `getBasicInfo` Describes the individual metadata for the specified object. |=== | Parameter | Type | Description | Default | Required | `sObjectName` | `String` | Name of SObject, e.g. `Account`. Alternatively, can be supplied in Body. | | x |=== *Output* Type: `SObjectBasicInfo` [[getDescription]] ==== sObject Describe `getDescription` Completely describes the individual metadata at all levels for the specified object. For example, this can be used to retrieve the fields, URLs, and child relationships for the Account object. |=== | Parameter | Type | Description | Default | Required | `sObjectName` | `String` | Name of SObject, e.g. `Account`. Alternatively, can be supplied in Body. | | x |=== *Output* Type: `SObjectDescription` [[getSObject]] ==== Retrieve SObject `getSObject` Accesses record based on the specified object ID. This operation requires the `packages` option to be set. |=== | Parameter | Type | Description | Default | Required | `sObjectName` | `String` | Name of SObject, e.g. `Account` | | x | `sObjectId` | `String` | Id of record to retrieve. | | x | `sObjectFields` | `String` | Comma-separated list of fields to retrieve|| | Body | `AbstractSObjectBase` | Instance of SObject that is used to query salesforce. If supplied, overrides `sObjectName` and `sObjectId` parameters. | | |=== *Output* Type: Subclass of `AbstractSObjectBase` [[getSObjectWithId]] ==== Retrieve SObject by External Id `getSObjectWithId` Accesses record based on an External ID value. This operation requires the `packages` option to be set. |=== | Parameter | Type | Description | Default | Required | `sObjectIdName` | `String` | Name of External ID field | | x | `sObjectIdValue` | `String` | External ID value | | x | `sObjectName` | `String` | Name of SObject, e.g. `Account` | | x | Body | `AbstractSObjectBase` | Instance of SObject that is used to query salesforce. If supplied, overrides `sObjectName` and `sObjectIdValue` parameters. | | |=== *Output* Type: Subclass of `AbstractSObjectBase` [[getBlobField]] ==== sObject Blob Retrieve `getBlobField` Retrieves the specified blob field from an individual record. |=== | Parameter | Type | Description | Default | Required | `sObjectBlobFieldName` | `String` | SOSL query | |x | `sObjectName` | `String` | Name of SObject, e.g. Account | | Required if SObject not supplied in body | `sObjectId` | `String` | Id of SObject | | Required if SObject not supplied in body | Body | `AbstractSObjectBase` | SObject to determine type and Id from. If not supplied, `sObjectId` and `sObjectName` parameters will be used. | | Required if `sObjectId` and `sObjectName` are not supplied |=== *Output* Type: `InputStream` [[createSObject]] ==== Create SObject `createSObject` Creates a record in salesforce. |=== | Parameter | Type | Description | Default | Required | Body | `AbstractSObjectBase` or `String` | Instance of SObject to create. | | x | `sObjectName` | `String` | Name of SObject, e.g. `Account`. Only used if Camel cannot determine from Body. | | If Body is a `String` |=== *Output* Type: `CreateSObjectResult` [[updateSObject]] ==== Update SObject `updateSObject` Updates a record in salesforce. |=== | Parameter | Type | Description | Default | Required | Body | `AbstractSObjectBase` or `String` | Instance of SObject to update. | | x | `sObjectName` | `String` | Name of SObject, e.g. `Account`. Only used if Camel cannot determine from Body. | | If Body is a `String` | `sObjectId` | `String` | Id of record to update. Only used if Camel cannot determine from Body. | | If Body is a `String` |=== [[upsertSObject]] ==== Upsert SObject `upsertSObject` Upserts a record by External ID. |=== | Parameter | Type | Description | Default | Required | Body | `AbstractSObjectBase` or `String` | SObject to update. | | x | `sObjectIdName` | `String` | External ID field name. ||x | `sObjectIdValue` | `String` | External ID value || If Body is a `String` | `sObjectName` | `String` | Name of SObject, e.g. `Account`. Only used if Camel cannot determine from Body. | | If Body is a `String` |=== *Output* Type: `UpsertSObjectResult` [[deleteSObject]] ==== Delete SObject `deleteSObject` Deletes a record in salesforce. |=== | Parameter | Type | Description | Default | Required | Body | `AbstractSObjectBase` | Instance of SObject to delete. | | | `sObjectName` | `String` | Name of SObject, e.g. `Account`. Only used if Camel cannot determine from Body. | | If Body is not an `AbstractSObjectBase` instance | `sObjectId` | `String` | Id of record to delete. | | If Body is not an `AbstractSObjectBase` instance |=== [[deleteSObjectWithId]] ==== Delete SObject by External Id `deleteSObjectWithId` Deletes a record in salesforce by External ID. |=== | Parameter | Type | Description | Default | Required | Body | `AbstractSObjectBase` | Instance of SObject to delete. | | | `sObjectIdName` | `String` | Name of External ID field | | If Body is not an `AbstractSObjectBase` instance | `sObjectIdValue` | `String` | External ID value | | If Body is not an `AbstractSObjectBase` instance | `sObjectName` | `String` | Name of SObject, e.g. `Account`. Only used if Camel cannot determine from Body. | | If Body is not an `AbstractSObjectBase` instance |=== [[query]] ==== Query `query` Runs a Salesforce SOQL query |=== | Parameter | Type | Description | Default | Required | Body or `sObjectQuery` | `String` | SOQL query | | x | streamQueryResult | `Boolean` | If true, returns a streaming `Iterator` and transparently retrieves all pages as needed. The `sObjectClass` option must reference an `AbstractQueryRecordsBase` subclass. | false | | `sObjectClass` | `String` | Fully qualified name of class to deserialize response to. Usually a subclass of `AbstractQueryRecordsBase`, e.g. `org.my.dto.QueryRecordsAccount`| |x |=== *Output* Type: Instance of class supplied in `sObjectClass`, or `Iterator` if `streamQueryResult` is true. [[queryMore]] ==== Query More `queryMore` Retrieves more results (in case of large number of results) using result link returned from the `query` and `queryAll` operations. |=== | Parameter | Type | Description | Default | Required | Body or `sObjectQuery` | `String` | `nextRecords` value. Can be found in a prior query result in the `AbstractQueryRecordsBase.nextRecordsUrl` property | | X | `sObjectClass` | `String` | Fully qualified name of class to deserialize response to. Usually a subclass of `AbstractQueryRecordsBase`, e.g. `org.my.dto.QueryRecordsAccount`| |x |=== *Output* Type: Instance of class supplied in `sObjectClass` [[queryAll]] ==== Query All `queryAll` Executes the specified SOQL query. Unlike the `query` operation , `queryAll` returns records that are deleted because of a merge or delete. It also returns information about archived task and event records. |=== | Parameter | Type | Description | Default | Required | Body or `sObjectQuery` | `String` | SOQL query | | x | streamQueryResult | `Boolean` | If true, returns a streaming `Iterable` and transparently retrieves all pages as needed. The `sObjectClass` option must reference an `AbstractQueryRecordsBase` subclass. | false | | `sObjectClass` | `String` | Fully qualified name of class to deserialize response to. Usually a subclass of `AbstractQueryRecordsBase`, e.g. `org.my.dto.QueryRecordsAccount`| |x |=== *Output* Type: Instance of class supplied in `sObjectClass`, or `Iterator` if `streamQueryResult` is true. [[sosl_search]] ==== Search `search` Runs a Salesforce SOSL search |=== | Parameter | Type | Description | Default | Required | Body or `sObjectSearch` | `String` | Name of field to retrieve | |x |=== *Output* Type: `SearchResult2` [[approval]] ==== Submit Approval `approval` Submit a record or records (batch) for approval process. |=== | Parameter | Type | Description | Default | Required | Body | `ApprovalRequest` or `List` | `ApprovalRequest`(s) to process | | | `Approval.` | Prefixed headers or endpoint options in lieu of passing an `ApprovalRequest` in the body. | | | |=== *Output* Type: `ApprovalResult` *Additional usage information* All the properties are named exactly the same as in the Salesforce REST API prefixed with `approval.`. You can set approval properties by setting `approval.PropertyName` of the Endpoint these will be used as template -- meaning that any property not present in either body or header will be taken from the Endpoint configuration. Or you can set the approval template on the Endpoint by assigning `approval` property to a reference onto a bean in the Registry. You can also provide header values using the same `approval.PropertyName` in the incoming message headers. And finally body can contain one `AprovalRequest` or an `Iterable` of `ApprovalRequest` objects to process as a batch. The important thing to remember is the priority of the values specified in these three mechanisms: . value in body takes precedence before any other . value in message header takes precedence before template value . value in template is set if no other value in header or body was given For example to send one record for approval using values in headers use: Given a route: [source,java] ---- from(""direct:example1"")// .setHeader(""approval.ContextId"", simple(""${body['contextId']}"")) .setHeader(""approval.NextApproverIds"", simple(""${body['nextApproverIds']}"")) .to(""salesforce:approval?""// + ""approval.actionType=Submit""// + ""&approval.comments=this is a test""// + ""&approval.processDefinitionNameOrId=Test_Account_Process""// + ""&approval.skipEntryCriteria=true""); ---- You could send a record for approval using: [source,java] ---- final Map body = new HashMap<>(); body.put(""contextId"", accountIds.iterator().next()); body.put(""nextApproverIds"", userId); final ApprovalResult result = template.requestBody(""direct:example1"", body, ApprovalResult.class); ---- [[approvals]] ==== Get Approvals `approvals` Returns a list of all approval processes. *Output* Type: `Approvals` [[composite]] ==== Composite `composite` Executes up to 25 REST API requests in a single call. You can use the output of one request as the input to a subsequent request. The response bodies and HTTP statuses of the requests are returned in a single response body. The entire series of requests counts as a single call toward your API limits. Use Salesforce Composite API to submit multiple chained requests. Individual requests and responses are linked with the provided _reference_. |=== | Parameter | Type | Description | Default | Required | Body | `SObjectComposite` | Contains REST API sub-requests to be executed. | | x | `rawPayload` | `Boolean` | Any (un)marshaling of requests and responses are assumed to be handled by the route | false | x | `compositeMethod` | `String` | HTTP method to use for rawPayload requests. | `POST` | |=== *Output* Type: `SObjectCompositeResponse` [NOTE] ==== Composite API supports only JSON payloads. ==== [NOTE] ==== As with the batch API, the results can vary from API to API so the body of each `SObjectCompositeResult` instance is given as a `java.lang.Object`. In most cases the result will be a `java.util.Map` with string keys and values or other `java.util.Map` as value. Requests are made in JSON format hold some type information (i.e. it is known what values are strings and what values are numbers). ==== Lets look at an example: [source,java] ---- SObjectComposite composite = new SObjectComposite(""38.0"", true); // first insert operation via an external id final Account updateAccount = new TestAccount(); updateAccount.setName(""Salesforce""); updateAccount.setBillingStreet(""Landmark @ 1 Market Street""); updateAccount.setBillingCity(""San Francisco""); updateAccount.setBillingState(""California""); updateAccount.setIndustry(Account_IndustryEnum.TECHNOLOGY); composite.addUpdate(""Account"", ""001xx000003DIpcAAG"", updateAccount, ""UpdatedAccount""); final Contact newContact = new TestContact(); newContact.setLastName(""John Doe""); newContact.setPhone(""1234567890""); composite.addCreate(newContact, ""NewContact""); final AccountContactJunction__c junction = new AccountContactJunction__c(); junction.setAccount__c(""001xx000003DIpcAAG""); junction.setContactId__c(""@{NewContact.id}""); composite.addCreate(junction, ""JunctionRecord""); final SObjectCompositeResponse response = template.requestBody(""salesforce:composite"", composite, SObjectCompositeResponse.class); final List results = response.getCompositeResponse(); final SObjectCompositeResult accountUpdateResult = results.stream().filter(r -> ""UpdatedAccount"".equals(r.getReferenceId())).findFirst().get() final int statusCode = accountUpdateResult.getHttpStatusCode(); // should be 200 final Map accountUpdateBody = accountUpdateResult.getBody(); final SObjectCompositeResult contactCreationResult = results.stream().filter(r -> ""JunctionRecord"".equals(r.getReferenceId())).findFirst().get() ---- *Using the `rawPayload` option* It's possible to directly call Salesforce composite by preparing the Salesforce JSON request in the route thanks to the `rawPayload` option. For instance, you can have the following route: ---- from(""timer:fire?period=2000"").setBody(constant(""{\\n"" + "" \\""allOrNone\\"" : true,\\n"" + "" \\""records\\"" : [ { \\n"" + "" \\""attributes\\"" : {\\""type\\"" : \\""FOO\\""},\\n"" + "" \\""Name\\"" : \\""123456789\\"",\\n"" + "" \\""FOO\\"" : \\""XXXX\\"",\\n"" + "" \\""ACCOUNT\\"" : 2100.0\\n"" + "" \\""ExternalID\\"" : \\""EXTERNAL\\""\\n"" "" }]\\n"" + ""}"") .to(""salesforce:composite?rawPayload=true"") .log(""${body}""); ---- The route directly creates the body as JSON and directly submit to salesforce endpoint using `rawPayload=true` option. With this approach, you have the complete control on the Salesforce request. `POST` is the default HTTP method used to send raw Composite requests to salesforce. Use the `compositeMethod` option to override to the other supported value, `GET`, which returns a list of other available composite resources. [[composite-tree]] ==== Composite Tree `composite-tree` Create up to 200 records with parent-child relationships (up to 5 levels) in one go. |=== | Parameter | Type | Description | Default | Required | Body | `SObjectTree` | Contains REST API sub-requests to be executed. | | x |=== *Output* Type: `SObjectTree` To create up to 200 records including parent-child relationships use `salesforce:composite-tree` operation. This requires an instance of `org.apache.camel.component.salesforce.api.dto.composite.SObjectTree` in the input message and returns the same tree of objects in the output message. The `org.apache.camel.component.salesforce.api.dto.AbstractSObjectBase` instances within the tree get updated with the identifier values (`Id` property) or their corresponding `org.apache.camel.component.salesforce.api.dto.composite.SObjectNode` is populated with `errors` on failure. Note that for some records operation can succeed and for some it can fail -- so you need to manually check for errors. Easiest way to use this functionality is to use the DTOs generated by the `camel-salesforce-maven-plugin`, but you also have the option of customizing the references that identify the each object in the tree, for instance primary keys from your database. Lets look at an example: [source,java] ---- Account account = ... Contact president = ... Contact marketing = ... Account anotherAccount = ... Contact sales = ... Asset someAsset = ... // build the tree SObjectTree request = new SObjectTree(); request.addObject(account).addChildren(president, marketing); request.addObject(anotherAccount).addChild(sales).addChild(someAsset); final SObjectTree response = template.requestBody(""salesforce:composite-tree"", tree, SObjectTree.class); final Map> result = response.allNodes() .collect(Collectors.groupingBy(SObjectNode::hasErrors)); final List withErrors = result.get(true); final List succeeded = result.get(false); final String firstId = succeeded.get(0).getId(); ---- [[composite-batch]] ==== Composite Batch `composite-batch` Submit a composition of requests in batch. Executes up to 25 sub-requests in a single request. |=== | Parameter | Type | Description | Default | Required | Body | `SObjectBatch` | Contains sub-requests to be executed. | | x |=== *Output* Type: `SObjectBatchResponse` The Composite API batch operation allows you to accumulate multiple requests in a batch and then submit them in one go, saving the round trip cost of multiple individual requests. Each response is then received in a list of responses with the order preserved, so that the n-th requests response is in the n-th place of the response. [NOTE] ==== The results can vary from API to API so the result of each sub-request (`SObjectBatchResult.result`) is given as a `java.lang.Object`. In most cases the result will be a `java.util.Map` with string keys and values or other `java.util.Map` as value. Requests are made in JSON format and hold some type information (i.e. it is known what values are strings and what values are numbers). ==== Lets look at an example: [source,java] ---- final String acountId = ... final SObjectBatch batch = new SObjectBatch(""53.0""); final Account updates = new Account(); updates.setName(""NewName""); batch.addUpdate(""Account"", accountId, updates); final Account newAccount = new Account(); newAccount.setName(""Account created from Composite batch API""); batch.addCreate(newAccount); batch.addGet(""Account"", accountId, ""Name"", ""BillingPostalCode""); batch.addDelete(""Account"", accountId); final SObjectBatchResponse response = template.requestBody(""salesforce:composite-batch"", batch, SObjectBatchResponse.class); boolean hasErrors = response.hasErrors(); // if any of the requests has resulted in either 4xx or 5xx HTTP status final List results = response.getResults(); // results of three operations sent in batch final SObjectBatchResult updateResult = results.get(0); // update result final int updateStatus = updateResult.getStatusCode(); // probably 204 final Object updateResultData = updateResult.getResult(); // probably null final SObjectBatchResult createResult = results.get(1); // create result @SuppressWarnings(""unchecked"") final Map createData = (Map) createResult.getResult(); final String newAccountId = createData.get(""id""); // id of the new account, this is for JSON, for XML it would be createData.get(""Result"").get(""id"") final SObjectBatchResult retrieveResult = results.get(2); // retrieve result @SuppressWarnings(""unchecked"") final Map retrieveData = (Map) retrieveResult.getResult(); final String accountName = retrieveData.get(""Name""); // Name of the retrieved account, this is for JSON, for XML it would be createData.get(""Account"").get(""Name"") final String accountBillingPostalCode = retrieveData.get(""BillingPostalCode""); // Name of the retrieved account, this is for JSON, for XML it would be createData.get(""Account"").get(""BillingPostalCode"") final SObjectBatchResult deleteResult = results.get(3); // delete result final int updateStatus = deleteResult.getStatusCode(); // probably 204 final Object updateResultData = deleteResult.getResult(); // probably null ---- [[compositeRetrieveSObjectCollections]] ==== Retrieve Multiple Records with Fewer Round-Trips `compositeRetrieveSObjectCollections` Retrieve one or more records of the same object type. |=== | Parameter | Type | Description | Default | Required | ids | List of String or comma-separated string | A list of one or more IDs of the objects to return. All IDs must belong to the same object type. | | x | fields | List of String or comma-separated string | A list of fields to include in the response. The field names you specify must be valid, and you must have read-level permissions to each field. | | x | sObjectName | String | Type of SObject, e.g. `Account` | | x | sObjectClass | String | Fully-qualified class name of DTO class to use for deserializing the response. | | Required if `sObjectName` parameter does not resolve to a class that exists in the package specified by the `package` option. |=== *Output* Type: `List` of class determined by `sObjectName` or `sObjectClass` header [[compositeCreateSObjectCollections]] ==== Create SObject Collections `compositeCreateSObjectCollections` Add up to 200 records. Mixed SObject types is supported. |=== | Parameter | Type | Description| Default| Required | Body | List of `SObject` | A list of SObjects to create | | x | `allOrNone` | boolean | Indicates whether to roll back the entire request when the creation of any object fails (true) or to continue with the independent creation of other objects in the request. | false | |=== *Output* Type: `List` [[compositeUpdateSObjectCollections]] ==== Update SObject Collections `compositeUpdateSObjectCollections` Update up to 200 records. Mixed SObject types is supported. |=== | Parameter | Type | Description | Default | Required | Body | List of `SObject` | A list of SObjects to update | | x | `allOrNone` | `boolean` | Indicates whether to roll back the entire request when the update of any object fails (true) or to continue with the independent update of other objects in the request. | false | |=== *Output* Type: `List` [[compositeUpsertSObjectCollections]] ==== Upsert SObject Collections `compositeUpsertSObjectCollections` Create or update (upsert) up to 200 records based on an external ID field. Mixed SObject types is not supported. |=== | Parameter | Type | Description | Default | Required | Body | List of `SObject` | A list of SObjects to upsert | | x | `allOrNone` | `boolean` | Indicates whether to roll back the entire request when the upsert of any object fails (true) or to continue with the independent upsert of other objects in the request. | false | | `sObjectName` | `String` | Type of SObject, e.g. `Account` | | x | `sObjectIdName` | `String` | Name of External ID field | | x |=== *Output* Type: `List` [[compositeDeleteSObjectCollections]] ==== Delete SObject Collections `compositeDeleteSObjectCollections` Delete up to 200 records. Mixed SObject types is supported. |=== | Parameter | Type | Description | Default | Required | `sObjectIds` or request body | List of String or comma-separated string | A list of up to 200 IDs of objects to be deleted. | | x | `allOrNone` | boolean | Indicates whether to roll back the entire request when the deletion of any object fails (true) or to continue with the independent deletion of other objects in the request. | false | |=== *Output* Type: `List` [[ApexRESTAPI]] === Apex REST API [[apexCall]] ==== Invoke an Apex REST Web Service method `apexCall` You can https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_rest_intro.htm[expose your Apex class and methods] so that external applications can access your code and your application through the REST architecture. The URI format for invoking Apex REST is: ---- salesforce:apexCall[/yourApexRestUrl][?options] ---- You can supply the apexUrl either in the endpoint (see above), or as the `apexUrl` option as listed in the table below. In either case the Apex URL can contain placeholders in the format of `\\{headerName}`. E.g., for the Apex URL `MyApexClass/\\{id}`, the value of the header named `id` will be used to replace the placeholder. |=== | Parameter | Type | Description| Default| Required | Body | `Map` if `GET`, otherwise `String` or `InputStream`| In the case of a `GET`, the body (`Map` instance) is transformed into query parameters. For other HTTP methods, the body is used for the HTTP body. | | | `apexUrl` | `String` | The portion of the endpoint URL after `https://instance.salesforce.com/services/apexrest/`, e.g., 'MyApexClass/' | | Yes, unless supplied in endpoint | `apexMethod` | `String` | The HTTP method (e.g. `GET`, `POST`) to use. | `GET` | | `rawPayload` | `Boolean` | If true, Camel will not serialize the request or response bodies. | false | | Header: `apexQueryParam.[paramName]` | Object | Headers that override apex parameters passed in the endpoint. | | | `sObjectName` | `String` | Name of sObject (e.g. `Merchandise__c`) used to deserialize the response | | If `rawPayload` is false and `sObjectClass` not supplied | `sObjectClass` | `String` | Fully qualified class name used to deserialize the response | | If `rawPayload` is false and `sObjectName` not supplied |=== *Output* Type: Instance of class supplied in `sObjectClass` input header. [[Bulk2API]] === Bulk 2.0 API The Bulk 2.0 API has a simplified model over the original Bulk API. Use it to quickly load a large amount of data into salesforce, or query a large amount of data out of salesforce. Data must be provided in CSV format, usually via an `InputStream` instance. PK chunking is performed automatically. The minimum API version for Bulk 2.0 is v41.0. The minimum API version for Bulk Queries is v47.0. DTO classes mentioned below are from the `org.apache.camel.component.salesforce.api.dto.bulkv2` package. The following operations are supported: * <> - Creates a bulk ingest job. * <> - Adds a batch of data to an ingest job. * <> - Closes an ingest job. * <> - Aborts an ingest job. * <> - Deletes an ingest job. * <> - Gets successful results for an ingest job. * <> - Gets failed results for an ingest job. * <> - Gets unprocessed records for an ingest job. * <> - Gets an ingest Job. * <> - Gets all ingest jobs. * <> - Creates a query job. * <> - Gets query job results. * <> - Aborts a query job. * <> - Deletes a query job. * <> - Gets a query job. * <> - Gets all query jobs. [[bulk2CreateJob]] ==== Create a Job `bulk2CreateJob` Creates a bulk ingest job. |=== | Parameter | Type | Description| Default| Required | Body | `Job` | Job to create | | x |=== *Output* Type: `Job` [[bulk2CreateBatch]] ==== Upload a Batch of Job Data `bulk2CreateBatch` Adds a batch of data to an ingest job. |=== | Parameter | Type | Description| Default| Required | Body | `InputStream` or `String` | CSV data. The first row must contain headers. | | Required if `jobId` not supplied | `jobId` | `String` | Id of Job to create batch under | | x |=== [[bulk2CloseJob]] ==== Close a Job `bulk2CloseJob` Closes an ingest job. You must close the job in order for it to be processed or aborted/deleted. |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job to close | | x |=== *Output* Type: `Job` [[bulk2AbortJob]] ==== Abort a Job `bulk2AbortJob` Aborts an ingest job. |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job to abort | | x |=== *Output* Type: `Job` [[bulk2DeleteJob]] ==== Delete a Job `bulk2DeleteJob` Deletes an ingest job. |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job to delete | | x |=== [[bulk2GetSuccessfulResults]] ==== Get Job Successful Record Results `bulk2GetSuccessfulResults` Gets successful results for an ingest job. |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job to get results for | | x |=== *Output* Type: `InputStream` + Contents: CSV data [[bulk2GetFailedResults]] ==== Get Job Failed Record Results `bulk2GetFailedResults` Gets failed results for an ingest job. |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job to get results for | | x |=== *Output* Type: `InputStream` + Contents: CSV data [[bulk2GetUnprocessedRecords]] ==== Get Job Unprocessed Record Results `bulk2GetUnprocessedRecords` Gets unprocessed records for an ingest job. |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job to get records for | | x |=== *Output* Type: `InputStream` Contents: CSV data [[bulk2GetJob]] ==== Get Job Info `bulk2GetJob` Gets an ingest Job. |=== | Parameter | Type | Description| Default| Required | Body | `Job` | Will use Id of supplied Job to retrieve Job | | Required if `jobId` not supplied | `jobId` | `String` | Id of Job to retrieve | | Required if `Job` not supplied in body |=== *Output* Type: `Job` [[bulk2GetAllJobs]] ==== Get All Jobs `bulk2GetAllJobs` Gets all ingest jobs. |=== | Parameter | Type | Description| Default| Required | `queryLocator` | `String` | Used in subsequent calls if results span multiple pages | | |=== *Output* Type: `Jobs` If the `done` property of the `Jobs` instance is false, there are additional pages to fetch, and the `nextRecordsUrl` property contains the value to be set in the `queryLocator` parameter on subsequent calls. [[bulk2CreateQueryJob]] ==== Create a Query Job `bulk2CreateQueryJob` Gets a query job. |=== | Parameter | Type | Description| Default| Required | Body | `QueryJob` | QueryJob to create | | x |=== *Output* Type: `QueryJob` [[bulk2GetQueryJobResults]] ==== Get Results for a Query Job `bulk2GetQueryJobResults` Get bulk query job results. `jobId` parameter is required. Accepts `maxRecords` and `locator` parameters. |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job to get results for | | x | `maxRecords` | `Integer` | Id of Job to get results for | | | `locator` | `locator` | Value to use for subsequent calls | | |=== *Output* Type: `InputStream` Contents: CSV data Response message headers include `Sforce-NumberOfRecords` and `Sforce-Locator` headers. The value of `Sforce-Locator` can be passed into subsequent calls via the `locator` parameter. [[bulk2AbortQueryJob]] ==== Abort a Query Job `bulk2AbortQueryJob` Aborts a query job. |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job to abort | | x |=== *Output* Type: `QueryJob` [[bulk2DeleteQueryJob]] ==== Delete a Query Job `bulk2DeleteQueryJob` Deletes a query job. |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job to delete | | x |=== [[bulk2GetQueryJob]] ==== Get Information About a Query Job `bulk2GetQueryJob` Gets a query job. |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job to retrieve | | x |=== *Output* Type: `QueryJob` [[bulk2GetAllQueryJobs]] ==== Get Information About All Query Jobs `bulk2GetAllQueryJobs` Gets all query jobs. |=== | Parameter | Type | Description| Default| Required | `queryLocator` | `String` | Used in subsequent calls if results span multiple pages | | |=== *Output* Type: `QueryJobs` If the `done` property of the `QueryJobs` instance is false, there are additional pages to fetch, and the `nextRecordsUrl` property contains the value to be set in the `queryLocator` parameter on subsequent calls. [[BulkAPI]] === Bulk (original) API Producer endpoints can use the following APIs. All Job data formats, i.e. xml, csv, zip/xml, and zip/csv are supported. + The request and response have to be marshalled/unmarshalled by the route. Usually the request will be some stream source like a CSV file, and the response may also be saved to a file to be correlated with the request. The following operations are supported: * <> - Creates a Salesforce Bulk Job. * <> - Gets a Job using its Salesforce Id * <> - Closes a Job * <> - Aborts a Job * <> - Submits a Batch within a Bulk Job * <> - Gets a Batch using Id * <> - Gets all Batches for a Bulk Job Id * <> - Gets Request data (XML/CSV) for a Batch * <> - Gets the results of the Batch when its complete * <> - Creates a Batch from an SOQL query * <> - Gets a list of Result Ids for a Batch Query * <> - Gets results for a Result Id [[createJob]] ==== Create a Job `createJob` Creates a Salesforce Bulk Job. PK Chunking is supported via the pkChunking* options. See an explanation https://developer.salesforce.com/docs/atlas.en-us.api_asynch.meta/api_asynch/async_api_headers_enable_pk_chunking.htm[here]. |=== | Parameter | Type | Description| Default| Required | Body | `JobInfo` | Job to create | | x | `pkChunking` | `Boolean` | Whether to use PK Chunking | false | | `pkChunkingChunkSize` | `Integer` | | | | `pkChunkingStartRow` | `Integer` | | | | `pkChunkingParent` | `String` | | | |=== *Output* Type: `JobInfo` [[getJob]] ==== Get Job Details `getJob` Gets a Job |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job to get | | Required if body not supplied | Body | `JobInfo` | `JobInfo` instance from which Id will be used | | Required if `jobId` not supplied |=== *Output* Type: `JobInfo` [[closeJob]] ==== Close a Job `closeJob` Closes a Job |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job | | Required if body not supplied | Body | `JobInfo` | `JobInfo` instance from which Id will be used | | Required if `jobId` not supplied |=== *Output* Type: `JobInfo` [[abortJob]] ==== Abort a Job `abortJob` Aborts a Job |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job | | Required if body not supplied | Body | `JobInfo` | `JobInfo` instance from which Id will be used | | Required if `jobId` not supplied |=== *Output* Type: `JobInfo` [[createBatch]] ==== Add a Batch to a Job `createBatch` Submits a Batch within a Bulk Job |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job | | x | `contentType` | `String` | Content type of body. Can be XML, CSV, ZIP_XML or ZIP_CSV | | x | `Body` | `InputStream` or `String` | Batch data | | x |=== *Output* Type: `BatchInfo` [[getBatch]] ==== Get Information for a Batch `getBatch` Get a Batch |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job | | Required if body not supplied | `batchId` | `String` | Id of Batch | | Required if body not supplied | Body | `BatchInfo` | `JobInfo` instance from which `jobId` and `batchId` will be used | | Required if `jobId` and `BatchId` not supplied |=== *Output* Type: `BatchInfo` [[getAllBatches]] ==== Get Information for All Batches in a Job `getAllBatches` Gets all Batches for a Bulk Job Id |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job | | Required if body not supplied | Body | `JobInfo` | `JobInfo` instance from which Id will be used | | Required if `jobId` not supplied |=== *Output* Type: `List` [[getRequest]] ==== Get a Batch Request `getRequest` Gets Request data (XML/CSV) for a Batch |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job | | Required if body not supplied | `batchId` | `String` | Id of Batch | | Required if body not supplied | Body | `BatchInfo` | `JobInfo` instance from which `jobId` and `batchId` will be used | | Required if `jobId` and `BatchId` not supplied |=== *Output* Type: `InputStream` [[getResults]] ==== Get Batch Results `getResults` Gets the results of the Batch when it's complete |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job | | Required if body not supplied | `batchId` | `String` | Id of Batch | | Required if body not supplied | Body | `BatchInfo` | `JobInfo` instance from which `jobId` and `batchId` will be used | | Required if `jobId` and `BatchId` not supplied |=== *Output* Type: `InputStream` [[createBatchQuery]] ==== Create Bulk Query Batch `createBatchQuery` Creates a Batch from an SOQL query |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job | | Required if body not supplied | `contentType` | `String` | Content type of body. Can be XML, CSV, ZIP_XML or ZIP_CSV | | Required if `JobInfo` instance not supplied in body | `sObjectQuery` | `String` | SOQL query to be used for this batch | | Required if not supplied in body | Body | `JobInfo` or `String` | Either `JobInfo` instance from which `jobId` and `contentType` will be used, or `String` to be used as the Batch query | | Required `JobInfo` if `jobId` and `contentType` not supplied. |=== *Output* Type: `BatchInfo` [[getQueryResultIds]] ==== Get Batch Results `getQueryResultIds` Gets a list of Result Ids for a Batch Query |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job | | Required if body not supplied | `batchId` | `String` | Id of Batch | | Required if body not supplied | Body | `BatchInfo` | `JobInfo` instance from which `jobId` and `batchId` will be used | | Required if `jobId` and `BatchId` not supplied |=== *Output* Type: `List` [[getQueryResult]] ==== Get Bulk Query Results `getQueryResult` Gets results for a Result Id |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job | | Required if body not supplied | `batchId` | `String` | Id of Batch | | Required if body not supplied | `resultId` | `String` | Id of Result | | If not passed in body | Body | `BatchInfo` or `String` | `JobInfo` instance from which `jobId` and `batchId` will be used. Otherwise can be a `String` containing the `resultId` | | `BatchInfo` Required if `jobId` and `BatchId` not supplied |=== *Output* Type: `InputStream` For example, the following producer endpoint uses the createBatch API to create a Job Batch. The in message must contain a body that can be converted into an `InputStream` (usually UTF-8 CSV or XML content from a file, etc.) and header fields 'jobId' for the Job and 'contentType' for the Job content type, which can be XML, CSV, ZIP_XML or ZIP_CSV. The put message body will contain `BatchInfo` on success, or throw a `SalesforceException` on error. [source,java] ---- ...to(""salesforce:createBatch"").. ---- [[StreamingAPI]] === Streaming API The Streaming API enables streaming of events using push technology and provides a subscription mechanism for receiving events in near real time. The Streaming API subscription mechanism supports multiple types of events, including PushTopic events, generic events, platform events, and Change Data Capture events. ==== Push Topics The URI format for consuming Push Topics is: ---- salesforce:[?options] ---- To create and subscribe to a topic [source,java] ---- from(""salesforce:CamelTestTopic?notifyForFields=ALL¬ifyForOperations=ALL&sObjectName=Merchandise__c&updateTopic=true&sObjectQuery=SELECT Id, Name FROM Merchandise__c"")... ---- To subscribe to an existing topic [source,java] ---- from(""salesforce:CamelTestTopic&sObjectName=Merchandise__c"")... ---- |=== | Parameter | Type | Description| Default| Required | `sObjectName` | `String` | SObject to monitor | | x | `sObjectQuery` | `String` | SOQL query used to create Push Topic | | Required for creating new topics | `updateTopic` | `Boolean` | Whether to update an existing Push Topic if exists | false | | `notifyForFields` | `NotifyForFieldsEnum` | Specifies how the record is evaluated against the PushTopic query. | Referenced | | `notifyForOperationCreate` | `Boolean` | Whether a create operation should generate a notification. | false | | `notifyForOperationDelete` | `Boolean` | Whether a delete operation should generate a notification. | false | | `notifyForOperationUndelete` | `Boolean` | Whether an undelete operation should generate a notification. | false | | `notifyForOperationUpdate` | `Boolean` | Whether an update operation should generate a notification. | false | | `notifyForOperations` | `NotifyForOperationsEnum` | Whether an update operation should generate a notification. Only for use in API version < 29.0 | All | | `replayId` | `int` | The replayId value to use when subscribing.| | | `defaultReplayId` | `int` | Default replayId setting if no value is found in initialReplayIdMap. | -1 | | `fallBackReplayId` | `int` | ReplayId to fall back to after an Invalid Replay Id response. | -1 | |=== *Output* Type: Class passed via `sObjectName` parameter ==== Platform Events To emit a platform event use the <> operation, passing an instance of a platform event, e.g. `Order_Event__e`. The URI format for consuming platform events is: ---- salesforce:event/ ---- For example, to receive platform events use for the event type `Order_Event__e`: [source,java] ---- from(""salesforce:event/Order_Event__e"") ---- |=== | Parameter | Type | Description| Default| Required | `rawPayload` | `Boolean` | If false, operation returns a `PlatformEvent`, otherwise returns the raw Bayeux Message | false | | `replayId` | `int` | The replayId value to use when subscribing.| | | `defaultReplayId` | `int` | Default replayId setting if no value is found in initialReplayIdMap. | -1 | | `fallBackReplayId` | `int` | ReplayId to fall back to after an Invalid Replay Id response. | -1 | |=== *Output* Type: `PlatformEvent` or `org.cometd.bayeux.Message` ==== Change Data Capture Events Change Data Capture (CDC) allows you to receive near-real-time changes of Salesforce records, and synchronize corresponding records in an external data store. Change Data Capture publishes change events, which represent changes to Salesforce records. Changes include creation of a new record, updates to an existing record, deletion of a record, and undeletion of a record. The URI format to consume CDC events is as follows: All Selected Entities ---- salesforce:data/ChangeEvents ---- Standard Objects ---- salesforce:data/ChangeEvent ---- Custom Objects ---- salesforce:data/__ChangeEvent ---- Here are a few examples [source,java] ---- from(""salesforce:data/ChangeEvents?replayId=-1"").log(""being notified of all change events"") from(""salesforce:data/AccountChangeEvent?replayId=-1"").log(""being notified of change events for Account records"") from(""salesforce:data/Employee__ChangeEvent?replayId=-1"").log(""being notified of change events for Employee__c custom object"") ---- More details about how to use the Camel Salesforce component change data capture capabilities could be found in the https://github.com/apache/camel/tree/main/components/camel-salesforce/camel-salesforce-component/src/test/java/org/apache/camel/component/salesforce/ChangeEventsConsumerIntegrationTest.java[ChangeEventsConsumerIntegrationTest]. The https://developer.salesforce.com/docs/atlas.en-us.change_data_capture.meta/change_data_capture/cdc_intro.htm[Salesforce developer guide] is a good fit to better know the subtleties of implementing a change data capture integration application. The dynamic nature of change event body fields, high level replication steps as well as security considerations could be of interest. |=== | Parameter | Type | Description| Default| Required | `rawPayload` | `Boolean` | If false, operation returns a `Map`, otherwise returns the raw Bayeux `Message` | false | | `replayId` | `int` | The replayId value to use when subscribing.| | | `defaultReplayId` | `int` | Default replayId setting if no value is found in initialReplayIdMap. | -1 | | `fallBackReplayId` | `int` | ReplayId to fall back to after an Invalid Replay Id response. | -1 | |=== *Output* Type: `Map` or `org.cometd.bayeux.Message` Headers |=== | Name | Description | `CamelSalesforceChangeType` | `CREATE`, `UPDATE`, `DELETE` or `UNDELETE` |=== [[ReportsAPI]] === Reports API * <> - Gets up to 200 of the reports you most recently viewed. * <> - Retrieves report description. * <> - Runs a report synchronously. * <> - Runs a report asynchronously. * <> - Returns a list of instances for a report that you requested to be run asynchronously. * <> - Retrieves results for an instance of a report run asynchronously. [[getRecentReports]] ==== Report List `getRecentReports` Gets up to 200 of the reports you most recently viewed. *Output* Type: `List` [[getReportDescription]] ==== Describe Report `getReportDescription` Retrieves the report, report type, and related metadata for a report, either in a tabular or summary or matrix format. |=== | Parameter | Type | Description| Default| Required | `reportId` | `String` | Id of Report | | Required if not supplied in body | Body | `String` | Id of Report | | Required if not supplied in `reportId` parameter |=== *Output* Type: `ReportDescription` [[executeSyncReport]] ==== Execute Sync `executeSyncReport` Runs a report synchronously with or without changing filters and returns the latest summary data. |=== | Parameter | Type | Description| Default| Required | `reportId` | `String` | Id of Report | | Required if not supplied in body | `includeDetails` | `Boolean` | Whether to include details | false| | `reportMetadata` | `ReportMetadata` | Optionally, pass ReportMetadata here instead of body | | | Body | `ReportMetadata` | If supplied, will use instead of `reportId` | | Required if not supplied in `reportId` parameter |=== *Output* Type: `AbstractReportResultsBase` [[executeAsyncReport]] ==== Execute Async `executeAsyncReport` Runs an instance of a report asynchronously with or without filters and returns the summary data with or without details. |=== | Parameter | Type | Description| Default| Required | `reportId` | `String` | Id of Report | | Required if not supplied in body | `includeDetails` | `Boolean` | Whether to include details | false| | `reportMetadata` | `ReportMetadata` | Optionally, pass ReportMetadata here instead of body | | | Body | `ReportMetadata` | If supplied, will use instead of `reportId` parameter | | Required if not supplied in `reportId` parameter |=== *Output* Type: `ReportInstance` [[getReportInstances]] ==== Instances List `getReportInstances` Returns a list of instances for a report that you requested to be run asynchronously. Each item in the list is treated as a separate instance of the report. |=== | Parameter | Type | Description| Default| Required | `reportId` | `String` | Id of Report | | Required if not supplied in body | Body | `String` | If supplied, will use instead of `reportId` parameter | | Required if not supplied in `reportId` parameter |=== *Output* Type: `List` [[getReportResults]] ==== Instance Results `getReportResults` Contains the results of running a report. |=== | Parameter | Type | Description| Default| Required | `reportId` | `String` | Id of Report | | Required if not supplied in body | `instanceId` | `String` | Id of Report instance | | x | Body | `String` | If supplied, will use instead of `reportId` parameter | | Required if not supplied in `reportId` parameter |=== *Output* Type: `AbstractReportResultsBase` == Miscellaneous Operations * <> - Send requests to salesforce and have full, raw control over endpoint, parameters, body, etc. [[raw]] === Raw `raw` Sends HTTP requests to salesforce with full, raw control of all aspects of the call. Any serialization or deserialization of request and response bodies must be performed in the route. The `Content-Type` HTTP header will be automatically set based on the `format` option, but this can be overridden with the `rawHttpHeaders` option. |=== | Parameter | Type | Description| Default| Required | Body | `String` or `InputStream` | Body of the HTTP request | | | `rawPath` | `String` | The portion of the endpoint URL after the domain name, e.g., '/services/data/v51.0/sobjects/Account/' | | x | `rawMethod` | `String` | The HTTP method | | x | `rawQueryParameters` | `String` | Comma separated list of message headers to include as query parameters. Do not url-encode values as this will be done automatically. | | | `rawHttpHeaders` | `String` | Comma separated list of message headers to include as HTTP headers | | |=== *Output* Type: `InputStream` ==== Query example In this example we'll send a query to the REST API. The query must be passed in a URL parameter called ""q"", so we'll create a message header called q and tell the raw operation to include that message header as a URL parameter: ---- from(""direct:queryExample"") .setHeader(""q"", ""SELECT Id, LastName FROM Contact"") .to(""salesforce:raw?format=JSON&rawMethod=GET&rawQueryParameters=q&rawPath=/services/data/v51.0/query"") // deserialize JSON results or handle in some other way ---- ==== SObject example In this example, we'll pass a Contact the REST API in a `create` operation. Since the `raw` operation does not perform any serialization, we make sure to pass XML in the message body ---- from(""direct:createAContact"") .setBody(constant(""TestLast"")) .to(""salesforce:raw?format=XML&rawMethod=POST&rawPath=/services/data/v51.0/sobjects/Contact"") ---- The response is: ---- 0034x00000RnV6zAAF true ---- == Uploading a document to a ContentWorkspace Create the ContentVersion in Java, using a Processor instance: [source,java] ---- public class ContentProcessor implements Processor { public void process(Exchange exchange) throws Exception { Message message = exchange.getIn(); ContentVersion cv = new ContentVersion(); ContentWorkspace cw = getWorkspace(exchange); cv.setFirstPublishLocationId(cw.getId()); cv.setTitle(""test document""); cv.setPathOnClient(""test_doc.html""); byte[] document = message.getBody(byte[].class); ObjectMapper mapper = new ObjectMapper(); String enc = mapper.convertValue(document, String.class); cv.setVersionDataUrl(enc); message.setBody(cv); } protected ContentWorkspace getWorkSpace(Exchange exchange) { // Look up the content workspace somehow, maybe use enrich() to add it to a // header that can be extracted here .... } } ---- Give the output from the processor to the Salesforce component: [source,java] ---- from(""file:///home/camel/library"") .to(new ContentProcessor()) // convert bytes from the file into a ContentVersion SObject // for the salesforce component .to(""salesforce:createSObject""); ---- == Generating SOQL query strings `org.apache.camel.component.salesforce.api.utils.QueryHelper` contains helper methods to generate SOQL queries. For instance to fetch all custom fields from _Account_ SObject you can simply generate the SOQL SELECT by invoking: [source,java] ---- String allCustomFieldsQuery = QueryHelper.queryToFetchFilteredFieldsOf(new Account(), SObjectField::isCustom); ---- [[MavenPlugin]] == Camel Salesforce Maven Plugin The Maven plugin generates Java DTOs to represent salesforce objects. Please refer to https://github.com/apache/camel/tree/main/components/camel-salesforce/camel-salesforce-maven-plugin[README.md] for details on how to use the plugin. include::spring-boot:partial$starter.adoc[] ",16158,True,3095.1931831802463,median "pragma Style_Checks (Off); -- This spec has been automatically generated from STM32F3x4.svd pragma Restrictions (No_Elaboration_Code); with HAL; with System; package STM32_SVD.ADC is pragma Preelaborate; --------------- -- Registers -- --------------- -- ISR_AWD array type ISR_AWD_Field_Array is array (1 .. 3) of Boolean with Component_Size => 1, Size => 3; -- Type definition for ISR_AWD type ISR_AWD_Field (As_Array : Boolean := False) is record case As_Array is when False => -- AWD as a value Val : HAL.UInt3; when True => -- AWD as an array Arr : ISR_AWD_Field_Array; end case; end record with Unchecked_Union, Size => 3; for ISR_AWD_Field use record Val at 0 range 0 .. 2; Arr at 0 range 0 .. 2; end record; -- interrupt and status register type ISR_Register is record -- ADRDY ADRDY : Boolean := False; -- EOSMP EOSMP : Boolean := False; -- EOC EOC : Boolean := False; -- EOS EOS : Boolean := False; -- OVR OVR : Boolean := False; -- JEOC JEOC : Boolean := False; -- JEOS JEOS : Boolean := False; -- AWD1 AWD : ISR_AWD_Field := (As_Array => False, Val => 16#0#); -- JQOVF JQOVF : Boolean := False; -- unspecified Reserved_11_31 : HAL.UInt21 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for ISR_Register use record ADRDY at 0 range 0 .. 0; EOSMP at 0 range 1 .. 1; EOC at 0 range 2 .. 2; EOS at 0 range 3 .. 3; OVR at 0 range 4 .. 4; JEOC at 0 range 5 .. 5; JEOS at 0 range 6 .. 6; AWD at 0 range 7 .. 9; JQOVF at 0 range 10 .. 10; Reserved_11_31 at 0 range 11 .. 31; end record; -- interrupt enable register type IER_Register is record -- ADRDYIE ADRDYIE : Boolean := False; -- EOSMPIE EOSMPIE : Boolean := False; -- EOCIE EOCIE : Boolean := False; -- EOSIE EOSIE : Boolean := False; -- OVRIE OVRIE : Boolean := False; -- JEOCIE JEOCIE : Boolean := False; -- JEOSIE JEOSIE : Boolean := False; -- AWD1IE AWD1IE : Boolean := False; -- AWD2IE AWD2IE : Boolean := False; -- AWD3IE AWD3IE : Boolean := False; -- JQOVFIE JQOVFIE : Boolean := False; -- unspecified Reserved_11_31 : HAL.UInt21 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for IER_Register use record ADRDYIE at 0 range 0 .. 0; EOSMPIE at 0 range 1 .. 1; EOCIE at 0 range 2 .. 2; EOSIE at 0 range 3 .. 3; OVRIE at 0 range 4 .. 4; JEOCIE at 0 range 5 .. 5; JEOSIE at 0 range 6 .. 6; AWD1IE at 0 range 7 .. 7; AWD2IE at 0 range 8 .. 8; AWD3IE at 0 range 9 .. 9; JQOVFIE at 0 range 10 .. 10; Reserved_11_31 at 0 range 11 .. 31; end record; -- control register type CR_Register is record -- ADEN ADEN : Boolean := False; -- ADDIS ADDIS : Boolean := False; -- ADSTART ADSTART : Boolean := False; -- JADSTART JADSTART : Boolean := False; -- ADSTP ADSTP : Boolean := False; -- JADSTP JADSTP : Boolean := False; -- unspecified Reserved_6_27 : HAL.UInt22 := 16#0#; -- ADVREGEN ADVREGEN : Boolean := False; -- DEEPPWD DEEPPWD : Boolean := False; -- ADCALDIF ADCALDIF : Boolean := False; -- ADCAL ADCAL : Boolean := False; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CR_Register use record ADEN at 0 range 0 .. 0; ADDIS at 0 range 1 .. 1; ADSTART at 0 range 2 .. 2; JADSTART at 0 range 3 .. 3; ADSTP at 0 range 4 .. 4; JADSTP at 0 range 5 .. 5; Reserved_6_27 at 0 range 6 .. 27; ADVREGEN at 0 range 28 .. 28; DEEPPWD at 0 range 29 .. 29; ADCALDIF at 0 range 30 .. 30; ADCAL at 0 range 31 .. 31; end record; subtype CFGR_RES_Field is HAL.UInt2; subtype CFGR_EXTSEL_Field is HAL.UInt4; subtype CFGR_EXTEN_Field is HAL.UInt2; subtype CFGR_DISCNUM_Field is HAL.UInt3; subtype CFGR_AWD1CH_Field is HAL.UInt5; -- configuration register type CFGR_Register is record -- DMAEN DMAEN : Boolean := False; -- DMACFG DMACFG : Boolean := False; -- unspecified Reserved_2_2 : HAL.Bit := 16#0#; -- RES RES : CFGR_RES_Field := 16#0#; -- ALIGN ALIGN : Boolean := False; -- EXTSEL EXTSEL : CFGR_EXTSEL_Field := 16#0#; -- EXTEN EXTEN : CFGR_EXTEN_Field := 16#0#; -- OVRMOD OVRMOD : Boolean := False; -- CONT CONT : Boolean := False; -- AUTDLY AUTDLY : Boolean := False; -- AUTOFF AUTOFF : Boolean := False; -- DISCEN DISCEN : Boolean := False; -- DISCNUM DISCNUM : CFGR_DISCNUM_Field := 16#0#; -- JDISCEN JDISCEN : Boolean := False; -- JQM JQM : Boolean := False; -- AWD1SGL AWD1SGL : Boolean := False; -- AWD1EN AWD1EN : Boolean := False; -- JAWD1EN JAWD1EN : Boolean := False; -- JAUTO JAUTO : Boolean := False; -- AWD1CH AWD1CH : CFGR_AWD1CH_Field := 16#0#; -- unspecified Reserved_31_31 : HAL.Bit := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CFGR_Register use record DMAEN at 0 range 0 .. 0; DMACFG at 0 range 1 .. 1; Reserved_2_2 at 0 range 2 .. 2; RES at 0 range 3 .. 4; ALIGN at 0 range 5 .. 5; EXTSEL at 0 range 6 .. 9; EXTEN at 0 range 10 .. 11; OVRMOD at 0 range 12 .. 12; CONT at 0 range 13 .. 13; AUTDLY at 0 range 14 .. 14; AUTOFF at 0 range 15 .. 15; DISCEN at 0 range 16 .. 16; DISCNUM at 0 range 17 .. 19; JDISCEN at 0 range 20 .. 20; JQM at 0 range 21 .. 21; AWD1SGL at 0 range 22 .. 22; AWD1EN at 0 range 23 .. 23; JAWD1EN at 0 range 24 .. 24; JAUTO at 0 range 25 .. 25; AWD1CH at 0 range 26 .. 30; Reserved_31_31 at 0 range 31 .. 31; end record; -- SMPR1_SMP array element subtype SMPR1_SMP_Element is HAL.UInt3; -- SMPR1_SMP array type SMPR1_SMP_Field_Array is array (1 .. 9) of SMPR1_SMP_Element with Component_Size => 3, Size => 27; -- Type definition for SMPR1_SMP type SMPR1_SMP_Field (As_Array : Boolean := False) is record case As_Array is when False => -- SMP as a value Val : HAL.UInt27; when True => -- SMP as an array Arr : SMPR1_SMP_Field_Array; end case; end record with Unchecked_Union, Size => 27; for SMPR1_SMP_Field use record Val at 0 range 0 .. 26; Arr at 0 range 0 .. 26; end record; -- sample time register 1 type SMPR1_Register is record -- unspecified Reserved_0_2 : HAL.UInt3 := 16#0#; -- SMP1 SMP : SMPR1_SMP_Field := (As_Array => False, Val => 16#0#); -- unspecified Reserved_30_31 : HAL.UInt2 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for SMPR1_Register use record Reserved_0_2 at 0 range 0 .. 2; SMP at 0 range 3 .. 29; Reserved_30_31 at 0 range 30 .. 31; end record; -- SMPR2_SMP array element subtype SMPR2_SMP_Element is HAL.UInt3; -- SMPR2_SMP array type SMPR2_SMP_Field_Array is array (10 .. 18) of SMPR2_SMP_Element with Component_Size => 3, Size => 27; -- Type definition for SMPR2_SMP type SMPR2_SMP_Field (As_Array : Boolean := False) is record case As_Array is when False => -- SMP as a value Val : HAL.UInt27; when True => -- SMP as an array Arr : SMPR2_SMP_Field_Array; end case; end record with Unchecked_Union, Size => 27; for SMPR2_SMP_Field use record Val at 0 range 0 .. 26; Arr at 0 range 0 .. 26; end record; -- sample time register 2 type SMPR2_Register is record -- SMP10 SMP : SMPR2_SMP_Field := (As_Array => False, Val => 16#0#); -- unspecified Reserved_27_31 : HAL.UInt5 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for SMPR2_Register use record SMP at 0 range 0 .. 26; Reserved_27_31 at 0 range 27 .. 31; end record; subtype TR1_LT1_Field is HAL.UInt12; subtype TR1_HT1_Field is HAL.UInt12; -- watchdog threshold register 1 type TR1_Register is record -- LT1 LT1 : TR1_LT1_Field := 16#0#; -- unspecified Reserved_12_15 : HAL.UInt4 := 16#0#; -- HT1 HT1 : TR1_HT1_Field := 16#FFF#; -- unspecified Reserved_28_31 : HAL.UInt4 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for TR1_Register use record LT1 at 0 range 0 .. 11; Reserved_12_15 at 0 range 12 .. 15; HT1 at 0 range 16 .. 27; Reserved_28_31 at 0 range 28 .. 31; end record; subtype TR2_LT2_Field is HAL.UInt8; subtype TR2_HT2_Field is HAL.UInt8; -- watchdog threshold register type TR2_Register is record -- LT2 LT2 : TR2_LT2_Field := 16#0#; -- unspecified Reserved_8_15 : HAL.UInt8 := 16#0#; -- HT2 HT2 : TR2_HT2_Field := 16#FF#; -- unspecified Reserved_24_31 : HAL.UInt8 := 16#F#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for TR2_Register use record LT2 at 0 range 0 .. 7; Reserved_8_15 at 0 range 8 .. 15; HT2 at 0 range 16 .. 23; Reserved_24_31 at 0 range 24 .. 31; end record; subtype TR3_LT3_Field is HAL.UInt8; subtype TR3_HT3_Field is HAL.UInt8; -- watchdog threshold register 3 type TR3_Register is record -- LT3 LT3 : TR3_LT3_Field := 16#0#; -- unspecified Reserved_8_15 : HAL.UInt8 := 16#0#; -- HT3 HT3 : TR3_HT3_Field := 16#FF#; -- unspecified Reserved_24_31 : HAL.UInt8 := 16#F#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for TR3_Register use record LT3 at 0 range 0 .. 7; Reserved_8_15 at 0 range 8 .. 15; HT3 at 0 range 16 .. 23; Reserved_24_31 at 0 range 24 .. 31; end record; subtype SQR1_L_Field is HAL.UInt4; subtype SQR1_SQ1_Field is HAL.UInt5; subtype SQR1_SQ2_Field is HAL.UInt5; subtype SQR1_SQ3_Field is HAL.UInt5; subtype SQR1_SQ4_Field is HAL.UInt5; -- regular sequence register 1 type SQR1_Register is record -- L L : SQR1_L_Field := 16#0#; -- unspecified Reserved_4_5 : HAL.UInt2 := 16#0#; -- SQ1 SQ1 : SQR1_SQ1_Field := 16#0#; -- unspecified Reserved_11_11 : HAL.Bit := 16#0#; -- SQ2 SQ2 : SQR1_SQ2_Field := 16#0#; -- unspecified Reserved_17_17 : HAL.Bit := 16#0#; -- SQ3 SQ3 : SQR1_SQ3_Field := 16#0#; -- unspecified Reserved_23_23 : HAL.Bit := 16#0#; -- SQ4 SQ4 : SQR1_SQ4_Field := 16#0#; -- unspecified Reserved_29_31 : HAL.UInt3 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for SQR1_Register use record L at 0 range 0 .. 3; Reserved_4_5 at 0 range 4 .. 5; SQ1 at 0 range 6 .. 10; Reserved_11_11 at 0 range 11 .. 11; SQ2 at 0 range 12 .. 16; Reserved_17_17 at 0 range 17 .. 17; SQ3 at 0 range 18 .. 22; Reserved_23_23 at 0 range 23 .. 23; SQ4 at 0 range 24 .. 28; Reserved_29_31 at 0 range 29 .. 31; end record; subtype SQR2_SQ5_Field is HAL.UInt5; subtype SQR2_SQ6_Field is HAL.UInt5; subtype SQR2_SQ7_Field is HAL.UInt5; subtype SQR2_SQ8_Field is HAL.UInt5; subtype SQR2_SQ9_Field is HAL.UInt5; -- regular sequence register 2 type SQR2_Register is record -- SQ5 SQ5 : SQR2_SQ5_Field := 16#0#; -- unspecified Reserved_5_5 : HAL.Bit := 16#0#; -- SQ6 SQ6 : SQR2_SQ6_Field := 16#0#; -- unspecified Reserved_11_11 : HAL.Bit := 16#0#; -- SQ7 SQ7 : SQR2_SQ7_Field := 16#0#; -- unspecified Reserved_17_17 : HAL.Bit := 16#0#; -- SQ8 SQ8 : SQR2_SQ8_Field := 16#0#; -- unspecified Reserved_23_23 : HAL.Bit := 16#0#; -- SQ9 SQ9 : SQR2_SQ9_Field := 16#0#; -- unspecified Reserved_29_31 : HAL.UInt3 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for SQR2_Register use record SQ5 at 0 range 0 .. 4; Reserved_5_5 at 0 range 5 .. 5; SQ6 at 0 range 6 .. 10; Reserved_11_11 at 0 range 11 .. 11; SQ7 at 0 range 12 .. 16; Reserved_17_17 at 0 range 17 .. 17; SQ8 at 0 range 18 .. 22; Reserved_23_23 at 0 range 23 .. 23; SQ9 at 0 range 24 .. 28; Reserved_29_31 at 0 range 29 .. 31; end record; subtype SQR3_SQ10_Field is HAL.UInt5; subtype SQR3_SQ11_Field is HAL.UInt5; subtype SQR3_SQ12_Field is HAL.UInt5; subtype SQR3_SQ13_Field is HAL.UInt5; subtype SQR3_SQ14_Field is HAL.UInt5; -- regular sequence register 3 type SQR3_Register is record -- SQ10 SQ10 : SQR3_SQ10_Field := 16#0#; -- unspecified Reserved_5_5 : HAL.Bit := 16#0#; -- SQ11 SQ11 : SQR3_SQ11_Field := 16#0#; -- unspecified Reserved_11_11 : HAL.Bit := 16#0#; -- SQ12 SQ12 : SQR3_SQ12_Field := 16#0#; -- unspecified Reserved_17_17 : HAL.Bit := 16#0#; -- SQ13 SQ13 : SQR3_SQ13_Field := 16#0#; -- unspecified Reserved_23_23 : HAL.Bit := 16#0#; -- SQ14 SQ14 : SQR3_SQ14_Field := 16#0#; -- unspecified Reserved_29_31 : HAL.UInt3 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for SQR3_Register use record SQ10 at 0 range 0 .. 4; Reserved_5_5 at 0 range 5 .. 5; SQ11 at 0 range 6 .. 10; Reserved_11_11 at 0 range 11 .. 11; SQ12 at 0 range 12 .. 16; Reserved_17_17 at 0 range 17 .. 17; SQ13 at 0 range 18 .. 22; Reserved_23_23 at 0 range 23 .. 23; SQ14 at 0 range 24 .. 28; Reserved_29_31 at 0 range 29 .. 31; end record; subtype SQR4_SQ15_Field is HAL.UInt5; subtype SQR4_SQ16_Field is HAL.UInt5; -- regular sequence register 4 type SQR4_Register is record -- SQ15 SQ15 : SQR4_SQ15_Field := 16#0#; -- unspecified Reserved_5_5 : HAL.Bit := 16#0#; -- SQ16 SQ16 : SQR4_SQ16_Field := 16#0#; -- unspecified Reserved_11_31 : HAL.UInt21 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for SQR4_Register use record SQ15 at 0 range 0 .. 4; Reserved_5_5 at 0 range 5 .. 5; SQ16 at 0 range 6 .. 10; Reserved_11_31 at 0 range 11 .. 31; end record; subtype DR_RDATA_Field is HAL.UInt16; -- regular Data Register type DR_Register is record -- Read-only. regularDATA RDATA : DR_RDATA_Field; -- unspecified Reserved_16_31 : HAL.UInt16; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for DR_Register use record RDATA at 0 range 0 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; subtype JSQR_JL_Field is HAL.UInt2; subtype JSQR_JEXTSEL_Field is HAL.UInt4; subtype JSQR_JEXTEN_Field is HAL.UInt2; subtype JSQR_JSQ1_Field is HAL.UInt5; subtype JSQR_JSQ2_Field is HAL.UInt5; subtype JSQR_JSQ3_Field is HAL.UInt5; subtype JSQR_JSQ4_Field is HAL.UInt5; -- injected sequence register type JSQR_Register is record -- JL JL : JSQR_JL_Field := 16#0#; -- JEXTSEL JEXTSEL : JSQR_JEXTSEL_Field := 16#0#; -- JEXTEN JEXTEN : JSQR_JEXTEN_Field := 16#0#; -- JSQ1 JSQ1 : JSQR_JSQ1_Field := 16#0#; -- unspecified Reserved_13_13 : HAL.Bit := 16#0#; -- JSQ2 JSQ2 : JSQR_JSQ2_Field := 16#0#; -- unspecified Reserved_19_19 : HAL.Bit := 16#0#; -- JSQ3 JSQ3 : JSQR_JSQ3_Field := 16#0#; -- unspecified Reserved_25_25 : HAL.Bit := 16#0#; -- JSQ4 JSQ4 : JSQR_JSQ4_Field := 16#0#; -- unspecified Reserved_31_31 : HAL.Bit := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for JSQR_Register use record JL at 0 range 0 .. 1; JEXTSEL at 0 range 2 .. 5; JEXTEN at 0 range 6 .. 7; JSQ1 at 0 range 8 .. 12; Reserved_13_13 at 0 range 13 .. 13; JSQ2 at 0 range 14 .. 18; Reserved_19_19 at 0 range 19 .. 19; JSQ3 at 0 range 20 .. 24; Reserved_25_25 at 0 range 25 .. 25; JSQ4 at 0 range 26 .. 30; Reserved_31_31 at 0 range 31 .. 31; end record; subtype OFR1_OFFSET1_Field is HAL.UInt12; subtype OFR1_OFFSET1_CH_Field is HAL.UInt5; -- offset register 1 type OFR1_Register is record -- OFFSET1 OFFSET1 : OFR1_OFFSET1_Field := 16#0#; -- unspecified Reserved_12_25 : HAL.UInt14 := 16#0#; -- OFFSET1_CH OFFSET1_CH : OFR1_OFFSET1_CH_Field := 16#0#; -- OFFSET1_EN OFFSET1_EN : Boolean := False; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for OFR1_Register use record OFFSET1 at 0 range 0 .. 11; Reserved_12_25 at 0 range 12 .. 25; OFFSET1_CH at 0 range 26 .. 30; OFFSET1_EN at 0 range 31 .. 31; end record; subtype OFR2_OFFSET2_Field is HAL.UInt12; subtype OFR2_OFFSET2_CH_Field is HAL.UInt5; -- offset register 2 type OFR2_Register is record -- OFFSET2 OFFSET2 : OFR2_OFFSET2_Field := 16#0#; -- unspecified Reserved_12_25 : HAL.UInt14 := 16#0#; -- OFFSET2_CH OFFSET2_CH : OFR2_OFFSET2_CH_Field := 16#0#; -- OFFSET2_EN OFFSET2_EN : Boolean := False; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for OFR2_Register use record OFFSET2 at 0 range 0 .. 11; Reserved_12_25 at 0 range 12 .. 25; OFFSET2_CH at 0 range 26 .. 30; OFFSET2_EN at 0 range 31 .. 31; end record; subtype OFR3_OFFSET3_Field is HAL.UInt12; subtype OFR3_OFFSET3_CH_Field is HAL.UInt5; -- offset register 3 type OFR3_Register is record -- OFFSET3 OFFSET3 : OFR3_OFFSET3_Field := 16#0#; -- unspecified Reserved_12_25 : HAL.UInt14 := 16#0#; -- OFFSET3_CH OFFSET3_CH : OFR3_OFFSET3_CH_Field := 16#0#; -- OFFSET3_EN OFFSET3_EN : Boolean := False; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for OFR3_Register use record OFFSET3 at 0 range 0 .. 11; Reserved_12_25 at 0 range 12 .. 25; OFFSET3_CH at 0 range 26 .. 30; OFFSET3_EN at 0 range 31 .. 31; end record; subtype OFR4_OFFSET4_Field is HAL.UInt12; subtype OFR4_OFFSET4_CH_Field is HAL.UInt5; -- offset register 4 type OFR4_Register is record -- OFFSET4 OFFSET4 : OFR4_OFFSET4_Field := 16#0#; -- unspecified Reserved_12_25 : HAL.UInt14 := 16#0#; -- OFFSET4_CH OFFSET4_CH : OFR4_OFFSET4_CH_Field := 16#0#; -- OFFSET4_EN OFFSET4_EN : Boolean := False; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for OFR4_Register use record OFFSET4 at 0 range 0 .. 11; Reserved_12_25 at 0 range 12 .. 25; OFFSET4_CH at 0 range 26 .. 30; OFFSET4_EN at 0 range 31 .. 31; end record; subtype JDR1_JDATA1_Field is HAL.UInt16; -- injected data register 1 type JDR1_Register is record -- Read-only. JDATA1 JDATA1 : JDR1_JDATA1_Field; -- unspecified Reserved_16_31 : HAL.UInt16; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for JDR1_Register use record JDATA1 at 0 range 0 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; subtype JDR2_JDATA2_Field is HAL.UInt16; -- injected data register 2 type JDR2_Register is record -- Read-only. JDATA2 JDATA2 : JDR2_JDATA2_Field; -- unspecified Reserved_16_31 : HAL.UInt16; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for JDR2_Register use record JDATA2 at 0 range 0 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; subtype JDR3_JDATA3_Field is HAL.UInt16; -- injected data register 3 type JDR3_Register is record -- Read-only. JDATA3 JDATA3 : JDR3_JDATA3_Field; -- unspecified Reserved_16_31 : HAL.UInt16; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for JDR3_Register use record JDATA3 at 0 range 0 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; subtype JDR4_JDATA4_Field is HAL.UInt16; -- injected data register 4 type JDR4_Register is record -- Read-only. JDATA4 JDATA4 : JDR4_JDATA4_Field; -- unspecified Reserved_16_31 : HAL.UInt16; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for JDR4_Register use record JDATA4 at 0 range 0 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; subtype AWD2CR_AWD2CH_Field is HAL.UInt18; -- Analog Watchdog 2 Configuration Register type AWD2CR_Register is record -- unspecified Reserved_0_0 : HAL.Bit := 16#0#; -- AWD2CH AWD2CH : AWD2CR_AWD2CH_Field := 16#0#; -- unspecified Reserved_19_31 : HAL.UInt13 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for AWD2CR_Register use record Reserved_0_0 at 0 range 0 .. 0; AWD2CH at 0 range 1 .. 18; Reserved_19_31 at 0 range 19 .. 31; end record; subtype AWD3CR_AWD3CH_Field is HAL.UInt18; -- Analog Watchdog 3 Configuration Register type AWD3CR_Register is record -- unspecified Reserved_0_0 : HAL.Bit := 16#0#; -- AWD3CH AWD3CH : AWD3CR_AWD3CH_Field := 16#0#; -- unspecified Reserved_19_31 : HAL.UInt13 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for AWD3CR_Register use record Reserved_0_0 at 0 range 0 .. 0; AWD3CH at 0 range 1 .. 18; Reserved_19_31 at 0 range 19 .. 31; end record; subtype DIFSEL_DIFSEL_1_15_Field is HAL.UInt15; subtype DIFSEL_DIFSEL_16_18_Field is HAL.UInt3; -- Differential Mode Selection Register 2 type DIFSEL_Register is record -- unspecified Reserved_0_0 : HAL.Bit := 16#0#; -- Differential mode for channels 15 to 1 DIFSEL_1_15 : DIFSEL_DIFSEL_1_15_Field := 16#0#; -- Read-only. Differential mode for channels 18 to 16 DIFSEL_16_18 : DIFSEL_DIFSEL_16_18_Field := 16#0#; -- unspecified Reserved_19_31 : HAL.UInt13 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for DIFSEL_Register use record Reserved_0_0 at 0 range 0 .. 0; DIFSEL_1_15 at 0 range 1 .. 15; DIFSEL_16_18 at 0 range 16 .. 18; Reserved_19_31 at 0 range 19 .. 31; end record; subtype CALFACT_CALFACT_S_Field is HAL.UInt7; subtype CALFACT_CALFACT_D_Field is HAL.UInt7; -- Calibration Factors type CALFACT_Register is record -- CALFACT_S CALFACT_S : CALFACT_CALFACT_S_Field := 16#0#; -- unspecified Reserved_7_15 : HAL.UInt9 := 16#0#; -- CALFACT_D CALFACT_D : CALFACT_CALFACT_D_Field := 16#0#; -- unspecified Reserved_23_31 : HAL.UInt9 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CALFACT_Register use record CALFACT_S at 0 range 0 .. 6; Reserved_7_15 at 0 range 7 .. 15; CALFACT_D at 0 range 16 .. 22; Reserved_23_31 at 0 range 23 .. 31; end record; -- ADC Common status register type CSR_Register is record -- Read-only. Master ADC ready ADRDY_MST : Boolean; -- Read-only. End of Sampling phase flag of the master ADC EOSMP_MST : Boolean; -- Read-only. End of regular conversion of the master ADC EOC_MST : Boolean; -- Read-only. End of regular sequence flag of the master ADC EOS_MST : Boolean; -- Read-only. Overrun flag of the master ADC OVR_MST : Boolean; -- Read-only. End of injected conversion flag of the master ADC JEOC_MST : Boolean; -- Read-only. End of injected sequence flag of the master ADC JEOS_MST : Boolean; -- Read-only. Analog watchdog 1 flag of the master ADC AWD1_MST : Boolean; -- Read-only. Analog watchdog 2 flag of the master ADC AWD2_MST : Boolean; -- Read-only. Analog watchdog 3 flag of the master ADC AWD3_MST : Boolean; -- Read-only. Injected Context Queue Overflow flag of the master ADC JQOVF_MST : Boolean; -- unspecified Reserved_11_15 : HAL.UInt5; -- Read-only. Slave ADC ready ADRDY_SLV : Boolean; -- Read-only. End of Sampling phase flag of the slave ADC EOSMP_SLV : Boolean; -- Read-only. End of regular conversion of the slave ADC EOC_SLV : Boolean; -- Read-only. End of regular sequence flag of the slave ADC EOS_SLV : Boolean; -- Read-only. Overrun flag of the slave ADC OVR_SLV : Boolean; -- Read-only. End of injected conversion flag of the slave ADC JEOC_SLV : Boolean; -- Read-only. End of injected sequence flag of the slave ADC JEOS_SLV : Boolean; -- Read-only. Analog watchdog 1 flag of the slave ADC AWD1_SLV : Boolean; -- Read-only. Analog watchdog 2 flag of the slave ADC AWD2_SLV : Boolean; -- Read-only. Analog watchdog 3 flag of the slave ADC AWD3_SLV : Boolean; -- Read-only. Injected Context Queue Overflow flag of the slave ADC JQOVF_SLV : Boolean; -- unspecified Reserved_27_31 : HAL.UInt5; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CSR_Register use record ADRDY_MST at 0 range 0 .. 0; EOSMP_MST at 0 range 1 .. 1; EOC_MST at 0 range 2 .. 2; EOS_MST at 0 range 3 .. 3; OVR_MST at 0 range 4 .. 4; JEOC_MST at 0 range 5 .. 5; JEOS_MST at 0 range 6 .. 6; AWD1_MST at 0 range 7 .. 7; AWD2_MST at 0 range 8 .. 8; AWD3_MST at 0 range 9 .. 9; JQOVF_MST at 0 range 10 .. 10; Reserved_11_15 at 0 range 11 .. 15; ADRDY_SLV at 0 range 16 .. 16; EOSMP_SLV at 0 range 17 .. 17; EOC_SLV at 0 range 18 .. 18; EOS_SLV at 0 range 19 .. 19; OVR_SLV at 0 range 20 .. 20; JEOC_SLV at 0 range 21 .. 21; JEOS_SLV at 0 range 22 .. 22; AWD1_SLV at 0 range 23 .. 23; AWD2_SLV at 0 range 24 .. 24; AWD3_SLV at 0 range 25 .. 25; JQOVF_SLV at 0 range 26 .. 26; Reserved_27_31 at 0 range 27 .. 31; end record; subtype CCR_DUAL_Field is HAL.UInt5; subtype CCR_DELAY_Field is HAL.UInt4; subtype CCR_MDMA_Field is HAL.UInt2; subtype CCR_CKMODE_Field is HAL.UInt2; -- ADC common control register type CCR_Register is record -- Dual ADC mode selection DUAL : CCR_DUAL_Field := 16#0#; -- unspecified Reserved_5_7 : HAL.UInt3 := 16#0#; -- Delay between 2 sampling phases DELAY_k : CCR_DELAY_Field := 16#0#; -- unspecified Reserved_12_12 : HAL.Bit := 16#0#; -- DMA configuration (for dual ADC mode) DMACFG : Boolean := False; -- Direct memory access mode for dual ADC mode MDMA : CCR_MDMA_Field := 16#0#; -- ADC clock mode CKMODE : CCR_CKMODE_Field := 16#0#; -- unspecified Reserved_18_21 : HAL.UInt4 := 16#0#; -- VREFINT enable VREFEN : Boolean := False; -- Temperature sensor enable TSEN : Boolean := False; -- VBAT enable VBATEN : Boolean := False; -- unspecified Reserved_25_31 : HAL.UInt7 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CCR_Register use record DUAL at 0 range 0 .. 4; Reserved_5_7 at 0 range 5 .. 7; DELAY_k at 0 range 8 .. 11; Reserved_12_12 at 0 range 12 .. 12; DMACFG at 0 range 13 .. 13; MDMA at 0 range 14 .. 15; CKMODE at 0 range 16 .. 17; Reserved_18_21 at 0 range 18 .. 21; VREFEN at 0 range 22 .. 22; TSEN at 0 range 23 .. 23; VBATEN at 0 range 24 .. 24; Reserved_25_31 at 0 range 25 .. 31; end record; subtype CDR_RDATA_MST_Field is HAL.UInt16; subtype CDR_RDATA_SLV_Field is HAL.UInt16; -- ADC common regular data register for dual mode type CDR_Register is record -- Read-only. Regular data of the master ADC RDATA_MST : CDR_RDATA_MST_Field; -- Read-only. Regular data of the slave ADC RDATA_SLV : CDR_RDATA_SLV_Field; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CDR_Register use record RDATA_MST at 0 range 0 .. 15; RDATA_SLV at 0 range 16 .. 31; end record; ----------------- -- Peripherals -- ----------------- -- Analog-to-Digital Converter type ADC1_Peripheral is record -- interrupt and status register ISR : aliased ISR_Register; -- interrupt enable register IER : aliased IER_Register; -- control register CR : aliased CR_Register; -- configuration register CFGR : aliased CFGR_Register; -- sample time register 1 SMPR1 : aliased SMPR1_Register; -- sample time register 2 SMPR2 : aliased SMPR2_Register; -- watchdog threshold register 1 TR1 : aliased TR1_Register; -- watchdog threshold register TR2 : aliased TR2_Register; -- watchdog threshold register 3 TR3 : aliased TR3_Register; -- regular sequence register 1 SQR1 : aliased SQR1_Register; -- regular sequence register 2 SQR2 : aliased SQR2_Register; -- regular sequence register 3 SQR3 : aliased SQR3_Register; -- regular sequence register 4 SQR4 : aliased SQR4_Register; -- regular Data Register DR : aliased DR_Register; -- injected sequence register JSQR : aliased JSQR_Register; -- offset register 1 OFR1 : aliased OFR1_Register; -- offset register 2 OFR2 : aliased OFR2_Register; -- offset register 3 OFR3 : aliased OFR3_Register; -- offset register 4 OFR4 : aliased OFR4_Register; -- injected data register 1 JDR1 : aliased JDR1_Register; -- injected data register 2 JDR2 : aliased JDR2_Register; -- injected data register 3 JDR3 : aliased JDR3_Register; -- injected data register 4 JDR4 : aliased JDR4_Register; -- Analog Watchdog 2 Configuration Register AWD2CR : aliased AWD2CR_Register; -- Analog Watchdog 3 Configuration Register AWD3CR : aliased AWD3CR_Register; -- Differential Mode Selection Register 2 DIFSEL : aliased DIFSEL_Register; -- Calibration Factors CALFACT : aliased CALFACT_Register; end record with Volatile; for ADC1_Peripheral use record ISR at 16#0# range 0 .. 31; IER at 16#4# range 0 .. 31; CR at 16#8# range 0 .. 31; CFGR at 16#C# range 0 .. 31; SMPR1 at 16#14# range 0 .. 31; SMPR2 at 16#18# range 0 .. 31; TR1 at 16#20# range 0 .. 31; TR2 at 16#24# range 0 .. 31; TR3 at 16#28# range 0 .. 31; SQR1 at 16#30# range 0 .. 31; SQR2 at 16#34# range 0 .. 31; SQR3 at 16#38# range 0 .. 31; SQR4 at 16#3C# range 0 .. 31; DR at 16#40# range 0 .. 31; JSQR at 16#4C# range 0 .. 31; OFR1 at 16#60# range 0 .. 31; OFR2 at 16#64# range 0 .. 31; OFR3 at 16#68# range 0 .. 31; OFR4 at 16#6C# range 0 .. 31; JDR1 at 16#80# range 0 .. 31; JDR2 at 16#84# range 0 .. 31; JDR3 at 16#88# range 0 .. 31; JDR4 at 16#8C# range 0 .. 31; AWD2CR at 16#A0# range 0 .. 31; AWD3CR at 16#A4# range 0 .. 31; DIFSEL at 16#B0# range 0 .. 31; CALFACT at 16#B4# range 0 .. 31; end record; -- Analog-to-Digital Converter ADC1_Periph : aliased ADC1_Peripheral with Import, Address => ADC1_Base; -- Analog-to-Digital Converter ADC2_Periph : aliased ADC1_Peripheral with Import, Address => ADC2_Base; -- ADC common registers type ADC_Common_Peripheral is record -- ADC Common status register CSR : aliased CSR_Register; -- ADC common control register CCR : aliased CCR_Register; -- ADC common regular data register for dual mode CDR : aliased CDR_Register; end record with Volatile; for ADC_Common_Peripheral use record CSR at 16#0# range 0 .. 31; CCR at 16#8# range 0 .. 31; CDR at 16#C# range 0 .. 31; end record; -- ADC common registers ADC_Common_Periph : aliased ADC_Common_Peripheral with Import, Address => ADC_Common_Base; end STM32_SVD.ADC; ",12506,True,3151.903293277765,median "------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- B I N D O . D I A G N O S T I C S -- -- -- -- B o d y -- -- -- -- Copyright (C) 2019-2020, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNAT; see file COPYING3. If not, go to -- -- http://www.gnu.org/licenses for a complete copy of the license. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ with Binderr; use Binderr; with Debug; use Debug; with Rident; use Rident; with Types; use Types; with Bindo.Validators; use Bindo.Validators; use Bindo.Validators.Cycle_Validators; with Bindo.Writers; use Bindo.Writers; use Bindo.Writers.Cycle_Writers; use Bindo.Writers.Phase_Writers; package body Bindo.Diagnostics is ----------------------- -- Local subprograms -- ----------------------- procedure Diagnose_All_Cycles (Inv_Graph : Invocation_Graph); pragma Inline (Diagnose_All_Cycles); -- Emit diagnostics for all cycles of library graph G procedure Diagnose_Cycle (Inv_Graph : Invocation_Graph; Cycle : Library_Graph_Cycle_Id); pragma Inline (Diagnose_Cycle); -- Emit diagnostics for cycle Cycle of library graph G procedure Find_And_Output_Invocation_Paths (Inv_Graph : Invocation_Graph; Source : Library_Graph_Vertex_Id; Destination : Library_Graph_Vertex_Id); pragma Inline (Find_And_Output_Invocation_Paths); -- Find all paths in invocation graph Inv_Graph that originate from vertex -- Source and reach vertex Destination of library graph Lib_Graph. Output -- the transitions of each such path. function Find_Elaboration_Root (Inv_Graph : Invocation_Graph; Vertex : Library_Graph_Vertex_Id) return Invocation_Graph_Vertex_Id; pragma Inline (Find_Elaboration_Root); -- Find the elaboration root in invocation graph Inv_Graph that corresponds -- to vertex Vertex of library graph Lib_Graph. procedure Output_All_Cycles_Suggestions (G : Library_Graph); pragma Inline (Output_All_Cycles_Suggestions); -- Suggest the diagnostic of all cycles in library graph G if circumstances -- allow it. procedure Output_Elaborate_All_Suggestions (G : Library_Graph; Pred : Library_Graph_Vertex_Id; Succ : Library_Graph_Vertex_Id); pragma Inline (Output_Elaborate_All_Suggestions); -- Suggest ways to break a cycle that involves an Elaborate_All edge that -- links predecessor Pred and successor Succ of library graph G. procedure Output_Elaborate_All_Transition (G : Library_Graph; Source : Library_Graph_Vertex_Id; Actual_Destination : Library_Graph_Vertex_Id; Expected_Destination : Library_Graph_Vertex_Id); pragma Inline (Output_Elaborate_All_Transition); -- Output a transition through an Elaborate_All edge of library graph G -- with successor Source and predecessor Actual_Destination. Parameter -- Expected_Destination denotes the predecessor as specified by the next -- edge in a cycle. procedure Output_Elaborate_Body_Suggestions (G : Library_Graph; Succ : Library_Graph_Vertex_Id); pragma Inline (Output_Elaborate_Body_Suggestions); -- Suggest ways to break a cycle that involves an edge where successor Succ -- is either a spec subject to pragma Elaborate_Body or the body of such a -- spec. procedure Output_Elaborate_Body_Transition (G : Library_Graph; Source : Library_Graph_Vertex_Id; Actual_Destination : Library_Graph_Vertex_Id; Expected_Destination : Library_Graph_Vertex_Id; Elaborate_All_Active : Boolean); pragma Inline (Output_Elaborate_Body_Transition); -- Output a transition through an edge of library graph G with successor -- Source and predecessor Actual_Destination. Vertex Source is either -- a spec subject to pragma Elaborate_Body or denotes the body of such -- a spec. Expected_Destination denotes the predecessor as specified by -- the next edge in a cycle. Elaborate_All_Active should be set when the -- transition occurs within a cycle that involves an Elaborate_All edge. procedure Output_Elaborate_Suggestions (G : Library_Graph; Pred : Library_Graph_Vertex_Id; Succ : Library_Graph_Vertex_Id); pragma Inline (Output_Elaborate_Suggestions); -- Suggest ways to break a cycle that involves an Elaborate edge that links -- predecessor Pred and successor Succ of library graph G. procedure Output_Elaborate_Transition (G : Library_Graph; Source : Library_Graph_Vertex_Id; Actual_Destination : Library_Graph_Vertex_Id; Expected_Destination : Library_Graph_Vertex_Id); pragma Inline (Output_Elaborate_Transition); -- Output a transition through an Elaborate edge of library graph G -- with successor Source and predecessor Actual_Destination. Parameter -- Expected_Destination denotes the predecessor as specified by the next -- edge in a cycle. procedure Output_Forced_Suggestions (G : Library_Graph; Pred : Library_Graph_Vertex_Id; Succ : Library_Graph_Vertex_Id); pragma Inline (Output_Forced_Suggestions); -- Suggest ways to break a cycle that involves a Forced edge that links -- predecessor Pred with successor Succ of library graph G. procedure Output_Forced_Transition (G : Library_Graph; Source : Library_Graph_Vertex_Id; Actual_Destination : Library_Graph_Vertex_Id; Expected_Destination : Library_Graph_Vertex_Id; Elaborate_All_Active : Boolean); pragma Inline (Output_Forced_Transition); -- Output a transition through a Forced edge of library graph G with -- successor Source and predecessor Actual_Destination. Parameter -- Expected_Destination denotes the predecessor as specified by the -- next edge in a cycle. Elaborate_All_Active should be set when the -- transition occurs within a cycle that involves an Elaborate_All edge. procedure Output_Full_Encoding_Suggestions (G : Library_Graph; Cycle : Library_Graph_Cycle_Id; First_Edge : Library_Graph_Edge_Id); pragma Inline (Output_Full_Encoding_Suggestions); -- Suggest the use of the full path invocation graph encoding to break -- cycle Cycle with initial edge First_Edge of library graph G. procedure Output_Invocation_Path (Inv_Graph : Invocation_Graph; Elaborated_Vertex : Library_Graph_Vertex_Id; Path : IGE_Lists.Doubly_Linked_List; Path_Id : in out Nat); pragma Inline (Output_Invocation_Path); -- Output path Path, which consists of invocation graph Inv_Graph edges. -- Elaborated_Vertex is the vertex of library graph Lib_Graph whose -- elaboration initiated the path. Path_Id is the unique id of the path. procedure Output_Invocation_Path_Transition (Inv_Graph : Invocation_Graph; Edge : Invocation_Graph_Edge_Id); pragma Inline (Output_Invocation_Path_Transition); -- Output a transition through edge Edge of invocation graph G, which is -- part of an invocation path. procedure Output_Invocation_Related_Suggestions (G : Library_Graph; Cycle : Library_Graph_Cycle_Id); pragma Inline (Output_Invocation_Related_Suggestions); -- Suggest ways to break cycle Cycle of library graph G that involves at -- least one invocation edge. procedure Output_Invocation_Transition (Inv_Graph : Invocation_Graph; Source : Library_Graph_Vertex_Id; Destination : Library_Graph_Vertex_Id); pragma Inline (Output_Invocation_Transition); -- Output a transition through an invocation edge of library graph G with -- successor Source and predecessor Destination. Inv_Graph is the related -- invocation graph. procedure Output_Reason_And_Circularity_Header (G : Library_Graph; First_Edge : Library_Graph_Edge_Id); pragma Inline (Output_Reason_And_Circularity_Header); -- Output the reason and circularity header for a circularity of library -- graph G with initial edge First_Edge. procedure Output_Suggestions (G : Library_Graph; Cycle : Library_Graph_Cycle_Id; First_Edge : Library_Graph_Edge_Id); pragma Inline (Output_Suggestions); -- Suggest various ways to break cycle Cycle with initial edge First_Edge -- of library graph G. procedure Output_Transition (Inv_Graph : Invocation_Graph; Current_Edge : Library_Graph_Edge_Id; Next_Edge : Library_Graph_Edge_Id; Elaborate_All_Active : Boolean); pragma Inline (Output_Transition); -- Output a transition described by edge Current_Edge, which is followed by -- edge Next_Edge of library graph Lib_Graph. Inv_Graph denotes the related -- invocation graph. Elaborate_All_Active should be set when the transition -- occurs within a cycle that involves an Elaborate_All edge. procedure Output_With_Transition (G : Library_Graph; Source : Library_Graph_Vertex_Id; Actual_Destination : Library_Graph_Vertex_Id; Expected_Destination : Library_Graph_Vertex_Id; Elaborate_All_Active : Boolean); pragma Inline (Output_With_Transition); -- Output a transition through a regular with edge of library graph G -- with successor Source and predecessor Actual_Destination. Parameter -- Expected_Destination denotes the predecessor as specified by the next -- edge in a cycle. Elaborate_All_Active should be set when the transition -- occurs within a cycle that involves an Elaborate_All edge. procedure Visit_Vertex (Inv_Graph : Invocation_Graph; Invoker : Invocation_Graph_Vertex_Id; Invoker_Vertex : Library_Graph_Vertex_Id; Last_Vertex : Library_Graph_Vertex_Id; Elaborated_Vertex : Library_Graph_Vertex_Id; End_Vertex : Library_Graph_Vertex_Id; Visited_Invokers : IGV_Sets.Membership_Set; Path : IGE_Lists.Doubly_Linked_List; Path_Id : in out Nat); pragma Inline (Visit_Vertex); -- Visit invocation graph vertex Invoker that resides in library graph -- vertex Invoker_Vertex as part of a DFS traversal. Last_Vertex denotes -- the previous vertex in the traversal. Elaborated_Vertex is the vertex -- whose elaboration started the traversal. End_Vertex is the vertex that -- terminates the traversal. Visited_Invoker is the set of all invokers -- visited so far. All edges along the path are recorded in Path. Path_Id -- is the id of the path. ------------------------- -- Diagnose_All_Cycles -- ------------------------- procedure Diagnose_All_Cycles (Inv_Graph : Invocation_Graph) is Lib_Graph : constant Library_Graph := Get_Lib_Graph (Inv_Graph); Cycle : Library_Graph_Cycle_Id; Iter : All_Cycle_Iterator; begin pragma Assert (Present (Inv_Graph)); pragma Assert (Present (Lib_Graph)); Iter := Iterate_All_Cycles (Lib_Graph); while Has_Next (Iter) loop Next (Iter, Cycle); Diagnose_Cycle (Inv_Graph => Inv_Graph, Cycle => Cycle); end loop; end Diagnose_All_Cycles; ---------------------------- -- Diagnose_Circularities -- ---------------------------- procedure Diagnose_Circularities (Inv_Graph : Invocation_Graph) is Lib_Graph : constant Library_Graph := Get_Lib_Graph (Inv_Graph); begin pragma Assert (Present (Inv_Graph)); pragma Assert (Present (Lib_Graph)); -- Find, validate, and output all cycles of the library graph Find_Cycles (Lib_Graph); Validate_Cycles (Lib_Graph); Write_Cycles (Lib_Graph); -- Diagnose all cycles in the graph regardless of their importance when -- switch -d_C (diagnose all cycles) is in effect. if Debug_Flag_Underscore_CC then Diagnose_All_Cycles (Inv_Graph); -- Otherwise diagnose the most important cycle in the graph else Diagnose_Cycle (Inv_Graph => Inv_Graph, Cycle => Highest_Precedence_Cycle (Lib_Graph)); end if; end Diagnose_Circularities; -------------------- -- Diagnose_Cycle -- -------------------- procedure Diagnose_Cycle (Inv_Graph : Invocation_Graph; Cycle : Library_Graph_Cycle_Id) is Lib_Graph : constant Library_Graph := Get_Lib_Graph (Inv_Graph); pragma Assert (Present (Inv_Graph)); pragma Assert (Present (Lib_Graph)); pragma Assert (Present (Cycle)); Elaborate_All_Active : constant Boolean := Contains_Elaborate_All_Edge (G => Lib_Graph, Cycle => Cycle); Current_Edge : Library_Graph_Edge_Id := No_Library_Graph_Edge; First_Edge : Library_Graph_Edge_Id; Iter : Edges_Of_Cycle_Iterator; Next_Edge : Library_Graph_Edge_Id; begin Start_Phase (Cycle_Diagnostics); First_Edge := No_Library_Graph_Edge; -- Inspect the edges of the cycle in pairs, emitting diagnostics based -- on their successors and predecessors. Iter := Iterate_Edges_Of_Cycle (Lib_Graph, Cycle); while Has_Next (Iter) loop -- Emit the reason for the cycle using the initial edge, which is the -- most important edge in the cycle. if not Present (First_Edge) then Next (Iter, Current_Edge); First_Edge := Current_Edge; Output_Reason_And_Circularity_Header (G => Lib_Graph, First_Edge => First_Edge); end if; -- Obtain the other edge of the pair exit when not Has_Next (Iter); Next (Iter, Next_Edge); -- Describe the transition from the current edge to the next edge by -- taking into account the predecessors and successors involved, as -- well as the nature of the edge. Output_Transition (Inv_Graph => Inv_Graph, Current_Edge => Current_Edge, Next_Edge => Next_Edge, Elaborate_All_Active => Elaborate_All_Active); Current_Edge := Next_Edge; end loop; -- Describe the transition from the last edge to the first edge Output_Transition (Inv_Graph => Inv_Graph, Current_Edge => Current_Edge, Next_Edge => First_Edge, Elaborate_All_Active => Elaborate_All_Active); -- Suggest various alternatives for breaking the cycle Output_Suggestions (G => Lib_Graph, Cycle => Cycle, First_Edge => First_Edge); End_Phase (Cycle_Diagnostics); end Diagnose_Cycle; -------------------------------------- -- Find_And_Output_Invocation_Paths -- -------------------------------------- procedure Find_And_Output_Invocation_Paths (Inv_Graph : Invocation_Graph; Source : Library_Graph_Vertex_Id; Destination : Library_Graph_Vertex_Id) is Lib_Graph : constant Library_Graph := Get_Lib_Graph (Inv_Graph); Path : IGE_Lists.Doubly_Linked_List; Path_Id : Nat; Visited : IGV_Sets.Membership_Set; begin pragma Assert (Present (Inv_Graph)); pragma Assert (Present (Lib_Graph)); pragma Assert (Present (Source)); pragma Assert (Present (Destination)); -- Nothing to do when the invocation graph encoding format of the source -- vertex does not contain detailed information about invocation paths. if Invocation_Graph_Encoding (Lib_Graph, Source) /= Full_Path_Encoding then return; end if; Path := IGE_Lists.Create; Path_Id := 1; Visited := IGV_Sets.Create (Number_Of_Vertices (Inv_Graph)); -- Start a DFS traversal over the invocation graph, in an attempt to -- reach Destination from Source. The actual start of the path is the -- elaboration root invocation vertex that corresponds to the Source. -- Each unique path is emitted as part of the current cycle diagnostic. Visit_Vertex (Inv_Graph => Inv_Graph, Invoker => Find_Elaboration_Root (Inv_Graph => Inv_Graph, Vertex => Source), Invoker_Vertex => Source, Last_Vertex => Source, Elaborated_Vertex => Source, End_Vertex => Destination, Visited_Invokers => Visited, Path => Path, Path_Id => Path_Id); IGE_Lists.Destroy (Path); IGV_Sets.Destroy (Visited); end Find_And_Output_Invocation_Paths; --------------------------- -- Find_Elaboration_Root -- --------------------------- function Find_Elaboration_Root (Inv_Graph : Invocation_Graph; Vertex : Library_Graph_Vertex_Id) return Invocation_Graph_Vertex_Id is Lib_Graph : constant Library_Graph := Get_Lib_Graph (Inv_Graph); Current_Vertex : Invocation_Graph_Vertex_Id; Iter : Elaboration_Root_Iterator; Root_Vertex : Invocation_Graph_Vertex_Id; begin pragma Assert (Present (Inv_Graph)); pragma Assert (Present (Lib_Graph)); pragma Assert (Present (Vertex)); -- Assume that the vertex does not have a corresponding elaboration root Root_Vertex := No_Invocation_Graph_Vertex; -- Inspect all elaboration roots trying to find the one that resides in -- the input vertex. -- -- IMPORTANT: -- -- * The iterator must run to completion in order to unlock the -- invocation graph. Iter := Iterate_Elaboration_Roots (Inv_Graph); while Has_Next (Iter) loop Next (Iter, Current_Vertex); if not Present (Root_Vertex) and then Body_Vertex (Inv_Graph, Current_Vertex) = Vertex then Root_Vertex := Current_Vertex; end if; end loop; return Root_Vertex; end Find_Elaboration_Root; ----------------------------------- -- Output_All_Cycles_Suggestions -- ----------------------------------- procedure Output_All_Cycles_Suggestions (G : Library_Graph) is begin pragma Assert (Present (G)); -- The library graph contains at least one cycle and only the highest -- priority cycle was diagnosed. Diagnosing all cycles may yield extra -- information for decision making. if Number_Of_Cycles (G) > 1 and then not Debug_Flag_Underscore_CC then Error_Msg_Info ("" diagnose all circularities (binder switch -d_C)""); end if; end Output_All_Cycles_Suggestions; -------------------------------------- -- Output_Elaborate_All_Suggestions -- -------------------------------------- procedure Output_Elaborate_All_Suggestions (G : Library_Graph; Pred : Library_Graph_Vertex_Id; Succ : Library_Graph_Vertex_Id) is begin pragma Assert (Present (G)); pragma Assert (Present (Pred)); pragma Assert (Present (Succ)); Error_Msg_Unit_1 := Name (G, Pred); Error_Msg_Unit_2 := Name (G, Succ); Error_Msg_Info ("" change pragma Elaborate_All for unit $ to Elaborate in unit $""); Error_Msg_Info ("" remove pragma Elaborate_All for unit $ in unit $""); end Output_Elaborate_All_Suggestions; ------------------------------------- -- Output_Elaborate_All_Transition -- ------------------------------------- procedure Output_Elaborate_All_Transition (G : Library_Graph; Source : Library_Graph_Vertex_Id; Actual_Destination : Library_Graph_Vertex_Id; Expected_Destination : Library_Graph_Vertex_Id) is begin pragma Assert (Present (G)); pragma Assert (Present (Source)); pragma Assert (Present (Actual_Destination)); pragma Assert (Present (Expected_Destination)); -- The actual and expected destination vertices match, and denote the -- initial declaration of a unit. -- -- Elaborate_All Actual_Destination -- Source ---------------> spec --> -- Expected_Destination -- -- Elaborate_All Actual_Destination -- Source ---------------> stand-alone body --> -- Expected_Destination if Actual_Destination = Expected_Destination then Error_Msg_Unit_1 := Name (G, Source); Error_Msg_Unit_2 := Name (G, Actual_Destination); Error_Msg_Info ("" unit $ has with clause and pragma Elaborate_All for unit $""); -- Otherwise the actual destination vertex denotes the spec of a unit, -- while the expected destination is the corresponding body. -- -- Elaborate_All Actual_Destination -- Source ---------------> spec -- -- body --> -- Expected_Destination else pragma Assert (Is_Spec_With_Body (G, Actual_Destination)); pragma Assert (Is_Body_With_Spec (G, Expected_Destination)); pragma Assert (Proper_Body (G, Actual_Destination) = Expected_Destination); Error_Msg_Unit_1 := Name (G, Source); Error_Msg_Unit_2 := Name (G, Actual_Destination); Error_Msg_Info ("" unit $ has with clause and pragma Elaborate_All for unit $""); Error_Msg_Unit_1 := Name (G, Expected_Destination); Error_Msg_Info ("" unit $ is in the closure of pragma Elaborate_All""); end if; end Output_Elaborate_All_Transition; --------------------------------------- -- Output_Elaborate_Body_Suggestions -- --------------------------------------- procedure Output_Elaborate_Body_Suggestions (G : Library_Graph; Succ : Library_Graph_Vertex_Id) is Spec : Library_Graph_Vertex_Id; begin pragma Assert (Present (G)); pragma Assert (Present (Succ)); -- Find the initial declaration of the unit because it is the one -- subject to pragma Elaborate_Body. if Is_Body_With_Spec (G, Succ) then Spec := Proper_Spec (G, Succ); else Spec := Succ; end if; Error_Msg_Unit_1 := Name (G, Spec); Error_Msg_Info ("" remove pragma Elaborate_Body in unit $""); end Output_Elaborate_Body_Suggestions; -------------------------------------- -- Output_Elaborate_Body_Transition -- -------------------------------------- procedure Output_Elaborate_Body_Transition (G : Library_Graph; Source : Library_Graph_Vertex_Id; Actual_Destination : Library_Graph_Vertex_Id; Expected_Destination : Library_Graph_Vertex_Id; Elaborate_All_Active : Boolean) is begin pragma Assert (Present (G)); pragma Assert (Present (Source)); pragma Assert (Present (Actual_Destination)); pragma Assert (Present (Expected_Destination)); -- The actual and expected destination vertices match -- -- Actual_Destination -- Source --------> spec --> -- Elaborate_Body Expected_Destination -- -- spec -- -- Actual_Destination -- Source --------> body --> -- Elaborate_Body Expected_Destination if Actual_Destination = Expected_Destination then Error_Msg_Unit_1 := Name (G, Source); Error_Msg_Unit_2 := Name (G, Actual_Destination); Error_Msg_Info ("" unit $ has with clause for unit $""); -- The actual destination vertex denotes the spec of a unit while the -- expected destination is the corresponding body, and the unit is in -- the closure of an earlier Elaborate_All pragma. -- -- Actual_Destination -- Source --------> spec -- Elaborate_Body -- body --> -- Expected_Destination elsif Elaborate_All_Active then pragma Assert (Is_Spec_With_Body (G, Actual_Destination)); pragma Assert (Is_Body_With_Spec (G, Expected_Destination)); pragma Assert (Proper_Body (G, Actual_Destination) = Expected_Destination); Error_Msg_Unit_1 := Name (G, Source); Error_Msg_Unit_2 := Name (G, Actual_Destination); Error_Msg_Info ("" unit $ has with clause for unit $""); Error_Msg_Unit_1 := Name (G, Expected_Destination); Error_Msg_Info ("" unit $ is in the closure of pragma Elaborate_All""); -- Otherwise the actual destination vertex is the spec of a unit subject -- to pragma Elaborate_Body and the expected destination vertex is the -- completion body. -- -- Actual_Destination -- Source --------> spec Elaborate_Body -- Elaborate_Body -- body --> -- Expected_Destination else pragma Assert (Is_Elaborate_Body_Pair (G => G, Spec_Vertex => Actual_Destination, Body_Vertex => Expected_Destination)); Error_Msg_Unit_1 := Name (G, Source); Error_Msg_Unit_2 := Name (G, Actual_Destination); Error_Msg_Info ("" unit $ has with clause for unit $""); Error_Msg_Unit_1 := Name (G, Actual_Destination); Error_Msg_Info ("" unit $ is subject to pragma Elaborate_Body""); Error_Msg_Unit_1 := Name (G, Expected_Destination); Error_Msg_Info ("" unit $ is in the closure of pragma Elaborate_Body""); end if; end Output_Elaborate_Body_Transition; ---------------------------------- -- Output_Elaborate_Suggestions -- ---------------------------------- procedure Output_Elaborate_Suggestions (G : Library_Graph; Pred : Library_Graph_Vertex_Id; Succ : Library_Graph_Vertex_Id) is begin pragma Assert (Present (G)); pragma Assert (Present (Pred)); pragma Assert (Present (Succ)); Error_Msg_Unit_1 := Name (G, Pred); Error_Msg_Unit_2 := Name (G, Succ); Error_Msg_Info ("" remove pragma Elaborate for unit $ in unit $""); end Output_Elaborate_Suggestions; --------------------------------- -- Output_Elaborate_Transition -- --------------------------------- procedure Output_Elaborate_Transition (G : Library_Graph; Source : Library_Graph_Vertex_Id; Actual_Destination : Library_Graph_Vertex_Id; Expected_Destination : Library_Graph_Vertex_Id) is Spec : Library_Graph_Vertex_Id; begin pragma Assert (Present (G)); pragma Assert (Present (Source)); pragma Assert (Present (Actual_Destination)); pragma Assert (Present (Expected_Destination)); -- The actual and expected destination vertices match, and denote the -- initial declaration of a unit. -- -- Elaborate Actual_Destination -- Source -----------> spec --> -- Expected_Destination -- -- Elaborate Actual_Destination -- Source -----------> stand-alone body --> -- Expected_Destination -- -- The processing of pragma Elaborate body generates an edge between a -- successor and predecessor body. -- -- spec -- -- Elaborate Actual_Destination -- Source -----------> body --> -- Expected_Destination if Actual_Destination = Expected_Destination then -- Find the initial declaration of the unit because it is the one -- subject to pragma Elaborate. if Is_Body_With_Spec (G, Actual_Destination) then Spec := Proper_Spec (G, Actual_Destination); else Spec := Actual_Destination; end if; Error_Msg_Unit_1 := Name (G, Source); Error_Msg_Unit_2 := Name (G, Spec); Error_Msg_Info ("" unit $ has with clause and pragma Elaborate for unit $""); if Actual_Destination /= Spec then Error_Msg_Unit_1 := Name (G, Actual_Destination); Error_Msg_Info ("" unit $ is in the closure of pragma Elaborate""); end if; -- Otherwise the actual destination vertex denotes the spec of a unit -- while the expected destination vertex is the corresponding body. -- -- Elaborate Actual_Destination -- Source -----------> spec -- -- body --> -- Expected_Destination else pragma Assert (Is_Spec_With_Body (G, Actual_Destination)); pragma Assert (Is_Body_With_Spec (G, Expected_Destination)); pragma Assert (Proper_Body (G, Actual_Destination) = Expected_Destination); Error_Msg_Unit_1 := Name (G, Source); Error_Msg_Unit_2 := Name (G, Actual_Destination); Error_Msg_Info ("" unit $ has with clause and pragma Elaborate for unit $""); Error_Msg_Unit_1 := Name (G, Expected_Destination); Error_Msg_Info ("" unit $ is in the closure of pragma Elaborate""); end if; end Output_Elaborate_Transition; ------------------------------- -- Output_Forced_Suggestions -- ------------------------------- procedure Output_Forced_Suggestions (G : Library_Graph; Pred : Library_Graph_Vertex_Id; Succ : Library_Graph_Vertex_Id) is begin pragma Assert (Present (G)); pragma Assert (Present (Pred)); pragma Assert (Present (Succ)); Error_Msg_Unit_1 := Name (G, Succ); Error_Msg_Unit_2 := Name (G, Pred); Error_Msg_Info ("" remove the dependency of unit $ on unit $ from the argument of "" & ""switch -f""); Error_Msg_Info ("" remove switch -f""); end Output_Forced_Suggestions; ------------------------------ -- Output_Forced_Transition -- ------------------------------ procedure Output_Forced_Transition (G : Library_Graph; Source : Library_Graph_Vertex_Id; Actual_Destination : Library_Graph_Vertex_Id; Expected_Destination : Library_Graph_Vertex_Id; Elaborate_All_Active : Boolean) is begin pragma Assert (Present (G)); pragma Assert (Present (Source)); pragma Assert (Present (Actual_Destination)); pragma Assert (Present (Expected_Destination)); -- The actual and expected destination vertices match -- -- Forced Actual_Destination -- Source --------> spec --> -- Expected_Destination -- -- Forced Actual_Destination -- Source --------> body --> -- Expected_Destination if Actual_Destination = Expected_Destination then Error_Msg_Unit_1 := Name (G, Source); Error_Msg_Unit_2 := Name (G, Actual_Destination); Error_Msg_Info ("" unit $ has a dependency on unit $ forced by -f switch""); -- The actual destination vertex denotes the spec of a unit while the -- expected destination is the corresponding body, and the unit is in -- the closure of an earlier Elaborate_All pragma. -- -- Forced Actual_Destination -- Source --------> spec -- -- body --> -- Expected_Destination elsif Elaborate_All_Active then pragma Assert (Is_Spec_With_Body (G, Actual_Destination)); pragma Assert (Is_Body_With_Spec (G, Expected_Destination)); pragma Assert (Proper_Body (G, Actual_Destination) = Expected_Destination); Error_Msg_Unit_1 := Name (G, Source); Error_Msg_Unit_2 := Name (G, Actual_Destination); Error_Msg_Info ("" unit $ has a dependency on unit $ forced by -f switch""); Error_Msg_Unit_1 := Name (G, Expected_Destination); Error_Msg_Info ("" unit $ is in the closure of pragma Elaborate_All""); -- Otherwise the actual destination vertex denotes a spec subject to -- pragma Elaborate_Body while the expected destination denotes the -- corresponding body. -- -- Forced Actual_Destination -- Source --------> spec Elaborate_Body -- -- body --> -- Expected_Destination else pragma Assert (Is_Elaborate_Body_Pair (G => G, Spec_Vertex => Actual_Destination, Body_Vertex => Expected_Destination)); Error_Msg_Unit_1 := Name (G, Source); Error_Msg_Unit_2 := Name (G, Actual_Destination); Error_Msg_Info ("" unit $ has a dependency on unit $ forced by -f switch""); Error_Msg_Unit_1 := Name (G, Actual_Destination); Error_Msg_Info ("" unit $ is subject to pragma Elaborate_Body""); Error_Msg_Unit_1 := Name (G, Expected_Destination); Error_Msg_Info ("" unit $ is in the closure of pragma Elaborate_Body""); end if; end Output_Forced_Transition; -------------------------------------- -- Output_Full_Encoding_Suggestions -- -------------------------------------- procedure Output_Full_Encoding_Suggestions (G : Library_Graph; Cycle : Library_Graph_Cycle_Id; First_Edge : Library_Graph_Edge_Id) is Succ : Library_Graph_Vertex_Id; begin pragma Assert (Present (G)); pragma Assert (Present (Cycle)); pragma Assert (Present (First_Edge)); if Is_Invocation_Edge (G, First_Edge) then Succ := Successor (G, First_Edge); if Invocation_Graph_Encoding (G, Succ) /= Full_Path_Encoding then Error_Msg_Info ("" use detailed invocation information (compiler switch "" & ""-gnatd_F)""); end if; end if; end Output_Full_Encoding_Suggestions; ---------------------------- -- Output_Invocation_Path -- ----------------------------- procedure Output_Invocation_Path (Inv_Graph : Invocation_Graph; Elaborated_Vertex : Library_Graph_Vertex_Id; Path : IGE_Lists.Doubly_Linked_List; Path_Id : in out Nat) is Lib_Graph : constant Library_Graph := Get_Lib_Graph (Inv_Graph); Edge : Invocation_Graph_Edge_Id; Iter : IGE_Lists.Iterator; begin pragma Assert (Present (Inv_Graph)); pragma Assert (Present (Lib_Graph)); pragma Assert (Present (Elaborated_Vertex)); pragma Assert (IGE_Lists.Present (Path)); Error_Msg_Nat_1 := Path_Id; Error_Msg_Info ("" path #:""); Error_Msg_Unit_1 := Name (Lib_Graph, Elaborated_Vertex); Error_Msg_Info ("" elaboration of unit $""); Iter := IGE_Lists.Iterate (Path); while IGE_Lists.Has_Next (Iter) loop IGE_Lists.Next (Iter, Edge); Output_Invocation_Path_Transition (Inv_Graph => Inv_Graph, Edge => Edge); end loop; Path_Id := Path_Id + 1; end Output_Invocation_Path; --------------------------------------- -- Output_Invocation_Path_Transition -- --------------------------------------- procedure Output_Invocation_Path_Transition (Inv_Graph : Invocation_Graph; Edge : Invocation_Graph_Edge_Id) is Lib_Graph : constant Library_Graph := Get_Lib_Graph (Inv_Graph); pragma Assert (Present (Inv_Graph)); pragma Assert (Present (Lib_Graph)); pragma Assert (Present (Edge)); Declared : constant String := ""declared at {:#:#""; Targ : constant Invocation_Graph_Vertex_Id := Target (Inv_Graph, Edge); Targ_Extra : constant Name_Id := Extra (Inv_Graph, Edge); Targ_Vertex : constant Library_Graph_Vertex_Id := Spec_Vertex (Inv_Graph, Targ); begin Error_Msg_Name_1 := Name (Inv_Graph, Targ); Error_Msg_Nat_1 := Line (Inv_Graph, Targ); Error_Msg_Nat_2 := Column (Inv_Graph, Targ); Error_Msg_File_1 := File_Name (Lib_Graph, Targ_Vertex); case Kind (Inv_Graph, Edge) is when Accept_Alternative => Error_Msg_Info ("" selection of entry % "" & Declared); when Access_Taken => Error_Msg_Info ("" aliasing of subprogram % "" & Declared); when Call => Error_Msg_Info ("" call to subprogram % "" & Declared); when Controlled_Adjustment | Internal_Controlled_Adjustment => Error_Msg_Name_1 := Targ_Extra; Error_Msg_Info ("" adjustment actions for type % "" & Declared); when Controlled_Finalization | Internal_Controlled_Finalization => Error_Msg_Name_1 := Targ_Extra; Error_Msg_Info ("" finalization actions for type % "" & Declared); when Controlled_Initialization | Internal_Controlled_Initialization | Type_Initialization => Error_Msg_Name_1 := Targ_Extra; Error_Msg_Info ("" initialization actions for type % "" & Declared); when Default_Initial_Condition_Verification => Error_Msg_Name_1 := Targ_Extra; Error_Msg_Info ("" verification of Default_Initial_Condition for type % "" & Declared); when Initial_Condition_Verification => Error_Msg_Info ("" verification of Initial_Condition "" & Declared); when Instantiation => Error_Msg_Info ("" instantiation % "" & Declared); when Invariant_Verification => Error_Msg_Name_1 := Targ_Extra; Error_Msg_Info ("" verification of invariant for type % "" & Declared); when Postcondition_Verification => Error_Msg_Name_1 := Targ_Extra; Error_Msg_Info ("" verification of postcondition for subprogram % "" & Declared); when Protected_Entry_Call => Error_Msg_Info ("" call to protected entry % "" & Declared); when Protected_Subprogram_Call => Error_Msg_Info ("" call to protected subprogram % "" & Declared); when Task_Activation => Error_Msg_Info ("" activation of local task "" & Declared); when Task_Entry_Call => Error_Msg_Info ("" call to task entry % "" & Declared); when others => pragma Assert (False); null; end case; end Output_Invocation_Path_Transition; ------------------------------------------- -- Output_Invocation_Related_Suggestions -- ------------------------------------------- procedure Output_Invocation_Related_Suggestions (G : Library_Graph; Cycle : Library_Graph_Cycle_Id) is begin pragma Assert (Present (G)); pragma Assert (Present (Cycle)); -- Nothing to do when the cycle does not contain an invocation edge if Invocation_Edge_Count (G, Cycle) = 0 then return; end if; -- The cycle contains at least one invocation edge, where at least -- one of the paths the edge represents activates a task. The use of -- restriction No_Entry_Calls_In_Elaboration_Code may halt the flow -- within the task body on a select or accept statement, eliminating -- subsequent invocation edges, thus breaking the cycle. if not Cumulative_Restrictions.Set (No_Entry_Calls_In_Elaboration_Code) and then Contains_Task_Activation (G, Cycle) then Error_Msg_Info ("" use pragma Restrictions "" & ""(No_Entry_Calls_In_Elaboration_Code)""); end if; -- The cycle contains at least one invocation edge where the successor -- was statically elaborated. The use of the dynamic model may remove -- one of the invocation edges in the cycle, thus breaking the cycle. if Contains_Static_Successor_Edge (G, Cycle) then Error_Msg_Info ("" use the dynamic elaboration model (compiler switch -gnatE)""); end if; end Output_Invocation_Related_Suggestions; ---------------------------------- -- Output_Invocation_Transition -- ---------------------------------- procedure Output_Invocation_Transition (Inv_Graph : Invocation_Graph; Source : Library_Graph_Vertex_Id; Destination : Library_Graph_Vertex_Id) is Lib_Graph : constant Library_Graph := Get_Lib_Graph (Inv_Graph); begin pragma Assert (Present (Inv_Graph)); pragma Assert (Present (Lib_Graph)); pragma Assert (Present (Source)); pragma Assert (Present (Destination)); Error_Msg_Unit_1 := Name (Lib_Graph, Source); Error_Msg_Unit_2 := Name (Lib_Graph, Destination); Error_Msg_Info ("" unit $ invokes a construct of unit $ at elaboration time""); Find_And_Output_Invocation_Paths (Inv_Graph => Inv_Graph, Source => Source, Destination => Destination); end Output_Invocation_Transition; ------------------------------------------ -- Output_Reason_And_Circularity_Header -- ------------------------------------------ procedure Output_Reason_And_Circularity_Header (G : Library_Graph; First_Edge : Library_Graph_Edge_Id) is pragma Assert (Present (G)); pragma Assert (Present (First_Edge)); Succ : constant Library_Graph_Vertex_Id := Successor (G, First_Edge); begin Error_Msg_Unit_1 := Name (G, Succ); Error_Msg (""Elaboration circularity detected""); Error_Msg_Info (""""); Error_Msg_Info ("" Reason:""); Error_Msg_Info (""""); Error_Msg_Info ("" unit $ depends on its own elaboration""); Error_Msg_Info (""""); Error_Msg_Info ("" Circularity:""); Error_Msg_Info (""""); end Output_Reason_And_Circularity_Header; ------------------------ -- Output_Suggestions -- ------------------------ procedure Output_Suggestions (G : Library_Graph; Cycle : Library_Graph_Cycle_Id; First_Edge : Library_Graph_Edge_Id) is pragma Assert (Present (G)); pragma Assert (Present (Cycle)); pragma Assert (Present (First_Edge)); Pred : constant Library_Graph_Vertex_Id := Predecessor (G, First_Edge); Succ : constant Library_Graph_Vertex_Id := Successor (G, First_Edge); begin Error_Msg_Info (""""); Error_Msg_Info ("" Suggestions:""); Error_Msg_Info (""""); -- Output edge-specific suggestions if Is_Elaborate_All_Edge (G, First_Edge) then Output_Elaborate_All_Suggestions (G => G, Pred => Pred, Succ => Succ); elsif Is_Elaborate_Body_Edge (G, First_Edge) then Output_Elaborate_Body_Suggestions (G => G, Succ => Succ); elsif Is_Elaborate_Edge (G, First_Edge) then Output_Elaborate_Suggestions (G => G, Pred => Pred, Succ => Succ); elsif Is_Forced_Edge (G, First_Edge) then Output_Forced_Suggestions (G => G, Pred => Pred, Succ => Succ); end if; -- Output general purpose suggestions Output_Invocation_Related_Suggestions (G => G, Cycle => Cycle); Output_Full_Encoding_Suggestions (G => G, Cycle => Cycle, First_Edge => First_Edge); Output_All_Cycles_Suggestions (G); Error_Msg_Info (""""); end Output_Suggestions; ----------------------- -- Output_Transition -- ----------------------- procedure Output_Transition (Inv_Graph : Invocation_Graph; Current_Edge : Library_Graph_Edge_Id; Next_Edge : Library_Graph_Edge_Id; Elaborate_All_Active : Boolean) is Lib_Graph : constant Library_Graph := Get_Lib_Graph (Inv_Graph); pragma Assert (Present (Inv_Graph)); pragma Assert (Present (Lib_Graph)); pragma Assert (Present (Current_Edge)); pragma Assert (Present (Next_Edge)); Actual_Destination : constant Library_Graph_Vertex_Id := Predecessor (Lib_Graph, Current_Edge); Expected_Destination : constant Library_Graph_Vertex_Id := Successor (Lib_Graph, Next_Edge); Source : constant Library_Graph_Vertex_Id := Successor (Lib_Graph, Current_Edge); begin if Is_Elaborate_All_Edge (Lib_Graph, Current_Edge) then Output_Elaborate_All_Transition (G => Lib_Graph, Source => Source, Actual_Destination => Actual_Destination, Expected_Destination => Expected_Destination); elsif Is_Elaborate_Body_Edge (Lib_Graph, Current_Edge) then Output_Elaborate_Body_Transition (G => Lib_Graph, Source => Source, Actual_Destination => Actual_Destination, Expected_Destination => Expected_Destination, Elaborate_All_Active => Elaborate_All_Active); elsif Is_Elaborate_Edge (Lib_Graph, Current_Edge) then Output_Elaborate_Transition (G => Lib_Graph, Source => Source, Actual_Destination => Actual_Destination, Expected_Destination => Expected_Destination); elsif Is_Forced_Edge (Lib_Graph, Current_Edge) then Output_Forced_Transition (G => Lib_Graph, Source => Source, Actual_Destination => Actual_Destination, Expected_Destination => Expected_Destination, Elaborate_All_Active => Elaborate_All_Active); elsif Is_Invocation_Edge (Lib_Graph, Current_Edge) then Output_Invocation_Transition (Inv_Graph => Inv_Graph, Source => Source, Destination => Expected_Destination); else pragma Assert (Is_With_Edge (Lib_Graph, Current_Edge)); Output_With_Transition (G => Lib_Graph, Source => Source, Actual_Destination => Actual_Destination, Expected_Destination => Expected_Destination, Elaborate_All_Active => Elaborate_All_Active); end if; end Output_Transition; ---------------------------- -- Output_With_Transition -- ---------------------------- procedure Output_With_Transition (G : Library_Graph; Source : Library_Graph_Vertex_Id; Actual_Destination : Library_Graph_Vertex_Id; Expected_Destination : Library_Graph_Vertex_Id; Elaborate_All_Active : Boolean) is begin pragma Assert (Present (G)); pragma Assert (Present (Source)); pragma Assert (Present (Actual_Destination)); pragma Assert (Present (Expected_Destination)); -- The actual and expected destination vertices match, and denote the -- initial declaration of a unit. -- -- with Actual_Destination -- Source ------> spec --> -- Expected_Destination -- -- with Actual_Destination -- Source ------> stand-alone body --> -- Expected_Destination if Actual_Destination = Expected_Destination then Error_Msg_Unit_1 := Name (G, Source); Error_Msg_Unit_2 := Name (G, Actual_Destination); Error_Msg_Info ("" unit $ has with clause for unit $""); -- The actual destination vertex denotes the spec of a unit while the -- expected destination is the corresponding body, and the unit is in -- the closure of an earlier Elaborate_All pragma. -- -- with Actual_Destination -- Source ------> spec -- -- body --> -- Expected_Destination elsif Elaborate_All_Active then pragma Assert (Is_Spec_With_Body (G, Actual_Destination)); pragma Assert (Is_Body_With_Spec (G, Expected_Destination)); pragma Assert (Proper_Body (G, Actual_Destination) = Expected_Destination); Error_Msg_Unit_1 := Name (G, Source); Error_Msg_Unit_2 := Name (G, Actual_Destination); Error_Msg_Info ("" unit $ has with clause for unit $""); Error_Msg_Unit_1 := Name (G, Expected_Destination); Error_Msg_Info ("" unit $ is in the closure of pragma Elaborate_All""); -- Otherwise the actual destination vertex denotes a spec subject to -- pragma Elaborate_Body while the expected destination denotes the -- corresponding body. -- -- with Actual_Destination -- Source ------> spec Elaborate_Body -- -- body --> -- Expected_Destination else pragma Assert (Is_Elaborate_Body_Pair (G => G, Spec_Vertex => Actual_Destination, Body_Vertex => Expected_Destination)); Error_Msg_Unit_1 := Name (G, Source); Error_Msg_Unit_2 := Name (G, Actual_Destination); Error_Msg_Info ("" unit $ has with clause for unit $""); Error_Msg_Unit_1 := Name (G, Actual_Destination); Error_Msg_Info ("" unit $ is subject to pragma Elaborate_Body""); Error_Msg_Unit_1 := Name (G, Expected_Destination); Error_Msg_Info ("" unit $ is in the closure of pragma Elaborate_Body""); end if; end Output_With_Transition; ------------------ -- Visit_Vertex -- ------------------ procedure Visit_Vertex (Inv_Graph : Invocation_Graph; Invoker : Invocation_Graph_Vertex_Id; Invoker_Vertex : Library_Graph_Vertex_Id; Last_Vertex : Library_Graph_Vertex_Id; Elaborated_Vertex : Library_Graph_Vertex_Id; End_Vertex : Library_Graph_Vertex_Id; Visited_Invokers : IGV_Sets.Membership_Set; Path : IGE_Lists.Doubly_Linked_List; Path_Id : in out Nat) is Lib_Graph : constant Library_Graph := Get_Lib_Graph (Inv_Graph); Edge : Invocation_Graph_Edge_Id; Iter : Edges_To_Targets_Iterator; Targ : Invocation_Graph_Vertex_Id; begin pragma Assert (Present (Inv_Graph)); pragma Assert (Present (Lib_Graph)); pragma Assert (Present (Invoker)); pragma Assert (Present (Invoker_Vertex)); pragma Assert (Present (Last_Vertex)); pragma Assert (Present (Elaborated_Vertex)); pragma Assert (Present (End_Vertex)); pragma Assert (IGV_Sets.Present (Visited_Invokers)); pragma Assert (IGE_Lists.Present (Path)); -- The current invocation vertex resides within the end library vertex. -- Emit the path that started from some elaboration root and ultimately -- reached the desired library vertex. if Body_Vertex (Inv_Graph, Invoker) = End_Vertex and then Invoker_Vertex /= Last_Vertex then Output_Invocation_Path (Inv_Graph => Inv_Graph, Elaborated_Vertex => Elaborated_Vertex, Path => Path, Path_Id => Path_Id); -- Otherwise extend the search for the end library vertex via all edges -- to targets. elsif not IGV_Sets.Contains (Visited_Invokers, Invoker) then -- Prepare for invoker backtracking IGV_Sets.Insert (Visited_Invokers, Invoker); -- Extend the search via all edges to targets Iter := Iterate_Edges_To_Targets (Inv_Graph, Invoker); while Has_Next (Iter) loop Next (Iter, Edge); -- Prepare for edge backtracking IGE_Lists.Append (Path, Edge); -- The traversal proceeds through the library vertex that houses -- the body of the target. Targ := Target (Inv_Graph, Edge); Visit_Vertex (Inv_Graph => Inv_Graph, Invoker => Targ, Invoker_Vertex => Body_Vertex (Inv_Graph, Targ), Last_Vertex => Invoker_Vertex, Elaborated_Vertex => Elaborated_Vertex, End_Vertex => End_Vertex, Visited_Invokers => Visited_Invokers, Path => Path, Path_Id => Path_Id); -- Backtrack the edge IGE_Lists.Delete_Last (Path); end loop; -- Backtrack the invoker IGV_Sets.Delete (Visited_Invokers, Invoker); end if; end Visit_Vertex; end Bindo.Diagnostics; ",12537,True,2636.3394906691683,median "// tag::HeaderFullDisplayName[] = sqlparse.RepoObject_SqlModules_32_ObjectClass - V // end::HeaderFullDisplayName[] == existing_properties // tag::existing_properties[] :ExistsProperty--antorareferencedlist: :ExistsProperty--antorareferencinglist: :ExistsProperty--is_repo_managed: :ExistsProperty--is_ssas: :ExistsProperty--pk_index_guid: :ExistsProperty--pk_indexpatterncolumndatatype: :ExistsProperty--pk_indexpatterncolumnname: :ExistsProperty--referencedobjectlist: :ExistsProperty--sql_modules_definition: :ExistsProperty--FK: :ExistsProperty--AntoraIndexList: :ExistsProperty--Columns: // end::existing_properties[] == RepoObject_guid // tag::RepoObject_guid[] FF8F291C-9D61-EB11-84DC-A81E8446D5B0 // end::RepoObject_guid[] == RepoObject_FullDisplayName2 // tag::RepoObject_FullDisplayName2[] sqlparse.RepoObject_SqlModules_32_ObjectClass // end::RepoObject_FullDisplayName2[] == SysObject_type // tag::SysObject_type[] V // end::SysObject_type[] == SysObject_type_name // tag::SysObject_type_name[] view // end::SysObject_type_name[] == SysObject_id // tag::SysObject_id[] 116911488 // end::SysObject_id[] == SysObject_modify_date // tag::SysObject_modify_date[] 2021-08-17 20:11:29 // end::SysObject_modify_date[] == AntoraColumnDetails // tag::AntoraColumnDetails[] [discrete] == _ [#column-repoobjectunderlineguid] === RepoObject_guid [cols=""d,8a,m,m,m""] |=== |1 |*RepoObject_guid* |uniqueidentifier |NOT NULL | |=== .Referenced Columns -- * xref:sqlparse.repoobject_sqlmodules_20_statement_children.adoc#column-repoobjectunderlineguid[+sqlparse.RepoObject_SqlModules_20_statement_children.RepoObject_guid+] -- [#column-class] === class [cols=""d,8a,m,m,m""] |=== |2 |*class* |nvarchar(500) |NULL | |=== .Referenced Columns -- * xref:sqlparse.repoobject_sqlmodules_20_statement_children.adoc#column-class[+sqlparse.RepoObject_SqlModules_20_statement_children.class+] -- [#column-minunderlinerownumberunderlineperunderlineclass] === Min_RowNumber_per_class [cols=""d,8a,m,m,m""] |=== | |Min_RowNumber_per_class |bigint |NULL | |=== .Referencing Columns -- * xref:sqlparse.repoobject_sqlmodules_39_object.adoc#column-minunderlinerownumberunderlineidentifierlist[+sqlparse.RepoObject_SqlModules_39_object.Min_RowNumber_IdentifierList+] * xref:sqlparse.repoobject_sqlmodules_39_object.adoc#column-minunderlinerownumberunderlinewhere[+sqlparse.RepoObject_SqlModules_39_object.Min_RowNumber_Where+] -- [#column-sysobjectunderlinefullname] === SysObject_fullname [cols=""d,8a,m,m,m""] |=== | |SysObject_fullname |nvarchar(261) |NULL | |=== .Description -- (concat('[',[SysObject_schema_name],'].[',[SysObject_name],']')) -- {empty} + .Referenced Columns -- * xref:sqlparse.repoobject_sqlmodules_20_statement_children.adoc#column-sysobjectunderlinefullname[+sqlparse.RepoObject_SqlModules_20_statement_children.SysObject_fullname+] -- // end::AntoraColumnDetails[] == AntoraPkColumnTableRows // tag::AntoraPkColumnTableRows[] |1 |*<>* |uniqueidentifier |NOT NULL | |2 |*<>* |nvarchar(500) |NULL | // end::AntoraPkColumnTableRows[] == AntoraNonPkColumnTableRows // tag::AntoraNonPkColumnTableRows[] | |<> |bigint |NULL | | |<> |nvarchar(261) |NULL | // end::AntoraNonPkColumnTableRows[] == AntoraIndexList // tag::AntoraIndexList[] [#index-pkunderlinerepoobjectunderlinesqlmodulesunderline32underlineobjectclass] === PK_RepoObject_SqlModules_32_ObjectClass * IndexSemanticGroup: xref:other/indexsemanticgroup.adoc#startbnoblankgroupendb[no_group] + -- * <>; uniqueidentifier * <>; nvarchar(500) -- * PK, Unique, Real: 1, 1, 0 [#index-idxunderlinerepoobjectunderlinesqlmodulesunderline32underlineobjectclassunderlineunderline2] === idx_RepoObject_SqlModules_32_ObjectClass++__++2 * IndexSemanticGroup: xref:other/indexsemanticgroup.adoc#startbnoblankgroupendb[no_group] + -- * <>; uniqueidentifier -- * PK, Unique, Real: 0, 0, 0 // end::AntoraIndexList[] == AntoraMeasureDetails // tag::AntoraMeasureDetails[] // end::AntoraMeasureDetails[] == AntoraMeasureDescriptions == AntoraParameterList // tag::AntoraParameterList[] // end::AntoraParameterList[] == AntoraXrefCulturesList // tag::AntoraXrefCulturesList[] * xref:dhw:sqldb:sqlparse.repoobject_sqlmodules_32_objectclass.adoc[] - // end::AntoraXrefCulturesList[] == cultures_count // tag::cultures_count[] 1 // end::cultures_count[] == Other tags source: property.RepoObjectProperty_cross As rop_cross === additional_reference_csv // tag::additional_reference_csv[] // end::additional_reference_csv[] === AdocUspSteps // tag::adocuspsteps[] // end::adocuspsteps[] === AntoraReferencedList // tag::antorareferencedlist[] * xref:dhw:sqldb:sqlparse.repoobject_sqlmodules_20_statement_children.adoc[] // end::antorareferencedlist[] === AntoraReferencingList // tag::antorareferencinglist[] * xref:dhw:sqldb:sqlparse.repoobject_sqlmodules_39_object.adoc[] // end::antorareferencinglist[] === Description // tag::description[] // end::description[] === exampleUsage // tag::exampleusage[] // end::exampleusage[] === exampleUsage_2 // tag::exampleusage_2[] // end::exampleusage_2[] === exampleUsage_3 // tag::exampleusage_3[] // end::exampleusage_3[] === exampleUsage_4 // tag::exampleusage_4[] // end::exampleusage_4[] === exampleUsage_5 // tag::exampleusage_5[] // end::exampleusage_5[] === exampleWrong_Usage // tag::examplewrong_usage[] // end::examplewrong_usage[] === has_execution_plan_issue // tag::has_execution_plan_issue[] // end::has_execution_plan_issue[] === has_get_referenced_issue // tag::has_get_referenced_issue[] // end::has_get_referenced_issue[] === has_history // tag::has_history[] // end::has_history[] === has_history_columns // tag::has_history_columns[] // end::has_history_columns[] === InheritanceType // tag::inheritancetype[] // end::inheritancetype[] === is_persistence // tag::is_persistence[] // end::is_persistence[] === is_persistence_check_duplicate_per_pk // tag::is_persistence_check_duplicate_per_pk[] // end::is_persistence_check_duplicate_per_pk[] === is_persistence_check_for_empty_source // tag::is_persistence_check_for_empty_source[] // end::is_persistence_check_for_empty_source[] === is_persistence_delete_changed // tag::is_persistence_delete_changed[] // end::is_persistence_delete_changed[] === is_persistence_delete_missing // tag::is_persistence_delete_missing[] // end::is_persistence_delete_missing[] === is_persistence_insert // tag::is_persistence_insert[] // end::is_persistence_insert[] === is_persistence_truncate // tag::is_persistence_truncate[] // end::is_persistence_truncate[] === is_persistence_update_changed // tag::is_persistence_update_changed[] // end::is_persistence_update_changed[] === is_repo_managed // tag::is_repo_managed[] 0 // end::is_repo_managed[] === is_ssas // tag::is_ssas[] 0 // end::is_ssas[] === microsoft_database_tools_support // tag::microsoft_database_tools_support[] // end::microsoft_database_tools_support[] === MS_Description // tag::ms_description[] // end::ms_description[] === persistence_source_RepoObject_fullname // tag::persistence_source_repoobject_fullname[] // end::persistence_source_repoobject_fullname[] === persistence_source_RepoObject_fullname2 // tag::persistence_source_repoobject_fullname2[] // end::persistence_source_repoobject_fullname2[] === persistence_source_RepoObject_guid // tag::persistence_source_repoobject_guid[] // end::persistence_source_repoobject_guid[] === persistence_source_RepoObject_xref // tag::persistence_source_repoobject_xref[] // end::persistence_source_repoobject_xref[] === pk_index_guid // tag::pk_index_guid[] F7EF4096-0799-EB11-84F4-A81E8446D5B0 // end::pk_index_guid[] === pk_IndexPatternColumnDatatype // tag::pk_indexpatterncolumndatatype[] uniqueidentifier,nvarchar(500) // end::pk_indexpatterncolumndatatype[] === pk_IndexPatternColumnName // tag::pk_indexpatterncolumnname[] RepoObject_guid,class // end::pk_indexpatterncolumnname[] === pk_IndexSemanticGroup // tag::pk_indexsemanticgroup[] // end::pk_indexsemanticgroup[] === ReferencedObjectList // tag::referencedobjectlist[] * [sqlparse].[RepoObject_SqlModules_20_statement_children] // end::referencedobjectlist[] === usp_persistence_RepoObject_guid // tag::usp_persistence_repoobject_guid[] // end::usp_persistence_repoobject_guid[] === UspExamples // tag::uspexamples[] // end::uspexamples[] === uspgenerator_usp_id // tag::uspgenerator_usp_id[] // end::uspgenerator_usp_id[] === UspParameters // tag::uspparameters[] // end::uspparameters[] == Boolean Attributes source: property.RepoObjectProperty WHERE property_int = 1 // tag::boolean_attributes[] // end::boolean_attributes[] == PlantUML diagrams === PlantUML Entity // tag::puml_entity[] [plantuml, entity-{docname}, svg, subs=macros] .... 'Left to right direction top to bottom direction hide circle 'avoide ""."" issues: set namespaceSeparator none skinparam class { BackgroundColor White BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<> LightGray BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<

    > Aqua BackgroundColor<> Aqua BackgroundColor<> Yellow BackgroundColor<> SlateBlue BackgroundColor<> LightGray BackgroundColor<> Tomato BackgroundColor<> White BackgroundColor<> WhiteSmoke BackgroundColor<> Aqua BackgroundColor<> AliceBlue } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_32_objectclass.adoc[]"" as sqlparse.RepoObject_SqlModules_32_ObjectClass << V >> { - **RepoObject_guid** : (uniqueidentifier) **class** : (nvarchar(500)) Min_RowNumber_per_class : (bigint) SysObject_fullname : (nvarchar(261)) -- } .... // end::puml_entity[] === PlantUML Entity 1 1 FK // tag::puml_entity_1_1_fk[] [plantuml, entity_1_1_fk-{docname}, svg, subs=macros] .... @startuml left to right direction 'top to bottom direction hide circle 'avoide ""."" issues: set namespaceSeparator none skinparam class { BackgroundColor White BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<> LightGray BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<

    > Aqua BackgroundColor<> Aqua BackgroundColor<> Yellow BackgroundColor<> SlateBlue BackgroundColor<> LightGray BackgroundColor<> Tomato BackgroundColor<> White BackgroundColor<> WhiteSmoke BackgroundColor<> Aqua BackgroundColor<> AliceBlue } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_32_objectclass.adoc[]"" as sqlparse.RepoObject_SqlModules_32_ObjectClass << V >> { - **PK_RepoObject_SqlModules_32_ObjectClass** .. RepoObject_guid; uniqueidentifier class; nvarchar(500) -- - idx_RepoObject_SqlModules_32_ObjectClass__2 .. RepoObject_guid; uniqueidentifier } footer The diagram is interactive and contains links. @enduml .... // end::puml_entity_1_1_fk[] === PlantUML 1 1 ObjectRef // tag::puml_entity_1_1_objectref[] [plantuml, entity_1_1_objectref-{docname}, svg, subs=macros] .... @startuml left to right direction 'top to bottom direction hide circle 'avoide ""."" issues: set namespaceSeparator none skinparam class { BackgroundColor White BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<> LightGray BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<

    > Aqua BackgroundColor<> Aqua BackgroundColor<> Yellow BackgroundColor<> SlateBlue BackgroundColor<> LightGray BackgroundColor<> Tomato BackgroundColor<> White BackgroundColor<> WhiteSmoke BackgroundColor<> Aqua BackgroundColor<> AliceBlue } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_20_statement_children.adoc[]"" as sqlparse.RepoObject_SqlModules_20_statement_children << V >> { - **RepoObject_guid** : (uniqueidentifier) - **json_key** : (nvarchar(4000)) -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_32_objectclass.adoc[]"" as sqlparse.RepoObject_SqlModules_32_ObjectClass << V >> { - **RepoObject_guid** : (uniqueidentifier) **class** : (nvarchar(500)) -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_39_object.adoc[]"" as sqlparse.RepoObject_SqlModules_39_object << V >> { -- } sqlparse.RepoObject_SqlModules_20_statement_children <.. sqlparse.RepoObject_SqlModules_32_ObjectClass sqlparse.RepoObject_SqlModules_32_ObjectClass <.. sqlparse.RepoObject_SqlModules_39_object footer The diagram is interactive and contains links. @enduml .... // end::puml_entity_1_1_objectref[] === PlantUML 30 0 ObjectRef // tag::puml_entity_30_0_objectref[] [plantuml, entity_30_0_objectref-{docname}, svg, subs=macros] .... @startuml 'Left to right direction top to bottom direction hide circle 'avoide ""."" issues: set namespaceSeparator none skinparam class { BackgroundColor White BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<> LightGray BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<

    > Aqua BackgroundColor<> Aqua BackgroundColor<> Yellow BackgroundColor<> SlateBlue BackgroundColor<> LightGray BackgroundColor<> Tomato BackgroundColor<> White BackgroundColor<> WhiteSmoke BackgroundColor<> Aqua BackgroundColor<> AliceBlue } entity ""puml-link:dhw:sqldb:config.ftv_get_parameter_value.adoc[]"" as config.ftv_get_parameter_value << IF >> { -- } entity ""puml-link:dhw:sqldb:config.parameter.adoc[]"" as config.Parameter << U >> { - **Parameter_name** : (varchar(100)) - **sub_Parameter** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:configt.parameter_default.adoc[]"" as configT.Parameter_default << V >> { - **Parameter_name** : (varchar(52)) - **sub_Parameter** : (nvarchar(26)) -- } entity ""puml-link:dhw:sqldb:property.external_repoobjectproperty.adoc[]"" as property.external_RepoObjectProperty << U >> { - **RepoObject_guid** : (uniqueidentifier) - **property_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:property.propertyname_repoobject.adoc[]"" as property.PropertyName_RepoObject << V >> { **property_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:property.propertyname_repoobject_t.adoc[]"" as property.PropertyName_RepoObject_T << U >> { **property_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:property.repoobjectproperty.adoc[]"" as property.RepoObjectProperty << U >> { - **RepoObjectProperty_id** : (int) -- } entity ""puml-link:dhw:sqldb:property.repoobjectproperty_external_src.adoc[]"" as property.RepoObjectProperty_external_src << V >> { - **RepoObject_guid** : (uniqueidentifier) - **property_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:property.repoobjectproperty_external_tgt.adoc[]"" as property.RepoObjectProperty_external_tgt << V >> { - **RepoObject_guid** : (uniqueidentifier) - **property_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:property.repoobjectproperty_selectedpropertyname_split.adoc[]"" as property.RepoObjectProperty_SelectedPropertyName_split << V >> { -- } entity ""puml-link:dhw:sqldb:reference.additional_reference.adoc[]"" as reference.additional_Reference << U >> { - **Id** : (int) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_from_properties_src.adoc[]"" as reference.additional_Reference_from_properties_src << V >> { **referenced_AntoraComponent** : (nvarchar(max)) **referenced_AntoraModule** : (nvarchar(max)) **referenced_Schema** : (nvarchar(max)) **referenced_Object** : (nvarchar(max)) **referenced_Column** : (nvarchar(max)) **referencing_AntoraComponent** : (nvarchar(max)) **referencing_AntoraModule** : (nvarchar(max)) **referencing_Schema** : (nvarchar(max)) **referencing_Object** : (nvarchar(max)) **referencing_Column** : (nvarchar(max)) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_from_properties_tgt.adoc[]"" as reference.additional_Reference_from_properties_tgt << V >> { **referenced_AntoraComponent** : (nvarchar(max)) **referenced_AntoraModule** : (nvarchar(max)) **referenced_Schema** : (nvarchar(max)) **referenced_Object** : (nvarchar(max)) **referenced_Column** : (nvarchar(max)) **referencing_AntoraComponent** : (nvarchar(max)) **referencing_AntoraModule** : (nvarchar(max)) **referencing_Schema** : (nvarchar(max)) **referencing_Object** : (nvarchar(max)) **referencing_Column** : (nvarchar(max)) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_from_ssas_src.adoc[]"" as reference.additional_Reference_from_ssas_src << V >> { **referenced_AntoraComponent** : (nvarchar(128)) **referenced_AntoraModule** : (nvarchar(128)) **referenced_Schema** : (nvarchar(max)) **referenced_Object** : (nvarchar(max)) **referenced_Column** : (nvarchar(500)) **referencing_AntoraComponent** : (nvarchar(max)) **referencing_AntoraModule** : (nvarchar(max)) - **referencing_Schema** : (nvarchar(128)) - **referencing_Object** : (nvarchar(128)) **referencing_Column** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_from_ssas_tgt.adoc[]"" as reference.additional_Reference_from_ssas_tgt << V >> { **referenced_AntoraComponent** : (nvarchar(128)) **referenced_AntoraModule** : (nvarchar(128)) **referenced_Schema** : (nvarchar(max)) **referenced_Object** : (nvarchar(max)) **referenced_Column** : (nvarchar(500)) **referencing_AntoraComponent** : (nvarchar(max)) **referencing_AntoraModule** : (nvarchar(max)) - **referencing_Schema** : (nvarchar(128)) - **referencing_Object** : (nvarchar(128)) **referencing_Column** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_is_external.adoc[]"" as reference.additional_Reference_is_external << V >> { -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_object.adoc[]"" as reference.additional_Reference_Object << V >> { - **AntoraComponent** : (nvarchar(128)) - **AntoraModule** : (nvarchar(128)) - **SchemaName** : (nvarchar(128)) - **ObjectName** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_object_t.adoc[]"" as reference.additional_Reference_Object_T << U >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_wo_columns_from_properties_src.adoc[]"" as reference.additional_Reference_wo_columns_from_properties_src << V >> { **referenced_AntoraComponent** : (nvarchar(max)) **referenced_AntoraModule** : (nvarchar(max)) **referenced_Schema** : (nvarchar(max)) **referenced_Object** : (nvarchar(max)) **referencing_AntoraComponent** : (nvarchar(max)) **referencing_AntoraModule** : (nvarchar(max)) **referencing_Schema** : (nvarchar(max)) **referencing_Object** : (nvarchar(max)) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_wo_columns_from_properties_tgt.adoc[]"" as reference.additional_Reference_wo_columns_from_properties_tgt << V >> { **referenced_AntoraComponent** : (nvarchar(max)) **referenced_AntoraModule** : (nvarchar(max)) **referenced_Schema** : (nvarchar(max)) **referenced_Object** : (nvarchar(max)) **referencing_AntoraComponent** : (nvarchar(max)) **referencing_AntoraModule** : (nvarchar(max)) **referencing_Schema** : (nvarchar(max)) **referencing_Object** : (nvarchar(max)) -- } entity ""puml-link:dhw:sqldb:repo.repoobject.adoc[]"" as repo.RepoObject << U >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobject_external_src.adoc[]"" as repo.RepoObject_external_src << V >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobject_external_tgt.adoc[]"" as repo.RepoObject_external_tgt << V >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobject_ssas_src.adoc[]"" as repo.RepoObject_SSAS_src << V >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobject_ssas_tgt.adoc[]"" as repo.RepoObject_SSAS_tgt << V >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.reposchema.adoc[]"" as repo.RepoSchema << U >> { - **RepoSchema_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.reposchema_ssas_src.adoc[]"" as repo.RepoSchema_ssas_src << V >> { - **RepoSchema_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:repo.reposchema_ssas_tgt.adoc[]"" as repo.RepoSchema_ssas_tgt << V >> { - **RepoSchema_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:sqlparse.ftv_sqlparse_with_some_children.adoc[]"" as sqlparse.ftv_sqlparse_with_some_children << IF >> { -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules.adoc[]"" as sqlparse.RepoObject_SqlModules << U >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_10_statement.adoc[]"" as sqlparse.RepoObject_SqlModules_10_statement << V >> { -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_20_statement_children.adoc[]"" as sqlparse.RepoObject_SqlModules_20_statement_children << V >> { - **RepoObject_guid** : (uniqueidentifier) - **json_key** : (nvarchar(4000)) -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_32_objectclass.adoc[]"" as sqlparse.RepoObject_SqlModules_32_ObjectClass << V >> { - **RepoObject_guid** : (uniqueidentifier) **class** : (nvarchar(500)) -- } entity ""puml-link:dhw:sqldb:ssas.additional_reference_step1.adoc[]"" as ssas.additional_Reference_step1 << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json.adoc[]"" as ssas.model_json << U >> { - **databasename** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_10.adoc[]"" as ssas.model_json_10 << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_20.adoc[]"" as ssas.model_json_20 << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_201_descriptions_multiline.adoc[]"" as ssas.model_json_201_descriptions_multiline << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_2011_descriptions_stragg.adoc[]"" as ssas.model_json_2011_descriptions_StrAgg << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_31_tables.adoc[]"" as ssas.model_json_31_tables << V >> { - **databasename** : (nvarchar(128)) **tables_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_31_tables_t.adoc[]"" as ssas.model_json_31_tables_T << U >> { - **databasename** : (nvarchar(128)) **tables_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_311_tables_columns.adoc[]"" as ssas.model_json_311_tables_columns << V >> { - **databasename** : (nvarchar(128)) - **tables_name** : (nvarchar(128)) **tables_columns_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_311_tables_columns_t.adoc[]"" as ssas.model_json_311_tables_columns_T << U >> { - **databasename** : (nvarchar(128)) - **tables_name** : (nvarchar(128)) **tables_columns_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_313_tables_partitions.adoc[]"" as ssas.model_json_313_tables_partitions << V >> { - **databasename** : (nvarchar(128)) - **tables_name** : (nvarchar(128)) **tables_partitions_name** : (nvarchar(500)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_3131_tables_partitions_source.adoc[]"" as ssas.model_json_3131_tables_partitions_source << V >> { - **databasename** : (nvarchar(128)) - **tables_name** : (nvarchar(128)) **tables_partitions_name** : (nvarchar(500)) **tables_partitions_source_name** : (nvarchar(500)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_31311_tables_partitions_source_posfrom.adoc[]"" as ssas.model_json_31311_tables_partitions_source_PosFrom << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_313111_tables_partitions_source_stringfrom.adoc[]"" as ssas.model_json_313111_tables_partitions_source_StringFrom << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_3131111_tables_partitions_source_posdot.adoc[]"" as ssas.model_json_3131111_tables_partitions_source_PosDot << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_31311111_tables_partitions_source_part123.adoc[]"" as ssas.model_json_31311111_tables_partitions_source_Part123 << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_33_datasources.adoc[]"" as ssas.model_json_33_dataSources << V >> { - **databasename** : (nvarchar(128)) **dataSources_name** : (nvarchar(500)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_33_datasources_t.adoc[]"" as ssas.model_json_33_dataSources_T << U >> { - **databasename** : (nvarchar(128)) **dataSources_name** : (nvarchar(500)) -- } config.ftv_get_parameter_value <.. repo.RepoObject_external_src config.ftv_get_parameter_value <.. reference.additional_Reference_is_external config.ftv_get_parameter_value <.. ssas.additional_Reference_step1 config.Parameter <.. config.ftv_get_parameter_value config.Parameter <.. property.PropertyName_RepoObject configT.Parameter_default <.. config.Parameter property.external_RepoObjectProperty <.. property.RepoObjectProperty_external_src property.PropertyName_RepoObject <.. property.PropertyName_RepoObject_T property.PropertyName_RepoObject_T <.. property.RepoObjectProperty_external_tgt property.RepoObjectProperty <.. property.PropertyName_RepoObject property.RepoObjectProperty <.. property.RepoObjectProperty_SelectedPropertyName_split property.RepoObjectProperty_external_src <.. property.RepoObjectProperty_external_tgt property.RepoObjectProperty_external_tgt <.. property.RepoObjectProperty property.RepoObjectProperty_SelectedPropertyName_split <.. reference.additional_Reference_from_properties_src property.RepoObjectProperty_SelectedPropertyName_split <.. reference.additional_Reference_wo_columns_from_properties_src reference.additional_Reference <.. reference.additional_Reference_is_external reference.additional_Reference_from_properties_src <.. reference.additional_Reference_from_properties_tgt reference.additional_Reference_from_properties_tgt <.. reference.additional_Reference reference.additional_Reference_from_ssas_src <.. reference.additional_Reference_from_ssas_tgt reference.additional_Reference_from_ssas_tgt <.. reference.additional_Reference reference.additional_Reference_is_external <.. reference.additional_Reference_Object reference.additional_Reference_Object <.. reference.additional_Reference_Object_T reference.additional_Reference_Object_T <.. repo.RepoObject_external_src reference.additional_Reference_wo_columns_from_properties_src <.. reference.additional_Reference_wo_columns_from_properties_tgt reference.additional_Reference_wo_columns_from_properties_tgt <.. reference.additional_Reference repo.RepoObject <.. sqlparse.RepoObject_SqlModules_10_statement repo.RepoObject <.. repo.RepoObject_external_src repo.RepoObject <.. property.RepoObjectProperty_external_tgt repo.RepoObject_external_src <.. repo.RepoObject_external_tgt repo.RepoObject_external_tgt <.. repo.RepoObject repo.RepoObject_SSAS_src <.. repo.RepoObject_SSAS_tgt repo.RepoObject_SSAS_tgt <.. repo.RepoObject repo.RepoSchema <.. repo.RepoObject_SSAS_src repo.RepoSchema_ssas_src <.. repo.RepoSchema_ssas_tgt repo.RepoSchema_ssas_tgt <.. repo.RepoSchema sqlparse.ftv_sqlparse_with_some_children <.. sqlparse.RepoObject_SqlModules_20_statement_children sqlparse.RepoObject_SqlModules <.. sqlparse.RepoObject_SqlModules_10_statement sqlparse.RepoObject_SqlModules_10_statement <.. sqlparse.RepoObject_SqlModules_20_statement_children sqlparse.RepoObject_SqlModules_20_statement_children <.. sqlparse.RepoObject_SqlModules_32_ObjectClass ssas.additional_Reference_step1 <.. reference.additional_Reference_from_ssas_src ssas.model_json <.. ssas.model_json_10 ssas.model_json_10 <.. ssas.model_json_20 ssas.model_json_20 <.. repo.RepoSchema_ssas_src ssas.model_json_20 <.. ssas.model_json_201_descriptions_multiline ssas.model_json_20 <.. ssas.model_json_31_tables ssas.model_json_20 <.. ssas.model_json_33_dataSources ssas.model_json_201_descriptions_multiline <.. ssas.model_json_2011_descriptions_StrAgg ssas.model_json_2011_descriptions_StrAgg <.. repo.RepoSchema_ssas_src ssas.model_json_31_tables <.. ssas.model_json_31_tables_T ssas.model_json_31_tables_T <.. repo.RepoObject_SSAS_src ssas.model_json_31_tables_T <.. ssas.model_json_311_tables_columns ssas.model_json_31_tables_T <.. ssas.model_json_313_tables_partitions ssas.model_json_311_tables_columns <.. ssas.model_json_311_tables_columns_T ssas.model_json_311_tables_columns_T <.. ssas.additional_Reference_step1 ssas.model_json_313_tables_partitions <.. ssas.model_json_3131_tables_partitions_source ssas.model_json_3131_tables_partitions_source <.. ssas.model_json_31311_tables_partitions_source_PosFrom ssas.model_json_31311_tables_partitions_source_PosFrom <.. ssas.model_json_313111_tables_partitions_source_StringFrom ssas.model_json_313111_tables_partitions_source_StringFrom <.. ssas.model_json_3131111_tables_partitions_source_PosDot ssas.model_json_3131111_tables_partitions_source_PosDot <.. ssas.model_json_31311111_tables_partitions_source_Part123 ssas.model_json_31311111_tables_partitions_source_Part123 <.. ssas.additional_Reference_step1 ssas.model_json_33_dataSources <.. ssas.model_json_33_dataSources_T ssas.model_json_33_dataSources_T <.. ssas.additional_Reference_step1 footer The diagram is interactive and contains links. @enduml .... // end::puml_entity_30_0_objectref[] === PlantUML 0 30 ObjectRef // tag::puml_entity_0_30_objectref[] [plantuml, entity_0_30_objectref-{docname}, svg, subs=macros] .... @startuml 'Left to right direction top to bottom direction hide circle 'avoide ""."" issues: set namespaceSeparator none skinparam class { BackgroundColor White BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<> LightGray BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<

    > Aqua BackgroundColor<> Aqua BackgroundColor<> Yellow BackgroundColor<> SlateBlue BackgroundColor<> LightGray BackgroundColor<> Tomato BackgroundColor<> White BackgroundColor<> WhiteSmoke BackgroundColor<> Aqua BackgroundColor<> AliceBlue } entity ""puml-link:dhw:sqldb:docs.antoranavlistpage_by_schema.adoc[]"" as docs.AntoraNavListPage_by_schema << V >> { -- } entity ""puml-link:dhw:sqldb:docs.ftv_repoobject_reference_plantuml_entityreflist.adoc[]"" as docs.ftv_RepoObject_Reference_PlantUml_EntityRefList << IF >> { -- } entity ""puml-link:dhw:sqldb:docs.objectrefcyclic.adoc[]"" as docs.ObjectRefCyclic << V >> { -- } entity ""puml-link:dhw:sqldb:docs.objectrefcyclic_entitylist.adoc[]"" as docs.ObjectRefCyclic_EntityList << V >> { -- } entity ""puml-link:dhw:sqldb:docs.repoobject_adoc.adoc[]"" as docs.RepoObject_Adoc << V >> { -- } entity ""puml-link:dhw:sqldb:docs.repoobject_adoc_t.adoc[]"" as docs.RepoObject_Adoc_T << U >> { - **RepoObject_guid** : (uniqueidentifier) - **cultures_name** : (nvarchar(10)) -- } entity ""puml-link:dhw:sqldb:docs.repoobject_columnlist.adoc[]"" as docs.RepoObject_ColumnList << V >> { -- } entity ""puml-link:dhw:sqldb:docs.repoobject_columnlist_t.adoc[]"" as docs.RepoObject_ColumnList_T << U >> { - **RepoObject_guid** : (uniqueidentifier) - **cultures_name** : (nvarchar(10)) -- } entity ""puml-link:dhw:sqldb:docs.repoobject_plantuml.adoc[]"" as docs.RepoObject_Plantuml << V >> { - **RepoObject_guid** : (uniqueidentifier) **cultures_name** : (nvarchar(10)) -- } entity ""puml-link:dhw:sqldb:docs.repoobject_plantuml_colreflist_1_1.adoc[]"" as docs.RepoObject_Plantuml_ColRefList_1_1 << V >> { -- } entity ""puml-link:dhw:sqldb:docs.repoobject_plantuml_entity.adoc[]"" as docs.RepoObject_Plantuml_Entity << V >> { -- } entity ""puml-link:dhw:sqldb:docs.repoobject_plantuml_entity_t.adoc[]"" as docs.RepoObject_Plantuml_Entity_T << U >> { - **RepoObject_guid** : (uniqueidentifier) - **cultures_name** : (nvarchar(10)) -- } entity ""puml-link:dhw:sqldb:docs.repoobject_plantuml_pumlentityfklist.adoc[]"" as docs.RepoObject_PlantUml_PumlEntityFkList << V >> { **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:docs.repoobject_plantuml_t.adoc[]"" as docs.RepoObject_Plantuml_T << U >> { - **RepoObject_guid** : (uniqueidentifier) **cultures_name** : (nvarchar(10)) -- } entity ""puml-link:dhw:sqldb:docs.schema_entitylist.adoc[]"" as docs.Schema_EntityList << V >> { - **RepoObject_schema_name** : (nvarchar(128)) - **cultures_name** : (nvarchar(10)) -- } entity ""puml-link:dhw:sqldb:docs.schema_puml.adoc[]"" as docs.Schema_puml << V >> { - **RepoSchema_guid** : (uniqueidentifier) **cultures_name** : (nvarchar(10)) -- } entity ""puml-link:dhw:sqldb:docs.usp_antoraexport.adoc[]"" as docs.usp_AntoraExport << P >> { -- } entity ""puml-link:dhw:sqldb:docs.usp_antoraexport_objectpartialscontent.adoc[]"" as docs.usp_AntoraExport_ObjectPartialsContent << P >> { -- } entity ""puml-link:dhw:sqldb:docs.usp_antoraexport_objectpuml.adoc[]"" as docs.usp_AntoraExport_ObjectPuml << P >> { -- } entity ""puml-link:dhw:sqldb:docs.usp_persist_repoobject_adoc_t.adoc[]"" as docs.usp_PERSIST_RepoObject_Adoc_T << P >> { -- } entity ""puml-link:dhw:sqldb:docs.usp_persist_repoobject_columnlist_t.adoc[]"" as docs.usp_PERSIST_RepoObject_ColumnList_T << P >> { -- } entity ""puml-link:dhw:sqldb:docs.usp_persist_repoobject_plantuml_entity_t.adoc[]"" as docs.usp_PERSIST_RepoObject_Plantuml_Entity_T << P >> { -- } entity ""puml-link:dhw:sqldb:docs.usp_persist_repoobject_plantuml_t.adoc[]"" as docs.usp_PERSIST_RepoObject_Plantuml_T << P >> { -- } entity ""puml-link:dhw:sqldb:property.repoobjectproperty_collect_source_rogross.adoc[]"" as property.RepoObjectProperty_Collect_source_ROGross << V >> { - **RepoObject_guid** : (uniqueidentifier) - **property_name** : (varchar(39)) -- } entity ""puml-link:dhw:sqldb:property.usp_repoobject_inheritance.adoc[]"" as property.usp_RepoObject_Inheritance << P >> { -- } entity ""puml-link:dhw:sqldb:property.usp_repoobjectproperty_collect.adoc[]"" as property.usp_RepoObjectProperty_collect << P >> { -- } entity ""puml-link:dhw:sqldb:reference.ftv_repoobject_columreferencerepoobject.adoc[]"" as reference.ftv_RepoObject_ColumReferenceRepoObject << IF >> { -- } entity ""puml-link:dhw:sqldb:reference.ftv_repoobject_dbmlcolumnrelation.adoc[]"" as reference.ftv_RepoObject_DbmlColumnRelation << IF >> { -- } entity ""puml-link:dhw:sqldb:reference.ftv_repoobjectcolumn_referencetree.adoc[]"" as reference.ftv_RepoObjectColumn_ReferenceTree << IF >> { -- } entity ""puml-link:dhw:sqldb:reference.repoobjectcolumn_reference.adoc[]"" as reference.RepoObjectColumn_reference << V >> { **referenced_RepoObjectColumn_guid** : (uniqueidentifier) **referencing_RepoObjectColumn_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:reference.repoobjectcolumn_reference_sqlmodules.adoc[]"" as reference.RepoObjectColumn_reference_SqlModules << V >> { **referencing_id** : (int) **referencing_minor_id** : (int) **referenced_id** : (int) **referenced_minor_id** : (int) -- } entity ""puml-link:dhw:sqldb:reference.repoobjectcolumn_reference_t.adoc[]"" as reference.RepoObjectColumn_reference_T << U >> { **referenced_RepoObjectColumn_guid** : (uniqueidentifier) **referencing_RepoObjectColumn_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:reference.repoobjectcolumn_reference_union.adoc[]"" as reference.RepoObjectColumn_reference_union << V >> { -- } entity ""puml-link:dhw:sqldb:reference.repoobjectcolumn_referencedlist.adoc[]"" as reference.RepoObjectColumn_ReferencedList << V >> { -- } entity ""puml-link:dhw:sqldb:reference.repoobjectcolumn_referencedreferencing.adoc[]"" as reference.RepoObjectColumn_ReferencedReferencing << V >> { -- } entity ""puml-link:dhw:sqldb:reference.repoobjectcolumn_referencetree.adoc[]"" as reference.RepoObjectColumn_ReferenceTree << V >> { -- } entity ""puml-link:dhw:sqldb:reference.repoobjectcolumn_referencinglist.adoc[]"" as reference.RepoObjectColumn_ReferencingList << V >> { -- } entity ""puml-link:dhw:sqldb:reference.repoobjectcolumn_relationscript.adoc[]"" as reference.RepoObjectColumn_RelationScript << V >> { -- } entity ""puml-link:dhw:sqldb:reference.usp_persist_repoobjectcolumn_reference_t.adoc[]"" as reference.usp_PERSIST_RepoObjectColumn_reference_T << P >> { -- } entity ""puml-link:dhw:sqldb:repo.check_indexcolumn_virtual_referenced_setpoint.adoc[]"" as repo.check_IndexColumn_virtual_referenced_setpoint << V >> { -- } entity ""puml-link:dhw:sqldb:repo.index_referencing_indexpatterncolumnguid.adoc[]"" as repo.Index_referencing_IndexPatternColumnGuid << V >> { **source_index_guid** : (uniqueidentifier) **referencing_RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.indexcolumn_referencedreferencing_hasfullcolumnsinreferencing.adoc[]"" as repo.IndexColumn_ReferencedReferencing_HasFullColumnsInReferencing << V >> { - **index_guid** : (uniqueidentifier) - **index_column_id** : (int) **RowNumberInReferencing** : (bigint) -- } entity ""puml-link:dhw:sqldb:repo.indexcolumn_referencedreferencing_hasfullcolumnsinreferencing_check.adoc[]"" as repo.IndexColumn_ReferencedReferencing_HasFullColumnsInReferencing_check << V >> { -- } entity ""puml-link:dhw:sqldb:repo.indexcolumn_referencedreferencing_hasfullcolumnsinreferencing_t.adoc[]"" as repo.IndexColumn_ReferencedReferencing_HasFullColumnsInReferencing_T << U >> { **index_guid** : (uniqueidentifier) - **index_column_id** : (int) **RowNumberInReferencing** : (bigint) -- } entity ""puml-link:dhw:sqldb:repo.indexcolumn_virtual_referenced_setpoint.adoc[]"" as repo.IndexColumn_virtual_referenced_setpoint << V >> { - **index_guid** : (uniqueidentifier) - **index_column_id** : (int) -- } entity ""puml-link:dhw:sqldb:repo.indexreferencedreferencing_hasfullcolumnsinreferencing.adoc[]"" as repo.IndexReferencedReferencing_HasFullColumnsInReferencing << V >> { -- } entity ""puml-link:dhw:sqldb:repo.repoobject_columnlist.adoc[]"" as repo.RepoObject_ColumnList << V >> { -- } entity ""puml-link:dhw:sqldb:repo.repoobject_gross2.adoc[]"" as repo.RepoObject_gross2 << V >> { -- } entity ""puml-link:dhw:sqldb:repo.repoobject_sat2.adoc[]"" as repo.RepoObject_sat2 << V >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobject_sat2_t.adoc[]"" as repo.RepoObject_sat2_T << U >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobject_sqlcreatetable.adoc[]"" as repo.RepoObject_SqlCreateTable << V >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobjectcolumn_gross2.adoc[]"" as repo.RepoObjectColumn_gross2 << V >> { -- } entity ""puml-link:dhw:sqldb:repo.repoobjectcolumn_missingsource_typev.adoc[]"" as repo.RepoObjectColumn_MissingSource_TypeV << V >> { -- } entity ""puml-link:dhw:sqldb:repo.usp_index_inheritance.adoc[]"" as repo.usp_index_inheritance << P >> { -- } entity ""puml-link:dhw:sqldb:repo.usp_main.adoc[]"" as repo.usp_main << P >> { -- } entity ""puml-link:dhw:sqldb:repo.usp_persist_indexcolumn_referencedreferencing_hasfullcolumnsinreferencing_t.adoc[]"" as repo.usp_PERSIST_IndexColumn_ReferencedReferencing_HasFullColumnsInReferencing_T << P >> { -- } entity ""puml-link:dhw:sqldb:repo.usp_persist_repoobject_sat2_t.adoc[]"" as repo.usp_PERSIST_RepoObject_sat2_T << P >> { -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_32_objectclass.adoc[]"" as sqlparse.RepoObject_SqlModules_32_ObjectClass << V >> { - **RepoObject_guid** : (uniqueidentifier) **class** : (nvarchar(500)) -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_39_object.adoc[]"" as sqlparse.RepoObject_SqlModules_39_object << V >> { -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_41_from.adoc[]"" as sqlparse.RepoObject_SqlModules_41_from << V >> { -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_41_from_t.adoc[]"" as sqlparse.RepoObject_SqlModules_41_from_T << U >> { -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_42_from_identifier.adoc[]"" as sqlparse.RepoObject_SqlModules_42_from_Identifier << V >> { -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_43_from_identifier.adoc[]"" as sqlparse.RepoObject_SqlModules_43_from_Identifier << V >> { -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_44_from_identifier_quotename.adoc[]"" as sqlparse.RepoObject_SqlModules_44_from_Identifier_QuoteName << V >> { -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_61_selectidentifier_union.adoc[]"" as sqlparse.RepoObject_SqlModules_61_SelectIdentifier_Union << V >> { -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_61_selectidentifier_union_t.adoc[]"" as sqlparse.RepoObject_SqlModules_61_SelectIdentifier_Union_T << U >> { -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_71_reference_explicitetablealias.adoc[]"" as sqlparse.RepoObject_SqlModules_71_reference_ExpliciteTableAlias << V >> { -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_72_reference_notablealias.adoc[]"" as sqlparse.RepoObject_SqlModules_72_reference_NoTableAlias << V >> { -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_79_reference_union.adoc[]"" as sqlparse.RepoObject_SqlModules_79_reference_union << V >> { -- } entity ""puml-link:dhw:sqldb:sqlparse.usp_persist_repoobject_sqlmodules_41_from_t.adoc[]"" as sqlparse.usp_PERSIST_RepoObject_SqlModules_41_from_T << P >> { -- } entity ""puml-link:dhw:sqldb:sqlparse.usp_persist_repoobject_sqlmodules_61_selectidentifier_union_t.adoc[]"" as sqlparse.usp_PERSIST_RepoObject_SqlModules_61_SelectIdentifier_Union_T << P >> { -- } entity ""puml-link:dhw:sqldb:sqlparse.usp_sqlparse.adoc[]"" as sqlparse.usp_sqlparse << P >> { -- } entity ""puml-link:dhw:sqldb:uspgenerator.generatoruspstep_persistence_src.adoc[]"" as uspgenerator.GeneratorUspStep_Persistence_src << V >> { - **usp_id** : (int) -- } entity ""puml-link:dhw:sqldb:uspgenerator.usp_generatorusp_insert_update_persistence.adoc[]"" as uspgenerator.usp_GeneratorUsp_insert_update_persistence << P >> { -- } docs.ftv_RepoObject_Reference_PlantUml_EntityRefList <.. docs.RepoObject_Plantuml docs.ObjectRefCyclic_EntityList <.. docs.ObjectRefCyclic docs.RepoObject_Adoc <.. docs.usp_PERSIST_RepoObject_Adoc_T docs.RepoObject_Adoc <.. docs.RepoObject_Adoc_T docs.REpoObject_Adoc_T <.. docs.usp_PERSIST_RepoObject_Adoc_T docs.RepoObject_ColumnList <.. docs.usp_PERSIST_RepoObject_ColumnList_T docs.RepoObject_ColumnList <.. docs.RepoObject_ColumnList_T docs.RepoObject_ColumnList_T <.. docs.RepoObject_Adoc docs.RepoObject_ColumnList_T <.. docs.RepoObject_Plantuml_Entity docs.RepoObject_ColumnList_T <.. docs.usp_PERSIST_RepoObject_ColumnList_T docs.RepoObject_Plantuml <.. docs.RepoObject_Plantuml_T docs.RepoObject_Plantuml <.. docs.usp_PERSIST_RepoObject_Plantuml_T docs.RepoObject_Plantuml_ColRefList_1_1 <.. docs.RepoObject_Plantuml docs.RepoObject_Plantuml_Entity <.. docs.RepoObject_Plantuml_Entity_T docs.RepoObject_Plantuml_Entity <.. docs.usp_PERSIST_RepoObject_Plantuml_Entity_T docs.RepoObject_Plantuml_Entity_T <.. docs.RepoObject_Adoc docs.RepoObject_Plantuml_Entity_T <.. docs.usp_PERSIST_RepoObject_Plantuml_Entity_T docs.RepoObject_Plantuml_Entity_T <.. docs.ftv_RepoObject_Reference_PlantUml_EntityRefList docs.RepoObject_Plantuml_Entity_T <.. docs.Schema_EntityList docs.RepoObject_Plantuml_Entity_T <.. docs.RepoObject_PlantUml_PumlEntityFkList docs.RepoObject_Plantuml_Entity_T <.. docs.ObjectRefCyclic_EntityList docs.RepoObject_PlantUml_PumlEntityFkList <.. docs.RepoObject_Plantuml docs.RepoObject_Plantuml_T <.. docs.RepoObject_Adoc docs.RepoObject_Plantuml_T <.. docs.usp_PERSIST_RepoObject_Plantuml_T docs.Schema_EntityList <.. docs.Schema_puml docs.Schema_puml <.. docs.AntoraNavListPage_by_schema docs.usp_AntoraExport_ObjectPartialsContent <.. docs.usp_AntoraExport docs.usp_AntoraExport_ObjectPuml <.. docs.usp_AntoraExport docs.usp_PERSIST_RepoObject_Adoc_T <.. docs.usp_AntoraExport_ObjectPartialsContent docs.usp_PERSIST_RepoObject_ColumnList_T <.. docs.usp_AntoraExport_ObjectPartialsContent docs.usp_PERSIST_RepoObject_Plantuml_Entity_T <.. docs.usp_AntoraExport_ObjectPuml docs.usp_PERSIST_RepoObject_Plantuml_T <.. docs.usp_AntoraExport_ObjectPuml property.RepoObjectProperty_Collect_source_ROGross <.. property.usp_RepoObjectProperty_collect property.usp_RepoObject_Inheritance <.. repo.usp_main property.usp_RepoObjectProperty_collect <.. property.usp_RepoObject_Inheritance property.usp_RepoObjectProperty_collect <.. repo.usp_main reference.ftv_RepoObjectColumn_ReferenceTree <.. reference.RepoObjectColumn_ReferenceTree reference.RepoObjectColumn_reference <.. reference.usp_PERSIST_RepoObjectColumn_reference_T reference.RepoObjectColumn_reference <.. reference.RepoObjectColumn_reference_T reference.RepoObjectColumn_reference_SqlModules <.. reference.RepoObjectColumn_reference_union reference.RepoObjectColumn_reference_T <.. docs.RepoObject_Plantuml_ColRefList_1_1 reference.RepoObjectColumn_reference_T <.. reference.usp_PERSIST_RepoObjectColumn_reference_T reference.RepoObjectColumn_reference_T <.. reference.RepoObjectColumn_ReferencedReferencing reference.RepoObjectColumn_reference_T <.. reference.RepoObjectColumn_RelationScript reference.RepoObjectColumn_reference_T <.. repo.RepoObjectColumn_MissingSource_TypeV reference.RepoObjectColumn_reference_T <.. repo.IndexColumn_ReferencedReferencing_HasFullColumnsInReferencing reference.RepoObjectColumn_reference_union <.. reference.RepoObjectColumn_reference reference.RepoObjectColumn_ReferencedList <.. repo.RepoObjectColumn_gross2 reference.RepoObjectColumn_ReferencedReferencing <.. reference.RepoObjectColumn_ReferencingList reference.RepoObjectColumn_ReferencedReferencing <.. reference.RepoObjectColumn_ReferencedList reference.RepoObjectColumn_ReferencedReferencing <.. reference.ftv_RepoObject_DbmlColumnRelation reference.RepoObjectColumn_ReferencedReferencing <.. reference.ftv_RepoObjectColumn_ReferenceTree reference.RepoObjectColumn_ReferenceTree <.. reference.ftv_RepoObject_ColumReferenceRepoObject reference.RepoObjectColumn_ReferencingList <.. repo.RepoObjectColumn_gross2 reference.RepoObjectColumn_RelationScript <.. reference.ftv_RepoObject_ColumReferenceRepoObject reference.usp_PERSIST_RepoObjectColumn_reference_T <.. repo.usp_main repo.Index_referencing_IndexPatternColumnGuid <.. repo.IndexReferencedReferencing_HasFullColumnsInReferencing repo.IndexColumn_ReferencedReferencing_HasFullColumnsInReferencing <.. repo.IndexColumn_ReferencedReferencing_HasFullColumnsInReferencing_T repo.IndexColumn_ReferencedReferencing_HasFullColumnsInReferencing <.. repo.usp_PERSIST_IndexColumn_ReferencedReferencing_HasFullColumnsInReferencing_T repo.IndexColumn_ReferencedReferencing_HasFullColumnsInReferencing_T <.. repo.IndexColumn_virtual_referenced_setpoint repo.IndexColumn_ReferencedReferencing_HasFullColumnsInReferencing_T <.. repo.IndexReferencedReferencing_HasFullColumnsInReferencing repo.IndexColumn_ReferencedReferencing_HasFullColumnsInReferencing_T <.. repo.Index_referencing_IndexPatternColumnGuid repo.IndexColumn_ReferencedReferencing_HasFullColumnsInReferencing_T <.. repo.usp_PERSIST_IndexColumn_ReferencedReferencing_HasFullColumnsInReferencing_T repo.IndexColumn_ReferencedReferencing_HasFullColumnsInReferencing_T <.. repo.IndexColumn_ReferencedReferencing_HasFullColumnsInReferencing_check repo.IndexColumn_virtual_referenced_setpoint <.. repo.check_IndexColumn_virtual_referenced_setpoint repo.IndexColumn_virtual_referenced_setpoint <.. repo.usp_index_inheritance repo.IndexReferencedReferencing_HasFullColumnsInReferencing <.. repo.usp_index_inheritance repo.RepoObject_ColumnList <.. repo.RepoObject_gross2 repo.RepoObject_ColumnList <.. repo.RepoObject_sat2 repo.RepoObject_ColumnList <.. repo.RepoObject_SqlCreateTable repo.RepoObject_gross2 <.. uspgenerator.GeneratorUspStep_Persistence_src repo.RepoObject_sat2 <.. repo.RepoObject_sat2_T repo.RepoObject_sat2 <.. repo.usp_PERSIST_RepoObject_sat2_T repo.RepoObject_sat2_T <.. repo.usp_PERSIST_RepoObject_sat2_T repo.RepoObject_sat2_T <.. docs.RepoObject_Adoc repo.RepoObject_sat2_T <.. property.RepoObjectProperty_Collect_source_ROGross repo.RepoObject_SqlCreateTable <.. reference.ftv_RepoObject_ColumReferenceRepoObject repo.RepoObjectColumn_gross2 <.. repo.RepoObject_ColumnList repo.RepoObjectColumn_gross2 <.. uspgenerator.usp_GeneratorUsp_insert_update_persistence repo.RepoObjectColumn_gross2 <.. docs.RepoObject_ColumnList repo.usp_index_inheritance <.. repo.usp_main repo.usp_PERSIST_IndexColumn_ReferencedReferencing_HasFullColumnsInReferencing_T <.. repo.usp_index_inheritance repo.usp_PERSIST_RepoObject_sat2_T <.. repo.usp_main sqlparse.RepoObject_SqlModules_32_ObjectClass <.. sqlparse.RepoObject_SqlModules_39_object sqlparse.RepoObject_SqlModules_39_object <.. sqlparse.RepoObject_SqlModules_41_from sqlparse.RepoObject_SqlModules_39_object <.. sqlparse.RepoObject_SqlModules_61_SelectIdentifier_Union sqlparse.RepoObject_SqlModules_41_from <.. sqlparse.usp_PERSIST_RepoObject_SqlModules_41_from_T sqlparse.RepoObject_SqlModules_41_from <.. sqlparse.RepoObject_SqlModules_41_from_T sqlparse.RepoObject_SqlModules_41_from_T <.. sqlparse.RepoObject_SqlModules_42_from_Identifier sqlparse.RepoObject_SqlModules_41_from_T <.. sqlparse.usp_PERSIST_RepoObject_SqlModules_41_from_T sqlparse.RepoObject_SqlModules_42_from_Identifier <.. sqlparse.RepoObject_SqlModules_43_from_Identifier sqlparse.RepoObject_SqlModules_43_from_Identifier <.. sqlparse.RepoObject_SqlModules_44_from_Identifier_QuoteName sqlparse.RepoObject_SqlModules_44_from_Identifier_QuoteName <.. sqlparse.RepoObject_SqlModules_71_reference_ExpliciteTableAlias sqlparse.RepoObject_SqlModules_44_from_Identifier_QuoteName <.. sqlparse.RepoObject_SqlModules_72_reference_NoTableAlias sqlparse.RepoObject_SqlModules_61_SelectIdentifier_Union <.. sqlparse.RepoObject_SqlModules_61_SelectIdentifier_Union_T sqlparse.RepoObject_SqlModules_61_SelectIdentifier_Union <.. sqlparse.usp_PERSIST_RepoObject_SqlModules_61_SelectIdentifier_Union_T sqlparse.RepoObject_SqlModules_61_SelectIdentifier_Union_T <.. sqlparse.RepoObject_SqlModules_71_reference_ExpliciteTableAlias sqlparse.RepoObject_SqlModules_61_SelectIdentifier_Union_T <.. sqlparse.RepoObject_SqlModules_72_reference_NoTableAlias sqlparse.RepoObject_SqlModules_61_SelectIdentifier_Union_T <.. sqlparse.usp_PERSIST_RepoObject_SqlModules_61_SelectIdentifier_Union_T sqlparse.RepoObject_SqlModules_71_reference_ExpliciteTableAlias <.. sqlparse.RepoObject_SqlModules_79_reference_union sqlparse.RepoObject_SqlModules_72_reference_NoTableAlias <.. sqlparse.RepoObject_SqlModules_79_reference_union sqlparse.RepoObject_SqlModules_79_reference_union <.. reference.RepoObjectColumn_reference_SqlModules sqlparse.usp_PERSIST_RepoObject_SqlModules_41_from_T <.. sqlparse.usp_sqlparse sqlparse.usp_PERSIST_RepoObject_SqlModules_61_SelectIdentifier_Union_T <.. sqlparse.usp_sqlparse uspgenerator.GeneratorUspStep_Persistence_src <.. uspgenerator.usp_GeneratorUsp_insert_update_persistence uspgenerator.usp_GeneratorUsp_insert_update_persistence <.. repo.usp_main footer The diagram is interactive and contains links. @enduml .... // end::puml_entity_0_30_objectref[] === PlantUML 1 1 ColumnRef // tag::puml_entity_1_1_colref[] [plantuml, entity_1_1_colref-{docname}, svg, subs=macros] .... @startuml left to right direction 'top to bottom direction hide circle 'avoide ""."" issues: set namespaceSeparator none skinparam class { BackgroundColor White BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<> LightGray BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<

    > Aqua BackgroundColor<> Aqua BackgroundColor<> Yellow BackgroundColor<> SlateBlue BackgroundColor<> LightGray BackgroundColor<> Tomato BackgroundColor<> White BackgroundColor<> WhiteSmoke BackgroundColor<> Aqua BackgroundColor<> AliceBlue } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_20_statement_children.adoc[]"" as sqlparse.RepoObject_SqlModules_20_statement_children << V >> { - **RepoObject_guid** : (uniqueidentifier) - **json_key** : (nvarchar(4000)) child0_children : (nvarchar(max)) child0_class : (nvarchar(500)) child0_is_group : (bit) child0_is_keyword : (bit) child0_is_whitespace : (bit) child0_normalized : (nvarchar(max)) child1_children : (nvarchar(max)) child1_class : (nvarchar(500)) child1_is_group : (bit) child1_is_keyword : (bit) child1_is_whitespace : (bit) child1_normalized : (nvarchar(max)) child2_children : (nvarchar(max)) child2_class : (nvarchar(500)) child2_is_group : (bit) child2_is_keyword : (bit) child2_is_whitespace : (bit) child2_normalized : (nvarchar(max)) child3_children : (nvarchar(max)) child3_class : (nvarchar(500)) child3_is_group : (bit) child3_is_keyword : (bit) child3_is_whitespace : (bit) child3_normalized : (nvarchar(max)) child4_children : (nvarchar(max)) child4_class : (nvarchar(500)) child4_is_group : (bit) child4_is_keyword : (bit) child4_is_whitespace : (bit) child4_normalized : (nvarchar(max)) children : (nvarchar(max)) class : (nvarchar(500)) is_group : (bit) is_keyword : (bit) is_whitespace : (bit) normalized : (nvarchar(max)) RowNumber_per_Object : (bigint) SysObject_fullname : (nvarchar(261)) -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_32_objectclass.adoc[]"" as sqlparse.RepoObject_SqlModules_32_ObjectClass << V >> { - **RepoObject_guid** : (uniqueidentifier) **class** : (nvarchar(500)) Min_RowNumber_per_class : (bigint) SysObject_fullname : (nvarchar(261)) -- } entity ""puml-link:dhw:sqldb:sqlparse.repoobject_sqlmodules_39_object.adoc[]"" as sqlparse.RepoObject_SqlModules_39_object << V >> { has_GroupBy : (int) is_1_create : (int) is_2_view : (int) is_3_Identifier : (int) is_4_as : (int) is_5_select : (int) is_6_Identifier : (int) is_6_IdentifierList : (int) is_7_from : (int) is_7_IdentifierList : (int) is_8_IdentifierList : (int) is_create_view_Identifier_as_select : (int) is_select_IdentifierList_from : (int) is_union : (int) Min_RowNumber_From : (bigint) Min_RowNumber_GroupBy : (bigint) Min_RowNumber_IdentifierList : (bigint) Min_RowNumber_Where : (bigint) - RepoObject_guid : (uniqueidentifier) SysObject_fullname : (nvarchar(261)) -- } sqlparse.RepoObject_SqlModules_20_statement_children <.. sqlparse.RepoObject_SqlModules_32_ObjectClass sqlparse.RepoObject_SqlModules_32_ObjectClass <.. sqlparse.RepoObject_SqlModules_39_object ""sqlparse.RepoObject_SqlModules_20_statement_children::class"" <-- ""sqlparse.RepoObject_SqlModules_32_ObjectClass::class"" ""sqlparse.RepoObject_SqlModules_20_statement_children::RepoObject_guid"" <-- ""sqlparse.RepoObject_SqlModules_32_ObjectClass::RepoObject_guid"" ""sqlparse.RepoObject_SqlModules_20_statement_children::SysObject_fullname"" <-- ""sqlparse.RepoObject_SqlModules_32_ObjectClass::SysObject_fullname"" ""sqlparse.RepoObject_SqlModules_32_ObjectClass::Min_RowNumber_per_class"" <-- ""sqlparse.RepoObject_SqlModules_39_object::Min_RowNumber_Where"" ""sqlparse.RepoObject_SqlModules_32_ObjectClass::Min_RowNumber_per_class"" <-- ""sqlparse.RepoObject_SqlModules_39_object::Min_RowNumber_IdentifierList"" footer The diagram is interactive and contains links. @enduml .... // end::puml_entity_1_1_colref[] == sql_modules_definition // tag::sql_modules_definition[] [%collapsible] ======= [source,sql,numbered,indent=0] ---- CREATE View sqlparse.RepoObject_SqlModules_32_ObjectClass As -- Select T1.RepoObject_guid , T1.class , SysObject_fullname = Max ( T1.SysObject_fullname ) , Min_RowNumber_per_class = Min ( T1.RowNumber_per_Object ) From sqlparse.RepoObject_SqlModules_20_statement_children As T1 Group By T1.RepoObject_guid , T1.class ---- ======= // end::sql_modules_definition[] ",16161,True,3544.8901862911257,median "= Lint == Lint/AmbiguousBlockAssociation |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.48 | - |=== This cop checks for ambiguous block association with method when param passed without parentheses. === Examples [source,ruby] ---- # bad some_method a { |val| puts val } ---- [source,ruby] ---- # good # With parentheses, there's no ambiguity. some_method(a) { |val| puts val } # good # Operator methods require no disambiguation foo == bar { |b| b.baz } # good # Lambda arguments require no disambiguation foo = ->(bar) { bar.baz } ---- === References * https://rubystyle.guide#syntax == Lint/AmbiguousOperator |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.17 | 0.83 |=== This cop checks for ambiguous operators in the first argument of a method invocation without parentheses. === Examples [source,ruby] ---- # bad # The `*` is interpreted as a splat operator but it could possibly be # a `*` method invocation (i.e. `do_something.*(some_array)`). do_something *some_array ---- [source,ruby] ---- # good # With parentheses, there's no ambiguity. do_something(*some_array) ---- === References * https://rubystyle.guide#method-invocation-parens == Lint/AmbiguousRegexpLiteral |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.17 | 0.83 |=== This cop checks for ambiguous regexp literals in the first argument of a method invocation without parentheses. === Examples [source,ruby] ---- # bad # This is interpreted as a method invocation with a regexp literal, # but it could possibly be `/` method invocations. # (i.e. `do_something./(pattern)./(i)`) do_something /pattern/i ---- [source,ruby] ---- # good # With parentheses, there's no ambiguity. do_something(/pattern/i) ---- == Lint/AssignmentInCondition |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.9 | - |=== This cop checks for assignments in the conditions of if/while/until. `AllowSafeAssignment` option for safe assignment. By safe assignment we mean putting parentheses around an assignment to indicate ""I know I'm using an assignment as a condition. It's not a mistake."" === Examples [source,ruby] ---- # bad if some_var = true do_something end # good if some_var == true do_something end ---- ==== AllowSafeAssignment: true (default) [source,ruby] ---- # good if (some_var = true) do_something end ---- ==== AllowSafeAssignment: false [source,ruby] ---- # bad if (some_var = true) do_something end ---- === Configurable attributes |=== | Name | Default value | Configurable values | AllowSafeAssignment | `true` | Boolean |=== === References * https://rubystyle.guide#safe-assignment-in-condition == Lint/BigDecimalNew |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.53 | - |=== `BigDecimal.new()` is deprecated since BigDecimal 1.3.3. This cop identifies places where `BigDecimal.new()` can be replaced by `BigDecimal()`. === Examples [source,ruby] ---- # bad BigDecimal.new(123.456, 3) # good BigDecimal(123.456, 3) ---- == Lint/BooleanSymbol |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | No | Yes (Unsafe) | 0.50 | 0.83 |=== This cop checks for `:true` and `:false` symbols. In most cases it would be a typo. === Examples [source,ruby] ---- # bad :true # good true ---- [source,ruby] ---- # bad :false # good false ---- == Lint/CircularArgumentReference |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.33 | - |=== This cop checks for circular argument references in optional keyword arguments and optional ordinal arguments. This cop mirrors a warning produced by MRI since 2.2. === Examples [source,ruby] ---- # bad def bake(pie: pie) pie.heat_up end ---- [source,ruby] ---- # good def bake(pie:) pie.refrigerate end ---- [source,ruby] ---- # good def bake(pie: self.pie) pie.feed_to(user) end ---- [source,ruby] ---- # bad def cook(dry_ingredients = dry_ingredients) dry_ingredients.reduce(&:+) end ---- [source,ruby] ---- # good def cook(dry_ingredients = self.dry_ingredients) dry_ingredients.combine end ---- == Lint/Debugger |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.14 | 0.49 |=== This cop checks for calls to debugger or pry. === Examples [source,ruby] ---- # bad (ok during development) # using pry def some_method binding.pry do_something end ---- [source,ruby] ---- # bad (ok during development) # using byebug def some_method byebug do_something end ---- [source,ruby] ---- # good def some_method do_something end ---- == Lint/DeprecatedClassMethods |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.19 | - |=== This cop checks for uses of the deprecated class method usages. === Examples [source,ruby] ---- # bad File.exists?(some_path) Dir.exists?(some_path) iterator? ---- [source,ruby] ---- # good File.exist?(some_path) Dir.exist?(some_path) block_given? ---- == Lint/DeprecatedOpenSSLConstant |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Pending | Yes | Yes | 0.84 | - |=== Algorithmic constants for `OpenSSL::Cipher` and `OpenSSL::Digest` deprecated since OpenSSL version 2.2.0. Prefer passing a string instead. === Examples [source,ruby] ---- # Example for OpenSSL::Cipher instantiation. # bad OpenSSL::Cipher::AES.new(128, :GCM) # good OpenSSL::Cipher.new('AES-128-GCM') ---- [source,ruby] ---- # Example for OpenSSL::Digest instantiation. # bad OpenSSL::Digest::SHA256.new # good OpenSSL::Digest.new('SHA256') ---- [source,ruby] ---- # Example for ::Digest inherited class methods. # bad OpenSSL::Digest::SHA256.digest('foo') # good OpenSSL::Digest.digest('SHA256', 'foo') ---- == Lint/DisjunctiveAssignmentInConstructor |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | No | No | 0.62 | - |=== This cop checks constructors for disjunctive assignments that should be plain assignments. So far, this cop is only concerned with disjunctive assignment of instance variables. In ruby, an instance variable is nil until a value is assigned, so the disjunction is unnecessary. A plain assignment has the same effect. === Examples [source,ruby] ---- # bad def initialize @x ||= 1 end # good def initialize @x = 1 end ---- == Lint/DuplicateCaseCondition |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.45 | - |=== This cop checks that there are no repeated conditions used in case 'when' expressions. === Examples [source,ruby] ---- # bad case x when 'first' do_something when 'first' do_something_else end ---- [source,ruby] ---- # good case x when 'first' do_something when 'second' do_something_else end ---- == Lint/DuplicateHashKey |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.34 | 0.77 |=== This cop checks for duplicated keys in hash literals. This cop mirrors a warning in Ruby 2.2. === Examples [source,ruby] ---- # bad hash = { food: 'apple', food: 'orange' } ---- [source,ruby] ---- # good hash = { food: 'apple', other_food: 'orange' } ---- == Lint/DuplicateMethods |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.29 | - |=== This cop checks for duplicated instance (or singleton) method definitions. === Examples [source,ruby] ---- # bad def foo 1 end def foo 2 end ---- [source,ruby] ---- # bad def foo 1 end alias foo bar ---- [source,ruby] ---- # good def foo 1 end def bar 2 end ---- [source,ruby] ---- # good def foo 1 end alias bar foo ---- == Lint/EachWithObjectArgument |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.31 | - |=== This cop checks if each_with_object is called with an immutable argument. Since the argument is the object that the given block shall make calls on to build something based on the enumerable that each_with_object iterates over, an immutable argument makes no sense. It's definitely a bug. === Examples [source,ruby] ---- # bad sum = numbers.each_with_object(0) { |e, a| a += e } ---- [source,ruby] ---- # good num = 0 sum = numbers.each_with_object(num) { |e, a| a += e } ---- == Lint/ElseLayout |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.17 | - |=== This cop checks for odd else block layout - like having an expression on the same line as the else keyword, which is usually a mistake. === Examples [source,ruby] ---- # bad if something # ... else do_this do_that end ---- [source,ruby] ---- # good if something # ... else do_this do_that end ---- == Lint/EmptyEnsure |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.10 | 0.48 |=== This cop checks for empty `ensure` blocks === Examples [source,ruby] ---- # bad def some_method do_something ensure end ---- [source,ruby] ---- # bad begin do_something ensure end ---- [source,ruby] ---- # good def some_method do_something ensure do_something_else end ---- [source,ruby] ---- # good begin do_something ensure do_something_else end ---- === Configurable attributes |=== | Name | Default value | Configurable values | AutoCorrect | `false` | Boolean |=== == Lint/EmptyExpression |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.45 | - |=== This cop checks for the presence of empty expressions. === Examples [source,ruby] ---- # bad foo = () if () bar end ---- [source,ruby] ---- # good foo = (some_expression) if (some_expression) bar end ---- == Lint/EmptyInterpolation |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.20 | 0.45 |=== This cop checks for empty interpolation. === Examples [source,ruby] ---- # bad ""result is #{}"" ---- [source,ruby] ---- # good ""result is #{some_result}"" ---- == Lint/EmptyWhen |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.45 | 0.83 |=== This cop checks for the presence of `when` branches without a body. === Examples [source,ruby] ---- # bad case foo when bar do_something when baz end ---- [source,ruby] ---- # good case condition when foo do_something when bar nil end ---- ==== AllowComments: true (default) [source,ruby] ---- # good case condition when foo do_something when bar # noop end ---- ==== AllowComments: false [source,ruby] ---- # bad case condition when foo do_something when bar # do nothing end ---- === Configurable attributes |=== | Name | Default value | Configurable values | AllowComments | `true` | Boolean |=== == Lint/EnsureReturn |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.9 | 0.83 |=== This cop checks for `return` from an `ensure` block. Explicit return from an ensure block alters the control flow as the return will take precedence over any exception being raised, and the exception will be silently thrown away as if it were rescued. === Examples [source,ruby] ---- # bad begin do_something ensure do_something_else return end ---- [source,ruby] ---- # good begin do_something ensure do_something_else end ---- === References * https://rubystyle.guide#no-return-ensure == Lint/ErbNewArguments NOTE: Required Ruby version: 2.6 |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.56 | - |=== This cop emulates the following Ruby warnings in Ruby 2.6. % cat example.rb ERB.new('hi', nil, '-', '@output_buffer') % ruby -rerb example.rb example.rb:1: warning: Passing safe_level with the 2nd argument of ERB.new is deprecated. Do not use it, and specify other arguments as keyword arguments. example.rb:1: warning: Passing trim_mode with the 3rd argument of ERB.new is deprecated. Use keyword argument like ERB.new(str, trim_mode:...) instead. example.rb:1: warning: Passing eoutvar with the 4th argument of ERB.new is deprecated. Use keyword argument like ERB.new(str, eoutvar: ...) instead. Now non-keyword arguments other than first one are softly deprecated and will be removed when Ruby 2.5 becomes EOL. `ERB.new` with non-keyword arguments is deprecated since ERB 2.2.0. Use `:trim_mode` and `:eoutvar` keyword arguments to `ERB.new`. This cop identifies places where `ERB.new(str, trim_mode, eoutvar)` can be replaced by `ERB.new(str, :trim_mode: trim_mode, eoutvar: eoutvar)`. === Examples [source,ruby] ---- # Target codes supports Ruby 2.6 and higher only # bad ERB.new(str, nil, '-', '@output_buffer') # good ERB.new(str, trim_mode: '-', eoutvar: '@output_buffer') # Target codes supports Ruby 2.5 and lower only # good ERB.new(str, nil, '-', '@output_buffer') # Target codes supports Ruby 2.6, 2.5 and lower # bad ERB.new(str, nil, '-', '@output_buffer') # good # Ruby standard library style # https://github.com/ruby/ruby/commit/3406c5d if ERB.instance_method(:initialize).parameters.assoc(:key) # Ruby 2.6+ ERB.new(str, trim_mode: '-', eoutvar: '@output_buffer') else ERB.new(str, nil, '-', '@output_buffer') end # good # Use `RUBY_VERSION` style if RUBY_VERSION >= '2.6' ERB.new(str, trim_mode: '-', eoutvar: '@output_buffer') else ERB.new(str, nil, '-', '@output_buffer') end ---- == Lint/FlipFlop |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.16 | - |=== This cop looks for uses of flip-flop operator. flip-flop operator is deprecated since Ruby 2.6.0. === Examples [source,ruby] ---- # bad (1..20).each do |x| puts x if (x == 5) .. (x == 10) end # good (1..20).each do |x| puts x if (x >= 5) && (x <= 10) end ---- === References * https://rubystyle.guide#no-flip-flops == Lint/FloatOutOfRange |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.36 | - |=== This cop identifies Float literals which are, like, really really really really really really really really big. Too big. No-one needs Floats that big. If you need a float that big, something is wrong with you. === Examples [source,ruby] ---- # bad float = 3.0e400 ---- [source,ruby] ---- # good float = 42.9 ---- == Lint/FormatParameterMismatch |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.33 | - |=== This lint sees if there is a mismatch between the number of expected fields for format/sprintf/#% and what is actually passed as arguments. === Examples [source,ruby] ---- # bad format('A value: %s and another: %i', a_value) ---- [source,ruby] ---- # good format('A value: %s and another: %i', a_value, another) ---- == Lint/HeredocMethodCallPosition |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Disabled | Yes | Yes | 0.68 | - |=== This cop checks for the ordering of a method call where the receiver of the call is a HEREDOC. === Examples [source,ruby] ---- # bad <<-SQL bar SQL .strip_indent <<-SQL bar SQL .strip_indent .trim # good <<~SQL bar SQL <<~SQL.trim bar SQL ---- === References * https://rubystyle.guide#heredoc-method-calls == Lint/ImplicitStringConcatenation |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.36 | - |=== This cop checks for implicit string concatenation of string literals which are on the same line. === Examples [source,ruby] ---- # bad array = ['Item 1' 'Item 2'] ---- [source,ruby] ---- # good array = ['Item 1Item 2'] array = ['Item 1' + 'Item 2'] array = [ 'Item 1' \\ 'Item 2' ] ---- == Lint/IneffectiveAccessModifier |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.36 | - |=== This cop checks for `private` or `protected` access modifiers which are applied to a singleton method. These access modifiers do not make singleton methods private/protected. `private_class_method` can be used for that. === Examples [source,ruby] ---- # bad class C private def self.method puts 'hi' end end ---- [source,ruby] ---- # good class C def self.method puts 'hi' end private_class_method :method end ---- [source,ruby] ---- # good class C class << self private def method puts 'hi' end end end ---- == Lint/InheritException |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.41 | - |=== This cop looks for error classes inheriting from `Exception` and its standard library subclasses, excluding subclasses of `StandardError`. It is configurable to suggest using either `RuntimeError` (default) or `StandardError` instead. === Examples ==== EnforcedStyle: runtime_error (default) [source,ruby] ---- # bad class C < Exception; end C = Class.new(Exception) # good class C < RuntimeError; end C = Class.new(RuntimeError) ---- ==== EnforcedStyle: standard_error [source,ruby] ---- # bad class C < Exception; end C = Class.new(Exception) # good class C < StandardError; end C = Class.new(StandardError) ---- === Configurable attributes |=== | Name | Default value | Configurable values | EnforcedStyle | `runtime_error` | `runtime_error`, `standard_error` |=== == Lint/InterpolationCheck |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.50 | - |=== This cop checks for interpolation in a single quoted string. === Examples [source,ruby] ---- # bad foo = 'something with #{interpolation} inside' ---- [source,ruby] ---- # good foo = ""something with #{interpolation} inside"" ---- == Lint/LiteralAsCondition |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.51 | - |=== This cop checks for literals used as the conditions or as operands in and/or expressions serving as the conditions of if/while/until. === Examples [source,ruby] ---- # bad if 20 do_something end # bad if some_var && true do_something end # good if some_var && some_condition do_something end # good # When using a boolean value for an infinite loop. while true break if condition end ---- == Lint/LiteralInInterpolation |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.19 | 0.32 |=== This cop checks for interpolated literals. === Examples [source,ruby] ---- # bad ""result is #{10}"" ---- [source,ruby] ---- # good ""result is 10"" ---- == Lint/Loop |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.9 | - |=== This cop checks for uses of `begin...end while/until something`. === Examples [source,ruby] ---- # bad # using while begin do_something end while some_condition ---- [source,ruby] ---- # bad # using until begin do_something end until some_condition ---- [source,ruby] ---- # good # while replacement loop do do_something break unless some_condition end ---- [source,ruby] ---- # good # until replacement loop do do_something break if some_condition end ---- === References * https://rubystyle.guide#loop-with-break == Lint/MissingCopEnableDirective |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.52 | - |=== This cop checks that there is an `# rubocop:enable ...` statement after a `# rubocop:disable ...` statement. This will prevent leaving cop disables on wide ranges of code, that latter contributors to a file wouldn't be aware of. === Examples [source,ruby] ---- # Lint/MissingCopEnableDirective: # MaximumRangeSize: .inf # good # rubocop:disable Layout/SpaceAroundOperators x= 0 # rubocop:enable Layout/SpaceAroundOperators # y = 1 # EOF # bad # rubocop:disable Layout/SpaceAroundOperators x= 0 # EOF ---- [source,ruby] ---- # Lint/MissingCopEnableDirective: # MaximumRangeSize: 2 # good # rubocop:disable Layout/SpaceAroundOperators x= 0 # With the previous, there are 2 lines on which cop is disabled. # rubocop:enable Layout/SpaceAroundOperators # bad # rubocop:disable Layout/SpaceAroundOperators x= 0 x += 1 # Including this, that's 3 lines on which the cop is disabled. # rubocop:enable Layout/SpaceAroundOperators ---- === Configurable attributes |=== | Name | Default value | Configurable values | MaximumRangeSize | `Infinity` | Float |=== == Lint/MultipleComparison |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.47 | 0.77 |=== In math and Python, we can use `x < y < z` style comparison to compare multiple value. However, we can't use the comparison in Ruby. However, the comparison is not syntax error. This cop checks the bad usage of comparison operators. === Examples [source,ruby] ---- # bad x < y < z 10 <= x <= 20 ---- [source,ruby] ---- # good x < y && y < z 10 <= x && x <= 20 ---- == Lint/NestedMethodDefinition |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.32 | - |=== This cop checks for nested method definitions. === Examples [source,ruby] ---- # bad # `bar` definition actually produces methods in the same scope # as the outer `foo` method. Furthermore, the `bar` method # will be redefined every time `foo` is invoked. def foo def bar end end ---- [source,ruby] ---- # good def foo bar = -> { puts 'hello' } bar.call end ---- [source,ruby] ---- # good def foo self.class.class_eval do def bar end end end def foo self.class.module_exec do def bar end end end ---- [source,ruby] ---- # good def foo class << self def bar end end end ---- === References * https://rubystyle.guide#no-nested-methods == Lint/NestedPercentLiteral |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.52 | - |=== This cop checks for nested percent literals. === Examples [source,ruby] ---- # bad # The percent literal for nested_attributes is parsed as four tokens, # yielding the array [:name, :content, :""%i[incorrectly"", :""nested]""]. attributes = { valid_attributes: %i[name content], nested_attributes: %i[name content %i[incorrectly nested]] } ---- == Lint/NextWithoutAccumulator |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.36 | - |=== Don't omit the accumulator when calling `next` in a `reduce` block. === Examples [source,ruby] ---- # bad result = (1..4).reduce(0) do |acc, i| next if i.odd? acc + i end ---- [source,ruby] ---- # good result = (1..4).reduce(0) do |acc, i| next acc if i.odd? acc + i end ---- == Lint/NonDeterministicRequireOrder |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | No | Yes (Unsafe) | 0.78 | - |=== `Dir[...]` and `Dir.glob(...)` do not make any guarantees about the order in which files are returned. The final order is determined by the operating system and file system. This means that using them in cases where the order matters, such as requiring files, can lead to intermittent failures that are hard to debug. To ensure this doesn't happen, always sort the list. === Examples [source,ruby] ---- # bad Dir[""./lib/**/*.rb""].each do |file| require file end # good Dir[""./lib/**/*.rb""].sort.each do |file| require file end ---- [source,ruby] ---- # bad Dir.glob(Rails.root.join(__dir__, 'test', '*.rb')) do |file| require file end # good Dir.glob(Rails.root.join(__dir__, 'test', '*.rb')).sort.each do |file| require file end ---- == Lint/NonLocalExitFromIterator |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.30 | - |=== This cop checks for non-local exits from iterators without a return value. It registers an offense under these conditions: * No value is returned, * the block is preceded by a method chain, * the block has arguments, * the method which receives the block is not `define_method` or `define_singleton_method`, * the return is not contained in an inner scope, e.g. a lambda or a method definition. === Examples [source,ruby] ---- class ItemApi rescue_from ValidationError do |e| # non-iteration block with arg return { message: 'validation error' } unless e.errors # allowed error_array = e.errors.map do |error| # block with method chain return if error.suppress? # warned return ""#{error.param}: invalid"" unless error.message # allowed ""#{error.param}: #{error.message}"" end { message: 'validation error', errors: error_array } end def update_items transaction do # block without arguments return unless update_necessary? # allowed find_each do |item| # block without method chain return if item.stock == 0 # false-negative... item.update!(foobar: true) end end end end ---- == Lint/NumberConversion |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Disabled | Yes | Yes (Unsafe) | 0.53 | 0.70 |=== This cop warns the usage of unsafe number conversions. Unsafe number conversion can cause unexpected error if auto type conversion fails. Cop prefer parsing with number class instead. === Examples [source,ruby] ---- # bad '10'.to_i '10.2'.to_f '10'.to_c # good Integer('10', 10) Float('10.2') Complex('10') ---- == Lint/OrderedMagicComments |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.53 | - |=== Checks the proper ordering of magic comments and whether a magic comment is not placed before a shebang. === Examples [source,ruby] ---- # bad # frozen_string_literal: true # encoding: ascii p [''.frozen?, ''.encoding] #=> [true, #] # good # encoding: ascii # frozen_string_literal: true p [''.frozen?, ''.encoding] #=> [true, #] # good #!/usr/bin/env ruby # encoding: ascii # frozen_string_literal: true p [''.frozen?, ''.encoding] #=> [true, #] ---- == Lint/ParenthesesAsGroupedExpression |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.12 | 0.83 |=== Checks for space between the name of a called method and a left parenthesis. === Examples [source,ruby] ---- # bad do_something (foo) # good do_something(foo) do_something (2 + 3) * 4 do_something (foo * bar).baz ---- === References * https://rubystyle.guide#parens-no-spaces == Lint/PercentStringArray |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | No | Yes (Unsafe) | 0.41 | - |=== This cop checks for quotes and commas in %w, e.g. `%w('foo', ""bar"")` It is more likely that the additional characters are unintended (for example, mistranslating an array of literals to percent string notation) rather than meant to be part of the resulting strings. === Examples [source,ruby] ---- # bad %w('foo', ""bar"") ---- [source,ruby] ---- # good %w(foo bar) ---- == Lint/PercentSymbolArray |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.41 | - |=== This cop checks for colons and commas in %i, e.g. `%i(:foo, :bar)` It is more likely that the additional characters are unintended (for example, mistranslating an array of literals to percent string notation) rather than meant to be part of the resulting symbols. === Examples [source,ruby] ---- # bad %i(:foo, :bar) ---- [source,ruby] ---- # good %i(foo bar) ---- == Lint/RaiseException |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Pending | Yes | No | 0.81 | - |=== This cop checks for `raise` or `fail` statements which are raising `Exception` class. You can specify a module name that will be an implicit namespace using `AllowedImplicitNamespaces` option. The cop cause a false positive for namespaced `Exception` when a namespace is omitted. This option can prevent the false positive by specifying a namespace to be omitted for `Exception`. Alternatively, make `Exception` a fully qualified class name with an explicit namespace. === Examples [source,ruby] ---- # bad raise Exception, 'Error message here' # good raise StandardError, 'Error message here' ---- ==== AllowedImplicitNamespaces: ['Gem'] [source,ruby] ---- # good module Gem def self.foo raise Exception # This exception means `Gem::Exception`. end end ---- === Configurable attributes |=== | Name | Default value | Configurable values | AllowedImplicitNamespaces | `Gem` | Array |=== === References * https://rubystyle.guide#raise-exception == Lint/RandOne |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.36 | - |=== This cop checks for `rand(1)` calls. Such calls always return `0`. === Examples [source,ruby] ---- # bad rand 1 Kernel.rand(-1) rand 1.0 rand(-1.0) ---- [source,ruby] ---- # good 0 # just use 0 instead ---- == Lint/RedundantCopDisableDirective |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.76 | - |=== This cop detects instances of rubocop:disable comments that can be removed without causing any offenses to be reported. It's implemented as a cop in that it inherits from the Cop base class and calls add_offense. The unusual part of its implementation is that it doesn't have any on_* methods or an investigate method. This means that it doesn't take part in the investigation phase when the other cops do their work. Instead, it waits until it's called in a later stage of the execution. The reason it can't be implemented as a normal cop is that it depends on the results of all other cops to do its work. === Examples [source,ruby] ---- # bad # rubocop:disable Layout/LineLength x += 1 # rubocop:enable Layout/LineLength # good x += 1 ---- == Lint/RedundantCopEnableDirective |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.76 | - |=== This cop detects instances of rubocop:enable comments that can be removed. When comment enables all cops at once `rubocop:enable all` that cop checks whether any cop was actually enabled. === Examples [source,ruby] ---- # bad foo = 1 # rubocop:enable Layout/LineLength # good foo = 1 ---- [source,ruby] ---- # bad # rubocop:disable Style/StringLiterals foo = ""1"" # rubocop:enable Style/StringLiterals baz # rubocop:enable all # good # rubocop:disable Style/StringLiterals foo = ""1"" # rubocop:enable all baz ---- == Lint/RedundantRequireStatement |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.76 | - |=== Checks for unnecessary `require` statement. The following features are unnecessary `require` statement because they are already loaded. ruby -ve 'p $LOADED_FEATURES.reject { |feature| %r|/| =~ feature }' ruby 2.2.8p477 (2017-09-14 revision 59906) [x86_64-darwin13] [""enumerator.so"", ""rational.so"", ""complex.so"", ""thread.rb""] This cop targets Ruby 2.2 or higher containing these 4 features. === Examples [source,ruby] ---- # bad require 'unloaded_feature' require 'thread' # good require 'unloaded_feature' ---- == Lint/RedundantSplatExpansion |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.76 | - |=== This cop checks for unneeded usages of splat expansion === Examples [source,ruby] ---- # bad a = *[1, 2, 3] a = *'a' a = *1 begin foo rescue *[StandardError, ApplicationError] bar end case foo when *[1, 2, 3] bar else baz end ---- [source,ruby] ---- # good c = [1, 2, 3] a = *c a, b = *c a, *b = *c a = *1..10 a = ['a'] begin foo rescue StandardError, ApplicationError bar end case foo when 1, 2, 3 bar else baz end ---- == Lint/RedundantStringCoercion |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.19 | 0.77 |=== This cop checks for string conversion in string interpolation, which is redundant. === Examples [source,ruby] ---- # bad ""result is #{something.to_s}"" ---- [source,ruby] ---- # good ""result is #{something}"" ---- === References * https://rubystyle.guide#no-to-s == Lint/RedundantWithIndex |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.50 | - |=== This cop checks for redundant `with_index`. === Examples [source,ruby] ---- # bad ary.each_with_index do |v| v end # good ary.each do |v| v end # bad ary.each.with_index do |v| v end # good ary.each do |v| v end ---- == Lint/RedundantWithObject |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.51 | - |=== This cop checks for redundant `with_object`. === Examples [source,ruby] ---- # bad ary.each_with_object([]) do |v| v end # good ary.each do |v| v end # bad ary.each.with_object([]) do |v| v end # good ary.each do |v| v end ---- == Lint/RegexpAsCondition |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.51 | - |=== This cop checks for regexp literals used as `match-current-line`. If a regexp literal is in condition, the regexp matches `$_` implicitly. === Examples [source,ruby] ---- # bad if /foo/ do_something end # good if /foo/ =~ $_ do_something end ---- == Lint/RequireParentheses |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.18 | - |=== This cop checks for expressions where there is a call to a predicate method with at least one argument, where no parentheses are used around the parameter list, and a boolean operator, && or ||, is used in the last argument. The idea behind warning for these constructs is that the user might be under the impression that the return value from the method call is an operand of &&/||. === Examples [source,ruby] ---- # bad if day.is? :tuesday && month == :jan # ... end ---- [source,ruby] ---- # good if day.is?(:tuesday) && month == :jan # ... end ---- == Lint/RescueException |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.9 | 0.27.1 |=== This cop checks for `rescue` blocks targeting the Exception class. === Examples [source,ruby] ---- # bad begin do_something rescue Exception handle_exception end ---- [source,ruby] ---- # good begin do_something rescue ArgumentError handle_exception end ---- === References * https://rubystyle.guide#no-blind-rescues == Lint/RescueType |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.49 | - |=== Check for arguments to `rescue` that will result in a `TypeError` if an exception is raised. === Examples [source,ruby] ---- # bad begin bar rescue nil baz end # bad def foo bar rescue 1, 'a', ""#{b}"", 0.0, [], {} baz end # good begin bar rescue baz end # good def foo bar rescue NameError baz end ---- == Lint/ReturnInVoidContext |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.50 | - |=== This cop checks for the use of a return with a value in a context where the value will be ignored. (initialize and setter methods) === Examples [source,ruby] ---- # bad def initialize foo return :qux if bar? baz end def foo=(bar) return 42 end ---- [source,ruby] ---- # good def initialize foo return if bar? baz end def foo=(bar) return end ---- == Lint/SafeNavigationChain |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.47 | 0.77 |=== The safe navigation operator returns nil if the receiver is nil. If you chain an ordinary method call after a safe navigation operator, it raises NoMethodError. We should use a safe navigation operator after a safe navigation operator. This cop checks for the problem outlined above. === Examples [source,ruby] ---- # bad x&.foo.bar x&.foo + bar x&.foo[bar] ---- [source,ruby] ---- # good x&.foo&.bar x&.foo || bar ---- === Configurable attributes |=== | Name | Default value | Configurable values | AllowedMethods | `present?`, `blank?`, `presence`, `try`, `try!` | Array |=== == Lint/SafeNavigationConsistency |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.55 | 0.77 |=== This cop check to make sure that if safe navigation is used for a method call in an `&&` or `||` condition that safe navigation is used for all method calls on that same object. === Examples [source,ruby] ---- # bad foo&.bar && foo.baz # bad foo.bar || foo&.baz # bad foo&.bar && (foobar.baz || foo.baz) # good foo.bar && foo.baz # good foo&.bar || foo&.baz # good foo&.bar && (foobar.baz || foo&.baz) ---- === Configurable attributes |=== | Name | Default value | Configurable values | AllowedMethods | `present?`, `blank?`, `presence`, `try`, `try!` | Array |=== == Lint/SafeNavigationWithEmpty |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.62 | - |=== This cop checks to make sure safe navigation isn't used with `empty?` in a conditional. While the safe navigation operator is generally a good idea, when checking `foo&.empty?` in a conditional, `foo` being `nil` will actually do the opposite of what the author intends. === Examples [source,ruby] ---- # bad return if foo&.empty? return unless foo&.empty? # good return if foo && foo.empty? return unless foo && foo.empty? ---- == Lint/ScriptPermission |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.49 | 0.50 |=== This cop checks if a file which has a shebang line as its first line is granted execute permission. === Examples [source,ruby] ---- # bad # A file which has a shebang line as its first line is not # granted execute permission. #!/usr/bin/env ruby puts 'hello, world' # good # A file which has a shebang line as its first line is # granted execute permission. #!/usr/bin/env ruby puts 'hello, world' # good # A file which has not a shebang line as its first line is not # granted execute permission. puts 'hello, world' ---- == Lint/SendWithMixinArgument |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.75 | - |=== This cop checks for `send`, `public_send`, and `__send__` methods when using mix-in. `include` and `prepend` methods were private methods until Ruby 2.0, they were mixed-in via `send` method. This cop uses Ruby 2.1 or higher style that can be called by public methods. And `extend` method that was originally a public method is also targeted for style unification. === Examples [source,ruby] ---- # bad Foo.send(:include, Bar) Foo.send(:prepend, Bar) Foo.send(:extend, Bar) # bad Foo.public_send(:include, Bar) Foo.public_send(:prepend, Bar) Foo.public_send(:extend, Bar) # bad Foo.__send__(:include, Bar) Foo.__send__(:prepend, Bar) Foo.__send__(:extend, Bar) # good Foo.include Bar Foo.prepend Bar Foo.extend Bar ---- == Lint/ShadowedArgument |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.52 | - |=== This cop checks for shadowed arguments. This cop has `IgnoreImplicitReferences` configuration option. It means argument shadowing is used in order to pass parameters to zero arity `super` when `IgnoreImplicitReferences` is `true`. === Examples [source,ruby] ---- # bad do_something do |foo| foo = 42 puts foo end def do_something(foo) foo = 42 puts foo end # good do_something do |foo| foo = foo + 42 puts foo end def do_something(foo) foo = foo + 42 puts foo end def do_something(foo) puts foo end ---- ==== IgnoreImplicitReferences: false (default) [source,ruby] ---- # bad def do_something(foo) foo = 42 super end def do_something(foo) foo = super bar end ---- ==== IgnoreImplicitReferences: true [source,ruby] ---- # good def do_something(foo) foo = 42 super end def do_something(foo) foo = super bar end ---- === Configurable attributes |=== | Name | Default value | Configurable values | IgnoreImplicitReferences | `false` | Boolean |=== == Lint/ShadowedException |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.41 | - |=== This cop checks for a rescued exception that get shadowed by a less specific exception being rescued before a more specific exception is rescued. === Examples [source,ruby] ---- # bad begin something rescue Exception handle_exception rescue StandardError handle_standard_error end # good begin something rescue StandardError handle_standard_error rescue Exception handle_exception end # good, however depending on runtime environment. # # This is a special case for system call errors. # System dependent error code depends on runtime environment. # For example, whether `Errno::EAGAIN` and `Errno::EWOULDBLOCK` are # the same error code or different error code depends on environment. # This good case is for `Errno::EAGAIN` and `Errno::EWOULDBLOCK` with # the same error code. begin something rescue Errno::EAGAIN, Errno::EWOULDBLOCK handle_standard_error end ---- == Lint/ShadowingOuterLocalVariable |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.9 | - |=== This cop looks for use of the same name as outer local variables for block arguments or block local variables. This is a mimic of the warning ""shadowing outer local variable - foo"" from `ruby -cw`. === Examples [source,ruby] ---- # bad def some_method foo = 1 2.times do |foo| # shadowing outer `foo` do_something(foo) end end ---- [source,ruby] ---- # good def some_method foo = 1 2.times do |bar| do_something(bar) end end ---- == Lint/StructNewOverride |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Pending | Yes | No | 0.81 | - |=== This cop checks unexpected overrides of the `Struct` built-in methods via `Struct.new`. === Examples [source,ruby] ---- # bad Bad = Struct.new(:members, :clone, :count) b = Bad.new([], true, 1) b.members #=> [] (overriding `Struct#members`) b.clone #=> true (overriding `Object#clone`) b.count #=> 1 (overriding `Enumerable#count`) # good Good = Struct.new(:id, :name) g = Good.new(1, ""foo"") g.members #=> [:id, :name] g.clone #=> # g.count #=> 2 ---- == Lint/SuppressedException |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.9 | 0.81 |=== This cop checks for `rescue` blocks with no body. === Examples [source,ruby] ---- # bad def some_method do_something rescue end # bad begin do_something rescue end # good def some_method do_something rescue handle_exception end # good begin do_something rescue handle_exception end ---- ==== AllowComments: true (default) [source,ruby] ---- # good def some_method do_something rescue # do nothing end # good begin do_something rescue # do nothing end ---- ==== AllowComments: false [source,ruby] ---- # bad def some_method do_something rescue # do nothing end # bad begin do_something rescue # do nothing end ---- === Configurable attributes |=== | Name | Default value | Configurable values | AllowComments | `true` | Boolean |=== === References * https://rubystyle.guide#dont-hide-exceptions == Lint/Syntax |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.9 | - |=== This is not actually a cop. It does not inspect anything. It just provides methods to repack Parser's diagnostics/errors into RuboCop's offenses. == Lint/ToJSON |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.66 | - |=== This cop checks to make sure `#to_json` includes an optional argument. When overriding `#to_json`, callers may invoke JSON generation via `JSON.generate(your_obj)`. Since `JSON#generate` allows for an optional argument, your method should too. === Examples [source,ruby] ---- # bad def to_json end # good def to_json(*_args) end ---- == Lint/UnderscorePrefixedVariableName |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.21 | - |=== This cop checks for underscore-prefixed variables that are actually used. Since block keyword arguments cannot be arbitrarily named at call sites, the `AllowKeywordBlockArguments` will allow use of underscore- prefixed block keyword arguments. === Examples ==== AllowKeywordBlockArguments: false (default) [source,ruby] ---- # bad [1, 2, 3].each do |_num| do_something(_num) end query(:sales) do |_id:, revenue:, cost:| {_id: _id, profit: revenue - cost} end # good [1, 2, 3].each do |num| do_something(num) end [1, 2, 3].each do |_num| do_something # not using `_num` end ---- ==== AllowKeywordBlockArguments: true [source,ruby] ---- # good query(:sales) do |_id:, revenue:, cost:| {_id: _id, profit: revenue - cost} end ---- === Configurable attributes |=== | Name | Default value | Configurable values | AllowKeywordBlockArguments | `false` | Boolean |=== == Lint/UnifiedInteger |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.43 | - |=== This cop checks for using Fixnum or Bignum constant. === Examples [source,ruby] ---- # bad 1.is_a?(Fixnum) 1.is_a?(Bignum) ---- [source,ruby] ---- # good 1.is_a?(Integer) ---- == Lint/UnreachableCode |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.9 | - |=== This cop checks for unreachable code. The check are based on the presence of flow of control statement in non-final position in `begin` (implicit) blocks. === Examples [source,ruby] ---- # bad def some_method return do_something end # bad def some_method if cond return else return end do_something end ---- [source,ruby] ---- # good def some_method do_something end ---- == Lint/UnusedBlockArgument |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.21 | 0.22 |=== This cop checks for unused block arguments. === Examples [source,ruby] ---- # bad do_something do |used, unused| puts used end do_something do |bar| puts :foo end define_method(:foo) do |bar| puts :baz end # good do_something do |used, _unused| puts used end do_something do puts :foo end define_method(:foo) do |_bar| puts :baz end ---- ==== IgnoreEmptyBlocks: true (default) [source,ruby] ---- # good do_something { |unused| } ---- ==== IgnoreEmptyBlocks: false [source,ruby] ---- # bad do_something { |unused| } ---- ==== AllowUnusedKeywordArguments: false (default) [source,ruby] ---- # bad do_something do |unused: 42| foo end ---- ==== AllowUnusedKeywordArguments: true [source,ruby] ---- # good do_something do |unused: 42| foo end ---- === Configurable attributes |=== | Name | Default value | Configurable values | IgnoreEmptyBlocks | `true` | Boolean | AllowUnusedKeywordArguments | `false` | Boolean |=== === References * https://rubystyle.guide#underscore-unused-vars == Lint/UnusedMethodArgument |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.21 | 0.81 |=== This cop checks for unused method arguments. === Examples [source,ruby] ---- # bad def some_method(used, unused, _unused_but_allowed) puts used end # good def some_method(used, _unused, _unused_but_allowed) puts used end ---- ==== AllowUnusedKeywordArguments: false (default) [source,ruby] ---- # bad def do_something(used, unused: 42) used end ---- ==== AllowUnusedKeywordArguments: true [source,ruby] ---- # good def do_something(used, unused: 42) used end ---- ==== IgnoreEmptyMethods: true (default) [source,ruby] ---- # good def do_something(unused) end ---- ==== IgnoreEmptyMethods: false [source,ruby] ---- # bad def do_something(unused) end ---- ==== IgnoreNotImplementedMethods: true (default) [source,ruby] ---- # good def do_something(unused) raise NotImplementedError end def do_something_else(unused) fail ""TODO"" end ---- ==== IgnoreNotImplementedMethods: false [source,ruby] ---- # bad def do_something(unused) raise NotImplementedError end def do_something_else(unused) fail ""TODO"" end ---- === Configurable attributes |=== | Name | Default value | Configurable values | AllowUnusedKeywordArguments | `false` | Boolean | IgnoreEmptyMethods | `true` | Boolean | IgnoreNotImplementedMethods | `true` | Boolean |=== === References * https://rubystyle.guide#underscore-unused-vars == Lint/UriEscapeUnescape |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.50 | - |=== This cop identifies places where `URI.escape` can be replaced by `CGI.escape`, `URI.encode_www_form`, or `URI.encode_www_form_component` depending on your specific use case. Also this cop identifies places where `URI.unescape` can be replaced by `CGI.unescape`, `URI.decode_www_form`, or `URI.decode_www_form_component` depending on your specific use case. === Examples [source,ruby] ---- # bad URI.escape('http://example.com') URI.encode('http://example.com') # good CGI.escape('http://example.com') URI.encode_www_form([['example', 'param'], ['lang', 'en']]) URI.encode_www_form(page: 10, locale: 'en') URI.encode_www_form_component('http://example.com') # bad URI.unescape(enc_uri) URI.decode(enc_uri) # good CGI.unescape(enc_uri) URI.decode_www_form(enc_uri) URI.decode_www_form_component(enc_uri) ---- == Lint/UriRegexp |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.50 | - |=== This cop identifies places where `URI.regexp` is obsolete and should not be used. Instead, use `URI::DEFAULT_PARSER.make_regexp`. === Examples [source,ruby] ---- # bad URI.regexp('http://example.com') # good URI::DEFAULT_PARSER.make_regexp('http://example.com') ---- == Lint/UselessAccessModifier |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | Yes | 0.20 | 0.83 |=== This cop checks for redundant access modifiers, including those with no code, those which are repeated, and leading `public` modifiers in a class or module body. Conditionally-defined methods are considered as always being defined, and thus access modifiers guarding such methods are not redundant. This cop has `ContextCreatingMethods` option. The default setting value is an empty array that means no method is specified. This setting is an array of methods which, when called, are known to create its own context in the module's current access context. It also has `MethodCreatingMethods` option. The default setting value is an empty array that means no method is specified. This setting is an array of methods which, when called, are known to create other methods in the module's current access context. === Examples [source,ruby] ---- # bad class Foo public # this is redundant (default access is public) def method end end # bad class Foo # The following is redundant (methods defined on the class' # singleton class are not affected by the public modifier) public def self.method3 end end # bad class Foo protected define_method(:method2) do end protected # this is redundant (repeated from previous modifier) [1,2,3].each do |i| define_method(""foo#{i}"") do end end end # bad class Foo private # this is redundant (no following methods are defined) end # good class Foo private # this is not redundant (a method is defined) def method2 end end # good class Foo # The following is not redundant (conditionally defined methods are # considered as always defining a method) private if condition? def method end end end # good class Foo protected # this is not redundant (a method is defined) define_method(:method2) do end end ---- ==== ContextCreatingMethods: concerning [source,ruby] ---- # Lint/UselessAccessModifier: # ContextCreatingMethods: # - concerning # good require 'active_support/concern' class Foo concerning :Bar do def some_public_method end private def some_private_method end end # this is not redundant because `concerning` created its own context private def some_other_private_method end end ---- ==== MethodCreatingMethods: delegate [source,ruby] ---- # Lint/UselessAccessModifier: # MethodCreatingMethods: # - delegate # good require 'active_support/core_ext/module/delegation' class Foo # this is not redundant because `delegate` creates methods private delegate :method_a, to: :method_b end ---- === Configurable attributes |=== | Name | Default value | Configurable values | ContextCreatingMethods | `[]` | Array | MethodCreatingMethods | `[]` | Array |=== == Lint/UselessAssignment |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.11 | - |=== This cop checks for every useless assignment to local variable in every scope. The basic idea for this cop was from the warning of `ruby -cw`: assigned but unused variable - foo Currently this cop has advanced logic that detects unreferenced reassignments and properly handles varied cases such as branch, loop, rescue, ensure, etc. === Examples [source,ruby] ---- # bad def some_method some_var = 1 do_something end ---- [source,ruby] ---- # good def some_method some_var = 1 do_something(some_var) end ---- === References * https://rubystyle.guide#underscore-unused-vars == Lint/UselessComparison |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.11 | - |=== This cop checks for comparison of something with itself. === Examples [source,ruby] ---- # bad x.top >= x.top ---- == Lint/UselessElseWithoutRescue |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.17 | - |=== This cop checks for useless `else` in `begin..end` without `rescue`. NOTE: This syntax is no longer valid on Ruby 2.6 or higher and this cop is going to be removed at some point the future. === Examples [source,ruby] ---- # bad begin do_something else do_something_else # This will never be run. end ---- [source,ruby] ---- # good begin do_something rescue handle_errors else do_something_else end ---- == Lint/UselessSetterCall |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | No | No | 0.13 | 0.80 |=== This cop checks for setter call to local variable as the final expression of a function definition. NOTE: There are edge cases in which the local variable references a value that is also accessible outside the local scope. This is not detected by the cop, and it can yield a false positive. === Examples [source,ruby] ---- # bad def something x = Something.new x.attr = 5 end ---- [source,ruby] ---- # good def something x = Something.new x.attr = 5 x end ---- == Lint/Void |=== | Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged | Enabled | Yes | No | 0.9 | - |=== This cop checks for operators, variables, literals, and nonmutating methods used in void context. === Examples ==== CheckForMethodsWithNoSideEffects: false (default) [source,ruby] ---- # bad def some_method some_num * 10 do_something end def some_method(some_var) some_var do_something end ---- ==== CheckForMethodsWithNoSideEffects: true [source,ruby] ---- # bad def some_method(some_array) some_array.sort do_something(some_array) end # good def some_method do_something some_num * 10 end def some_method(some_var) do_something some_var end def some_method(some_array) some_array.sort! do_something(some_array) end ---- === Configurable attributes |=== | Name | Default value | Configurable values | CheckForMethodsWithNoSideEffects | `false` | Boolean |=== ",16376,True,3828.6807782092856,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) //// = rhpam78-prod :toc: :toc-placement!: :toclevels: 5 Application template for a managed HA production runtime environment, for Red Hat Process Automation Manager 7.8 - Deprecated toc::[] == Parameters Templates allow you to define parameters which 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. Refer to the https://docs.okd.io/latest/architecture/core_concepts/templates.html#parameters[Openshift documentation] for more information. |======================================================================= |Variable name |Image Environment Variable |Description |Example value |Required |`APPLICATION_NAME` | -- | The name for the application. | myapp | True |`MAVEN_MIRROR_URL` | `MAVEN_MIRROR_URL` | Maven mirror that the KIE server must use. If you configure a mirror, this mirror must contain all artifacts that are required for deploying your services. | -- | False |`MAVEN_MIRROR_OF` | `MAVEN_MIRROR_OF` | Maven mirror configuration for KIE server. | external:* | 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-rhpamcentr,!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/ | True |`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 |`BUSINESS_CENTRAL_MAVEN_SERVICE` | `RHPAMCENTR_MAVEN_REPO_SERVICE` | The service name for the optional Business Central, where it can be reached, to allow service lookups (for maven repo usage), if required. | myapp-rhpamcentr | False |`CREDENTIALS_SECRET` | -- | Secret containing the KIE_ADMIN_USER and KIE_ADMIN_PWD values | rhpam-credentials | True |`IMAGE_STREAM_NAMESPACE` | -- | Namespace in which the ImageStreams for Red Hat Process Automation Manager images are installed. These ImageStreams are normally installed in the openshift namespace. You need to modify this parameter only if you installed the ImageStream in a different namespace/project. Default is ""openshift"". | openshift | True |`KIE_SERVER_IMAGE_STREAM_NAME` | -- | The name of the image stream to use for KIE server. Default is ""rhpam-kieserver-rhel8"". | rhpam-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 |`SMART_ROUTER_HOSTNAME_HTTP` | -- | Custom hostname for http service route. Leave blank for default hostname, e.g. -smartrouter-.' | -- | False |`SMART_ROUTER_HOSTNAME_HTTPS` | -- | Custom hostname for https service route. Leave blank for default hostname, e.g. secure--smartrouter-.' | -- | False |`KIE_SERVER_ROUTER_ID` | `KIE_SERVER_ROUTER_ID` | Router ID used when connecting to the controller. (router property org.kie.server.router.id) | kie-server-router | True |`KIE_SERVER_ROUTER_PROTOCOL` | `KIE_SERVER_ROUTER_PROTOCOL` | KIE server router protocol. (Used to build the org.kie.server.router.url.external property) | http | False |`KIE_SERVER_ROUTER_URL_EXTERNAL` | `KIE_SERVER_ROUTER_URL_EXTERNAL` | Public URL where the router can be found. Format http://: (router property org.kie.server.router.url.external) | -- | False |`KIE_SERVER_ROUTER_NAME` | `KIE_SERVER_ROUTER_NAME` | Router name used when connecting to the controller. (router property org.kie.server.router.name) | KIE Server Router | 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_PERSISTENCE_DS` | `KIE_SERVER_PERSISTENCE_DS` | KIE server persistence datasource. (Sets the org.kie.server.persistence.ds system property) | java:/jboss/datasources/rhpam | False |`POSTGRESQL_IMAGE_STREAM_NAMESPACE` | -- | Namespace in which the ImageStream for the PostgreSQL image is installed. The ImageStream is already installed in the openshift namespace. You need to modify this parameter only if you installed the ImageStream in a different namespace/project. Default is ""openshift"". | openshift | False |`POSTGRESQL_IMAGE_STREAM_TAG` | -- | The PostgreSQL image version, which is intended to correspond to the PostgreSQL version. Default is ""10"". | 10 | False |`KIE_SERVER_POSTGRESQL_USER` | `RHPAM_USERNAME` | KIE server PostgreSQL database user name. | rhpam | False |`KIE_SERVER_POSTGRESQL_PWD` | `RHPAM_PASSWORD` | KIE server PostgreSQL database password. | -- | False |`KIE_SERVER_POSTGRESQL_DB` | `RHPAM_DATABASE` | KIE server PostgreSQL database name. | rhpam7 | False |`POSTGRESQL_MAX_PREPARED_TRANSACTIONS` | `POSTGRESQL_MAX_PREPARED_TRANSACTIONS` | Allows the PostgreSQL to handle XA transactions. | 100 | True |`DB_VOLUME_CAPACITY` | -- | Size of persistent storage for the database volume. | 1Gi | True |`KIE_SERVER_POSTGRESQL_DIALECT` | `KIE_SERVER_PERSISTENCE_DIALECT` | KIE server PostgreSQL Hibernate dialect. | org.hibernate.dialect.PostgreSQLDialect | True |`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). | `PRODUCTION` | 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 |`BUSINESS_CENTRAL_HOSTNAME_HTTP` | `HOSTNAME_HTTP` | Custom hostname for http service route. Leave blank for default hostname, e.g.: -rhpamcentrmon-. | -- | False |`BUSINESS_CENTRAL_HOSTNAME_HTTPS` | `HOSTNAME_HTTPS` | Custom hostname for https service route. Leave blank for default hostname, e.g.: secure--rhpamcentrmon-. | -- | False |KIE_SERVER1_HOSTNAME_HTTP | `HOSTNAME_HTTP` | Custom hostname for http service route. Leave blank for default hostname, e.g.: -kieserver-. | -- | False |KIE_SERVER1_HOSTNAME_HTTPS | `HOSTNAME_HTTPS` | Custom hostname for https service route. Leave blank for default hostname, e.g.: secure--kieserver-. | -- | False |KIE_SERVER1_USE_SECURE_ROUTE_NAME | `KIE_SERVER_USE_SECURE_ROUTE_NAME` | If true, the KIE server will use secure--kieserver vs. -kieserver as the KIE server route endpoint for Business Central to report. Therefore, Business Central displays the secure link to the user. | false | False |KIE_SERVER2_HOSTNAME_HTTP | `HOSTNAME_HTTP` | Custom hostname for http service route. Leave blank for default hostname, e.g.: -kieserver-. | -- | False |KIE_SERVER2_HOSTNAME_HTTPS | `HOSTNAME_HTTPS` | Custom hostname for https service route. Leave blank for default hostname, e.g.: secure--kieserver-. | -- | False |KIE_SERVER2_USE_SECURE_ROUTE_NAME | `KIE_SERVER_USE_SECURE_ROUTE_NAME` | If true, will use secure-APPLICATION_NAME-kieserver-2 vs. APPLICATION_NAME-kieserver-2 as the route name. | false | False |`BUSINESS_CENTRAL_HTTPS_SECRET` | -- | The name of the secret containing the keystore file for Business Central. | businesscentral-app-secret | True |`BUSINESS_CENTRAL_HTTPS_KEYSTORE` | `HTTPS_KEYSTORE` | The name of the keystore file within the secret. | keystore.jks | False |`BUSINESS_CENTRAL_HTTPS_NAME` | `HTTPS_NAME` | The name associated with the server certificate. | jboss | False |`BUSINESS_CENTRAL_HTTPS_PASSWORD` | `HTTPS_PASSWORD` | The password for the keystore and certificate. | mykeystorepass | False |`KIE_SERVER_ROUTER_HTTPS_SECRET` | -- | The name of the secret containing the keystore file for Smart Router. | smartrouter-app-secret | True |`KIE_SERVER_ROUTER_HTTPS_KEYSTORE` | -- | The name of the keystore file within the secret. | keystore.jks | False |`KIE_SERVER_ROUTER_HTTPS_NAME` | `KIE_SERVER_ROUTER_TLS_KEYSTORE_KEYALIAS` | The name associated with the server certificate. | jboss | False |`KIE_SERVER_ROUTER_HTTPS_PASSWORD` | `KIE_SERVER_ROUTER_TLS_KEYSTORE_PASSWORD` | The password for the keystore and certificate. | 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. | keystore.jks | False |`KIE_SERVER_HTTPS_NAME` | `HTTPS_NAME` | The name associated with the server certificate. | jboss | False |`KIE_SERVER_HTTPS_PASSWORD` | `HTTPS_PASSWORD` | The password for the keystore and certificate. | mykeystorepass | 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 |`TIMER_SERVICE_DATA_STORE_REFRESH_INTERVAL` | `TIMER_SERVICE_DATA_STORE_REFRESH_INTERVAL` | Sets refresh-interval for the EJB timer service database-data-store. | 30000 | False |`BUSINESS_CENTRAL_MEMORY_LIMIT` | -- | Business Central Monitoring Container memory limit. | 2Gi | False |`KIE_SERVER_MEMORY_LIMIT` | -- | KIE server Container memory limit. | 1Gi | False |`SMART_ROUTER_MEMORY_LIMIT` | -- | Smart Router Container memory limit | 512Mi | False |`BUSINESS_CENTRAL_MONITORING_CONTAINER_REPLICAS` | -- | Business Central Monitoring Container Replicas, defines how many Business Central Monitoring containers will be started. | 3 | True |`SMART_ROUTER_CONTAINER_REPLICAS` | -- | Smart Router Container Replicas, defines how many smart router containers will be started. | 2 | True |`KIE_SERVER_CONTAINER_REPLICAS` | -- | KIE Server Container Replicas, defines how many KIE Server containers will be started. | 3 | True |`SSO_URL` | `SSO_URL` | RH-SSO URL. | https://rh-sso.example.com/auth | False |`SSO_REALM` | `SSO_REALM` | RH-SSO Realm name. | -- | False |`BUSINESS_CENTRAL_SSO_CLIENT` | `SSO_CLIENT` | Business Central Monitoring RH-SSO Client name. | -- | False |`BUSINESS_CENTRAL_SSO_SECRET` | `SSO_SECRET` | Business Central Monitoring RH-SSO Client Secret. | 252793ed-7118-4ca8-8dab-5622fa97d892 | False |KIE_SERVER1_SSO_CLIENT | `SSO_CLIENT` | KIE Server 1 RH-SSO Client name. | -- | False |KIE_SERVER1_SSO_SECRET | `SSO_SECRET` | KIE Server 1 RH-SSO Client Secret. | 252793ed-7118-4ca8-8dab-5622fa97d892 | False |KIE_SERVER2_SSO_CLIENT | `SSO_CLIENT` | KIE Server 2 RH-SSO Client name. | -- | False |KIE_SERVER2_SSO_SECRET | `SSO_SECRET` | KIE Server 2 RH-SSO Client Secret. | 252793ed-7118-4ca8-8dab-5622fa97d892 | False |`SSO_USERNAME` | `SSO_USERNAME` | RH-SSO Realm admin user name for creating 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://docs.okd.io/latest/cli_reference/basic_cli_operations.html#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. Refer to the https://cloud.google.com/container-engine/docs/services/[container-engine documentation] for more information. |============= |Service |Port |Name | Description .2+| `${APPLICATION_NAME}-rhpamcentrmon` |8080 | http .2+| All the Business Central Monitoring web server's ports. |8443 | https .1+| `${APPLICATION_NAME}-rhpamcentrmon-ping` |8888 | ping .1+| The JGroups ping port for clustering. .2+| `${APPLICATION_NAME}-smartrouter` |9000 | http .2+| The smart router server http and https ports. |9443 | https .2+| `${APPLICATION_NAME}-kieserver-1` |8080 | http .2+| All the KIE server web server's ports. (First KIE server) |8443 | https .1+| `${APPLICATION_NAME}-kieserver-1-ping` |8888 | ping .1+| The JGroups ping port for clustering. .2+| `${APPLICATION_NAME}-kieserver-2` |8080 | http .2+| All the KIE server web server's ports. (Second KIE server) |8443 | https .1+| `${APPLICATION_NAME}-kieserver-2-ping` |8888 | ping .1+| The JGroups ping port for clustering. .1+| `${APPLICATION_NAME}-postgresql-1` |5432 | -- .1+| The first database server's port. .1+| `${APPLICATION_NAME}-postgresql-2` |5432 | -- .1+| The second database server's port. |============= === 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. Refer to the https://docs.okd.io/latest/architecture/networking/routes.html[Openshift documentation] for more information. |============= | Service | Security | Hostname |`${APPLICATION_NAME}-rhpamcentrmon-http` | none | `${BUSINESS_CENTRAL_HOSTNAME_HTTP}` |`${APPLICATION_NAME}-rhpamcentrmon-https` | TLS passthrough | `${BUSINESS_CENTRAL_HOSTNAME_HTTPS}` |`${APPLICATION_NAME}-kieserver-1-http` | none | `${KIE_SERVER1_HOSTNAME_HTTP}` |`${APPLICATION_NAME}-kieserver-1-https` | TLS passthrough | `${KIE_SERVER1_HOSTNAME_HTTPS}` |`${APPLICATION_NAME}-kieserver-2-http` | none | `${KIE_SERVER2_HOSTNAME_HTTP}` |`${APPLICATION_NAME}-kieserver-2-https` | TLS passthrough | `${KIE_SERVER2_HOSTNAME_HTTPS}` |`${APPLICATION_NAME}-smartrouter-http` | none | `${SMART_ROUTER_HOSTNAME_HTTP}` |`${APPLICATION_NAME}-smartrouter-https` | TLS passthrough | `${SMART_ROUTER_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. Refer to the https://docs.okd.io/latest/dev_guide/deployments/how_deployments_work.html#creating-a-deployment-configuration[Openshift documentation] for more information. ==== Triggers A trigger drives the creation of new deployments in response to events, both inside and outside OpenShift. Refer to the https://docs.okd.io/latest/dev_guide/builds/triggering_builds.html#config-change-triggers[Openshift documentation] for more information. |============ |Deployment | Triggers |`${APPLICATION_NAME}-rhpamcentrmon` | ImageChange |`${APPLICATION_NAME}-smartrouter` | ImageChange |`${APPLICATION_NAME}-kieserver-1` | ImageChange |`${APPLICATION_NAME}-postgresql-1` | ImageChange |`${APPLICATION_NAME}-kieserver-2` | ImageChange |`${APPLICATION_NAME}-postgresql-2` | 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. Refer to the https://cloud.google.com/container-engine/docs/replicationcontrollers/[container-engine documentation] for more information. |============ |Deployment | Replicas |`${APPLICATION_NAME}-rhpamcentrmon` | 3 |`${APPLICATION_NAME}-smartrouter` | 2 |`${APPLICATION_NAME}-kieserver-1` | 3 |`${APPLICATION_NAME}-postgresql-1` | 1 |`${APPLICATION_NAME}-kieserver-2` | 3 |`${APPLICATION_NAME}-postgresql-2` | 1 |============ ==== 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. Refer to the https://docs.okd.io/latest/dev_guide/service_accounts.html#dev-managing-service-accounts[Openshift documentation] for more information. |============ |Deployment | Service Account |`${APPLICATION_NAME}-smartrouter` | `${APPLICATION_NAME}-smartrouter` |`${APPLICATION_NAME}-kieserver-1` | `${APPLICATION_NAME}-kieserver` |`${APPLICATION_NAME}-kieserver-2` | `${APPLICATION_NAME}-kieserver` |============ ===== Image |============ |Deployment | Image |`${APPLICATION_NAME}-rhpamcentrmon` | rhpam-businesscentral-monitoring-rhel8 |`${APPLICATION_NAME}-smartrouter` | rhpam-smartrouter-rhel8 |`${APPLICATION_NAME}-kieserver-1` | `${KIE_SERVER_IMAGE_STREAM_NAME}` |`${APPLICATION_NAME}-postgresql-1` | postgresql |`${APPLICATION_NAME}-kieserver-2` | `${KIE_SERVER_IMAGE_STREAM_NAME}` |`${APPLICATION_NAME}-postgresql-2` | postgresql |============ ===== Readiness Probe .${APPLICATION_NAME}-rhpamcentrmon ---- Http Get on http://localhost:8080/rest/ready ---- .${APPLICATION_NAME}-kieserver-1 ---- Http Get on http://localhost:8080/services/rest/server/readycheck ---- .${APPLICATION_NAME}-postgresql-1 ---- /usr/libexec/check-container ---- .${APPLICATION_NAME}-kieserver-2 ---- Http Get on http://localhost:8080/services/rest/server/readycheck ---- .${APPLICATION_NAME}-postgresql-2 ---- /usr/libexec/check-container ---- ===== Liveness Probe .${APPLICATION_NAME}-rhpamcentrmon ---- Http Get on http://localhost:8080/rest/healthy ---- .${APPLICATION_NAME}-kieserver-1 ---- Http Get on http://localhost:8080/services/rest/server/healthcheck ---- .${APPLICATION_NAME}-postgresql-1 ---- /usr/libexec/check-container --live ---- .${APPLICATION_NAME}-kieserver-2 ---- Http Get on http://localhost:8080/services/rest/server/healthcheck ---- .${APPLICATION_NAME}-postgresql-2 ---- /usr/libexec/check-container --live ---- ===== Exposed Ports |============= |Deployments | Name | Port | Protocol .4+| `${APPLICATION_NAME}-rhpamcentrmon` |jolokia | 8778 | `TCP` |http | 8080 | `TCP` |https | 8443 | `TCP` |ping | 8888 | `TCP` .1+| `${APPLICATION_NAME}-smartrouter` |http | 9000 | `TCP` .4+| `${APPLICATION_NAME}-kieserver-1` |jolokia | 8778 | `TCP` |http | 8080 | `TCP` |https | 8443 | `TCP` |ping | 8888 | `TCP` .1+| `${APPLICATION_NAME}-postgresql-1` |-- | 5432 | `TCP` .4+| `${APPLICATION_NAME}-kieserver-2` |jolokia | 8778 | `TCP` |http | 8080 | `TCP` |https | 8443 | `TCP` |ping | 8888 | `TCP` .1+| `${APPLICATION_NAME}-postgresql-2` |-- | 5432 | `TCP` |============= ===== Image Environment Variables |======================================================================= |Deployment |Variable name |Description |Example value .51+| `${APPLICATION_NAME}-rhpamcentrmon` |`APPLICATION_USERS_PROPERTIES` | -- | `/opt/kie/data/configuration/application-users.properties` |`APPLICATION_ROLES_PROPERTIES` | -- | `/opt/kie/data/configuration/application-roles.properties` |`KIE_ADMIN_USER` | -- | -- |`KIE_ADMIN_PWD` | -- | -- |`MAVEN_MIRROR_URL` | Maven mirror that the KIE server must use. If you configure a mirror, this mirror must contain all artifacts that are required for 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-rhpamcentr,!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}` |`KIE_SERVER_CONTROLLER_TOKEN` | KIE server controller token for bearer authentication. (Sets the org.kie.server.controller.token system property) | `${KIE_SERVER_CONTROLLER_TOKEN}` |`HTTPS_KEYSTORE_DIR` | -- | `/etc/businesscentral-secret-volume` |`HTTPS_KEYSTORE` | The name of the keystore file within the secret. | `${BUSINESS_CENTRAL_HTTPS_KEYSTORE}` |`HTTPS_NAME` | The name associated with the server certificate. | `${BUSINESS_CENTRAL_HTTPS_NAME}` |`HTTPS_PASSWORD` | The password for the keystore and certificate. | `${BUSINESS_CENTRAL_HTTPS_PASSWORD}` |`JGROUPS_PING_PROTOCOL` | -- | openshift.DNS_PING |`OPENSHIFT_DNS_PING_SERVICE_NAME` | -- | `${APPLICATION_NAME}-rhpamcentrmon-ping` |`OPENSHIFT_DNS_PING_SERVICE_PORT` | -- | 8888 |`SSO_URL` | RH-SSO URL. | `${SSO_URL}` |`SSO_OPENIDCONNECT_DEPLOYMENTS` | -- | ROOT.war |`SSO_REALM` | RH-SSO Realm name. | `${SSO_REALM}` |`SSO_SECRET` | Business Central Monitoring RH-SSO Client Secret. | `${BUSINESS_CENTRAL_SSO_SECRET}` |`SSO_CLIENT` | Business Central Monitoring RH-SSO Client name. | `${BUSINESS_CENTRAL_SSO_CLIENT}` |`SSO_USERNAME` | RH-SSO Realm admin user name for creating 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. Leave blank for default hostname, e.g.: -rhpamcentrmon-. | `${BUSINESS_CENTRAL_HOSTNAME_HTTP}` |`HOSTNAME_HTTPS` | Custom hostname for https service route. Leave blank for default hostname, e.g.: secure--rhpamcentrmon-. | `${BUSINESS_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}` .19+| `${APPLICATION_NAME}-smartrouter` |`KIE_ADMIN_USER` | -- | -- |`KIE_ADMIN_PWD` | -- | -- |`KIE_SERVER_ROUTER_HOST` | -- | -- |`KIE_SERVER_ROUTER_PORT` | -- | 9000 |`KIE_SERVER_ROUTER_PORT_TLS` | -- | 9443 |`KIE_SERVER_ROUTER_URL_EXTERNAL` | Public URL where the router can be found. Format http://: (router property org.kie.server.router.url.external) | `${KIE_SERVER_ROUTER_URL_EXTERNAL}` |`KIE_SERVER_ROUTER_ID` | Router ID used when connecting to the controller. (router property org.kie.server.router.id) | `${KIE_SERVER_ROUTER_ID}` |`KIE_SERVER_ROUTER_NAME` | Router name used when connecting to the controller. (router property org.kie.server.router.name) | `${KIE_SERVER_ROUTER_NAME}` |`KIE_SERVER_ROUTER_ROUTE_NAME` | -- | `${APPLICATION_NAME}-smartrouter` |`KIE_SERVER_ROUTER_SERVICE` | -- | `${APPLICATION_NAME}-smartrouter` |`KIE_SERVER_ROUTER_PROTOCOL` | KIE server router protocol. (Used to build the org.kie.server.router.url.external property) | `${KIE_SERVER_ROUTER_PROTOCOL}` |`KIE_SERVER_ROUTER_TLS_KEYSTORE_KEYALIAS` | The name associated with the server certificate. | `${KIE_SERVER_ROUTER_HTTPS_NAME}` |`KIE_SERVER_ROUTER_TLS_KEYSTORE_PASSWORD` | The password for the keystore and certificate. | `${KIE_SERVER_ROUTER_HTTPS_PASSWORD}` |`KIE_SERVER_ROUTER_TLS_KEYSTORE` | -- | `/etc/smartrouter-secret-volume/${KIE_SERVER_ROUTER_HTTPS_KEYSTORE}` |`KIE_SERVER_CONTROLLER_TOKEN` | KIE server controller token for bearer authentication. (Sets the org.kie.server.controller.token system property) | `${KIE_SERVER_CONTROLLER_TOKEN}` |`KIE_SERVER_CONTROLLER_SERVICE` | -- | `${APPLICATION_NAME}-rhpamcentrmon` |`KIE_SERVER_CONTROLLER_PROTOCOL` | -- | http |`KIE_SERVER_ROUTER_REPO` | -- | `/opt/rhpam-smartrouter/data` |`KIE_SERVER_ROUTER_CONFIG_WATCHER_ENABLED` | -- | true .81+| `${APPLICATION_NAME}-kieserver-1` |`KIE_ADMIN_USER` | -- | -- |`KIE_ADMIN_PWD` | -- | -- |`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_TOKEN` | KIE server controller token for bearer authentication. (Sets the org.kie.server.controller.token system property) | `${KIE_SERVER_CONTROLLER_TOKEN}` |`KIE_SERVER_CONTROLLER_SERVICE` | -- | `${APPLICATION_NAME}-rhpamcentrmon` |`KIE_SERVER_CONTROLLER_PROTOCOL` | -- | ws |`KIE_SERVER_ID` | -- | `${APPLICATION_NAME}-kieserver-1` |`KIE_SERVER_ROUTE_NAME` | -- | `${APPLICATION_NAME}-kieserver-1` |`KIE_SERVER_USE_SECURE_ROUTE_NAME` | If true, the KIE server will use secure--kieserver vs. -kieserver as the KIE server route endpoint for Business Central to report. Therefore, Business Central displays the secure link to the user. | `${KIE_SERVER1_USE_SECURE_ROUTE_NAME}` |`KIE_SERVER_CONTAINER_DEPLOYMENT` | -- | |`MAVEN_MIRROR_URL` | Maven mirror that the KIE server must use. If you configure a mirror, this mirror must contain all artifacts that are required for deploying your services. | `${MAVEN_MIRROR_URL}` |`MAVEN_MIRROR_OF` | Maven mirror configuration for KIE server. | `${MAVEN_MIRROR_OF}` |`MAVEN_REPOS` | -- | RHPAMCENTR,EXTERNAL |`RHPAMCENTR_MAVEN_REPO_ID` | -- | repo-rhpamcentr |`RHPAMCENTR_MAVEN_REPO_SERVICE` | The service name for the optional Business Central, where it can be reached, to allow service lookups (for maven repo usage), if required. | `${BUSINESS_CENTRAL_MAVEN_SERVICE}` |`RHPAMCENTR_MAVEN_REPO_PATH` | -- | `/maven2/` |`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-rhpamcentr,!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}` |`KIE_SERVER_ROUTER_SERVICE` | -- | `${APPLICATION_NAME}-smartrouter` |`KIE_SERVER_ROUTER_PORT` | -- | 9000 |`KIE_SERVER_ROUTER_PROTOCOL` | KIE server router protocol. (Used to build the org.kie.server.router.url.external property) | `${KIE_SERVER_ROUTER_PROTOCOL}` |`KIE_SERVER_PERSISTENCE_DS` | KIE server persistence datasource. (Sets the org.kie.server.persistence.ds system property) | `${KIE_SERVER_PERSISTENCE_DS}` |`DATASOURCES` | -- | `RHPAM` |`RHPAM_JNDI` | KIE server persistence datasource. (Sets the org.kie.server.persistence.ds system property) | `${KIE_SERVER_PERSISTENCE_DS}` |`RHPAM_JTA` | -- | true |`RHPAM_DATABASE` | KIE server PostgreSQL database name. | `${KIE_SERVER_POSTGRESQL_DB}` |`RHPAM_DRIVER` | -- | postgresql |`KIE_SERVER_PERSISTENCE_DIALECT` | KIE server PostgreSQL Hibernate dialect. | `${KIE_SERVER_POSTGRESQL_DIALECT}` |`RHPAM_USERNAME` | KIE server PostgreSQL database user name. | `${KIE_SERVER_POSTGRESQL_USER}` |`RHPAM_PASSWORD` | KIE server PostgreSQL database password. | `${KIE_SERVER_POSTGRESQL_PWD}` |`RHPAM_SERVICE_HOST` | -- | `${APPLICATION_NAME}-postgresql-1` |`RHPAM_SERVICE_PORT` | -- | 5432 |`TIMER_SERVICE_DATA_STORE` | -- | `${APPLICATION_NAME}-postgresql-1` |`TIMER_SERVICE_DATA_STORE_REFRESH_INTERVAL` | Sets refresh-interval for the EJB timer service database-data-store. | `${TIMER_SERVICE_DATA_STORE_REFRESH_INTERVAL}` |`HTTPS_KEYSTORE_DIR` | -- | `/etc/kieserver-secret-volume` |`HTTPS_KEYSTORE` | The name of the keystore file within the secret. | `${KIE_SERVER_HTTPS_KEYSTORE}` |`HTTPS_NAME` | The name associated with the server certificate. | `${KIE_SERVER_HTTPS_NAME}` |`HTTPS_PASSWORD` | The password for the keystore and certificate. | `${KIE_SERVER_HTTPS_PASSWORD}` |`JGROUPS_PING_PROTOCOL` | -- | openshift.DNS_PING |`OPENSHIFT_DNS_PING_SERVICE_NAME` | -- | `${APPLICATION_NAME}-kieserver-1-ping` |`OPENSHIFT_DNS_PING_SERVICE_PORT` | -- | 8888 |`SSO_URL` | RH-SSO URL. | `${SSO_URL}` |`SSO_OPENIDCONNECT_DEPLOYMENTS` | -- | ROOT.war |`SSO_REALM` | RH-SSO Realm name. | `${SSO_REALM}` |`SSO_SECRET` | KIE Server 1 RH-SSO Client Secret. | `${KIE_SERVER1_SSO_SECRET}` |`SSO_CLIENT` | KIE Server 1 RH-SSO Client name. | `${KIE_SERVER1_SSO_CLIENT}` |`SSO_USERNAME` | RH-SSO Realm admin user name for creating 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. Leave blank for default hostname, e.g.: -kieserver-. | `${KIE_SERVER1_HOSTNAME_HTTP}` |`HOSTNAME_HTTPS` | Custom hostname for https service route. Leave blank for default hostname, e.g.: secure--kieserver-. | `${KIE_SERVER1_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}` .4+| `${APPLICATION_NAME}-postgresql-1` |`POSTGRESQL_USER` | KIE server PostgreSQL database user name. | `${KIE_SERVER_POSTGRESQL_USER}` |`POSTGRESQL_PASSWORD` | KIE server PostgreSQL database password. | `${KIE_SERVER_POSTGRESQL_PWD}` |`POSTGRESQL_DATABASE` | KIE server PostgreSQL database name. | `${KIE_SERVER_POSTGRESQL_DB}` |`POSTGRESQL_MAX_PREPARED_TRANSACTIONS` | Allows the PostgreSQL to handle XA transactions. | `${POSTGRESQL_MAX_PREPARED_TRANSACTIONS}` .81+| `${APPLICATION_NAME}-kieserver-2` |`KIE_ADMIN_USER` | -- | -- |`KIE_ADMIN_PWD` | -- | -- |`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_TOKEN` | KIE server controller token for bearer authentication. (Sets the org.kie.server.controller.token system property) | `${KIE_SERVER_CONTROLLER_TOKEN}` |`KIE_SERVER_CONTROLLER_SERVICE` | -- | `${APPLICATION_NAME}-rhpamcentrmon` |`KIE_SERVER_CONTROLLER_PROTOCOL` | -- | ws |`KIE_SERVER_ID` | -- | `${APPLICATION_NAME}-kieserver-2` |`KIE_SERVER_ROUTE_NAME` | -- | `${APPLICATION_NAME}-kieserver-2` |`KIE_SERVER_USE_SECURE_ROUTE_NAME` | If true, will use secure-APPLICATION_NAME-kieserver-2 vs. APPLICATION_NAME-kieserver-2 as the route name. | `${KIE_SERVER2_USE_SECURE_ROUTE_NAME}` |`KIE_SERVER_CONTAINER_DEPLOYMENT` | -- | |`MAVEN_MIRROR_URL` | Maven mirror that the KIE server must use. If you configure a mirror, this mirror must contain all artifacts that are required for deploying your services. | `${MAVEN_MIRROR_URL}` |`MAVEN_MIRROR_OF` | Maven mirror configuration for KIE server. | `${MAVEN_MIRROR_OF}` |`MAVEN_REPOS` | -- | RHPAMCENTR,EXTERNAL |`RHPAMCENTR_MAVEN_REPO_ID` | -- | repo-rhpamcentr |`RHPAMCENTR_MAVEN_REPO_SERVICE` | The service name for the optional Business Central, where it can be reached, to allow service lookups (for maven repo usage), if required. | `${BUSINESS_CENTRAL_MAVEN_SERVICE}` |`RHPAMCENTR_MAVEN_REPO_PATH` | -- | `/maven2/` |`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-rhpamcentr,!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}` |`KIE_SERVER_ROUTER_SERVICE` | -- | `${APPLICATION_NAME}-smartrouter` |`KIE_SERVER_ROUTER_PORT` | -- | 9000 |`KIE_SERVER_ROUTER_PROTOCOL` | KIE server router protocol. (Used to build the org.kie.server.router.url.external property) | `${KIE_SERVER_ROUTER_PROTOCOL}` |`KIE_SERVER_PERSISTENCE_DS` | KIE server persistence datasource. (Sets the org.kie.server.persistence.ds system property) | `${KIE_SERVER_PERSISTENCE_DS}` |`DATASOURCES` | -- | `RHPAM` |`RHPAM_JNDI` | KIE server persistence datasource. (Sets the org.kie.server.persistence.ds system property) | `${KIE_SERVER_PERSISTENCE_DS}` |`RHPAM_JTA` | -- | true |`RHPAM_DATABASE` | KIE server PostgreSQL database name. | `${KIE_SERVER_POSTGRESQL_DB}` |`RHPAM_DRIVER` | -- | postgresql |`KIE_SERVER_PERSISTENCE_DIALECT` | KIE server PostgreSQL Hibernate dialect. | `${KIE_SERVER_POSTGRESQL_DIALECT}` |`RHPAM_USERNAME` | KIE server PostgreSQL database user name. | `${KIE_SERVER_POSTGRESQL_USER}` |`RHPAM_PASSWORD` | KIE server PostgreSQL database password. | `${KIE_SERVER_POSTGRESQL_PWD}` |`RHPAM_SERVICE_HOST` | -- | `${APPLICATION_NAME}-postgresql-2` |`RHPAM_SERVICE_PORT` | -- | 5432 |`TIMER_SERVICE_DATA_STORE` | -- | `${APPLICATION_NAME}-postgresql-2` |`TIMER_SERVICE_DATA_STORE_REFRESH_INTERVAL` | Sets refresh-interval for the EJB timer service database-data-store. | `${TIMER_SERVICE_DATA_STORE_REFRESH_INTERVAL}` |`HTTPS_KEYSTORE_DIR` | -- | `/etc/kieserver-secret-volume` |`HTTPS_KEYSTORE` | The name of the keystore file within the secret. | `${KIE_SERVER_HTTPS_KEYSTORE}` |`HTTPS_NAME` | The name associated with the server certificate. | `${KIE_SERVER_HTTPS_NAME}` |`HTTPS_PASSWORD` | The password for the keystore and certificate. | `${KIE_SERVER_HTTPS_PASSWORD}` |`JGROUPS_PING_PROTOCOL` | -- | openshift.DNS_PING |`OPENSHIFT_DNS_PING_SERVICE_NAME` | -- | `${APPLICATION_NAME}-kieserver-2-ping` |`OPENSHIFT_DNS_PING_SERVICE_PORT` | -- | 8888 |`SSO_URL` | RH-SSO URL. | `${SSO_URL}` |`SSO_OPENIDCONNECT_DEPLOYMENTS` | -- | ROOT.war |`SSO_REALM` | RH-SSO Realm name. | `${SSO_REALM}` |`SSO_SECRET` | KIE Server 2 RH-SSO Client Secret. | `${KIE_SERVER2_SSO_SECRET}` |`SSO_CLIENT` | KIE Server 2 RH-SSO Client name. | `${KIE_SERVER2_SSO_CLIENT}` |`SSO_USERNAME` | RH-SSO Realm admin user name for creating 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. Leave blank for default hostname, e.g.: -kieserver-. | `${KIE_SERVER2_HOSTNAME_HTTP}` |`HOSTNAME_HTTPS` | Custom hostname for https service route. Leave blank for default hostname, e.g.: secure--kieserver-. | `${KIE_SERVER2_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}` .4+| `${APPLICATION_NAME}-postgresql-2` |`POSTGRESQL_USER` | KIE server PostgreSQL database user name. | `${KIE_SERVER_POSTGRESQL_USER}` |`POSTGRESQL_PASSWORD` | KIE server PostgreSQL database password. | `${KIE_SERVER_POSTGRESQL_PWD}` |`POSTGRESQL_DATABASE` | KIE server PostgreSQL database name. | `${KIE_SERVER_POSTGRESQL_DB}` |`POSTGRESQL_MAX_PREPARED_TRANSACTIONS` | Allows the PostgreSQL to handle XA transactions. | `${POSTGRESQL_MAX_PREPARED_TRANSACTIONS}` |======================================================================= ===== Volumes |============= |Deployment |Name | mountPath | Purpose | readOnly |`${APPLICATION_NAME}-rhpamcentrmon` | businesscentral-keystore-volume | `/etc/businesscentral-secret-volume` | ssl certs | True |`${APPLICATION_NAME}-smartrouter` | `${APPLICATION_NAME}-smartrouter` | `/opt/rhpam-smartrouter/data` | -- | false |`${APPLICATION_NAME}-kieserver-1` | kieserver-keystore-volume | `/etc/kieserver-secret-volume` | ssl certs | True |`${APPLICATION_NAME}-postgresql-1` | `${APPLICATION_NAME}-postgresql-pvol` | `/var/lib/pgsql/data` | postgresql | false |`${APPLICATION_NAME}-kieserver-2` | kieserver-keystore-volume | `/etc/kieserver-secret-volume` | ssl certs | True |`${APPLICATION_NAME}-postgresql-2` | `${APPLICATION_NAME}-postgresql-pvol` | `/var/lib/pgsql/data` | postgresql | false |============= === 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. Refer to the https://docs.okd.io/latest/dev_guide/persistent_volumes.html[Openshift documentation] for more information. |============= |Name | Access Mode |`${APPLICATION_NAME}-postgresql-claim-1` | ReadWriteOnce |`${APPLICATION_NAME}-postgresql-claim-2` | ReadWriteOnce |`${APPLICATION_NAME}-smartrouter-claim` | ReadWriteMany |`${APPLICATION_NAME}-rhpamcentr-claim` | ReadWriteMany |============= ==== Secrets This template requires the following secrets to be installed for the application to run. businesscentral-app-secret smartrouter-app-secret kieserver-app-secret ",16325,True,3902.876065463816,median "------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- S C N -- -- -- -- B o d y -- -- -- -- $Revision$ -- -- -- Copyright (C) 1992-2001 Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 2, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNAT; see file COPYING. If not, write -- -- to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, -- -- MA 02111-1307, USA. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ with Atree; use Atree; with Csets; use Csets; with Errout; use Errout; with Hostparm; use Hostparm; with Namet; use Namet; with Opt; use Opt; with Scans; use Scans; with Sinput; use Sinput; with Sinfo; use Sinfo; with Snames; use Snames; with Style; with Widechar; use Widechar; with System.CRC32; with System.WCh_Con; use System.WCh_Con; package body Scn is use ASCII; -- Make control characters visible Used_As_Identifier : array (Token_Type) of Boolean; -- Flags set True if a given keyword is used as an identifier (used to -- make sure that we only post an error message for incorrect use of a -- keyword as an identifier once for a given keyword). ----------------------- -- Local Subprograms -- ----------------------- procedure Accumulate_Checksum (C : Character); pragma Inline (Accumulate_Checksum); -- This routine accumulates the checksum given character C. During the -- scanning of a source file, this routine is called with every character -- in the source, excluding blanks, and all control characters (except -- that ESC is included in the checksum). Upper case letters not in string -- literals are folded by the caller. See Sinput spec for the documentation -- of the checksum algorithm. Note: checksum values are only used if we -- generate code, so it is not necessary to worry about making the right -- sequence of calls in any error situation. procedure Accumulate_Checksum (C : Char_Code); pragma Inline (Accumulate_Checksum); -- This version is identical, except that the argument, C, is a character -- code value instead of a character. This is used when wide characters -- are scanned. We use the character code rather than the ASCII characters -- so that the checksum is independent of wide character encoding method. procedure Initialize_Checksum; pragma Inline (Initialize_Checksum); -- Initialize checksum value procedure Check_End_Of_Line; -- Called when end of line encountered. Checks that line is not -- too long, and that other style checks for the end of line are met. function Determine_License return License_Type; -- Scan header of file and check that it has an appropriate GNAT-style -- header with a proper license statement. Returns GPL, Unrestricted, -- or Modified_GPL depending on header. If none of these, returns Unknown. function Double_Char_Token (C : Character) return Boolean; -- This function is used for double character tokens like := or <>. It -- checks if the character following Source (Scan_Ptr) is C, and if so -- bumps Scan_Ptr past the pair of characters and returns True. A space -- between the two characters is also recognized with an appropriate -- error message being issued. If C is not present, False is returned. -- Note that Double_Char_Token can only be used for tokens defined in -- the Ada syntax (it's use for error cases like && is not appropriate -- since we do not want a junk message for a case like &-space-&). procedure Error_Illegal_Character; -- Give illegal character error, Scan_Ptr points to character. On return, -- Scan_Ptr is bumped past the illegal character. procedure Error_Illegal_Wide_Character; -- Give illegal wide character message. On return, Scan_Ptr is bumped -- past the illegal character, which may still leave us pointing to -- junk, not much we can do if the escape sequence is messed up! procedure Error_Long_Line; -- Signal error of excessively long line procedure Error_No_Double_Underline; -- Signal error of double underline character procedure Nlit; -- This is the procedure for scanning out numeric literals. On entry, -- Scan_Ptr points to the digit that starts the numeric literal (the -- checksum for this character has not been accumulated yet). On return -- Scan_Ptr points past the last character of the numeric literal, Token -- and Token_Node are set appropriately, and the checksum is updated. function Set_Start_Column return Column_Number; -- This routine is called with Scan_Ptr pointing to the first character -- of a line. On exit, Scan_Ptr is advanced to the first non-blank -- character of this line (or to the terminating format effector if the -- line contains no non-blank characters), and the returned result is the -- column number of this non-blank character (zero origin), which is the -- value to be stored in the Start_Column scan variable. procedure Slit; -- This is the procedure for scanning out string literals. On entry, -- Scan_Ptr points to the opening string quote (the checksum for this -- character has not been accumulated yet). On return Scan_Ptr points -- past the closing quote of the string literal, Token and Token_Node -- are set appropriately, and the checksum is upated. ------------------------- -- Accumulate_Checksum -- ------------------------- procedure Accumulate_Checksum (C : Character) is begin System.CRC32.Update (System.CRC32.CRC32 (Checksum), C); end Accumulate_Checksum; procedure Accumulate_Checksum (C : Char_Code) is begin Accumulate_Checksum (Character'Val (C / 256)); Accumulate_Checksum (Character'Val (C mod 256)); end Accumulate_Checksum; ----------------------- -- Check_End_Of_Line -- ----------------------- procedure Check_End_Of_Line is Len : constant Int := Int (Scan_Ptr) - Int (Current_Line_Start); begin if Len > Hostparm.Max_Line_Length then Error_Long_Line; elsif Style_Check then Style.Check_Line_Terminator (Len); end if; end Check_End_Of_Line; ----------------------- -- Determine_License -- ----------------------- function Determine_License return License_Type is GPL_Found : Boolean := False; function Contains (S : String) return Boolean; -- See if current comment contains successive non-blank characters -- matching the contents of S. If so leave Scan_Ptr unchanged and -- return True, otherwise leave Scan_Ptr unchanged and return False. procedure Skip_EOL; -- Skip to line terminator character -------------- -- Contains -- -------------- function Contains (S : String) return Boolean is CP : Natural; SP : Source_Ptr; SS : Source_Ptr; begin SP := Scan_Ptr; while Source (SP) /= CR and then Source (SP) /= LF loop if Source (SP) = S (S'First) then SS := SP; CP := S'First; loop SS := SS + 1; CP := CP + 1; if CP > S'Last then return True; end if; while Source (SS) = ' ' loop SS := SS + 1; end loop; exit when Source (SS) /= S (CP); end loop; end if; SP := SP + 1; end loop; return False; end Contains; -------------- -- Skip_EOL -- -------------- procedure Skip_EOL is begin while Source (Scan_Ptr) /= CR and then Source (Scan_Ptr) /= LF loop Scan_Ptr := Scan_Ptr + 1; end loop; end Skip_EOL; -- Start of processing for Determine_License begin loop if Source (Scan_Ptr) /= '-' or else Source (Scan_Ptr + 1) /= '-' then if GPL_Found then return GPL; else return Unknown; end if; elsif Contains (""Asaspecialexception"") then if GPL_Found then return Modified_GPL; end if; elsif Contains (""GNUGeneralPublicLicense"") then GPL_Found := True; elsif Contains (""ThisspecificationisadaptedfromtheAdaSemanticInterface"") or else Contains (""ThisspecificationisderivedfromtheAdaReferenceManual"") then return Unrestricted; end if; Skip_EOL; Check_End_Of_Line; declare Physical : Boolean; begin Skip_Line_Terminators (Scan_Ptr, Physical); -- If we are at start of physical line, update scan pointers -- to reflect the start of the new line. if Physical then Current_Line_Start := Scan_Ptr; Start_Column := Set_Start_Column; First_Non_Blank_Location := Scan_Ptr; end if; end; end loop; end Determine_License; ---------------------------- -- Determine_Token_Casing -- ---------------------------- function Determine_Token_Casing return Casing_Type is begin return Determine_Casing (Source (Token_Ptr .. Scan_Ptr - 1)); end Determine_Token_Casing; ----------------------- -- Double_Char_Token -- ----------------------- function Double_Char_Token (C : Character) return Boolean is begin if Source (Scan_Ptr + 1) = C then Accumulate_Checksum (C); Scan_Ptr := Scan_Ptr + 2; return True; elsif Source (Scan_Ptr + 1) = ' ' and then Source (Scan_Ptr + 2) = C then Scan_Ptr := Scan_Ptr + 1; Error_Msg_S (""no space allowed here""); Scan_Ptr := Scan_Ptr + 2; return True; else return False; end if; end Double_Char_Token; ----------------------------- -- Error_Illegal_Character -- ----------------------------- procedure Error_Illegal_Character is begin Error_Msg_S (""illegal character""); Scan_Ptr := Scan_Ptr + 1; end Error_Illegal_Character; ---------------------------------- -- Error_Illegal_Wide_Character -- ---------------------------------- procedure Error_Illegal_Wide_Character is begin if OpenVMS then Error_Msg_S (""illegal wide character, check "" & ""'/'W'I'D'E'_'C'H'A'R'A'C'T'E'R'_'E'N'C'O'D'I'N'G qualifer""); else Error_Msg_S (""illegal wide character, check -gnatW switch""); end if; Scan_Ptr := Scan_Ptr + 1; end Error_Illegal_Wide_Character; --------------------- -- Error_Long_Line -- --------------------- procedure Error_Long_Line is begin Error_Msg (""this line is too long"", Current_Line_Start + Hostparm.Max_Line_Length); end Error_Long_Line; ------------------------------- -- Error_No_Double_Underline -- ------------------------------- procedure Error_No_Double_Underline is begin Error_Msg_S (""two consecutive underlines not permitted""); end Error_No_Double_Underline; ------------------------- -- Initialize_Checksum -- ------------------------- procedure Initialize_Checksum is begin System.CRC32.Initialize (System.CRC32.CRC32 (Checksum)); end Initialize_Checksum; ------------------------ -- Initialize_Scanner -- ------------------------ procedure Initialize_Scanner (Unit : Unit_Number_Type; Index : Source_File_Index) is GNAT_Hedr : constant Text_Buffer (1 .. 78) := (others => '-'); begin -- Set up Token_Type values in Names Table entries for reserved keywords -- We use the Pos value of the Token_Type value. Note we are relying on -- the fact that Token_Type'Val (0) is not a reserved word! Set_Name_Table_Byte (Name_Abort, Token_Type'Pos (Tok_Abort)); Set_Name_Table_Byte (Name_Abs, Token_Type'Pos (Tok_Abs)); Set_Name_Table_Byte (Name_Abstract, Token_Type'Pos (Tok_Abstract)); Set_Name_Table_Byte (Name_Accept, Token_Type'Pos (Tok_Accept)); Set_Name_Table_Byte (Name_Access, Token_Type'Pos (Tok_Access)); Set_Name_Table_Byte (Name_And, Token_Type'Pos (Tok_And)); Set_Name_Table_Byte (Name_Aliased, Token_Type'Pos (Tok_Aliased)); Set_Name_Table_Byte (Name_All, Token_Type'Pos (Tok_All)); Set_Name_Table_Byte (Name_Array, Token_Type'Pos (Tok_Array)); Set_Name_Table_Byte (Name_At, Token_Type'Pos (Tok_At)); Set_Name_Table_Byte (Name_Begin, Token_Type'Pos (Tok_Begin)); Set_Name_Table_Byte (Name_Body, Token_Type'Pos (Tok_Body)); Set_Name_Table_Byte (Name_Case, Token_Type'Pos (Tok_Case)); Set_Name_Table_Byte (Name_Constant, Token_Type'Pos (Tok_Constant)); Set_Name_Table_Byte (Name_Declare, Token_Type'Pos (Tok_Declare)); Set_Name_Table_Byte (Name_Delay, Token_Type'Pos (Tok_Delay)); Set_Name_Table_Byte (Name_Delta, Token_Type'Pos (Tok_Delta)); Set_Name_Table_Byte (Name_Digits, Token_Type'Pos (Tok_Digits)); Set_Name_Table_Byte (Name_Do, Token_Type'Pos (Tok_Do)); Set_Name_Table_Byte (Name_Else, Token_Type'Pos (Tok_Else)); Set_Name_Table_Byte (Name_Elsif, Token_Type'Pos (Tok_Elsif)); Set_Name_Table_Byte (Name_End, Token_Type'Pos (Tok_End)); Set_Name_Table_Byte (Name_Entry, Token_Type'Pos (Tok_Entry)); Set_Name_Table_Byte (Name_Exception, Token_Type'Pos (Tok_Exception)); Set_Name_Table_Byte (Name_Exit, Token_Type'Pos (Tok_Exit)); Set_Name_Table_Byte (Name_For, Token_Type'Pos (Tok_For)); Set_Name_Table_Byte (Name_Function, Token_Type'Pos (Tok_Function)); Set_Name_Table_Byte (Name_Generic, Token_Type'Pos (Tok_Generic)); Set_Name_Table_Byte (Name_Goto, Token_Type'Pos (Tok_Goto)); Set_Name_Table_Byte (Name_If, Token_Type'Pos (Tok_If)); Set_Name_Table_Byte (Name_In, Token_Type'Pos (Tok_In)); Set_Name_Table_Byte (Name_Is, Token_Type'Pos (Tok_Is)); Set_Name_Table_Byte (Name_Limited, Token_Type'Pos (Tok_Limited)); Set_Name_Table_Byte (Name_Loop, Token_Type'Pos (Tok_Loop)); Set_Name_Table_Byte (Name_Mod, Token_Type'Pos (Tok_Mod)); Set_Name_Table_Byte (Name_New, Token_Type'Pos (Tok_New)); Set_Name_Table_Byte (Name_Not, Token_Type'Pos (Tok_Not)); Set_Name_Table_Byte (Name_Null, Token_Type'Pos (Tok_Null)); Set_Name_Table_Byte (Name_Of, Token_Type'Pos (Tok_Of)); Set_Name_Table_Byte (Name_Or, Token_Type'Pos (Tok_Or)); Set_Name_Table_Byte (Name_Others, Token_Type'Pos (Tok_Others)); Set_Name_Table_Byte (Name_Out, Token_Type'Pos (Tok_Out)); Set_Name_Table_Byte (Name_Package, Token_Type'Pos (Tok_Package)); Set_Name_Table_Byte (Name_Pragma, Token_Type'Pos (Tok_Pragma)); Set_Name_Table_Byte (Name_Private, Token_Type'Pos (Tok_Private)); Set_Name_Table_Byte (Name_Procedure, Token_Type'Pos (Tok_Procedure)); Set_Name_Table_Byte (Name_Protected, Token_Type'Pos (Tok_Protected)); Set_Name_Table_Byte (Name_Raise, Token_Type'Pos (Tok_Raise)); Set_Name_Table_Byte (Name_Range, Token_Type'Pos (Tok_Range)); Set_Name_Table_Byte (Name_Record, Token_Type'Pos (Tok_Record)); Set_Name_Table_Byte (Name_Rem, Token_Type'Pos (Tok_Rem)); Set_Name_Table_Byte (Name_Renames, Token_Type'Pos (Tok_Renames)); Set_Name_Table_Byte (Name_Requeue, Token_Type'Pos (Tok_Requeue)); Set_Name_Table_Byte (Name_Return, Token_Type'Pos (Tok_Return)); Set_Name_Table_Byte (Name_Reverse, Token_Type'Pos (Tok_Reverse)); Set_Name_Table_Byte (Name_Select, Token_Type'Pos (Tok_Select)); Set_Name_Table_Byte (Name_Separate, Token_Type'Pos (Tok_Separate)); Set_Name_Table_Byte (Name_Subtype, Token_Type'Pos (Tok_Subtype)); Set_Name_Table_Byte (Name_Tagged, Token_Type'Pos (Tok_Tagged)); Set_Name_Table_Byte (Name_Task, Token_Type'Pos (Tok_Task)); Set_Name_Table_Byte (Name_Terminate, Token_Type'Pos (Tok_Terminate)); Set_Name_Table_Byte (Name_Then, Token_Type'Pos (Tok_Then)); Set_Name_Table_Byte (Name_Type, Token_Type'Pos (Tok_Type)); Set_Name_Table_Byte (Name_Until, Token_Type'Pos (Tok_Until)); Set_Name_Table_Byte (Name_Use, Token_Type'Pos (Tok_Use)); Set_Name_Table_Byte (Name_When, Token_Type'Pos (Tok_When)); Set_Name_Table_Byte (Name_While, Token_Type'Pos (Tok_While)); Set_Name_Table_Byte (Name_With, Token_Type'Pos (Tok_With)); Set_Name_Table_Byte (Name_Xor, Token_Type'Pos (Tok_Xor)); -- Initialize scan control variables Current_Source_File := Index; Source := Source_Text (Current_Source_File); Current_Source_Unit := Unit; Scan_Ptr := Source_First (Current_Source_File); Token := No_Token; Token_Ptr := Scan_Ptr; Current_Line_Start := Scan_Ptr; Token_Node := Empty; Token_Name := No_Name; Start_Column := Set_Start_Column; First_Non_Blank_Location := Scan_Ptr; Initialize_Checksum; -- Set default for Comes_From_Source. All nodes built now until we -- reenter the analyzer will have Comes_From_Source set to True Set_Comes_From_Source_Default (True); -- Check license if GNAT type header possibly present if Source_Last (Index) - Scan_Ptr > 80 and then Source (Scan_Ptr .. Scan_Ptr + 77) = GNAT_Hedr then Set_License (Current_Source_File, Determine_License); end if; -- Scan initial token (note this initializes Prev_Token, Prev_Token_Ptr) Scan; -- Clear flags for reserved words used as identifiers for J in Token_Type loop Used_As_Identifier (J) := False; end loop; end Initialize_Scanner; ---------- -- Nlit -- ---------- procedure Nlit is separate; ---------- -- Scan -- ---------- procedure Scan is begin Prev_Token := Token; Prev_Token_Ptr := Token_Ptr; Token_Name := Error_Name; -- The following loop runs more than once only if a format effector -- (tab, vertical tab, form feed, line feed, carriage return) is -- encountered and skipped, or some error situation, such as an -- illegal character, is encountered. loop -- Skip past blanks, loop is opened up for speed while Source (Scan_Ptr) = ' ' loop if Source (Scan_Ptr + 1) /= ' ' then Scan_Ptr := Scan_Ptr + 1; exit; end if; if Source (Scan_Ptr + 2) /= ' ' then Scan_Ptr := Scan_Ptr + 2; exit; end if; if Source (Scan_Ptr + 3) /= ' ' then Scan_Ptr := Scan_Ptr + 3; exit; end if; if Source (Scan_Ptr + 4) /= ' ' then Scan_Ptr := Scan_Ptr + 4; exit; end if; if Source (Scan_Ptr + 5) /= ' ' then Scan_Ptr := Scan_Ptr + 5; exit; end if; if Source (Scan_Ptr + 6) /= ' ' then Scan_Ptr := Scan_Ptr + 6; exit; end if; if Source (Scan_Ptr + 7) /= ' ' then Scan_Ptr := Scan_Ptr + 7; exit; end if; Scan_Ptr := Scan_Ptr + 8; end loop; -- We are now at a non-blank character, which is the first character -- of the token we will scan, and hence the value of Token_Ptr. Token_Ptr := Scan_Ptr; -- Here begins the main case statement which transfers control on -- the basis of the non-blank character we have encountered. case Source (Scan_Ptr) is -- Line terminator characters when CR | LF | FF | VT => Line_Terminator_Case : begin -- Check line too long Check_End_Of_Line; declare Physical : Boolean; begin Skip_Line_Terminators (Scan_Ptr, Physical); -- If we are at start of physical line, update scan pointers -- to reflect the start of the new line. if Physical then Current_Line_Start := Scan_Ptr; Start_Column := Set_Start_Column; First_Non_Blank_Location := Scan_Ptr; end if; end; end Line_Terminator_Case; -- Horizontal tab, just skip past it when HT => if Style_Check then Style.Check_HT; end if; Scan_Ptr := Scan_Ptr + 1; -- End of file character, treated as an end of file only if it -- is the last character in the buffer, otherwise it is ignored. when EOF => if Scan_Ptr = Source_Last (Current_Source_File) then Check_End_Of_Line; Token := Tok_EOF; return; else Scan_Ptr := Scan_Ptr + 1; end if; -- Ampersand when '&' => Accumulate_Checksum ('&'); if Source (Scan_Ptr + 1) = '&' then Error_Msg_S (""'&'& should be `AND THEN`""); Scan_Ptr := Scan_Ptr + 2; Token := Tok_And; return; else Scan_Ptr := Scan_Ptr + 1; Token := Tok_Ampersand; return; end if; -- Asterisk (can be multiplication operator or double asterisk -- which is the exponentiation compound delimtier). when '*' => Accumulate_Checksum ('*'); if Source (Scan_Ptr + 1) = '*' then Accumulate_Checksum ('*'); Scan_Ptr := Scan_Ptr + 2; Token := Tok_Double_Asterisk; return; else Scan_Ptr := Scan_Ptr + 1; Token := Tok_Asterisk; return; end if; -- Colon, which can either be an isolated colon, or part of an -- assignment compound delimiter. when ':' => Accumulate_Checksum (':'); if Double_Char_Token ('=') then Token := Tok_Colon_Equal; if Style_Check then Style.Check_Colon_Equal; end if; return; elsif Source (Scan_Ptr + 1) = '-' and then Source (Scan_Ptr + 2) /= '-' then Token := Tok_Colon_Equal; Error_Msg ("":- should be :="", Scan_Ptr); Scan_Ptr := Scan_Ptr + 2; return; else Scan_Ptr := Scan_Ptr + 1; Token := Tok_Colon; if Style_Check then Style.Check_Colon; end if; return; end if; -- Left parenthesis when '(' => Accumulate_Checksum ('('); Scan_Ptr := Scan_Ptr + 1; Token := Tok_Left_Paren; if Style_Check then Style.Check_Left_Paren; end if; return; -- Left bracket when '[' => if Source (Scan_Ptr + 1) = '""' then Name_Len := 0; goto Scan_Identifier; else Error_Msg_S (""illegal character, replaced by """"(""""""); Scan_Ptr := Scan_Ptr + 1; Token := Tok_Left_Paren; return; end if; -- Left brace when '{' => Error_Msg_S (""illegal character, replaced by """"(""""""); Scan_Ptr := Scan_Ptr + 1; Token := Tok_Left_Paren; return; -- Comma when ',' => Accumulate_Checksum (','); Scan_Ptr := Scan_Ptr + 1; Token := Tok_Comma; if Style_Check then Style.Check_Comma; end if; return; -- Dot, which is either an isolated period, or part of a double -- dot compound delimiter sequence. We also check for the case of -- a digit following the period, to give a better error message. when '.' => Accumulate_Checksum ('.'); if Double_Char_Token ('.') then Token := Tok_Dot_Dot; if Style_Check then Style.Check_Dot_Dot; end if; return; elsif Source (Scan_Ptr + 1) in '0' .. '9' then Error_Msg_S (""numeric literal cannot start with point""); Scan_Ptr := Scan_Ptr + 1; else Scan_Ptr := Scan_Ptr + 1; Token := Tok_Dot; return; end if; -- Equal, which can either be an equality operator, or part of the -- arrow (=>) compound delimiter. when '=' => Accumulate_Checksum ('='); if Double_Char_Token ('>') then Token := Tok_Arrow; if Style_Check then Style.Check_Arrow; end if; return; elsif Source (Scan_Ptr + 1) = '=' then Error_Msg_S (""== should be =""); Scan_Ptr := Scan_Ptr + 1; end if; Scan_Ptr := Scan_Ptr + 1; Token := Tok_Equal; return; -- Greater than, which can be a greater than operator, greater than -- or equal operator, or first character of a right label bracket. when '>' => Accumulate_Checksum ('>'); if Double_Char_Token ('=') then Token := Tok_Greater_Equal; return; elsif Double_Char_Token ('>') then Token := Tok_Greater_Greater; return; else Scan_Ptr := Scan_Ptr + 1; Token := Tok_Greater; return; end if; -- Less than, which can be a less than operator, less than or equal -- operator, or the first character of a left label bracket, or the -- first character of a box (<>) compound delimiter. when '<' => Accumulate_Checksum ('<'); if Double_Char_Token ('=') then Token := Tok_Less_Equal; return; elsif Double_Char_Token ('>') then Token := Tok_Box; if Style_Check then Style.Check_Box; end if; return; elsif Double_Char_Token ('<') then Token := Tok_Less_Less; return; else Scan_Ptr := Scan_Ptr + 1; Token := Tok_Less; return; end if; -- Minus, which is either a subtraction operator, or the first -- character of double minus starting a comment when '-' => Minus_Case : begin if Source (Scan_Ptr + 1) = '>' then Error_Msg_S (""invalid token""); Scan_Ptr := Scan_Ptr + 2; Token := Tok_Arrow; return; elsif Source (Scan_Ptr + 1) /= '-' then Accumulate_Checksum ('-'); Scan_Ptr := Scan_Ptr + 1; Token := Tok_Minus; return; -- Comment else -- Source (Scan_Ptr + 1) = '-' then if Style_Check then Style.Check_Comment; end if; Scan_Ptr := Scan_Ptr + 2; -- Loop to scan comment (this loop runs more than once only if -- a horizontal tab or other non-graphic character is scanned) loop -- Scan to non graphic character (opened up for speed) loop exit when Source (Scan_Ptr) not in Graphic_Character; Scan_Ptr := Scan_Ptr + 1; exit when Source (Scan_Ptr) not in Graphic_Character; Scan_Ptr := Scan_Ptr + 1; exit when Source (Scan_Ptr) not in Graphic_Character; Scan_Ptr := Scan_Ptr + 1; exit when Source (Scan_Ptr) not in Graphic_Character; Scan_Ptr := Scan_Ptr + 1; exit when Source (Scan_Ptr) not in Graphic_Character; Scan_Ptr := Scan_Ptr + 1; end loop; -- Keep going if horizontal tab if Source (Scan_Ptr) = HT then if Style_Check then Style.Check_HT; end if; Scan_Ptr := Scan_Ptr + 1; -- Terminate scan of comment if line terminator elsif Source (Scan_Ptr) in Line_Terminator then exit; -- Terminate scan of comment if end of file encountered -- (embedded EOF character or real last character in file) elsif Source (Scan_Ptr) = EOF then exit; -- Keep going if character in 80-FF range, or is ESC. These -- characters are allowed in comments by RM-2.1(1), 2.7(2). -- They are allowed even in Ada 83 mode according to the -- approved AI. ESC was added to the AI in June 93. elsif Source (Scan_Ptr) in Upper_Half_Character or else Source (Scan_Ptr) = ESC then Scan_Ptr := Scan_Ptr + 1; -- Otherwise we have an illegal comment character else Error_Illegal_Character; end if; end loop; -- Note that we do NOT execute a return here, instead we fall -- through to reexecute the scan loop to look for a token. end if; end Minus_Case; -- Double quote or percent starting a string literal when '""' | '%' => Slit; return; -- Apostrophe. This can either be the start of a character literal, -- or an isolated apostrophe used in a qualified expression or an -- attribute. We treat it as a character literal if it does not -- follow a right parenthesis, identifier, the keyword ALL or -- a literal. This means that we correctly treat constructs like: -- A := CHARACTER'('A'); -- Note that RM-2.2(7) does not require a separator between -- ""CHARACTER"" and ""'"" in the above. when ''' => Char_Literal_Case : declare Code : Char_Code; Err : Boolean; begin Accumulate_Checksum ('''); Scan_Ptr := Scan_Ptr + 1; -- Here is where we make the test to distinguish the cases. Treat -- as apostrophe if previous token is an identifier, right paren -- or the reserved word ""all"" (latter case as in A.all'Address) -- Also treat it as apostrophe after a literal (this catches -- some legitimate cases, like A.""abs""'Address, and also gives -- better error behavior for impossible cases like 123'xxx). if Prev_Token = Tok_Identifier or else Prev_Token = Tok_Right_Paren or else Prev_Token = Tok_All or else Prev_Token in Token_Class_Literal then Token := Tok_Apostrophe; return; -- Otherwise the apostrophe starts a character literal else -- Case of wide character literal with ESC or [ encoding if (Source (Scan_Ptr) = ESC and then Wide_Character_Encoding_Method in WC_ESC_Encoding_Method) or else (Source (Scan_Ptr) in Upper_Half_Character and then Upper_Half_Encoding) or else (Source (Scan_Ptr) = '[' and then Source (Scan_Ptr + 1) = '""') then Scan_Wide (Source, Scan_Ptr, Code, Err); Accumulate_Checksum (Code); if Err then Error_Illegal_Wide_Character; end if; if Source (Scan_Ptr) /= ''' then Error_Msg_S (""missing apostrophe""); else Scan_Ptr := Scan_Ptr + 1; end if; -- If we do not find a closing quote in the expected place then -- assume that we have a misguided attempt at a string literal. -- However, if previous token is RANGE, then we return an -- apostrophe instead since this gives better error recovery elsif Source (Scan_Ptr + 1) /= ''' then if Prev_Token = Tok_Range then Token := Tok_Apostrophe; return; else Scan_Ptr := Scan_Ptr - 1; Error_Msg_S (""strings are delimited by double quote character""); Scn.Slit; return; end if; -- Otherwise we have a (non-wide) character literal else Accumulate_Checksum (Source (Scan_Ptr)); if Source (Scan_Ptr) not in Graphic_Character then if Source (Scan_Ptr) in Upper_Half_Character then if Ada_83 then Error_Illegal_Character; end if; else Error_Illegal_Character; end if; end if; Code := Get_Char_Code (Source (Scan_Ptr)); Scan_Ptr := Scan_Ptr + 2; end if; -- Fall through here with Scan_Ptr updated past the closing -- quote, and Code set to the Char_Code value for the literal Accumulate_Checksum ('''); Token := Tok_Char_Literal; Token_Node := New_Node (N_Character_Literal, Token_Ptr); Set_Char_Literal_Value (Token_Node, Code); Set_Character_Literal_Name (Code); Token_Name := Name_Find; Set_Chars (Token_Node, Token_Name); return; end if; end Char_Literal_Case; -- Right parenthesis when ')' => Accumulate_Checksum (')'); Scan_Ptr := Scan_Ptr + 1; Token := Tok_Right_Paren; if Style_Check then Style.Check_Right_Paren; end if; return; -- Right bracket or right brace, treated as right paren when ']' | '}' => Error_Msg_S (""illegal character, replaced by """")""""""); Scan_Ptr := Scan_Ptr + 1; Token := Tok_Right_Paren; return; -- Slash (can be division operator or first character of not equal) when '/' => Accumulate_Checksum ('/'); if Double_Char_Token ('=') then Token := Tok_Not_Equal; return; else Scan_Ptr := Scan_Ptr + 1; Token := Tok_Slash; return; end if; -- Semicolon when ';' => Accumulate_Checksum (';'); Scan_Ptr := Scan_Ptr + 1; Token := Tok_Semicolon; if Style_Check then Style.Check_Semicolon; end if; return; -- Vertical bar when '|' => Vertical_Bar_Case : begin Accumulate_Checksum ('|'); -- Special check for || to give nice message if Source (Scan_Ptr + 1) = '|' then Error_Msg_S (""""""||"""" should be `OR ELSE`""); Scan_Ptr := Scan_Ptr + 2; Token := Tok_Or; return; else Scan_Ptr := Scan_Ptr + 1; Token := Tok_Vertical_Bar; if Style_Check then Style.Check_Vertical_Bar; end if; return; end if; end Vertical_Bar_Case; -- Exclamation, replacement character for vertical bar when '!' => Exclamation_Case : begin Accumulate_Checksum ('!'); if Source (Scan_Ptr + 1) = '=' then Error_Msg_S (""'!= should be /=""); Scan_Ptr := Scan_Ptr + 2; Token := Tok_Not_Equal; return; else Scan_Ptr := Scan_Ptr + 1; Token := Tok_Vertical_Bar; return; end if; end Exclamation_Case; -- Plus when '+' => Plus_Case : begin Accumulate_Checksum ('+'); Scan_Ptr := Scan_Ptr + 1; Token := Tok_Plus; return; end Plus_Case; -- Digits starting a numeric literal when '0' .. '9' => Nlit; if Identifier_Char (Source (Scan_Ptr)) then Error_Msg_S (""delimiter required between literal and identifier""); end if; return; -- Lower case letters when 'a' .. 'z' => Name_Len := 1; Name_Buffer (1) := Source (Scan_Ptr); Accumulate_Checksum (Name_Buffer (1)); Scan_Ptr := Scan_Ptr + 1; goto Scan_Identifier; -- Upper case letters when 'A' .. 'Z' => Name_Len := 1; Name_Buffer (1) := Character'Val (Character'Pos (Source (Scan_Ptr)) + 32); Accumulate_Checksum (Name_Buffer (1)); Scan_Ptr := Scan_Ptr + 1; goto Scan_Identifier; -- Underline character when '_' => Error_Msg_S (""identifier cannot start with underline""); Name_Len := 1; Name_Buffer (1) := '_'; Scan_Ptr := Scan_Ptr + 1; goto Scan_Identifier; -- Space (not possible, because we scanned past blanks) when ' ' => raise Program_Error; -- Characters in top half of ASCII 8-bit chart when Upper_Half_Character => -- Wide character case. Note that Scan_Identifier will issue -- an appropriate message if wide characters are not allowed -- in identifiers. if Upper_Half_Encoding then Name_Len := 0; goto Scan_Identifier; -- Otherwise we have OK Latin-1 character else -- Upper half characters may possibly be identifier letters -- but can never be digits, so Identifier_Character can be -- used to test for a valid start of identifier character. if Identifier_Char (Source (Scan_Ptr)) then Name_Len := 0; goto Scan_Identifier; else Error_Illegal_Character; end if; end if; when ESC => -- ESC character, possible start of identifier if wide characters -- using ESC encoding are allowed in identifiers, which we can -- tell by looking at the Identifier_Char flag for ESC, which is -- only true if these conditions are met. if Identifier_Char (ESC) then Name_Len := 0; goto Scan_Identifier; else Error_Illegal_Wide_Character; end if; -- Invalid control characters when NUL | SOH | STX | ETX | EOT | ENQ | ACK | BEL | BS | SO | SI | DLE | DC1 | DC2 | DC3 | DC4 | NAK | SYN | ETB | CAN | EM | FS | GS | RS | US | DEL => Error_Illegal_Character; -- Invalid graphic characters when '#' | '$' | '?' | '@' | '`' | '\\' | '^' | '~' => Error_Illegal_Character; -- End switch on non-blank character end case; -- End loop past format effectors. The exit from this loop is by -- executing a return statement following completion of token scan -- (control never falls out of this loop to the code which follows) end loop; -- Identifier scanning routine. On entry, some initial characters -- of the identifier may have already been stored in Name_Buffer. -- If so, Name_Len has the number of characters stored. otherwise -- Name_Len is set to zero on entry. <> -- This loop scans as fast as possible past lower half letters -- and digits, which we expect to be the most common characters. loop if Source (Scan_Ptr) in 'a' .. 'z' or else Source (Scan_Ptr) in '0' .. '9' then Name_Buffer (Name_Len + 1) := Source (Scan_Ptr); Accumulate_Checksum (Source (Scan_Ptr)); elsif Source (Scan_Ptr) in 'A' .. 'Z' then Name_Buffer (Name_Len + 1) := Character'Val (Character'Pos (Source (Scan_Ptr)) + 32); Accumulate_Checksum (Name_Buffer (Name_Len + 1)); else exit; end if; -- Open out the loop a couple of times for speed if Source (Scan_Ptr + 1) in 'a' .. 'z' or else Source (Scan_Ptr + 1) in '0' .. '9' then Name_Buffer (Name_Len + 2) := Source (Scan_Ptr + 1); Accumulate_Checksum (Source (Scan_Ptr + 1)); elsif Source (Scan_Ptr + 1) in 'A' .. 'Z' then Name_Buffer (Name_Len + 2) := Character'Val (Character'Pos (Source (Scan_Ptr + 1)) + 32); Accumulate_Checksum (Name_Buffer (Name_Len + 2)); else Scan_Ptr := Scan_Ptr + 1; Name_Len := Name_Len + 1; exit; end if; if Source (Scan_Ptr + 2) in 'a' .. 'z' or else Source (Scan_Ptr + 2) in '0' .. '9' then Name_Buffer (Name_Len + 3) := Source (Scan_Ptr + 2); Accumulate_Checksum (Source (Scan_Ptr + 2)); elsif Source (Scan_Ptr + 2) in 'A' .. 'Z' then Name_Buffer (Name_Len + 3) := Character'Val (Character'Pos (Source (Scan_Ptr + 2)) + 32); Accumulate_Checksum (Name_Buffer (Name_Len + 3)); else Scan_Ptr := Scan_Ptr + 2; Name_Len := Name_Len + 2; exit; end if; if Source (Scan_Ptr + 3) in 'a' .. 'z' or else Source (Scan_Ptr + 3) in '0' .. '9' then Name_Buffer (Name_Len + 4) := Source (Scan_Ptr + 3); Accumulate_Checksum (Source (Scan_Ptr + 3)); elsif Source (Scan_Ptr + 3) in 'A' .. 'Z' then Name_Buffer (Name_Len + 4) := Character'Val (Character'Pos (Source (Scan_Ptr + 3)) + 32); Accumulate_Checksum (Name_Buffer (Name_Len + 4)); else Scan_Ptr := Scan_Ptr + 3; Name_Len := Name_Len + 3; exit; end if; Scan_Ptr := Scan_Ptr + 4; Name_Len := Name_Len + 4; end loop; -- If we fall through, then we have encountered either an underline -- character, or an extended identifier character (i.e. one from the -- upper half), or a wide character, or an identifier terminator. -- The initial test speeds us up in the most common case where we -- have an identifier terminator. Note that ESC is an identifier -- character only if a wide character encoding method that uses -- ESC encoding is active, so if we find an ESC character we know -- that we have a wide character. if Identifier_Char (Source (Scan_Ptr)) then -- Case of underline, check for error cases of double underline, -- and for a trailing underline character if Source (Scan_Ptr) = '_' then Accumulate_Checksum ('_'); Name_Len := Name_Len + 1; Name_Buffer (Name_Len) := '_'; if Identifier_Char (Source (Scan_Ptr + 1)) then Scan_Ptr := Scan_Ptr + 1; if Source (Scan_Ptr) = '_' then Error_No_Double_Underline; end if; else Error_Msg_S (""identifier cannot end with underline""); Scan_Ptr := Scan_Ptr + 1; end if; goto Scan_Identifier; -- Upper half character elsif Source (Scan_Ptr) in Upper_Half_Character and then not Upper_Half_Encoding then Accumulate_Checksum (Source (Scan_Ptr)); Store_Encoded_Character (Get_Char_Code (Fold_Lower (Source (Scan_Ptr)))); Scan_Ptr := Scan_Ptr + 1; goto Scan_Identifier; -- Left bracket not followed by a quote terminates an identifier. -- This is an error, but we don't want to give a junk error msg -- about wide characters in this case! elsif Source (Scan_Ptr) = '[' and then Source (Scan_Ptr + 1) /= '""' then null; -- We know we have a wide character encoding here (the current -- character is either ESC, left bracket, or an upper half -- character depending on the encoding method). else -- Scan out the wide character and insert the appropriate -- encoding into the name table entry for the identifier. declare Sptr : constant Source_Ptr := Scan_Ptr; Code : Char_Code; Err : Boolean; begin Scan_Wide (Source, Scan_Ptr, Code, Err); Accumulate_Checksum (Code); if Err then Error_Illegal_Wide_Character; else Store_Encoded_Character (Code); end if; -- Make sure we are allowing wide characters in identifiers. -- Note that we allow wide character notation for an OK -- identifier character. This in particular allows bracket -- or other notation to be used for upper half letters. if Identifier_Character_Set /= 'w' and then (not In_Character_Range (Code) or else not Identifier_Char (Get_Character (Code))) then Error_Msg (""wide character not allowed in identifier"", Sptr); end if; end; goto Scan_Identifier; end if; end if; -- Scan of identifier is complete. The identifier is stored in -- Name_Buffer, and Scan_Ptr points past the last character. Token_Name := Name_Find; -- Here is where we check if it was a keyword if Get_Name_Table_Byte (Token_Name) /= 0 and then (Ada_95 or else Token_Name not in Ada_95_Reserved_Words) then Token := Token_Type'Val (Get_Name_Table_Byte (Token_Name)); -- Deal with possible style check for non-lower case keyword, -- but we don't treat ACCESS, DELTA, DIGITS, RANGE as keywords -- for this purpose if they appear as attribute designators. -- Actually we only check the first character for speed. if Style_Check and then Source (Token_Ptr) <= 'Z' and then (Prev_Token /= Tok_Apostrophe or else (Token /= Tok_Access and then Token /= Tok_Delta and then Token /= Tok_Digits and then Token /= Tok_Range)) then Style.Non_Lower_Case_Keyword; end if; -- We must reset Token_Name since this is not an identifier -- and if we leave Token_Name set, the parser gets confused -- because it thinks it is dealing with an identifier instead -- of the corresponding keyword. Token_Name := No_Name; return; -- It is an identifier after all else Token_Node := New_Node (N_Identifier, Token_Ptr); Set_Chars (Token_Node, Token_Name); Token := Tok_Identifier; return; end if; end Scan; --------------------- -- Scan_First_Char -- --------------------- function Scan_First_Char return Source_Ptr is Ptr : Source_Ptr := Current_Line_Start; begin loop if Source (Ptr) = ' ' then Ptr := Ptr + 1; elsif Source (Ptr) = HT then if Style_Check then Style.Check_HT; end if; Ptr := Ptr + 1; else return Ptr; end if; end loop; end Scan_First_Char; ------------------------------ -- Scan_Reserved_Identifier -- ------------------------------ procedure Scan_Reserved_Identifier (Force_Msg : Boolean) is Token_Chars : constant String := Token_Type'Image (Token); begin -- We have in Token_Chars the image of the Token name, i.e. Tok_xxx. -- This code extracts the xxx and makes an identifier out of it. Name_Len := 0; for J in 5 .. Token_Chars'Length loop Name_Len := Name_Len + 1; Name_Buffer (Name_Len) := Fold_Lower (Token_Chars (J)); end loop; Token_Name := Name_Find; if not Used_As_Identifier (Token) or else Force_Msg then Error_Msg_Name_1 := Token_Name; Error_Msg_SC (""reserved word* cannot be used as identifier!""); Used_As_Identifier (Token) := True; end if; Token := Tok_Identifier; Token_Node := New_Node (N_Identifier, Token_Ptr); Set_Chars (Token_Node, Token_Name); end Scan_Reserved_Identifier; ---------------------- -- Set_Start_Column -- ---------------------- -- Note: it seems at first glance a little expensive to compute this value -- for every source line (since it is certainly not used for all source -- lines). On the other hand, it doesn't take much more work to skip past -- the initial white space on the line counting the columns than it would -- to scan past the white space using the standard scanning circuits. function Set_Start_Column return Column_Number is Start_Column : Column_Number := 0; begin -- Outer loop scans past horizontal tab characters Tabs_Loop : loop -- Inner loop scans past blanks as fast as possible, bumping Scan_Ptr -- past the blanks and adjusting Start_Column to account for them. Blanks_Loop : loop if Source (Scan_Ptr) = ' ' then if Source (Scan_Ptr + 1) = ' ' then if Source (Scan_Ptr + 2) = ' ' then if Source (Scan_Ptr + 3) = ' ' then if Source (Scan_Ptr + 4) = ' ' then if Source (Scan_Ptr + 5) = ' ' then if Source (Scan_Ptr + 6) = ' ' then Scan_Ptr := Scan_Ptr + 7; Start_Column := Start_Column + 7; else Scan_Ptr := Scan_Ptr + 6; Start_Column := Start_Column + 6; exit Blanks_Loop; end if; else Scan_Ptr := Scan_Ptr + 5; Start_Column := Start_Column + 5; exit Blanks_Loop; end if; else Scan_Ptr := Scan_Ptr + 4; Start_Column := Start_Column + 4; exit Blanks_Loop; end if; else Scan_Ptr := Scan_Ptr + 3; Start_Column := Start_Column + 3; exit Blanks_Loop; end if; else Scan_Ptr := Scan_Ptr + 2; Start_Column := Start_Column + 2; exit Blanks_Loop; end if; else Scan_Ptr := Scan_Ptr + 1; Start_Column := Start_Column + 1; exit Blanks_Loop; end if; else exit Blanks_Loop; end if; end loop Blanks_Loop; -- Outer loop keeps going only if a horizontal tab follows if Source (Scan_Ptr) = HT then if Style_Check then Style.Check_HT; end if; Scan_Ptr := Scan_Ptr + 1; Start_Column := (Start_Column / 8) * 8 + 8; else exit Tabs_Loop; end if; end loop Tabs_Loop; return Start_Column; end Set_Start_Column; ---------- -- Slit -- ---------- procedure Slit is separate; end Scn; ",12342,False,2483.650488619327,median "------------------------------------------------------------------------------ -- AGAR CORE LIBRARY -- -- A G A R . O B J E C T -- -- S p e c -- ------------------------------------------------------------------------------ with Agar.Data_Source; with Agar.Event; with Agar.Timer; with Agar.Types; use Agar.Types; with Interfaces; with Interfaces.C; with Interfaces.C.Strings; with System; -- -- Interface to the Agar Object System. This defines the base type, Agar.Object. -- It maps transparently to AG_Object(3) in C. This allows new Agar object -- classes to be written in Ada (and subclasses of Ada-implemented classes -- to be written also in Ada, or again in C). -- -- In C, Agar objects are structs derived from AG_Object. Similarly in Ada, -- Agar object instances are limited records which derive from Agar.Object. -- -- Shared, class-wide data is represented by limited records which derive -- from Agar.Class (equivalent to AG_ObjectClass in C). -- package Agar.Object is package C renames Interfaces.C; package CS renames Interfaces.C.Strings; package DS renames Agar.Data_Source; package EV renames Agar.Event; package TMR renames Agar.Timer; NAME_MAX : constant Natural := $AG_OBJECT_NAME_MAX; HIERARCHY_MAX : constant Natural := $AG_OBJECT_HIER_MAX; TYPE_MAX : constant Natural := $AG_OBJECT_TYPE_MAX; LIBRARIES_MAX : constant Natural := $AG_OBJECT_LIBS_MAX; ---------------- -- Base Types -- ---------------- type Signed_8 is range -127 .. 127 with Convention => C; for Signed_8'Size use 8; type Signed_16 is range -(2 **15) .. +(2 **15 - 1) with Convention => C; for Signed_16'Size use 16; type Signed_32 is range -(2 **31) .. +(2 **31 - 1) with Convention => C; for Signed_32'Size use 32; type Signed_64 is range -(2 **63) .. +(2 **63 - 1) with Convention => C; for Signed_64'Size use 64; subtype Unsigned_8 is Interfaces.Unsigned_8; subtype Unsigned_16 is Interfaces.Unsigned_16; subtype Unsigned_32 is Interfaces.Unsigned_32; subtype Unsigned_64 is Interfaces.Unsigned_64; #if HAVE_FLOAT subtype Float is Interfaces.C.C_float; subtype Double is Interfaces.C.double; # if HAVE_LONG_DOUBLE subtype Long_Double is Interfaces.C.long_double; # end if; #end if; -------------------------- -- Agar Object variable -- -------------------------- type Variable is array (1 .. $SIZEOF_AG_Variable) of aliased Interfaces.Unsigned_8 with Convention => C; for Variable'Size use $SIZEOF_AG_Variable * System.Storage_Unit; type Variable_Access is access all Variable with Convention => C; subtype Variable_not_null_Access is not null Variable_Access; ------------------------------- -- Serialized Object version -- ------------------------------- type Version_t is record Major : Interfaces.Unsigned_32; Minor : Interfaces.Unsigned_32; end record with Convention => C; type Version_Access is access all Version_t with Convention => C; -------------------------- -- Agar Object Instance -- -------------------------- type Object; type Object_Access is access all Object with Convention => C; subtype Object_not_null_Access is not null Object_Access; type Object_Name is array (1 .. NAME_MAX) of aliased c.char with Convention => C; type Class; type Class_Access is access all Class with Convention => C; subtype Class_not_null_Access is not null Class_Access; type Dependency is array (1 .. $SIZEOF_AG_ObjectDep) of aliased Interfaces.Unsigned_8 with Convention => C; for Dependency'Size use $SIZEOF_Ag_ObjectDep * System.Storage_Unit; type Dependency_Access is access all Dependency with Convention => C; subtype Dependency_not_null_Access is not null Dependency_Access; type Dependency_List is limited record First : Dependency_Access; Last : access Dependency_Access; end record with Convention => C; type Event_List is limited record First : EV.Event_Access; Last : access EV.Event_Access; end record with Convention => C; type Timer_List is limited record First : TMR.Timer_Access; Last : access TMR.Timer_Access; end record with Convention => C; type Variable_List is limited record First : Variable_Access; Last : access Variable_Access; end record with Convention => C; type Children_List is limited record First : Object_Access; Last : access Object_Access; end record with Convention => C; type Entry_in_Parent_t is limited record Next : Object_Access; Prev : access Object_Access; end record with Convention => C; type Object_Private is array (1 .. $SIZEOF_AG_ObjectPvt) of aliased Interfaces.Unsigned_8 with Convention => C; for Object_Private'Size use $SIZEOF_AG_ObjectPvt * System.Storage_Unit; OBJECT_FLOATING_VARIABLES : constant C.unsigned := 16#0_0001#; OBJECT_NON_PERSISTENT : constant C.unsigned := 16#0_0002#; OBJECT_INDESTRUCTIBLE : constant C.unsigned := 16#0_0004#; OBJECT_RESIDENT : constant C.unsigned := 16#0_0008#; OBJECT_PRESERVE_DEPENDENCIES : constant C.unsigned := 16#0_0010#; OBJECT_STATIC : constant C.unsigned := 16#0_0020#; OBJECT_READ_ONLY : constant C.unsigned := 16#0_0040#; OBJECT_WAS_RESIDENT : constant C.unsigned := 16#0_0080#; OBJECT_REOPEN_ON_LOAD : constant C.unsigned := 16#0_0200#; OBJECT_REMAIN_DATA : constant C.unsigned := 16#0_0400#; OBJECT_DEBUG : constant C.unsigned := 16#0_0800#; OBJECT_NAME_ON_ATTACH : constant C.unsigned := 16#0_1000#; OBJECT_CHILD_AUTO_SAVE : constant C.unsigned := 16#0_2000#; OBJECT_DEBUG_DATA : constant C.unsigned := 16#0_4000#; OBJECT_IN_ATTACH_ROUTINE : constant C.unsigned := 16#0_8000#; OBJECT_IN_DETACH_ROUTINE : constant C.unsigned := 16#1_0000#; OBJECT_BOUND_EVENTS : constant C.unsigned := 16#2_0000#; type Object is limited record Name : Object_Name; -- TODO 1.6 archivePath/savePfx are going away Archive_Path : CS.chars_ptr; Save_Prefix : CS.chars_ptr; Class : Class_not_null_Access; Flags : C.unsigned; Events : Event_List; Timers : Timer_List; Variables : Variable_List; Dependencies : Dependency_List; Children : Children_List; Entry_in_Parent : Entry_in_Parent_t; Parent : Object_Access; Root : Object_Access; Private_Data : Object_Private; end record with Convention => C; ------------------------------------- -- Accesses to Base Object Methods -- ------------------------------------- type Init_Func_Access is access procedure (Object : Object_Access) with Convention => C; type Reset_Func_Access is access procedure (Object : Object_Access) with Convention => C; type Destroy_Func_Access is access procedure (Object : Object_Access) with Convention => C; type Load_Func_Access is access function (Object : Object_Access; Source : DS.Data_Source_Access; Version : Version_Access) return C.int with Convention => C; type Save_Func_Access is access function (Object : Object_Access; Dest : DS.Data_Source_Access) return C.int with Convention => C; type Edit_Func_Access is access function (Object : Object_Access) return System.Address with Convention => C; ------------------------------ -- Object Class Description -- ------------------------------ type Class_Name is array (1 .. TYPE_MAX) of aliased c.char with Convention => C; type Class_Hierarchy is array (1 .. HIERARCHY_MAX) of aliased c.char with Convention => C; type Class_Private is array (1 .. $SIZEOF_AG_ObjectClassPvt) of aliased Interfaces.Unsigned_8 with Convention => C; for Class_Private'Size use $SIZEOF_AG_ObjectClassPvt * System.Storage_Unit; type Class_Private_Access is access all Class_Private with Convention => C; type Class is limited record Hierarchy : Class_Hierarchy; Size : AG_Size; Version : Version_t; Init_Func : Init_Func_Access; Reset_Func : Reset_Func_Access; Destroy_Func : Destroy_Func_Access; Load_Func : Load_Func_Access; Save_Func : Save_Func_Access; Edit_Func : Edit_Func_Access; -- Generated fields -- Name : Class_Name; Superclass : Class_Access; Private_Data : Class_Private; end record with Convention => C; --------------------------------- -- Serialized Object Signature -- --------------------------------- type Object_Header is array (1 .. $SIZEOF_AG_ObjectHeader) of aliased Interfaces.Unsigned_8 with Convention => C; for Object_Header'Size use $SIZEOF_AG_ObjectHeader * System.Storage_Unit; type Header_Access is access all Object_Header with Convention => C; subtype Header_not_null_Access is not null Header_Access; ----------------------- -- Virtual Functions -- ----------------------- type Function_Access is access all EV.Event with Convention => C; subtype Function_not_null_Access is not null Function_Access; type Event_Func_Access is not null access procedure (Event : EV.Event_Access) with Convention => C; -- -- Create a new instance of Class under Parent with the given name. Fail -- and return null if an object of the same name already exists. -- function New_Object (Parent : in Object_Access; Name : in String; Class : in Class_not_null_Access) return Object_Access; -- -- Create a new instance of Class under Parent, without naming the object. -- function New_Object (Parent : in Object_Access; Class : in Class_not_null_Access) return Object_Access; -- -- Create a new instance of Class not attached to any parent. -- function New_Object (Class : in Class_not_null_Access) return Object_Access; -- -- Initialize an Agar Object. Used internally by New_Object. Static should be -- set unless Object points to auto-allocated and Agar-freeable memory. -- procedure Init_Object (Object : in Object_not_null_Access; Class : in Class_not_null_Access; Static : in Boolean := False); -- -- Make Object a child of Parent. -- procedure Attach (Parent : in Object_Access; Child : in Object_not_null_Access); -- -- Detach Object from its current Parent (if any). -- procedure Detach (Object : in Object_not_null_Access) with Import, Convention => C, Link_Name => ""AG_ObjectDetach""; -- -- Change an object's position within its parent's list of child objects. -- This list is ordered and the order is preserved by serialization. -- procedure Move_Up (Object : in Object_not_null_Access) with Import, Convention => C, Link_Name => ""AG_ObjectMoveUp""; procedure Move_Down (Object : in Object_not_null_Access) with Import, Convention => C, Link_Name => ""AG_ObjectMoveDown""; procedure Move_To_Head (Object : in Object_not_null_Access) with Import, Convention => C, Link_Name => ""AG_ObjectMoveToHead""; procedure Move_To_Tail (Object : in Object_not_null_Access) with Import, Convention => C, Link_Name => ""AG_ObjectMoveToTail""; -- Shorthand for Detach and Destroy. --procedure Delete (Object : in Object_not_null_Access) -- with Import, Convention => C, Link_Name => ""AG_ObjectDelete""; -- -- Return the root object of the VFS that Object is part of. -- May return the Object itself if Object is the VFS root. -- function Root (Object : in Object_not_null_Access) return Object_not_null_Access with Import, Convention => C, Link_Name => ""AG_ObjectRoot""; -- -- Return an access to the Parent of an Object (which can be Null). -- function Parent (Object : in Object_not_null_Access) return Object_Access with Import, Convention => C, Link_Name => ""AG_ObjectParent""; -- -- Lookup an object using an absolute path name (relative to the root of -- the VFS which has object Root as its root). -- function Find (Root : in Object_not_null_Access; Path : in String) return Object_Access; -- -- Search for a parent object matching Name and Object_Type. -- function Find_Parent (Object : in Object_not_null_Access; Name : in String; Class : in String) return Object_Access; -- -- Return Parent's first immediate child object called Name. -- function Find_Child (Parent : in Object_not_null_Access; Name : in String) return Object_Access; -- -- Return the fully qualified path name of Object (within its parent VFS). -- The ""/"" character is used as path separator. -- function Get_Name (Object : in Object_not_null_Access) return String; -- -- Acquire or release the general-purpose mutex lock protecting Object's data. -- This lock is always held implicitely during event processing. -- procedure Lock (Object : in Object_not_null_Access) with Import, Convention => C, Link_Name => ""ag_object_lock""; procedure Unlock (Object : in Object_not_null_Access) with Import, Convention => C, Link_Name => ""ag_object_unlock""; -- -- Acquire or release the mutex lock protecting the entire VFS. -- procedure Lock_VFS (Object : in Object_not_null_Access) with Import, Convention => C, Link_Name => ""ag_lock_vfs""; procedure Unlock_VFS(Object : in Object_not_null_Access) with Import, Convention => C, Link_Name => ""ag_unlock_vfs""; -- -- Rename the object. Does not check for potential conflict. -- procedure Set_Name (Object : in Object_not_null_Access; Name : in String); -- -- Return a unique (relative to its Parent) name for the Object. -- With a class argument, use the form : "" #123"" -- With a Prefix string, use the form : "" #123"" -- function Generate_Name (Object : in Object_not_null_Access; Class : in Class_not_null_Access) return String; function Generate_Name (Object : in Object_not_null_Access; Prefix : in String) return String; -- -- Register a new class given a class description. -- procedure Register_Class (Class : Class_not_null_Access) with Import, Convention => C, Link_Name => ""AG_RegisterClass""; -- -- Delete an existing class. -- procedure Unregister_Class (Class : Class_not_null_Access) with Import, Convention => C, Link_Name => ""AG_UnregisterClass""; -- -- Register a new Agar object class. -- function Create_Class (Hierarchy : in String; Object_Size : in Natural; Class_Size : in Natural; Major : in Natural := 1; Minor : in Natural := 0; Init_Func : in Init_Func_Access := null; Reset_Func : in Reset_Func_Access := null; Destroy_Func : in Destroy_Func_Access := null; Load_Func : in Load_Func_Access := null; Save_Func : in Save_Func_Access := null; Edit_Func : in Edit_Func_Access := null) return Class_not_null_Access; -- -- Remove and deallocate an Agar object class. -- procedure Destroy_Class (Class : Class_not_null_Access) with Import, Convention => C, Link_Name => ""AG_DestroyClass""; -- -- Modify the initialization procedure of a class. -- procedure Class_Set_Init (Class : in Class_not_null_Access; Init_Func : in Init_Func_Access); function Class_Set_Init (Class : in Class_not_null_Access; Init_Func : in Init_Func_Access) return Init_Func_Access; -- -- Modify the reset procedure of a class. -- procedure Class_Set_Reset (Class : in Class_not_null_Access; Reset_Func : in Reset_Func_Access); function Class_Set_Reset (Class : in Class_not_null_Access; Reset_Func : in Reset_Func_Access) return Reset_Func_Access; -- -- Modify the finalization procedure of a class. -- procedure Class_Set_Destroy (Class : in Class_not_null_Access; Destroy_Func : in Destroy_Func_Access); function Class_Set_Destroy (Class : in Class_not_null_Access; Destroy_Func : in Destroy_Func_Access) return Destroy_Func_Access; -- -- Modify the deserialization function of a class. -- procedure Class_Set_Load (Class : in Class_not_null_Access; Load_Func : in Load_Func_Access); function Class_Set_Load (Class : in Class_not_null_Access; Load_Func : in Load_Func_Access) return Load_Func_Access; -- -- Modify the serialization function of a class. -- procedure Class_Set_Save (Class : in Class_not_null_Access; Save_Func : in Save_Func_Access); function Class_Set_Save (Class : in Class_not_null_Access; Save_Func : in Save_Func_Access) return Save_Func_Access; -- -- Modify the (application-specific) edit function of a class. -- procedure Class_Set_Edit (Class : in Class_not_null_Access; Edit_Func : in Edit_Func_Access); function Class_Set_Edit (Class : in Class_not_null_Access; Edit_Func : in Edit_Func_Access) return Edit_Func_Access; -- -- Register a new namespace and prefix. This is used for expanding inheritance -- hierarchy strings such as ""Agar(Foo:Bar)"" to ""AG_Foo:AG_Bar"". -- For example, (""Agar"", ""AG_"", ""http://libagar.org/""). -- procedure Register_Namespace (Name : in String; Prefix : in String; URL : in String); procedure Unregister_Namespace (Name : in String); -- -- Return access to the registered class described by a hierarchy string. -- function Lookup_Class (Class : in String) return Class_Access; -- -- Load any module (and register any class) required to satisfy the given -- inheritance hierarchy. Modules are specified as a comma-separated list -- following '@'. For example: ""MySuper:MySubclass@mymodule"" specifies -- that Load_Class should scan the registered Module Directories for a DSO -- such as mymodule.so. If found, it expects to find a symbol ""mySubclass"" -- pointing to an initialized Class describing MySubclass. -- function Load_Class (Class : in String) return Class_Access; -- -- Add or remove directories to the search path used by Load_Class. -- procedure Register_Module_Directory (Path : in String); procedure Unregister_Module_Directory (Path : in String); -- -- Test if Object is a member of the class described by a String pattern. -- Pattern describes an inheritance hierarchy with possible wildcards (""*""). -- ""Vehicle:Car"" <= True if this is a Car (but not a subclass of Car). -- ""Vehicle:Car:*"" <= True if this is a Car (or a subclass of Car). -- function Is_Of_Class (Object : in Object_not_null_Access; Pattern : in String) return Boolean; function Is_A (Object : in Object_not_null_Access; Pattern : in String) return Boolean; -- -- Test if an object is being referenced by another object in the same VFS. -- function In_Use (Object : in Object_not_null_Access) return Boolean; -- -- Add Dependency to Object's dependency table. If Persistent is True, -- mark the reference as serializable. -- function Add_Dependency (Object : in Object_not_null_Access; Dependency : in Object_not_null_Access; Persistent : in Boolean := False) return Dependency_Access; -- -- Remove Dependency from Object's dependency table. -- procedure Delete_Dependency (Object : in Object_not_null_Access; Dependency : in Object_not_null_Access) with Import, Convention => C, Link_Name => ""AG_ObjectDelDep""; -- -- Return a serializable handle uniquely identifying the entry corresponding -- to the object Dependency within Object's dependency table. -- function Encode_Dependency (Object : in Object_not_null_Access; Dependency : in Object_not_null_Access) return Interfaces.Unsigned_32 with Import, Convention => C, Link_Name => ""AG_ObjectEncodeName""; -- -- Resolve a dependency handle previously generated by Encode_Dependency. If -- successful, return access to the resolved Object in Pointer. -- function Find_Dependency (Object : in Object_not_null_Access; Index : in Interfaces.Unsigned_32; Pointer : access Object_not_null_Access) return Boolean; -- -- Free an Object instance from memory. -- procedure Destroy (Object : in Object_not_null_Access) with Import, Convention => C, Link_Name => ""AG_ObjectDestroy""; -- -- Restore the Object to an initial state. Invoked by both Load and Destroy. -- procedure Reset (Object : in Object_not_null_Access) with Import, Convention => C, Link_Name => ""AG_ObjectReset""; -- -- Clear the registered event handlers, Variables and Dependencies. -- procedure Free_Events (Object : in Object_not_null_Access) with Import, Convention => C, Link_Name => ""AG_ObjectFreeEvents""; procedure Free_Variables (Object : in Object_not_null_Access) with Import, Convention => C, Link_Name => ""AG_ObjectFreeVariables""; procedure Free_Dependencies (Object : in Object_not_null_Access) with Import, Convention => C, Link_Name => ""AG_ObjectFreeDeps""; -- -- Remove any dependencies with a reference count of 0. -- procedure Clean_Up_Dependencies (Object : in Object_not_null_Access) with Import, Convention => C, Link_Name => ""AG_ObjectFreeDummyDeps""; -- -- Detach and Destroy all child objects. -- procedure Free_Children (Object : in Object_not_null_Access) with Import, Convention => C, Link_Name => ""AG_ObjectFreeChildren""; -- -- Load the state of an object from serialized storage. -- -- If File is not given, load from the application's default data directory -- (see: Agar.Init.Init_Core arguments Program_Name, Create_Directory). -- function Load (Object : in Object_not_null_Access) return Boolean; function Load (Object : in Object_not_null_Access; File : in String) return Boolean; -- -- Load an Object's data part only (ignoring the generic Object part). -- function Load_Data (Object : in Object_not_null_Access) return Boolean; function Load_Data (Object : in Object_not_null_Access; File : in String) return Boolean; -- -- Load an Object's generic part only (ignoring its data part). -- function Load_Generic (Object : in Object_not_null_Access) return Boolean; function Load_Generic (Object : in Object_not_null_Access; File : in String) return Boolean; -- -- Save the state of an object to serialized storage. -- -- If File is not given, save to the application's default data directory -- (see: Agar.Init.Init_Core arguments Program_Name, Create_Directory). -- function Save (Object : in Object_not_null_Access) return Boolean; function Save (Object : in Object_not_null_Access; File : in String) return Boolean; -- -- Save the state of an Object and all of its descendants to the default -- data directory. -- function Save_All (Object : in Object_not_null_Access) return Boolean; -- -- Transfer a serialized representation of an object from/to an Agar data -- source (which could be a file, memory, network stream, etc). -- function Serialize (Object : in Object_not_null_Access; Source : in DS.Data_Source_not_null_Access) return Boolean; function Unserialize (Object : in Object_not_null_Access; Source : in DS.Data_Source_not_null_Access) return Boolean; -- -- Try reading an Agar object signature from a data source. If successful -- (True), return signature information in Header. -- function Read_Header (Source : in DS.Data_Source_not_null_Access; Header : in Header_Access) return Boolean; -- -- Page the data of an object in or out of serialized storage. -- function Page_In (Object : in Object_not_null_Access) return Boolean; function Page_Out (Object : in Object_not_null_Access) return Boolean; -- -- Set a callback routine for handling an event. The function forms -- returns an Event access which can be used to specify arguments -- (see Agar.Event). Set_Event does not allow more than one callback -- per event. -- -- Async => True : Process events in a separate thread. -- Propagate => True : Broadcast events to all child objects. -- function Set_Event (Object : in Object_not_null_Access; Event : in String; Func : in Event_Func_Access; Async : in Boolean := False; Propagate : in Boolean := False) return EV.Event_not_null_Access; procedure Set_Event (Object : in Object_not_null_Access; Event : in String; Func : in Event_Func_Access; Async : in Boolean := False; Propagate : in Boolean := False); -- -- Variant of Set_Event which allows more than one callback per Event. -- Instead of replacing an existing Event, Add_Event appends the callback -- the list. All registered callbacks will be invoked by Post_Event. -- function Add_Event (Object : in Object_not_null_Access; Event : in String; Func : in Event_Func_Access; Async : in Boolean := False; Propagate : in Boolean := False) return EV.Event_not_null_Access; procedure Add_Event (Object : in Object_not_null_Access; Event : in String; Func : in Event_Func_Access; Async : in Boolean := False; Propagate : in Boolean := False); -- -- Post an Event to a Target object. -- Message-passing style with specified Source object. -- procedure Post_Event (Source : in Object_Access; Target : in Object_not_null_Access; Event : in String); procedure Post_Event (Source : in Object_Access; Target : in Object_not_null_Access; Event : in EV.Event_not_null_Access); -- -- Post an Event to a Target object. -- Anonymous style without specified Source. -- procedure Post_Event (Target : in Object_not_null_Access; Event : in String); procedure Post_Event (Target : in Object_not_null_Access; Event : in EV.Event_not_null_Access); -- -- Log object name and message to the console for debugging purposes. -- procedure Debug (Object : in Object_Access; Message : in String); -- -- Attach an initialized timer to an object and activate it. The callback -- routine will be executed after the timer expires in Interval milliseconds. -- Timer will be restarted or deleted based on the callback's return value. -- function Add_Timer (Object : in Object_Access; Timer : in TMR.Timer_not_null_Access; Interval : in Interfaces.Unsigned_32; Func : in TMR.Timer_Callback) return Boolean; -- -- Auto-allocated alternative to Init_Timer and Add_Timer. The timer structure -- will be auto allocated and freed implicitely. -- function Add_Timer (Object : in Object_Access; Interval : in Interfaces.Unsigned_32; Func : in TMR.Timer_Callback) return TMR.Timer_Access; -- -- Cancel and delete an active timer. -- procedure Delete_Timer (Object : in Object_not_null_Access; Timer : in TMR.Timer_not_null_Access) with Import, Convention => C, Link_Name => ""AG_DelTimer""; -- -- Evaluate whether a variable is set. -- function Defined (Object : in Object_not_null_Access; Variable : in String) return Boolean; -- -- Compare two variables with no dereference. Discrete types are compared -- by value. Strings are compared case-sensitively. Reference types are -- compared by their pointer value. -- function ""="" (Left, Right : in Variable_not_null_Access) return Boolean; private -- -- AG_Object(3) -- function AG_ObjectNew (Parent : in System.Address; Name : in CS.chars_ptr; Class : in Class_not_null_Access) return Object_Access with Import, Convention => C, Link_Name => ""AG_ObjectNew""; procedure AG_ObjectInit (Object : in Object_not_null_Access; Class : in Class_not_null_Access) with Import, Convention => C, Link_Name => ""AG_ObjectInit""; procedure AG_ObjectInitStatic (Object : in Object_not_null_Access; Class : in Class_not_null_Access) with Import, Convention => C, Link_Name => ""AG_ObjectInitStatic""; procedure AG_ObjectAttach (Parent : in Object_Access; Child : in Object_not_null_Access) with Import, Convention => C, Link_Name => ""AG_ObjectAttach""; function AG_ObjectFindS (Root : in Object_not_null_Access; Path : in CS.chars_ptr) return Object_Access with Import, Convention => C, Link_Name => ""AG_ObjectFindS""; function AG_ObjectFindParent (Object : in Object_not_null_Access; Name : in CS.chars_ptr; Class : in CS.chars_ptr) return Object_Access with Import, Convention => C, Link_Name => ""AG_ObjectFindParent""; function AG_ObjectFindChild (Parent : in Object_not_null_Access; Name : in CS.chars_ptr) return Object_Access with Import, Convention => C, Link_Name => ""ag_object_find_child""; function AG_ObjectCopyName (Object : in Object_not_null_Access; Buffer : in System.Address; Size : in AG_Size) return C.int with Import, Convention => C, Link_Name => ""AG_ObjectCopyName""; procedure AG_ObjectSetNameS (Object : in Object_not_null_Access; Name : in CS.chars_ptr) with Import, Convention => C, Link_Name => ""AG_ObjectSetNameS""; procedure AG_ObjectGenName (Object : in Object_not_null_Access; Class : in Class_not_null_Access; Buffer : in System.Address; Size : in AG_Size) with Import, Convention => C, Link_Name => ""AG_ObjectGenName""; procedure AG_ObjectGenNamePfx (Object : in Object_not_null_Access; Prefix : in CS.chars_ptr; Buffer : in System.Address; Size : in AG_Size) with Import, Convention => C, Link_Name => ""AG_ObjectGenNamePfx""; function AG_CreateClass (Hierarchy : in CS.chars_ptr; Object_Size : in AG_Size; Class_Size : in AG_Size; Major : in C.unsigned; Minor : in C.unsigned) return Class_not_null_Access with Import, Convention => C, Link_Name => ""AG_CreateClass""; procedure AG_ClassSetInit (Class : in Class_not_null_Access; Init_Func : in Init_Func_Access) with Import, Convention => C, Link_Name => ""AG_ClassSetInit""; function AG_ClassSetInit (Class : in Class_not_null_Access; Init_Func : in Init_Func_Access) return Init_Func_Access with Import, Convention => C, Link_Name => ""AG_ClassSetInit""; procedure AG_ClassSetReset (Class : in Class_not_null_Access; Reset_Func : in Reset_Func_Access) with Import, Convention => C, Link_Name => ""AG_ClassSetReset""; function AG_ClassSetReset (Class : in Class_not_null_Access; Reset_Func : in Reset_Func_Access) return Reset_Func_Access with Import, Convention => C, Link_Name => ""AG_ClassSetReset""; procedure AG_ClassSetDestroy (Class : in Class_not_null_Access; Destroy_Func : in Destroy_Func_Access) with Import, Convention => C, Link_Name => ""AG_ClassSetDestroy""; function AG_ClassSetDestroy (Class : in Class_not_null_Access; Destroy_Func : in Destroy_Func_Access) return Destroy_Func_Access with Import, Convention => C, Link_Name => ""AG_ClassSetDestroy""; procedure AG_ClassSetLoad (Class : in Class_not_null_Access; Load_Func : in Load_Func_Access) with Import, Convention => C, Link_Name => ""AG_ClassSetLoad""; function AG_ClassSetLoad (Class : in Class_not_null_Access; Load_Func : in Load_Func_Access) return Load_Func_Access with Import, Convention => C, Link_Name => ""AG_ClassSetLoad""; procedure AG_ClassSetSave (Class : in Class_not_null_Access; Save_Func : in Save_Func_Access) with Import, Convention => C, Link_Name => ""AG_ClassSetSave""; function AG_ClassSetSave (Class : in Class_not_null_Access; Save_Func : in Save_Func_Access) return Save_Func_Access with Import, Convention => C, Link_Name => ""AG_ClassSetSave""; procedure AG_ClassSetEdit (Class : in Class_not_null_Access; Edit_Func : in Edit_Func_Access) with Import, Convention => C, Link_Name => ""AG_ClassSetEdit""; function AG_ClassSetEdit (Class : in Class_not_null_Access; Edit_Func : in Edit_Func_Access) return Edit_Func_Access with Import, Convention => C, Link_Name => ""AG_ClassSetEdit""; procedure AG_RegisterNamespace (Name : in CS.chars_ptr; Prefix : in CS.chars_ptr; URL : in CS.chars_ptr) with Import, Convention => C, Link_Name => ""AG_RegisterNamespace""; procedure AG_UnregisterNamespace (Name : in CS.chars_ptr) with Import, Convention => C, Link_Name => ""AG_UnregisterNamespace""; function AG_LookupClass (Class : in CS.chars_ptr) return Class_Access with Import, Convention => C, Link_Name => ""AG_LookupClass""; function AG_LoadClass (Class : in CS.chars_ptr) return Class_Access with Import, Convention => C, Link_Name => ""AG_LoadClass""; procedure AG_RegisterModuleDirectory (Path : in CS.chars_ptr) with Import, Convention => C, Link_Name => ""AG_RegisterModuleDirectory""; procedure AG_UnregisterModuleDirectory (Path : in CS.chars_ptr) with Import, Convention => C, Link_Name => ""AG_UnregisterModuleDirectory""; function AG_OfClass (Object : in Object_not_null_Access; Pattern : in CS.chars_ptr) return C.int with Import, Convention => C, Link_Name => ""ag_of_class""; function AG_ObjectInUse (Object : in Object_not_null_Access) return C.int with Import, Convention => C, Link_Name => ""AG_ObjectInUse""; function AG_ObjectAddDep (Object : in Object_not_null_Access; Dependency : in Object_not_null_Access; Persistent : in C.int) return Dependency_Access with Import, Convention => C, Link_Name => ""AG_ObjectAddDep""; function AG_ObjectFindDep (Object : in Object_not_null_Access; Index : in Interfaces.Unsigned_32; Pointer : access Object_not_null_Access) return C.int with Import, Convention => C, Link_Name => ""AG_ObjectFindDep""; function AG_ObjectLoad (Object : in Object_not_null_Access) return C.int with Import, Convention => C, Link_Name => ""AG_ObjectLoad""; function AG_ObjectLoadFromFile (Object : in Object_not_null_Access; File : in CS.chars_ptr) return C.int with Import, Convention => C, Link_Name => ""AG_ObjectLoadFromFile""; function AG_ObjectLoadData (Object : in Object_not_null_Access) return C.int with Import, Convention => C, Link_Name => ""AG_ObjectLoadData""; function AG_ObjectLoadDataFromFile (Object : in Object_not_null_Access; File : in CS.chars_ptr) return C.int with Import, Convention => C, Link_Name => ""AG_ObjectLoadDataFromFile""; function AG_ObjectLoadGeneric (Object : in Object_not_null_Access) return C.int with Import, Convention => C, Link_Name => ""AG_ObjectLoadGeneric""; function AG_ObjectLoadGenericFromFile (Object : in Object_not_null_Access; File : in CS.chars_ptr) return C.int with Import, Convention => C, Link_Name => ""AG_ObjectLoadGenericFromFile""; function AG_ObjectSave (Object : in Object_not_null_Access) return C.int with Import, Convention => C, Link_Name => ""AG_ObjectSave""; function AG_ObjectSaveAll (Object : in Object_not_null_Access) return C.int with Import, Convention => C, Link_Name => ""AG_ObjectSaveAll""; function AG_ObjectSaveToFile (Object : in Object_not_null_Access; File : in CS.chars_ptr) return C.int with Import, Convention => C, Link_Name => ""AG_ObjectSaveToFile""; function AG_ObjectSerialize (Object : in Object_not_null_Access; Source : in DS.Data_Source_not_null_Access) return C.int with Import, Convention => C, Link_Name => ""AG_ObjectSerialize""; function AG_ObjectUnserialize (Object : in Object_not_null_Access; Source : in DS.Data_Source_not_null_Access) return C.int with Import, Convention => C, Link_Name => ""AG_ObjectUnserialize""; function AG_ObjectReadHeader (Object : in DS.Data_Source_not_null_Access; Header : in Header_Access) return C.int with Import, Convention => C, Link_Name => ""AG_ObjectReadHeader""; function AG_ObjectPageIn (Object : in Object_not_null_Access) return C.int with Import, Convention => C, Link_Name => ""AG_ObjectPageIn""; function AG_ObjectPageOut (Object : in Object_not_null_Access) return C.int with Import, Convention => C, Link_Name => ""AG_ObjectPageOut""; procedure AG_Debug (Object : in Object_Access; Format : in CS.chars_ptr; Message : in CS.chars_ptr) with Import, Convention => C, Link_Name => ""AG_Debug""; -- -- AG_Event(3) -- function AG_SetEvent (Object : in Object_not_null_Access; Event : in CS.chars_ptr; Func : in Event_Func_Access; Format : in CS.chars_ptr) return EV.Event_not_null_Access with Import, Convention => C, Link_Name => ""AG_SetEvent""; procedure AG_SetEvent (Object : in Object_not_null_Access; Event : in CS.chars_ptr; Func : in Event_Func_Access; Format : in CS.chars_ptr) with Import, Convention => C, Link_Name => ""AG_SetEvent""; function AG_AddEvent (Object : in Object_not_null_Access; Event : in CS.chars_ptr; Func : in Event_Func_Access; Format : in CS.chars_ptr) return EV.Event_not_null_Access with Import, Convention => C, Link_Name => ""AG_AddEvent""; procedure AG_AddEvent (Object : in Object_not_null_Access; Event : in CS.chars_ptr; Func : in Event_Func_Access; Format : in CS.chars_ptr) with Import, Convention => C, Link_Name => ""AG_AddEvent""; function AG_PostEvent (Source : in Object_Access; Target : in Object_not_null_Access; Event : in CS.chars_ptr; Format : in CS.chars_ptr) return EV.Event_not_null_Access with Import, Convention => C, Link_Name => ""AG_PostEvent""; procedure AG_PostEvent (Source : in Object_Access; Target : in Object_not_null_Access; Event : in CS.chars_ptr; Format : in CS.chars_ptr) with Import, Convention => C, Link_Name => ""AG_PostEvent""; procedure AG_PostEventByPtr (Source : in Object_Access; Target : in Object_not_null_Access; Event : in EV.Event_Access; Format : in CS.chars_ptr) with Import, Convention => C, Link_Name => ""AG_PostEventByPtr""; -- -- AG_Timer(3) -- function AG_AddTimer (Object : in Object_Access; Timer : in TMR.Timer_not_null_Access; Interval : in Interfaces.Unsigned_32; Func : in TMR.Timer_Callback; Flags : in C.unsigned; Format : in CS.chars_ptr) return C.int with Import, Convention => C, Link_Name => ""AG_AddTimer""; function AG_AddTimerAuto (Object : in Object_Access; Interval : in Interfaces.Unsigned_32; Func : in TMR.Timer_Callback; Format : in CS.chars_ptr) return TMR.Timer_Access with Import, Convention => C, Link_Name => ""AG_AddTimerAuto""; -------------------- -- AG_Variable(3) -- -------------------- function AG_Defined (Object : in Object_not_null_Access; Name : in CS.chars_ptr) return C.int with Import, Convention => C, Link_Name => ""ag_defined""; procedure AG_CopyVariable (Destination : in Variable_not_null_Access; Source : in Variable_not_null_Access) with Import, Convention => C, Link_Name => ""AG_CopyVariable""; procedure AG_Unset (Object : in Object_not_null_Access; Name : in System.Address) with Import, Convention => C, Link_Name => ""AG_Unset""; procedure AG_GetUint8 (Object : in Object_not_null_Access; Name : in System.Address) with Import, Convention => C, Link_Name => ""AG_GetUint8""; function AG_SetUint8 (Object : in System.Address; Name : in System.Address; Value : in Interfaces.Unsigned_8) return Variable_not_null_Access with Import, Convention => C, Link_Name => ""AG_SetUint8""; function AG_BindUint8 (Object : in System.Address; Name : in System.Address; Value : access Interfaces.Unsigned_8) return Variable_not_null_Access with Import, Convention => C, Link_Name => ""AG_BindUint8""; function AG_GetSint8 (Object : in System.Address; Name : in System.Address) return Variable_not_null_Access with Import, Convention => C, Link_Name => ""AG_GetSint8""; function AG_SetSint8 (Object : in System.Address; Name : in System.Address; Value : in Signed_8) return Variable_not_null_Access with Import, Convention => C, Link_Name => ""AG_SetSint8""; function AG_BindSint8 (Object : in System.Address; Name : in System.Address; Value : access Signed_8) return Variable_not_null_Access with Import, Convention => C, Link_Name => ""AG_BindSint8""; procedure AG_GetUint16 (Object : in System.Address; Name : in System.Address) with Import, Convention => C, Link_Name => ""AG_GetUint16""; function AG_SetUint16 (Object : in System.Address; Name : in System.Address; Value : in Interfaces.Unsigned_16) return Variable_not_null_Access with Import, Convention => C, Link_Name => ""AG_SetUint16""; function AG_BindUint16 (Object : in System.Address; Name : in System.Address; Value : access Interfaces.Unsigned_16) return Variable_not_null_Access with Import, Convention => C, Link_Name => ""AG_BindUint16""; function AG_GetSint16 (Object : in System.Address; Name : in System.Address) return Variable_not_null_Access with Import, Convention => C, Link_Name => ""AG_GetSint16""; function AG_SetSint16 (Object : in System.Address; Name : in System.Address; Value : in Signed_16) return Variable_not_null_Access with Import, Convention => C, Link_Name => ""AG_SetSint16""; function AG_BindSint16 (Object : in System.Address; Name : in System.Address; Value : access Signed_16) return Variable_not_null_Access with Import, Convention => C, Link_Name => ""AG_BindSint16""; procedure AG_GetUint32 (Object : in System.Address; Name : in System.Address) with Import, Convention => C, Link_Name => ""AG_GetUint32""; function AG_SetUint32 (Object : in System.Address; Name : in System.Address; Value : in Interfaces.Unsigned_32) return Variable_not_null_Access with Import, Convention => C, Link_Name => ""AG_SetUint32""; function AG_BindUint32 (Object : in System.Address; Name : in System.Address; Value : access Interfaces.Unsigned_32) return Variable_not_null_Access with Import, Convention => C, Link_Name => ""AG_BindUint32""; function AG_GetSint32 (Object : in System.Address; Name : in System.Address) return Variable_not_null_Access with Import, Convention => C, Link_Name => ""AG_GetSint32""; function AG_SetSint32 (Object : in System.Address; Name : in System.Address; Value : in Signed_32) return Variable_not_null_Access with Import, Convention => C, Link_Name => ""AG_SetSint32""; function AG_BindSint32 (Object : in System.Address; Name : in System.Address; Value : access Signed_32) return Variable_not_null_Access with Import, Convention => C, Link_Name => ""AG_BindSint32""; #if HAVE_64BIT procedure AG_GetUint64 (Object : in System.Address; Name : in System.Address) with Import, Convention => C, Link_Name => ""AG_GetUint64""; function AG_SetUint64 (Object : in System.Address; Name : in System.Address; Value : in Interfaces.Unsigned_64) return Variable_not_null_Access with Import, Convention => C, Link_Name => ""AG_SetUint64""; function AG_BindUint64 (Object : in System.Address; Name : in System.Address; Value : access Interfaces.Unsigned_64) return Variable_not_null_Access with Import, Convention => C, Link_Name => ""AG_BindUint64""; function AG_GetSint64 (Object : in System.Address; Name : in System.Address) return Variable_not_null_Access with Import, Convention => C, Link_Name => ""AG_GetSint64""; function AG_SetSint64 (Object : in System.Address; Name : in System.Address; Value : in Signed_64) return Variable_not_null_Access with Import, Convention => C, Link_Name => ""AG_SetSint64""; function AG_BindSint64 (Object : in System.Address; Name : in System.Address; Value : access Signed_64) return Variable_not_null_Access with Import, Convention => C, Link_Name => ""AG_BindSint64""; #end if; #if HAVE_FLOAT function AG_GetFloat (Object : in System.Address; Name : in System.Address) return Variable_not_null_Access with Import, Convention => C, Link_Name => ""AG_GetFloat""; function AG_SetFloat (Object : in System.Address; Name : in System.Address; Value : in Float) return Variable_not_null_Access with Import, Convention => C, Link_Name => ""AG_SetFloat""; function AG_BindFloat (Object : in System.Address; Name : in System.Address; Value : access Float) return Variable_not_null_Access with Import, Convention => C, Link_Name => ""AG_BindFloat""; function AG_GetDouble (Object : in System.Address; Name : in System.Address) return Variable_not_null_Access with Import, Convention => C, Link_Name => ""AG_GetDouble""; function AG_SetDouble (Object : in System.Address; Name : in System.Address; Value : in Double) return Variable_not_null_Access with Import, Convention => C, Link_Name => ""AG_SetDouble""; function AG_BindDouble (Object : in System.Address; Name : in System.Address; Value : access Double) return Variable_not_null_Access with Import, Convention => C, Link_Name => ""AG_BindDouble""; # if HAVE_LONG_DOUBLE function AG_GetLongDouble (Object : in System.Address; Name : in System.Address) return Variable_not_null_Access with Import, Convention => C, Link_Name => ""AG_GetLongDouble""; function AG_SetLongDouble (Object : in System.Address; Name : in System.Address; Value : in Long_Double) return Variable_not_null_Access with Import, Convention => C, Link_Name => ""AG_SetLongDouble""; function AG_BindLongDouble (Object : in System.Address; Name : in System.Address; Value : access Long_Double) return Variable_not_null_Access with Import, Convention => C, Link_Name => ""AG_BindLongDouble""; # end if; #end if; function AG_GetString (Object : in System.Address; Name : in System.Address; Buffer : in System.Address; Size : in AG_Size) return AG_Size with Import, Convention => C, Link_Name => ""AG_GetString""; function AG_GetStringDup (Object : in System.Address; Name : in System.Address) return System.Address with Import, Convention => C, Link_Name => ""AG_GetStringDup""; function AG_SetString (Variable : in Variable_not_null_Access; Name : in System.Address; Data : in System.Address) return Variable_Access with Import, Convention => C, Link_Name => ""AG_SetString""; function AG_BindString (Variable : in Variable_not_null_Access; Name : in System.Address; Data : in System.Address; Size : in AG_Size) return Variable_Access with Import, Convention => C, Link_Name => ""AG_BindString""; function AG_GetPointer (Object : in System.Address; Name : in System.Address) return System.Address with Import, Convention => C, Link_Name => ""AG_GetPointer""; function AG_SetPointer (Variable : in Variable_not_null_Access; Name : in System.Address; Data : in System.Address) return Variable_Access with Import, Convention => C, Link_Name => ""AG_SetPointer""; function AG_BindPointer (Variable : in Variable_not_null_Access; Name : in System.Address; Data : access System.Address) return Variable_Access with Import, Convention => C, Link_Name => ""AG_BindPointer""; function AG_CompareVariables (Left, Right : in Variable_not_null_Access) return C.int with Import, Convention => C, Link_Name => ""AG_CompareVariables""; end Agar.Object; ",12302,True,2767.8273873787907,median ":sectnums: == NEORV32 Central Processing Unit (CPU) image::riscv_logo.png[width=350,align=center] **Key Features** * 32-bit multi-cycle in-order `rv32` RISC-V CPU * Optional RISC-V extensions: ** `A` - atomic memory access operations ** `B` - bit-manipulation instructions ** `C` - 16-bit compressed instructions ** `I` - integer base ISA (always enabled) ** `E` - embedded CPU version (reduced register file size) ** `M` - integer multiplication and division hardware ** `U` - less-privileged _user_ mode ** `Zfinx` - single-precision floating-point unit ** `Zicsr` - control and status register access (privileged architecture) ** `Zicntr` - CPU base counters ** `Zihpm` - hardware performance monitors ** `Zifencei` - instruction stream synchronization ** `Zmmul` - integer multiplication hardware ** `PMP` - physical memory protection ** `Debug` - debug mode * Compatible to the RISC-V user specifications and a subset of the RISC-V privileged architecture specifications - passes the official RISC-V Architecture Tests (v2+) * Official RISC-V open-source architecture ID * Standard RISC-V interrupts (_external_, _timer_, _software_) plus 16 _fast_ interrupts * Supports _all_ of the machine-level traps from the RISC-V specifications (including bus access exceptions and all unimplemented/illegal/malformed instructions) ** This is a special aspect on _execution safety_ by <<_full_virtualization>> * Optional physical memory configuration (PMP), compatible to the RISC-V specifications * Optional hardware performance monitors (HPM) for application benchmarking * Separated interfaces for instruction fetch and data access (merged into a single processor bus)) * little-endian byte order * Configurable hardware reset * No hardware support of unaligned data/instruction accesses - they will trigger an exception. [NOTE] It is recommended to use the **NEORV32 Processor** as default top instance even if you only want to use the actual CPU. Simply disable all the processor-internal modules via the generics and you will get a ""CPU wrapper"" that provides a minimal CPU environment and an external bus interface (like AXI4). This setup also allows to further use the default bootloader and software framework. From this base you can start building your own SoC. Of course you can also use the CPU in it's true stand-alone mode. [NOTE] This documentation assumes the reader is familiar with the official RISC-V ""User"" and ""Privileged Architecture"" specifications. <<< // #################################################################################################################### :sectnums: === Architecture The NEORV32 CPU was designed from scratch based only on the official ISA / privileged architecture specifications. The following figure shows the simplified architecture of the CPU. image::neorv32_cpu.png[align=center] The CPU implements a _multi-cycle_ architecture. Hence, each instruction is executed as a series of consecutive micro-operations. In order to increase performance, the CPU's **front-end** (instruction fetch) and **back-end** (instruction execution) are de-couples via a FIFO (the ""instruction prefetch buffer""). Therefore, the front-end can already fetch new instructions while the back-end is still processing previously-fetched instructions. The front-end is responsible for fetching 32-bit chunks of instruction words (one aligned 32-bit instruction, two 16-bit instructions or a mixture if 32-bit instructions are not aligned to 32-bit boundaries). The instruction data is stored to a FIFO queue - the instruction prefetch buffer. The back-end is responsible for the actual execution of the instruction. It includes an ""issue engine"", which takes data from the instruction prefetch buffer and assembles 32-bit instruction words (plain 32-bit instruction or decompressed 16-bit instructions) for execution. Front-end and back-end operate in parallel and with overlapping operations. Hence, the optimal CPI (cycles per instructions) is 2, but it can be significantly higher: for instance when executing loads/stores (accessing memory-mapped devices with high latency), executing multi-cycle ALU operations (like divisions) or when the CPU front-end has to reload the prefetch buffer due to a taken branch. Basically, the NEORV32 CPU is somewhere between a classical pipelined architecture, where each stage requires exactly one processing cycle (if not stalled) and a classical multi-cycle architecture, which executes every single instruction (_including_ fetch) in a series of consecutive micro-operations. The combination of these two classical design paradigms allows an increased instruction execution in contrast to a pure multi-cycle approach (due to overlapping operation of fetch and execute) at a reduced hardware footprint (due to the multi-cycle concept). As a Von-Neumann machine, the CPU provides independent interfaces for instruction fetch and data access. These two bus interfaces are merged into a single processor-internal bus via a prioritizing bus switch (data accesses have higher priority). Hence, ALL memory locations including peripheral devices are mapped to a single unified 32-bit address space. // #################################################################################################################### :sectnums: === Full Virtualization Just like the RISC-V ISA the NEORV32 aims to provide _maximum virtualization_ capabilities on CPU _and_ SoC level to allow a high standard of **execution safety**. The CPU supports **all** traps specified by the official RISC-V specifications. footnote:[If the `Zicsr` CPU extension is enabled (implementing the full set of the privileged architecture).] Thus, the CPU provides defined hardware fall-backs via traps for any expected and unexpected situation (e.g. executing an malformed instruction word or accessing a not-allocated memory address). For any kind of trap the core is always in a defined and fully synchronized state throughout the whole architecture (i.e. there are no out-of-order operations that might have to reverted). This allows predictable execution behavior at any time improving overall _execution safety_. **Execution Safety - NEORV32 Virtualization Features** * Due to the acknowledged memory accesses the CPU is _always_ sync with the memory system (i.e. there is no speculative execution / no out-of-order states). * The CPU supports _all_ RISC-V compatible bus exceptions including access exceptions, which are triggered if an accessed address does not respond or encounters an internal error during access. * Accessed memory addresses (plain memory, but also memory-mapped devices) need to respond within a fixed time window. Otherwise a bus access exception is raised. * The RISC-V specs. state that executing an malformed instruction results in unpredictable behavior. As an additional execution safety feature the NEORV32 CPU ensures that _all_ unimplemented/malformed/illegal instructions do raise an illegal instruction exceptions and do not commit any state-changing operation (like writing registers or triggering memory operations). * To be continued... // #################################################################################################################### :sectnums: === RISC-V Compatibility The NEORV32 CPU passes the rv32_m/I, rv32_m/M, rv32_m/C, rv32_m/privilege, and rv32_m/Zifencei tests of the official RISC-V Architecture Tests (GitHub). The port files for the NEORV32 processor are located in the repository's `sw/isa-test` folder. [NOTE] See section https://stnolting.github.io/neorv32/ug/#_risc_v_architecture_test_framework[User Guide: RISC-V Architecture Test Framework] for information how to run the tests on the NEORV32. .**RISC-V `rv32_m/C` Tests** ................................... Check cadd-01 ... OK Check caddi-01 ... OK Check caddi16sp-01 ... OK Check caddi4spn-01 ... OK Check cand-01 ... OK Check candi-01 ... OK Check cbeqz-01 ... OK Check cbnez-01 ... OK Check cebreak-01 ... OK Check cj-01 ... OK Check cjal-01 ... OK Check cjalr-01 ... OK Check cjr-01 ... OK Check cli-01 ... OK Check clui-01 ... OK Check clw-01 ... OK Check clwsp-01 ... OK Check cmv-01 ... OK Check cnop-01 ... OK Check cor-01 ... OK Check cslli-01 ... OK Check csrai-01 ... OK Check csrli-01 ... OK Check csub-01 ... OK Check csw-01 ... OK Check cswsp-01 ... OK Check cxor-01 ... OK -------------------------------- OK: 27/27 RISCV_TARGET=neorv32 RISCV_DEVICE=C XLEN=32 ................................... .**RISC-V `rv32_m/I` Tests** ................................... Check add-01 ... OK Check addi-01 ... OK Check and-01 ... OK Check andi-01 ... OK Check auipc-01 ... OK Check beq-01 ... OK Check bge-01 ... OK Check bgeu-01 ... OK Check blt-01 ... OK Check bltu-01 ... OK Check bne-01 ... OK Check fence-01 ... OK Check jal-01 ... OK Check jalr-01 ... OK Check lb-align-01 ... OK Check lbu-align-01 ... OK Check lh-align-01 ... OK Check lhu-align-01 ... OK Check lui-01 ... OK Check lw-align-01 ... OK Check or-01 ... OK Check ori-01 ... OK Check sb-align-01 ... OK Check sh-align-01 ... OK Check sll-01 ... OK Check slli-01 ... OK Check slt-01 ... OK Check slti-01 ... OK Check sltiu-01 ... OK Check sltu-01 ... OK Check sra-01 ... OK Check srai-01 ... OK Check srl-01 ... OK Check srli-01 ... OK Check sub-01 ... OK Check sw-align-01 ... OK Check xor-01 ... OK Check xori-01 ... OK Check fence-01 ... OK -------------------------------- OK: 39/39 RISCV_TARGET=neorv32 RISCV_DEVICE=I XLEN=32 ................................... .**RISC-V `rv32_m/M` Tests** ................................... Check div-01 ... OK Check divu-01 ... OK Check mul-01 ... OK Check mulh-01 ... OK Check mulhsu-01 ... OK Check mulhu-01 ... OK Check rem-01 ... OK Check remu-01 ... OK -------------------------------- OK: 8/8 RISCV_TARGET=neorv32 RISCV_DEVICE=M XLEN=32 ................................... .**RISC-V `rv32_m/privilege` Tests** ................................... Check ebreak ... OK Check ecall ... OK Check misalign-beq-01 ... OK Check misalign-bge-01 ... OK Check misalign-bgeu-01 ... OK Check misalign-blt-01 ... OK Check misalign-bltu-01 ... OK Check misalign-bne-01 ... OK Check misalign-jal-01 ... OK Check misalign-lh-01 ... OK Check misalign-lhu-01 ... OK Check misalign-lw-01 ... OK Check misalign-sh-01 ... OK Check misalign-sw-01 ... OK Check misalign1-jalr-01 ... OK Check misalign2-jalr-01 ... OK -------------------------------- OK: 16/16 RISCV_TARGET=neorv32 RISCV_DEVICE=privilege XLEN=32 ................................... .**RISC-V `rv32_m/Zifencei` Tests** ................................... Check Fencei ... OK -------------------------------- OK: 1/1 RISCV_TARGET=neorv32 RISCV_DEVICE=Zifencei XLEN=32 ................................... <<< :sectnums: ==== RISC-V Incompatibility Issues and Limitations This list shows the currently identified issues regarding full RISC-V-compatibility. More specific information can be found in section <<_instruction_sets_and_extensions>>. .Read-Only ""Read-Write"" CSRs [IMPORTANT] The `misa` and `mtval` CSRs in the NEORV32 are _read-only_. Any machine-mode write access to them is ignored and will _not_ cause any exceptions or side-effects to maintain RISC-V compatibility. .Physical Memory Protection [IMPORTANT] The physical memory protection (see section <<_machine_physical_memory_protection_csrs>>) only supports the modes _OFF_ and _NAPOT_ yet and a minimal granularity of 8 bytes per region. .Atomic Memory Operations [IMPORTANT] The `A` CPU extension only implements the `lr.w` and `sc.w` instructions yet. However, these instructions are sufficient to emulate all further atomic memory operations. .Bit-Manipulation ISA Extension [IMPORTANT] The NEORV32 `B` extension only implements the _basic bit-manipulation instructions_ (`Zbb`) subset and the _address generation instructions_ (`Zba`) subset yet. <<< // #################################################################################################################### :sectnums: === CPU Top Entity - Signals The following table shows all interface signals of the CPU top entity `rtl/core/neorv32_cpu.vhd`. The type of all signals is _std_ulogic_ or _std_ulogic_vector_, respectively. The ""Dir."" column shows the signal direction seen from the CPU. .NEORV32 CPU top entity signals [cols=""<2,^1,^1,<6""] [options=""header"", grid=""rows""] |======================= | Signal | Width | Dir. | Function 4+^| **Global Signals** | `clk_i` | 1 | in | global clock line, all registers triggering on rising edge | `rstn_i` | 1 | in | global reset, low-active | `sleep_o` | 1 | out | CPU is in sleep mode when set | `debug_o` | 1 | out | CPU is in debug mode when set 4+^| **Instruction Bus Interface (<<_bus_interface>>)** | `i_bus_addr_o` | 32 | out | destination address | `i_bus_rdata_i` | 32 | in | read data | `i_bus_wdata_o` | 32 | out | write data (always zero) | `i_bus_ben_o` | 4 | out | byte enable | `i_bus_we_o` | 1 | out | write transaction (always zero) | `i_bus_re_o` | 1 | out | read transaction | `i_bus_lock_o` | 1 | out | exclusive access request (always zero) | `i_bus_ack_i` | 1 | in | bus transfer acknowledge from accessed peripheral | `i_bus_err_i` | 1 | in | bus transfer terminate from accessed peripheral | `i_bus_fence_o` | 1 | out | indicates an executed _fence.i_ instruction | `i_bus_priv_o` | 2 | out | current CPU privilege level 4+^| **Data Bus Interface (<<_bus_interface>>)** | `d_bus_addr_o` | 32 | out | destination address | `d_bus_rdata_i` | 32 | in | read data | `d_bus_wdata_o` | 32 | out | write data | `d_bus_ben_o` | 4 | out | byte enable | `d_bus_we_o` | 1 | out | write transaction | `d_bus_re_o` | 1 | out | read transaction | `d_bus_lock_o` | 1 | out | exclusive access request | `d_bus_ack_i` | 1 | in | bus transfer acknowledge from accessed peripheral | `d_bus_err_i` | 1 | in | bus transfer terminate from accessed peripheral | `d_bus_fence_o` | 1 | out | indicates an executed _fence_ instruction | `d_bus_priv_o` | 2 | out | current CPU privilege level 4+^| **System Time (see <<_timeh>> CSR)** | `time_i` | 64 | in | system time input (from MTIME) 4+^| **Interrupts, RISC-V-compatible (<<_traps_exceptions_and_interrupts>>)** | `msw_irq_i` | 1 | in | RISC-V machine software interrupt | `mext_irq_i` | 1 | in | RISC-V machine external interrupt | `mtime_irq_i` | 1 | in | RISC-V machine timer interrupt 4+^| **Fast Interrupts, NEORV32-specific (<<_traps_exceptions_and_interrupts>>)** | `firq_i` | 16 | in | fast interrupt request signals 4+^| **Enter Debug Mode Request (<<_on_chip_debugger_ocd>>)** | `db_halt_req_i` | 1 | in | request CPU to halt and enter debug mode |======================= <<< // #################################################################################################################### :sectnums: === CPU Top Entity - Generics Most of the CPU configuration generics are a subset of the actual Processor configuration generics (see section <<_processor_top_entity_generics>>). and are not listed here. However, the CPU provides some _specific_ generics that are used to configure the CPU for the NEORV32 processor setup. These generics are assigned by the processor setup only and are not available for user defined configuration. The _specific_ generics are listed below. [cols=""4,4,2""] [frame=""all"",grid=""none""] |====== | **CPU_BOOT_ADDR** | _std_ulogic_vector(31 downto 0)_ | 0x00000000 3+| This address defines the reset address at which the CPU starts fetching instructions after reset. In terms of the NEORV32 processor, this generic is configured with the base address of the bootloader ROM (default) or with the base address of the processor-internal instruction memory (IMEM) if the bootloader is disabled (_INT_BOOTLOADER_EN_ = _false_). See section <<_address_space>> for more information. |====== [cols=""4,4,2""] [frame=""all"",grid=""none""] |====== | **CPU_DEBUG_ADDR** | _std_ulogic_vector(31 downto 0)_ | 0x00000000 3+| This address defines the entry address for the ""execution based"" on-chip debugger. By default, this generic is configured with the base address of the debugger memory. See section <<_on_chip_debugger_ocd>> for more information. |====== [cols=""4,4,2""] [frame=""all"",grid=""none""] |====== | **CPU_EXTENSION_RISCV_DEBUG** | _boolean_ | false 3+| Implement RISC-V-compatible ""debug"" CPU operation mode. See section <<_cpu_debug_mode>> for more information. |====== <<< // #################################################################################################################### :sectnums: === Instruction Sets and Extensions The basic NEORV32 is a RISC-V `rv32i` architecture that provides several _optional_ RISC-V CPU and ISA (instruction set architecture) extensions. For more information regarding the RISC-V ISA extensions please see the the _RISC-V Instruction Set Manual - Volume I: Unprivileged ISA_ and _The RISC-V Instruction Set Manual Volume II: Privileged Architecture_, which are available in the projects `docs/references` folder. [TIP] The CPU can discover available ISA extensions via the <<_misa>> CSR and the `CPU` <<_system_configuration_information_memory_sysinfo, SYSINFO>> register or by executing an instruction and checking for an _illegal instruction exception_. [NOTE] Executing an instruction from an extension that is not supported yet or that is currently not enabled (via the according top entity generic) will raise an _illegal instruction_ exception. ==== **`A`** - Atomic Memory Access Atomic memory access instructions allow more sophisticated memory operations like implementing semaphores and mutexes. The RICS-C specs. defines a specific _atomic_ extension that provides instructions for atomic memory accesses. The `A` ISA extension is enabled if the `CPU_EXTENSION_RISCV_A` configuration generic is _true_. In this case the following additional instructions are available: * `lr.w`: load-reservate * `sc.w`: store-conditional [NOTE] Even though only `lr.w` and `sc.w` instructions are implemented yet, all further atomic operations (load-modify-write instruction) can be emulated using these two instruction. Furthermore, the instruction's ordering flags (`aq` and `lr`) are ignored by the CPU hardware. Using any other (not yet implemented) AMO (atomic memory operation) will raise an illegal instruction exception. The *load-reservate* instruction behaves as a ""normal"" load-word instruction (`lw`) but will also set a CPU-internal _data memory access lock_. Executing a *store-conditional* behaves as ""normal"" store-word instruction (`sw`) that will only conduct an actual memory write operations if the lock is still intact. Additionally, the store-conditional instruction will also return the lock state (returns zero if the lock is still intact or non-zero if the lock has been broken). After the execution of the `sc` instruction, the lock is automatically removed. The lock is broken if at least one of the following conditions occur: . executing any data memory access instruction other than `lr.w` . raising _any_ t (for example an interrupt or a memory access exception) [NOTE] The atomic instructions have special requirements for memory system / bus interconnect. More information can be found in sections <<_bus_interface>> and <<_processor_external_memory_interface_wishbone_axi4_lite>>, respectively. ==== **`B`** - Bit-Manipulation Operations The `B` ISA extension adds instructions for bit-manipulation operations. This extension is enabled if the `CPU_EXTENSION_RISCV_B` configuration generic is _true_. The official RISC-V specifications can be found here: https://github.com/riscv/riscv-bitmanip [IMPORTANT] The NEORV32 `B` extension only implements the _basic bit-manipulation instructions_ (`Zbb`) subset and the _address generation instructions_ (`Zba`) subset yet. The `Zbb` sub-extension adds the following instructions: * `andn` `orn` `xnor` * `clz` `ctz` `cpop` * `max` `maxu` `min` `minu` * `sext.b` `sext.h` `zext.h` * `rol` `ror` `rori` * `orc.b` `rev8` The `Zba` sub-extension adds the following instructions: * `sh1add` `sh2add` `sh3add` [TIP] By default, the bit-manipulation unit uses an _iterative_ approach to compute shift-related operations like `clz` and `rol`. To increase performance (at the cost of additional hardware resources) the <<_fast_shift_en>> generic can be enabled to implement full-parallel logic (like barrel shifters) for all shift-related `B` instructions. [WARNING] The `B` extension is frozen but not officially ratified yet. There is no software support for this extension in the upstream GCC RISC-V port yet. However, an intrinsic library is provided to utilize the provided `B` extension features from C-language code (see `sw/example/bitmanip_test`). ==== **`C`** - Compressed Instructions The _compressed_ ISA extension provides 16-bit encodings of commonly used instructions to reduce code space size. The `C` extension is available when the `CPU_EXTENSION_RISCV_C` configuration generic is _true_. In this case the following instructions are available: * `c.addi4spn` `c.lw` `c.sw` `c.nop` `c.addi` `c.jal` `c.li` `c.addi16sp` `c.lui` `c.srli` `c.srai` `c.andi` `c.sub` `c.xor` `c.or` `c.and` `c.j` `c.beqz` `c.bnez` `c.slli` `c.lwsp` `c.jr` `c.mv` `c.ebreak` `c.jalr` `c.add` `c.swsp` [NOTE] When the compressed instructions extension is enabled, branches to an _unaligned_ and _uncompressed_ instruction require an additional instruction fetch to load the according second half-word of that instruction. The performance can be increased again by forcing a 32-bit alignment of branch target addresses. By default, this is enforced via the GCC `-falign-functions=4`, `-falign-labels=4`, `-falign-loops=4` and `-falign-jumps=4` compile flags (via the makefile). ==== **`E`** - Embedded CPU The embedded CPU extensions reduces the size of the general purpose register file from 32 entries to 16 entries to decrease physical hardware requirements (for example block RAM). This extensions is enabled when the `CPU_EXTENSION_RISCV_E` configuration generic is _true_. Accesses to registers beyond `x15` will raise and _illegal instruction exception_. This extension does not add any additional instructions or features. [NOTE] Due to the reduced register file size an alternate toolchain ABI (**`ilp32e`**) is required. ==== **`I`** - Base Integer ISA The CPU always supports the complete `rv32i` base integer instruction set. This base set is always enabled regardless of the setting of the remaining exceptions. The base instruction set includes the following instructions: * immediate: `lui` `auipc` * jumps: `jal` `jalr` * branches: `beq` `bne` `blt` `bge` `bltu` `bgeu` * memory: `lb` `lh` `lw` `lbu` `lhu` `sb` `sh` `sw` * alu: `addi` `slti` `sltiu` `xori` `ori` `andi` `slli` `srli` `srai` `add` `sub` `sll` `slt` `sltu` `xor` `srl` `sra` `or` `and` * environment: `ecall` `ebreak` `fence` [NOTE] In order to keep the hardware footprint low, the CPU's shift unit uses a bit-serial approach. Hence, shift operations take up to 32 cycles (plus overhead) depending on the actual shift amount. Alternatively, the shift operations can be processed completely in parallel by a fast (but large) barrel shifter if the `FAST_SHIFT_EN` generic is _true_. In that case, shift operations complete within 2 cycles (plus overhead) regardless of the actual shift amount. [NOTE] Internally, the `fence` instruction does not perform any operation inside the CPU. It only sets the top's `d_bus_fence_o` signal high for one cycle to inform the memory system a `fence` instruction has been executed. Any flags within the `fence` instruction word are ignore by the hardware. ==== **`M`** - Integer Multiplication and Division Hardware-accelerated integer multiplication and division operations are available when the `CPU_EXTENSION_RISCV_M` configuration generic is _true_. In this case the following instructions are available: * multiplication: `mul` `mulh` `mulhsu` `mulhu` * division: `div` `divu` `rem` `remu` [NOTE] By default, multiplication and division operations are executed in a bit-serial approach. Alternatively, the multiplier core can be implemented using DSP blocks if the `FAST_MUL_EN` generic is _true_ allowing faster execution. Multiplications and divisions always require a fixed amount of cycles to complete - regardless of the input operands. ==== **`Zmmul`** - Integer Multiplication This is a _sub-extension_ of the `M` ISA extension. It implements the multiplication-only operations of the `M` extensions and is intended for size-constrained setups that require hardware-based integer multiplications but not hardware-based divisions, which will be computed entirely in software. This extension requires only ~50% of the hardware utilization of the ""full"" `M` extension. * multiplication: `mul` `mulh` `mulhsu` `mulhu` If `Zmmul` is enabled, executing any division instruction from the `M` ISA extension (`div`, `divu`, `rem`, `remu`) will raise an _illegal instruction exception_. Note that `M` and `Zmmul` extensions _cannot_ be enabled at the same time. [TIP] If your RISC-V GCC toolchain does not (yet) support the `_Zmmul` ISA extensions, it can be ""emulated"" using a `rv32im` machine architecture and setting the `-mno-div` compiler flag (example `$ make MARCH=rv32im USER_FLAGS+=-mno-div clean_all exe`). ==== **`U`** - Less-Privileged User Mode In addition to the basic (and highest-privileged) machine-mode, the _user-mode_ ISA extensions adds a second less-privileged operation mode. It is implemented if the `CPU_EXTENSION_RISCV_U` configuration generic is _true_. Code executed in user-mode cannot access machine-mode CSRs. Furthermore, user-mode access to the address space (like peripheral/IO devices) can be constrained via the physical memory protection (_PMP_). Any kind of privilege rights violation will raise an exception to allow full virtualization. ==== **`X`** - NEORV32-Specific (Custom) Extensions The NEORV32-specific extensions are always enabled and are indicated by the set `X` bit in the `misa` CSR. The most important points of the NEORV32-specific extensions are: * The CPU provides 16 _fast interrupt_ interrupts (`FIRQ)`, which are controlled via custom bits in the `mie` and `mip` CSR. This extension is mapped to CSR bits, that are available for custom use (according to the RISC-V specs). Also, custom trap codes for `mcause` are implemented. * All undefined/unimplemented/malformed/illegal instructions do raise an illegal instruction exception (see <<_full_virtualization>>). ==== **`Zfinx`** Single-Precision Floating-Point Operations The `Zfinx` floating-point extension is an _alternative_ of the standard `F` floating-point ISA extension. The `Zfinx` extensions also uses the integer register file `x` to store and operate on floating-point data instead of a dedicated floating-point register file (hence, `F-in-x`). Thus, the `Zfinx` extension requires less hardware resources and features faster context changes. This also implies that there are NO dedicated `f` register file-related load/store or move instructions. The official RISC-V specifications can be found here: https://github.com/riscv/riscv-zfinx [NOTE] The NEORV32 floating-point unit used by the `Zfinx` extension is compatible to the _IEEE-754_ specifications. The `Zfinx` extensions only supports single-precision (`.s` instruction suffix), so it is a direct alternative to the `F` extension. The `Zfinx` extension is implemented when the `CPU_EXTENSION_RISCV_Zfinx` configuration generic is _true_. In this case the following instructions and CSRs are available: * conversion: `fcvt.s.w` `fcvt.s.wu` `fcvt.w.s` `fcvt.wu.s` * comparison: `fmin.s` `fmax.s` `feq.s` `flt.s` `fle.s` * computational: `fadd.s` `fsub.s` `fmul.s` * sign-injection: `fsgnj.s` `fsgnjn.s` `fsgnjx.s` * number classification: `fclass.s` * additional CSRs: `fcsr` `frm` `fflags` [WARNING] Fused multiply-add instructions `f[n]m[add/sub].s` are not supported! Division `fdiv.s` and square root `fsqrt.s` instructions are not supported yet! [WARNING] Subnormal numbers (""de-normalized"" numbers) are not supported by the NEORV32 FPU. Subnormal numbers (exponent = 0) are _flushed to zero_ setting them to +/- 0 before entering the FPU's processing core. If a computational instruction (like `fmul.s`) generates a subnormal result, the result is also flushed to zero during normalization. [WARNING] The `Zfinx` extension is not yet officially ratified, but is expected to stay unchanged. There is no software support for the `Zfinx` extension in the upstream GCC RISC-V port yet. However, an intrinsic library is provided to utilize the provided `Zfinx` floating-point extension from C-language code (see `sw/example/floating_point_test`). ==== **`Zicsr`** Control and Status Register Access / Privileged Architecture The CSR access instructions as well as the exception and interrupt system (= the privileged architecture) is implemented when the `CPU_EXTENSION_RISCV_Zicsr` configuration generic is _true_. [IMPORTANT] If the `Zicsr` extension is disabled the CPU does not provide any _privileged architecture_ features at all! In order to provide the full set of privileged functions that are required to run more complex tasks like operating system and to allow a secure execution environment the `Zicsr` extension should be always enabled. In this case the following instructions are available: * CSR access: `csrrw` `csrrs` `csrrc` `csrrwi` `csrrsi` `csrrci` * environment: `mret` `wfi` [NOTE] If `rd=x0` for the `csrrw[i]` instructions there will be no actual read access to the according CSR. However, access privileges are still enforced so these instruction variants _do_ cause side-effects (the RISC-V spec. state that these combinations ""_shall_ not cause any side-effects""). [NOTE] The ""wait for interrupt instruction"" `wfi` acts like a sleep command. When executed, the CPU is halted until a valid interrupt request occurs. To wake up again, the according interrupt source has to be enabled via the `mie` CSR and the global interrupt enable flag in `mstatus` has to be set. The `wfi` instruction may also be executed in user-mode without causing an exception as <<_mstatus>> bit `TW` (timeout wait) is _hardwired_ to zero. ==== **`Zicntr`** CPU Base Counters The `Zicntr` ISA extension adds the basic cycle `[m]cycle[h]`), instruction-retired (`[m]instret[h]`) and time (`time[h]`) counters. This extensions is stated is _mandatory_ by the RISC-V spec. However, size-constrained setups may remove support for these counters. Section <<_machine_counter_and_timer_csrs>> shows a list of all `Zicntr`-related CSRs. These are available if the `Zicntr` ISA extensions is enabled via the <<_cpu_extension_riscv_zicntr>> generic. [NOTE] Disabling the `Zicntr` extension does not remove the `time[h]`-driving MTIME unit. If `Zicntr` is disabled, all accesses to the according counter CSRs will raise an illegal instruction exception. ==== **`Zihpm`** Hardware Performance Monitors In additions to the base cycle, instructions-retired and time counters the NEORV32 CPU provides up to 29 hardware performance monitors (HPM 3..31), which can be used to benchmark applications. Each HPM consists of an N-bit wide counter (split in a high-word 32-bit CSR and a low-word 32-bit CSR), where N is defined via the top's `HPM_CNT_WIDTH` generic (0..64-bit) and a corresponding event configuration CSR. The event configuration CSR defines the architectural events that lead to an increment of the associated HPM counter. The HPM counters are available if the `Zihpm` ISA extensions is enabled via the <<_cpu_extension_riscv_zihpm>> generic. Depending on the configuration the following additional CSR are available: * counters: `mhpmcounter*[h]` (3..31, depending on `HPM_NUM_CNTS`) * event configuration: `mhpmevent*` (3..31, depending on `HPM_NUM_CNTS`) [IMPORTANT] The HPM counter CSR can only be accessed in machine-mode. Hence, the according `mcounteren` CSR bits are always zero and read-only. Any access from less-privileged modes will raise an illegal instruction exception. [TIP] Auto-increment of the HPMs can be individually deactivated via the `mcountinhibit` CSR. [TIP] For a list of all HPM-related CSRs and all provided event configurations see section <<_hardware_performance_monitors_hpm>>. ==== **`Zifencei`** Instruction Stream Synchronization The `Zifencei` CPU extension is implemented if the `CPU_EXTENSION_RISCV_Zifencei` configuration generic is _true_. It allows manual synchronization of the instruction stream via the following instruction: * `fence.i` The `fence.i` instruction resets the CPU's front-end (instruction fetch) and flushes the prefetch buffer. This allows a clean re-fetch of modified instructions from memory. Also, the top's `i_bus_fencei_o` signal is set high for one cycle to inform the memory system (like the i-cache to perform a flush/reload. Any additional flags within the `fence.i` instruction word are ignore by the hardware. ==== **`PMP`** Physical Memory Protection The NEORV32 physical memory protection (PMP) is compatible to the RISC-V PMP specifications. It can be used to constrain memory read/write/execute rights for each available privilege level. The NEORV32 PMP only supports _NAPOT_ mode yet and a minimal region size (granularity) of 8 bytes. Larger minimal sizes can be configured via the top `PMP_MIN_GRANULARITY` generic to reduce hardware requirements. The physical memory protection system is implemented when the `PMP_NUM_REGIONS` configuration generic is >0. In this case the following additional CSRs are available: * `pmpcfg*` (0..15, depending on configuration): PMP configuration registers * `pmpaddr*` (0..63, depending on configuration): PMP address registers [TIP] See section <<_machine_physical_memory_protection_csrs>> for more information regarding the PMP CSRs. The actual number of regions and the minimal region granularity are defined via the top entity `PMP_MIN_GRANULARITY` and `PMP_NUM_REGIONS` generics. `PMP_MIN_GRANULARITY` defines the minimal available granularity of each region in bytes. `PMP_NUM_REGIONS` defines the total number of implemented regions and thus, the number of available `pmpcfg*` and `pmpaddr*` CSRs. When implementing more PMP regions that a _certain critical limit_ *an additional register stage is automatically inserted* into the CPU's memory interfaces to reduce critical path length. Unfortunately, this will also increase the latency of instruction fetches and data access by +1 cycle. The critical limit can be adapted for custom use by a constant from the main VHDL package file (`rtl/core/neorv32_package.vhd`). The default value is 8: [source,vhdl] ---- -- ""critical"" number of PMP regions -- constant pmp_num_regions_critical_c : natural := 8; ---- **Operation** Any CPU memory access address (from the instruction fetch or data access interface) is tested if it is accessing _any_ of the specified PMP regions(configured via `pmpaddr*` and enabled via `pmpcfg*`). If an address matches one of these regions, the configured access rights (attributes in `pmpcfg*`) are enforced: * a write access (store) will fail if no write attribute is set * a read access (load) will fail if no read attribute is set * an instruction fetch access will fail if no execute attribute is set If an access to a protected region does not have the according access rights it will raise the according instruction/load/store _access fault_ exception. By default, all PMP checks are enforced for user-level programs only. If you wish to enforce the physical memory protection also for machine-level programs you need to set the _locked bit_ in the according `pmpcfg*` configuration CSR. [IMPORTANT] After updating the address configuration registers `pmpaddr*` the system requires up to 33 cycles for internal (iterative) computations before the configuration becomes valid. [NOTE] For more information regarding RISC-V physical memory protection see the official _The RISC-V Instruction Set Manual - Volume II: Privileged Architecture_ specifications. <<< // #################################################################################################################### :sectnums: === Instruction Timing The instruction timing listed in the table below shows the required clock cycles for executing a certain instruction. These instruction cycles assume a bus access without additional wait states and a filled pipeline. Average CPI (cycles per instructions) values for ""real applications"" like for executing the CoreMark benchmark for different CPU configurations are presented in <<_cpu_performance>>. .Clock cycles per instruction [cols=""<2,^1,^4,<3""] [options=""header"", grid=""rows""] |======================= | Class | ISA | Instruction(s) | Execution cycles | ALU | `I/E` | `addi` `slti` `sltiu` `xori` `ori` `andi` `add` `sub` `slt` `sltu` `xor` `or` `and` `lui` `auipc` | 2 | ALU | `C` | `c.addi4spn` `c.nop` `c.addi` `c.li` `c.addi16sp` `c.lui` `c.andi` `c.sub` `c.xor` `c.or` `c.and` `c.add` `c.mv` | 2 | ALU | `I/E` | `slli` `srli` `srai` `sll` `srl` `sra` | 3 + SAfootnote:[Shift amount.]/4 + SA%4; FAST_SHIFTfootnote:[Barrel shift when `FAST_SHIFT_EN` is enabled.]: 4; TINY_SHIFTfootnote:[Serial shift when `TINY_SHIFT_EN` is enabled.]: 2..32 | ALU | `C` | `c.srli` `c.srai` `c.slli` | 3 + SAfootnote:[Shift amount (0..31).]; FAST_SHIFTfootnote:[Barrel shifter when `FAST_SHIFT_EN` is enabled.]: | Branches | `I/E` | `beq` `bne` `blt` `bge` `bltu` `bgeu` | Taken: 5 + MLfootnote:[Memory latency.]; Not taken: 3 | Branches | `C` | `c.beqz` `c.bnez` | Taken: 5 + MLfootnote:[Memory latency.]; Not taken: 3 | Jumps / Calls | `I/E` | `jal` `jalr` | 4 + ML | Jumps / Calls | `C` | `c.jal` `c.j` `c.jr` `c.jalr` | 4 + ML | Memory access | `I/E` | `lb` `lh` `lw` `lbu` `lhu` `sb` `sh` `sw` | 4 + ML | Memory access | `C` | `c.lw` `c.sw` `c.lwsp` `c.swsp` | 4 + ML | Memory access | `A` | `lr.w` `sc.w` | 4 + ML | Multiplication | `M` | `mul` `mulh` `mulhsu` `mulhu` | 2+32+2; FAST_MULfootnote:[DSP-based multiplication; enabled via `FAST_MUL_EN`.]: 4 | Division | `M` | `div` `divu` `rem` `remu` | 2+32+2 | CSR access | `Zicsr` | `csrrw` `csrrs` `csrrc` `csrrwi` `csrrsi` `csrrci` | 4 | System | `I/E`+`Zicsr` | `ecall` `ebreak` | 4 | System | `I/E` | `fence` | 3 | System | `C`+`Zicsr` | `c.break` | 4 | System | `Zicsr` | `mret` `wfi` | 5 | System | `Zifencei` | `fence.i` | 3 + ML | Floating-point - artihmetic | `Zfinx` | `fadd.s` | 110 | Floating-point - artihmetic | `Zfinx` | `fsub.s` | 112 | Floating-point - artihmetic | `Zfinx` | `fmul.s` | 22 | Floating-point - compare | `Zfinx` | `fmin.s` `fmax.s` `feq.s` `flt.s` `fle.s` | 13 | Floating-point - misc | `Zfinx` | `fsgnj.s` `fsgnjn.s` `fsgnjx.s` `fclass.s` | 12 | Floating-point - conversion | `Zfinx` | `fcvt.w.s` `fcvt.wu.s` | 47 | Floating-point - conversion | `Zfinx` | `fcvt.s.w` `fcvt.s.wu` | 48 | Bit-manipulation - arithmetic/logic | `B(Zbb)` | `sext.b` `sext.h` `min` `minu` `max` `maxu` `andn` `orn` `xnor` `zext`(pack) `rev8`(grevi) `orc.b`(gorci) | 3 | Bit-manipulation - arithmetic/logic | `B(Zba)` | `sh1add` `sh2add` `sh3add` | 3 | Bit-manipulation - shifts | `B(Zbb)` | `clz` `ctz` | 3 + 0..32 | Bit-manipulation - shifts | `B(Zbb)` | `cpop` | 3 + 32 | Bit-manipulation - shifts | `B(Zbb)` | `rol` `ror` `rori` | 3 + SA | Bit-manipulation - single-bit | `B(Zbs)` | `sbset[i]` `sbclr[i]` `sbinv[i]` `sbext[i]` | 3 | Bit-manipulation - shifted-add | `B(Zba)` | `sh1add` `sh2add` `sh3add` | 3 |======================= [NOTE] The presented values of the *floating-point execution cycles* are average values - obtained from 4096 instruction executions using pseudo-random input values. The execution time for emulating the instructions (using pure-software libraries) is ~17..140 times higher. <<< // #################################################################################################################### include::cpu_csr.adoc[] <<< // #################################################################################################################### :sectnums: ==== Traps, Exceptions and Interrupts In this document the following nomenclature regarding traps is used: * _interrupts_ = asynchronous exceptions * _exceptions_ = synchronous exceptions * _traps_ = exceptions + interrupts (synchronous or asynchronous exceptions) Whenever an exception or interrupt is triggered, the CPU transfers control to the address stored in `mtvec` CSR. The cause of the according interrupt or exception can be determined via the content of `mcause` CSR. The address that reflects the current program counter when a trap was taken is stored to `mepc` CSR. Additional information regarding the cause of the trap can be retrieved from `mtval` CSR and the processor's <<_internal_bus_monitor_buskeeper>> (for memory access exceptions) The traps are prioritized. If several _synchronous exceptions_ occur at once only the one with highest priority is triggered while all remaining exceptions are ignored. If several _asynchronous exceptions_ (interrupts) trigger at once, the one with highest priority is serviced first while the remaining ones stay _pending_. After completing the interrupt handler the interrupt with the second highest priority will get serviced and so on until no further interrupts are pending. .Interrupt Signal Requirements - Standard RISC-V Interrupts [IMPORTANT] All standard RISC-V interrupts request signals are **high-active**. A request has to stay at high-level (=asserted) until it is explicitly acknowledged by the CPU software (for example by writing to a specific memory-mapped register). .Interrupt Signal Requirements - Fast Interrupt Requests [IMPORTANT] The NEORV32-specific FIRQ request lines are triggered by a one-shot high-level (i.e. rising edge). Each request is buffered in the CPU control unit until the channel is either disabled (by clearing the according `mie` CSR bit) or the request is explicitly cleared (by setting the according `mip` CSR bit). .Instruction Atomicity [NOTE] All instructions execute as atomic operations - interrupts can only trigger _between_ two instructions. So even if there is a permanent interrupt request, exactly one instruction from the interrupt program will be executed before another interrupt handler can start. This allows program progress even if there are permanent interrupt requests. :sectnums: ==== Memory Access Exceptions If a load operation causes any exception, the instruction's destination register is _not written_ at all. Load exceptions caused by a misalignment or a physical memory protection fault do not trigger a bus/memory read-operation at all. Vice versa, exceptions caused by a store address misalignment or a store physical memory protection fault do not trigger a bus/memory write-operation at all. :sectnums: ==== Custom Fast Interrupt Request Lines As a custom extension, the NEORV32 CPU features 16 fast interrupt request (FIRQ) lines via the `firq_i` CPU top entity signals. These interrupts have custom configuration and status flags in the `mie` and `mip` CSRs and also provide custom trap codes in `mcause`. These FIRQs are reserved for NEORV32 processor-internal usage only. <<< // #################################################################################################################### :sectnums: ==== NEORV32 Trap Listing The following table shows all traps that are currently supported by the NEORV32 CPU. It also shows the prioritization and the CSR side-effects. A more detailed description of the actual trap triggering events is provided in a further table. [NOTE] _Asynchronous exceptions_ (= interrupts) set the MSB of `mcause` while _synchronous exception_ (= ""software exception"") clear the MSB. **Table Annotations** The ""Prio."" column shows the priority of each trap. The highest priority is 1. The ""`mcause`"" column shows the cause ID of the according trap that is written to `mcause` CSR. The ""[RISC-V]"" columns show the interrupt/exception code value from the official RISC-V privileged architecture manual. The ""[C]"" names are defined by the NEORV32 core library (the runtime environment _RTE_) and can be used in plain C code. The ""`mepc`"" and ""`mtval`"" columns show the value written to `mepc` and `mtval` CSRs when a trap is triggered: * _I-PC_ - address of interrupted instruction (instruction has not been execute/completed yet) * _B-ADR_- bad memory access address that cause the trap * _PC_ - address of instruction that caused the trap * _0_ - zero * _Inst_ - the faulting instruction itself .NEORV32 Trap Listing [cols=""3,6,5,14,11,4,4""] [options=""header"",grid=""rows""] |======================= | Prio. | `mcause` | [RISC-V] | ID [C] | Cause | `mepc` | `mtval` | 1 | `0x00000000` | 0.0 | _TRAP_CODE_I_MISALIGNED_ | instruction address misaligned | _B-ADR_ | _PC_ | 2 | `0x00000001` | 0.1 | _TRAP_CODE_I_ACCESS_ | instruction access fault | _B-ADR_ | _PC_ | 3 | `0x00000002` | 0.2 | _TRAP_CODE_I_ILLEGAL_ | illegal instruction | _PC_ | _Inst_ | 4 | `0x0000000B` | 0.11 | _TRAP_CODE_MENV_CALL_ | environment call from M-mode (`ecall` in machine-mode) | _PC_ | _PC_ | 5 | `0x00000008` | 0.8 | _TRAP_CODE_UENV_CALL_ | environment call from U-mode (`ecall` in user-mode) | _PC_ | _PC_ | 6 | `0x00000003` | 0.3 | _TRAP_CODE_BREAKPOINT_ | breakpoint (`ebreak`) | _PC_ | _PC_ | 7 | `0x00000006` | 0.6 | _TRAP_CODE_S_MISALIGNED_ | store address misaligned | _B-ADR_ | _B-ADR_ | 8 | `0x00000004` | 0.4 | _TRAP_CODE_L_MISALIGNED_ | load address misaligned | _B-ADR_ | _B-ADR_ | 9 | `0x00000007` | 0.7 | _TRAP_CODE_S_ACCESS_ | store access fault | _B-ADR_ | _B-ADR_ | 10 | `0x00000005` | 0.5 | _TRAP_CODE_L_ACCESS_ | load access fault | _B-ADR_ | _B-ADR_ | 11 | `0x80000010` | 1.16 | _TRAP_CODE_FIRQ_0_ | fast interrupt request channel 0 | _I-PC_ | _0_ | 12 | `0x80000011` | 1.17 | _TRAP_CODE_FIRQ_1_ | fast interrupt request channel 1 | _I-PC_ | _0_ | 13 | `0x80000012` | 1.18 | _TRAP_CODE_FIRQ_2_ | fast interrupt request channel 2 | _I-PC_ | _0_ | 14 | `0x80000013` | 1.19 | _TRAP_CODE_FIRQ_3_ | fast interrupt request channel 3 | _I-PC_ | _0_ | 15 | `0x80000014` | 1.20 | _TRAP_CODE_FIRQ_4_ | fast interrupt request channel 4 | _I-PC_ | _0_ | 16 | `0x80000015` | 1.21 | _TRAP_CODE_FIRQ_5_ | fast interrupt request channel 5 | _I-PC_ | _0_ | 17 | `0x80000016` | 1.22 | _TRAP_CODE_FIRQ_6_ | fast interrupt request channel 6 | _I-PC_ | _0_ | 18 | `0x80000017` | 1.23 | _TRAP_CODE_FIRQ_7_ | fast interrupt request channel 7 | _I-PC_ | _0_ | 19 | `0x80000018` | 1.24 | _TRAP_CODE_FIRQ_8_ | fast interrupt request channel 8 | _I-PC_ | _0_ | 20 | `0x80000019` | 1.25 | _TRAP_CODE_FIRQ_9_ | fast interrupt request channel 9 | _I-PC_ | _0_ | 21 | `0x8000001a` | 1.26 | _TRAP_CODE_FIRQ_10_ | fast interrupt request channel 10 | _I-PC_ | _0_ | 22 | `0x8000001b` | 1.27 | _TRAP_CODE_FIRQ_11_ | fast interrupt request channel 11 | _I-PC_ | _0_ | 23 | `0x8000001c` | 1.28 | _TRAP_CODE_FIRQ_12_ | fast interrupt request channel 12 | _I-PC_ | _0_ | 24 | `0x8000001d` | 1.29 | _TRAP_CODE_FIRQ_13_ | fast interrupt request channel 13 | _I-PC_ | _0_ | 25 | `0x8000001e` | 1.30 | _TRAP_CODE_FIRQ_14_ | fast interrupt request channel 14 | _I-PC_ | _0_ | 26 | `0x8000001f` | 1.31 | _TRAP_CODE_FIRQ_15_ | fast interrupt request channel 15 | _I-PC_ | _0_ | 27 | `0x8000000B` | 1.11 | _TRAP_CODE_MEI_ | machine external interrupt | _I-PC_ | _0_ | 28 | `0x80000003` | 1.3 | _TRAP_CODE_MSI_ | machine software interrupt | _I-PC_ | _0_ | 29 | `0x80000007` | 1.7 | _TRAP_CODE_MTI_ | machine timer interrupt | _I-PC_ | _0_ |======================= The following table provides a summarized description of the actual events for triggering a specific trap. .NEORV32 Trap Description [cols=""<3,<7""] [options=""header"",grid=""rows""] |======================= | Trap ID [C] | Triggered when ... | _TRAP_CODE_I_MISALIGNED_ | fetching an 32-bit instruction word that is not 32-bit-aligned (_see note below!_) | _TRAP_CODE_I_ACCESS_ | bus timeout or bus error during instruction word fetch | _TRAP_CODE_I_ILLEGAL_ | trying to execute an invalid instruction word (malformed or not supported) or on a privilege violation | _TRAP_CODE_MENV_CALL_ | executing `ecall` instruction in machine-mode | _TRAP_CODE_UENV_CALL_ | executing `ecall` instruction in user-mode | _TRAP_CODE_BREAKPOINT_ | executing `ebreak` instruction (or triggered by on-chip debugger) | _TRAP_CODE_S_MISALIGNED_ | storing data to an address that is not naturally aligned to the data size (byte, half, word) being stored | _TRAP_CODE_L_MISALIGNED_ | loading data from an address that is not naturally aligned to the data size (byte, half, word) being loaded | _TRAP_CODE_S_ACCESS_ | bus timeout or bus error during load data operation | _TRAP_CODE_L_ACCESS_ | bus timeout or bus error during store data operation | _TRAP_CODE_FIRQ_0_ ... _TRAP_CODE_FIRQ_15_| caused by interrupt-condition of processor-internal modules, see <<_neorv32_specific_fast_interrupt_requests>> | _TRAP_CODE_MEI_ | user-defined processor-external source (via dedicated top-entity signal) | _TRAP_CODE_MSI_ | user-defined processor-external source (via dedicated top-entity signal) | _TRAP_CODE_MTI_ | processor-internal machine timer overflow OR user-defined processor-external source (via dedicated top-entity signal) |======================= .Instruction Address Misaligned Exception [NOTE] For 32-bit-only instructions (= no `C` extension) the misaligned instruction exception is raised if bit 1 of the fetch address is set (i.e. not on a 32-bit boundary). If the `C` extension is implemented there will never be a misaligned instruction exception _at all_. In both cases bit 0 of the program counter (and all related registers) is hardwired to zero. <<< // #################################################################################################################### :sectnums: ==== Bus Interface The CPU provides two independent bus interfaces: One for fetching instructions (`i_bus_*`) and one for accessing data (`d_bus_*`) via load and store operations. Both interfaces use the same interface protocol. :sectnums: ===== Address Space The CPU is a 32-bit architecture with separated instruction and data interfaces making it a Harvard Architecture. Each of this interfaces can access an address space of up to 2^32^ bytes (4GB). The memory system is based on 32-bit words with a minimal granularity of 1 byte. Please note, that the NEORV32 CPU does not support unaligned memory accesses _in hardware_ - however, a software-based handling can be implemented as any unaligned memory access will trigger an according exception. :sectnums: ===== Interface Signals The following table shows the signals of the data and instruction interfaces seen from the CPU (`*_o` signals are driven by the CPU / outputs, `*_i` signals are read by the CPU / inputs). .CPU bus interface [cols=""<2,^1,<7""] [options=""header"",grid=""rows""] |======================= | Signal | Size | Function | `bus_addr_o` | 32 | access address | `bus_rdata_i` | 32 | data input for read operations | `bus_wdata_o` | 32 | data output for write operations | `bus_ben_o` | 4 | byte enable signal for write operations | `bus_we_o` | 1 | bus write access | `bus_re_o` | 1 | bus read access | `bus_lock_o` | 1 | exclusive access request | `bus_ack_i` | 1 | accessed peripheral indicates a successful completion of the bus transaction | `bus_err_i` | 1 | accessed peripheral indicates an error during the bus transaction | `bus_fence_o` | 1 | this signal is set for one cycle when the CPU executes a data/instruction fence operation | `bus_priv_o` | 2 | current CPU privilege level |======================= [NOTE] Currently, there a no pipelined or overlapping operations implemented within the same bus interface. So only a single transfer request can be ""on the fly"" (pending) at once. :sectnums: ===== Protocol A bus request is triggered either by the `bus_re_o` signal (for reading data) or by the `bus_we_o` signal (for writing data). These signals are active for exactly one cycle and initiate either a read or a write transaction. The transaction is completed when the accessed peripheral either sets the `bus_ack_i` signal (-> successful completion) or the `bus_err_i` signal is set (-> failed completion). All these control signals are only active (= high) for one single cycle. An error indicated via the `bus_err_i` signal during a transfer will trigger the according instruction bus access fault or load/store bus access fault exception. [NOTE] The transfer can be completed directly in the same cycle as it was initiated (via the `bus_re_o` or `bus_we_o` signal) if the peripheral sets `bus_ack_i` or `bus_err_i` high for one cycle. However, in order to shorten the critical path such ""asynchronous"" completion should be avoided. The default processor-internal module provide exactly **one cycle delay** between initiation and completion of transfers. .Bus Keeper: Processor-internal memories and memory-mapped devices with variable / high latency [IMPORTANT] Processor-internal peripherals or memories do not have to respond within one cycle after the transfer initiation (= latency > 1 cycle). However, the bus transaction has to be completed (= acknowledged) within a certain **response time window**. This time window is defined by the global `max_proc_int_response_time_c` constant (default = 15 cycles) from the processor's VHDL package file (`rtl/neorv32_package.vhd`). It defines the maximum number of cycles after which an _unacknowledged_ processor-internal bus transfer will timeout and raise a **bus fault exception**. The _BUSKEEPER_ hardware module (see section <<_internal_bus_monitor_buskeeper>>) keeps track of all _internal_ bus transactions. If any bus operations times out (for example when accessing ""address space holes"") this unit will issue a bus error to the CPU that will raise the according instruction fetch or data access bus exception. Note that **the bus keeper does not track external accesses via the external memory bus interface**. However, the external memory bus interface also provides an _optional_ bus timeout (see section <<_processor_external_memory_interface_wishbone_axi4_lite>>). **Exemplary Bus Accesses** .Example bus accesses: see read/write access description below [cols=""^2,^2""] [grid=""none""] |======================= a| image::cpu_interface_read_long.png[read,300,150] a| image::cpu_interface_write_long.png[write,300,150] | Read access | Write access |======================= **Write Access** For a write access, the accessed address (`bus_addr_o`), the data to be written (`bus_wdata_o`) and the byte enable signals (`bus_ben_o`) are set when bus_we_o goes high. These three signals are kept stable until the transaction is completed. In the example the accessed peripheral cannot answer directly in the next cycle after issuing. Here, the transaction is successful and the peripheral sets the `bus_ack_i` signal several cycles after issuing. **Read Access** For a read access, the accessed address (`bus_addr_o`) is set when `bus_re_o` goes high. The address is kept stable until the transaction is completed. In the example the accessed peripheral cannot answer directly in the next cycle after issuing. The peripheral hast to apply the read data right in the same cycle as the bus transaction is completed (here, the transaction is successful and the peripheral sets the `bus_ack_i` signal). **Access Boundaries** The instruction interface will always access memory on word (= 32-bit) boundaries even if fetching compressed (16-bit) instructions. The data interface can access memory on byte (= 8-bit), half-word (= 16- bit) and word (= 32-bit) boundaries. **Exclusive (Atomic) Access** The CPU can access memory in an exclusive manner by generating a load-reservate and store-conditional combination. Normally, these combinations should target the same memory address. The CPU starts an exclusive access to memory via the _load-reservate instruction_ (`lr.w`). This instruction will set the CPU-internal _exclusive access lock_, which directly drives the `d_bus_lock_o`. It is the task of the memory system to manage this exclusive access reservation by storing the according access address and the source of the access itself (for example via the CPU ID in a multi-core system). When the CPU executes a _store-conditional instruction_ (`sc.w`) the _CPU-internal exclusive access lock_ is evaluated to check if the exclusive access was successful. If the lock is still OK, the instruction will write-back zero and will allow the according store operation to the memory system. If the lock is broken, the instruction will write-back non-zero and will not generate an actual memory store operation. The CPU-internal exclusive access lock is broken if at least one of the situations appear. * when executing any other memory-access operation than `lr.w` * when any trap (sync. or async.) is triggered (for example to force a context switch) * when the memory system signals a bus error (via the `bus_err_i` signal) [TIP] For more information regarding the SoC-level behavior and requirements of atomic operations see section <<_processor_external_memory_interface_wishbone_axi4_lite>>. **Memory Barriers** Whenever the CPU executes a fence instruction, the according interface signal is set high for one cycle (`d_bus_fence_o` for a _fence_ instruction; `i_bus_fence_o` for a _fencei_ instruction). It is the task of the memory system to perform the necessary operations (like a cache flush and refill). <<< // #################################################################################################################### :sectnums: ==== CPU Hardware Reset In order to reduce routing constraints (and by this the actual hardware requirements), most uncritical registers of the NEORV32 CPU as well as most register of the whole NEORV32 Processor do not use **a dedicated hardware reset**. ""Uncritical registers"" in this context means that the initial value of these registers after power-up is not relevant for a defined CPU boot process. **Rationale** A good example to illustrate the concept of uncritical registers is a pipelined processing engine. Each stage of the engine features an N-bit _data register_ and a 1-bit _status register_. The status register is set when the data in the according data register is valid. At the end of the pipeline the status register might trigger a write-back of the processing result to some kind of memory. The initial status of the data registers after power-up is irrelevant as long as the status registers are all reset to a defined value that indicates there is no valid data in the pipeline's data register. Therefore, the pipeline data register do no require a dedicated reset as they do not control the actual operation (in contrast to the status register). This makes the pipeline data registers from this example ""uncritical registers"". **NEORV32 CPU Reset** In terms of the NEORV32 CPU, there are several pipeline registers, state machine registers and even status and control registers (CSRs) that do not require a defined initial state to ensure a correct boot process. The pipeline register will get initialized by the CPU's internal state machines, which are initialized from the main control engine that actually features a defined reset. The initialization of most of the CPU's core CSRs (like interrupt control) is done by the software (to be more specific, this is done by the `crt0.S` start-up code). During the very early boot process (where `crt0.S` is running) there is no chance for undefined behavior due to the lack of dedicated hardware resets of certain CSRs. For example the machine interrupt-enable CSR (`mie`) does not provide a dedicated reset. The value after reset of this register is uncritical as interrupts cannot fire because the global interrupt enabled flag in the status register (`mstatsus(mie)`) _do_ provide a dedicated hardware reset setting this bit to low (globally disabling interrupts). **Reset Configuration** Most CPU-internal register do provide an asynchronous reset in the VHDL code, but the ""don't care"" value (VHDL `'-'`) is used for initialization of all uncritical registers, effectively generating a flip-flop without a reset. However, certain applications or situations (like advanced gate-level / timing simulations) might require a more deterministic reset state. For this case, a defined reset level (reset-to-low) of all CPU registers can be enabled ba enabling a constant in the main VHDL package file (`rtl/core/neorv32_package.vhd`): [source,vhdl] ---- -- ""critical"" number of PMP regions -- constant dedicated_reset_c : boolean := false; -- use dedicated hardware reset value for UNCRITICAL registers (FALSE=reset value is irrelevant (might simplify HW), default; TRUE=defined LOW reset value) ---- ",16357,True,2744.315016917093,median "[[spring-cloud-dataflow-task]] = Tasks [partintro] -- This section goes into more detail about how you can orchestrate https://cloud.spring.io/spring-cloud-task/[Spring Cloud Task] applications on Spring Cloud Data Flow. If you are just starting out with Spring Cloud Data Flow, you should probably read the Getting Started guide for ""`<>`"" , ""`<>`"", ""`<>`"" before diving into this section. -- [[spring-cloud-dataflow-task-intro]] == Introduction A task application is short lived, meaning it stops running on purpose, and can be executed on demand or scheduled for execution. A use case might be to scrape a web page and write to the database. The https://cloud.spring.io/spring-cloud-task/[Spring Cloud Task] framework is based on Spring Boot and adds the capability for Boot applications to record the lifecycle events of a short lived application such as when it starts, when it ends and the exit status. The https://docs.spring.io/spring-cloud-task/docs/{spring-cloud-task-version}/reference/htmlsingle/#features-task-execution-details[TaskExecution] documentation shows which information is stored in the database. The entry point for code execution in a Spring Cloud Task application is most often an implementation of Boot's `CommandLineRunner` interface, as shown in this https://docs.spring.io/spring-cloud-task/docs/{spring-cloud-task-version}/reference/htmlsingle/#getting-started-writing-the-code[example]. The Spring Batch project is probably what comes to mind for Spring developers writing short lived applications. Spring Batch provides a much richer set of functionality than Spring Cloud Task and is recommended when processing large volumes of data. A use case might be to read many CSV files, transform each row of data, and write each transformed row to a database. Spring Batch provides its own database schema with a much more rich https://docs.spring.io/spring-batch/{spring-batch-doc-version}/reference/html/schema-appendix.html#metaDataSchema[set of information] about the execution of a Spring Batch job. Spring Cloud Task is integrated with Spring Batch so that if a Spring Cloud Task application defined a Spring Batch `Job`, a link between the Spring Cloud Task and Spring Cloud Batch execution tables is created. When running Data Flow on your local machine, Tasks are launched in a separate JVM. When running on Cloud Foundry, tasks are launched using https://docs.cloudfoundry.org/devguide/using-tasks.html[Cloud Foundry's Task] functionality and when running on Kubernetes, tasks are launched using either a `Pod` or a `Job` resource. == 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 https://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. .. Select your database dependency: Enter the database dependency that Data Flow is currently using. For example: `H2`. . 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 https://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-1.2.1.BUILD-SNAPSHOT.jar task.bar=file:///tmp/bar-1.2.1.BUILD-SNAPSHOT.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 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 https://dataflow.spring.io/task-maven-latest ``` 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 and version, it is not overridden by default. If you would like to override the pre-existing task app with a different uri or uri-metadata location, 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,bash,subs=attributes] ---- 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. ==== Automating the Creation of Task Definitions As of version 2.3.0, the Data Flow server can be configured to auto create task definitions by setting `spring.cloud.dataflow.task.autocreate-task-definitions` to `true`. This is not the default behavior but provided as a convenience. When this property is enabled, a task launch request can specify the registered task application name as the task name. If the task application is registered, the server will create a basic task definition that specifies only the app name, as required. This eliminates a manual step equivalent to something like: [source,bash,subs=attributes] ---- dataflow:>task create mytask --definition ""mytask"" ---- Command line arguments and deployment properties can still be specified for each task launch request. [[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,bash,subs=attributes] ---- 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,bash,subs=attributes] ---- 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""` ==== 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. The supported Task `` is task. NOTE: When restarting Spring Batch Jobs on Kubernetes, you must use the entry point of `shell` or `boot`. ===== Application Properties With Sensitive Information on Kubernetes When launching task applications where some of the properties may contain sensitive information, use the `shell` or `boot` as the `entryPointStyle`. This is because the `exec` (default) converts all properties to command line arguments and thus may not be secure in some environments. ==== 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,bash,subs=attributes] ---- --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-limit-concurrent-executions]] === Limit the number concurrent task launches Spring Cloud Data Flow allows a user to limit the maximum number of concurrently running tasks for each configured platform to prevent the saturation of IaaS/hardware resources. The limit is set to `20` for all supported platforms by default. If the number of concurrently running tasks on a platform instance is greater or equal to the limit, the next task launch request will fail and an error message will be returned via the RESTful API, Shell or UI. This limit can be configured for a platform instance by setting the corresponding deployer property, `spring.cloud.dataflow.task.platform..accounts[].deployment.maximumConcurrentTasks` property, where `` is the name of a configured platform account (`default` if no accounts are explicitly configured). The `` refers to one of the currently supported deployers: `local`, `cloudfoundry`, or `kubernetes`. The TaskLauncher implementation for each supported platform determines the number of currently executing tasks by querying the underlying platform's runtime state if possible. The method for identifying a `task` varies by platform. For example, launching a task on the local host uses the `LocalTaskLauncher`. The LocalTaskLauncher executes a process for each launch request and keeps track of these processes in memory. In this case, we don't query the underlying OS, as it is impractical to identify tasks this way. For Cloud Foundry, tasks are a core concept supported by its deployment model. The state of all tasks, running, completed, or failed, is available directly via the API. This means that every running task container in the account's org and space is included in the running execution count, whether or not it was launched using Spring Cloud Data Flow, or invoking the `CloudFoundryTaskLauncher` directly. For Kubernetes, launching a task via the `KubernetesTaskLauncher`, if successful, results in a running pod which we expect to eventually complete or fail. In this environment there is generally no easy way to identify pods that correspond to a task. For this reason, we only count pods that were launched by the `KubernetesTaskLauncher`. Since the task launcher provides `task-name` label in the pod's metadata, we filter all running pods by the presence of this label. [[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,bash,subs=attributes] ---- dataflow:>task destroy mytask Destroyed task 'mytask' ---- The `task destroy` command also has an option to `cleanup` the task executions of the task being destroyed, as shown in the following example: [source,bash,subs=attributes] ---- dataflow:>task destroy mytask --cleanup Destroyed task 'mytask' ---- By default, the `cleanup` option is set to `false` (ie., by default, the task executions are not cleaned up when destroying the task). To destroy all tasks through the shell, use the `task all destroy` command as shown in the following example: [source,bash,subs=attributes] ---- dataflow:>task all destroy Really destroy all tasks? [y, n]: y All tasks destroyed ---- Or use the force command: [source,bash,subs=attributes] ---- dataflow:>task all destroy --force All tasks destroyed ---- 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. NOTE: The `task destroy ` deletes only the definition and not the task deployed on Cloud Foundry. The only way to do this now is through the CLI in two steps. First, obtain a list of the apps by using the `cf apps` command. . Identify the task application to be deleted and run the `cf delete ` command. [[spring-cloud-dataflow-validate-task]] === Validating a Task Sometimes the one or more of the apps contained within a task definition contain an invalid URI in its registration. This can be caused by an invalid URI entered at app registration time or the app was removed from the repository from which it was to be drawn. To verify that all the apps contained in a task are resolve-able, a user can use the `validate` command. For example: [source,bash] ---- dataflow:>task validate time-stamp ╔══════════╤═══════════════╗ ║Task Name │Task Definition║ ╠══════════╪═══════════════╣ ║time-stamp│timestamp ║ ╚══════════╧═══════════════╝ time-stamp is a valid task. ╔═══════════════╤═════════════════╗ ║ App Name │Validation Status║ ╠═══════════════╪═════════════════╣ ║task:timestamp │valid ║ ╚═══════════════╧═════════════════╝ ---- In the example above the user validated their time-stamp task. As we see `task:timestamp` app is valid. Now let's see what happens if we have a stream definition with a registered app with an invalid URI. [source,bash] ---- dataflow:>task validate bad-timestamp ╔═════════════╤═══════════════╗ ║ Task Name │Task Definition║ ╠═════════════╪═══════════════╣ ║bad-timestamp│badtimestamp ║ ╚═════════════╧═══════════════╝ bad-timestamp is an invalid task. ╔══════════════════╤═════════════════╗ ║ App Name │Validation Status║ ╠══════════════════╪═════════════════╣ ║task:badtimestamp │invalid ║ ╚══════════════════╧═════════════════╝ ---- In this case Spring Cloud Data Flow states that the task is invalid because task:badtimestamp has an invalid URI. [[spring-cloud-dataflow-stopping-task-execution]] === Stopping a Task Execution In some cases a task that is executing on a platform may not stop because of a problem on the platform or the application business logic itself. For such cases Spring Cloud Data Flow offers the user the ability to send a request to the platform to terminate the task execution. To do this a user can submit a `task execution stop` for a given set of task executions. For example: [source,bash] ---- task execution stop --ids 5 Request to stop the task execution with id(s): 5 has been submitted ---- With the above command, the trigger to stop the execution of id=5 will be submitted to the underlying deployer implementation, and as a result, the operation will stop the execution of that task. When we view the result for the task execution, we will see that the task execution completed with a 0 exit code. [source,bash] ---- dataflow:>task execution list ╔══════════╤══╤════════════════════════════╤════════════════════════════╤═════════╗ ║Task Name │ID│ Start Time │ End Time │Exit Code║ ╠══════════╪══╪════════════════════════════╪════════════════════════════╪═════════╣ ║batch-demo│5 │Mon Jul 15 13:58:41 EDT 2019│Mon Jul 15 13:58:55 EDT 2019│0 ║ ║timestamp │1 │Mon Jul 15 09:26:41 EDT 2019│Mon Jul 15 09:26:41 EDT 2019│0 ║ ╚══════════╧══╧════════════════════════════╧════════════════════════════╧═════════╝ ---- If a user submits a stop for a task execution that has child task executions associated with it, like a composed task, a stop request will be sent for each of the child task executions. [WARNING] ==== When stopping a task execution that has a running Spring Batch job, the job will be left with the batch status of `STARTED`. Each of the supported platforms send a SIG-INT to the task application when a stop is requested that allows Spring Cloud Task to capture the state of the app, however Spring Batch does not handle a SIG-INT and thus the job stops in the STARTED status. ==== ==== Stopping a Task Execution that was started outside of Spring Cloud Data Flow You may wish to stop a task that has been launched outside of Spring Cloud Data Flow. An example of this is the worker applications launched by a Remote Batch Partitioned application. In such cases the Remote Batch Partitioned Application stores the external-execution-id for each of the worker applications, however no platform information is stored. So when Spring Cloud Data Flow has to stop a Remote Batch Partitioned application and its worker applications, you will need to specify the platform name as shown below: [source,bash] ---- dataflow:>task execution stop --ids 1 --platform myplatform Request to stop the task execution with id(s): 1 for platform myplatform has been submitted ---- [[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,bash,subs=attributes] ---- dataflow:>task create myTask --definition ""myBatchJob"" dataflow:>stream create task-event-subscriber1 --definition "":task-events > log"" --deploy dataflow:>task launch myTask ---- You can control the destination name for those events by specifying explicit names when launching the task, as follows: [source,bash,subs=attributes] ---- dataflow:>stream create task-event-subscriber2 --definition "":myTaskEvents > log"" --deploy dataflow:>task launch myTask --properties ""app.myBatchJob.spring.cloud.stream.bindings.task-events.destination=myTaskEvents"" ---- 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, Spring Cloud Data Flow retrieves the Composed Task Runner application from Maven Central for Cloud Foundry and local deployments and DockerHub for Kubernetes. It retrieves the Composed Task Runner upon the first use of composed tasks. If Maven Central or DockerHub cannot be reached for a given Spring Cloud Data Flow deployment a new URI can be specified to retrieve the Composed Task Runner using the `spring.cloud.dataflow.task.composed.task.runner.uri` 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 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. ===== Configuration Options The ComposedTaskRunner task has the following options: * *composed-task-arguments* The command line arguments to be used for each of the tasks. (String, default: ). * *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. When using this option it must be applied for all task launches for the desired application including the first 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) * *dataflow-server-uri* The URI for the dataflow server that will receive task launch requests. (String, default: http://localhost:9393) * *dataflow-server-username* The optional username for the dataflow server that will receive task launch requests. Used to access the the dataflow server using Basic Authentication. Not used if `dataflow-server-access-token` is set. * *dataflow-server-password* The optional password for the dataflow server that will receive task launch requests. Used to access the the dataflow server using Basic Authentication. Not used if `dataflow-server-access-token` is set. * *dataflow-server-access-token* This property sets optional OAuth2 Access Token. Typically the value is automatically set using the token from the currently logged in user, if available. However, for special use-cases this value can also be set explicitly. [INFO] ==== A special boolean property `dataflow-server-use-user-access-token` exists for the case where you want to use the access token of the currently logged user and propagate it to the Composed Task Runner. This property is used by Spring Cloud Data Flow and if set to `true` will auto-populate the property `dataflow-server-access-token`. When using `dataflow-server-use-user-access-token` it must be passed for each task execution. In some cases it maybe preferred that the user's `dataflow-server-access-token` must be passed for each composed task launch by default. In this case set the Spring Cloud Data Flow property `spring.cloud.dataflow.task.useUserAccessToken` to true. ==== 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,bash,subs=attributes] ---- 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' ---- ===== Launching a Composed Task using Custom Composed Task Runner In some cases a user will need to launch a composed task using a custom version of a Composed Task Runner other than default application that is shipped out-of-the-box. To do this, a user will need to register the custom version of the Composed Task Runner and then specify the --composedTaskRunnerName property pointing to the custom application at task launch as shown below: [source,bash,options=""nowrap""] ---- dataflow:>app register --name best-ctr --type task --uri maven://the.best.ctr.composed-task-runner:1.0.0.RELEASE dataflow:>task create mycomposedtask --definition ""te:timestamp && tr:timestamp"" Created new task 'mycomposedtask' dataflow:>task launch --name mycomposedtask --composedTaskRunnerName best-ctr ---- NOTE: The app specified by the `composedTaskRunnerName` needs to be a task registered in the Application Registry. ===== 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. NOTE: Tasks that are used in a split should not set the their `ExitMessage`. Setting the `ExitMessage` is only to be used with <>. ==== 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 the https://github.com/spring-cloud-stream-app-starters/tasklauncher-dataflow/blob/master/spring-cloud-starter-stream-sink-task-launcher-dataflow/README.adoc[tasklauncher-dataflow] sink. The sink connects to a Data Flow server and uses its REST API to launch any defined task. The sink accepts a https://github.com/spring-cloud-stream-app-starters/tasklauncher-dataflow/blob/master/spring-cloud-starter-stream-sink-task-launcher-dataflow/README.adoc#payload[JSON payload] representing a `task launch request` which provides the name of the task to launch, and may include command line arguments and deployment properties. The https://github.com/spring-cloud-stream-app-starters/core/blob/master/common/app-starters-task-launch-request-common/README.adoc[app-starters-task-launch-request-common] component , in conjunction with Spring Cloud Stream https://docs.spring.io/spring-cloud-stream/docs/current-snapshot/reference/htmlsingle/#_functional_composition[functional composition], can transform the output of any source or processor to a task launch request. Adding a dependency to `app-starters-task-launch-request-common`, auto-configures a `java.util.function.Function` implementation, registered via https://cloud.spring.io/spring-cloud-function/[Spring Cloud Function] as `taskLaunchRequest`. For example, you can start with the https://github.com/spring-cloud-stream-app-starters/time/tree/master/spring-cloud-starter-stream-source-time[time] source, add the following dependency, build it, and register it as a custom source. We'll call it `time-tlr` in this example. [source,xml] ---- org.springframework.cloud.stream.app app-starters-task-launch-request-common ---- TIP: https://start-scs.cfapps.io/[Spring Cloud Stream Initializr] provides a great starting point for creating stream applications. Next, <> the `tasklauncher-dataflow` sink, and create a task (we will use the provided timestamp task). ``` stream create --name task-every-minute --definition ""time-tlr --trigger.fixed-delay=60 --spring.cloud.stream.function.definition=taskLaunchRequest --task.launch.request.task-name=timestamp-task | tasklauncher-dataflow"" --deploy ``` The preceding stream will produce a task launch request every minute. The request provides the name of the task to launch : `{""name"":""timestamp-task""}`. The following stream definition illustrates the use of command line arguments. It will produce messages like `{""args"":[""foo=bar"",""time=12/03/18 17:44:12""],""deploymentProps"":{},""name"":""timestamp-task""}` to provide command line arguments to the task: ``` stream create --name task-every-second --definition ""time-tlr --spring.cloud.stream.function.definition=taskLaunchRequest --task.launch.request.task-name=timestamp-task --task.launch.request.args=foo=bar --task.launch.request.arg-expressions=time=payload | tasklauncher-dataflow"" --deploy ``` Note the use of SpEL expressions to map each message payload to the `time` command line argument, along with a static argument `foo=bar`. 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 ║ ╚════════════════════╧══╧════════════════════════════╧════════════════════════════╧═════════╝ ---- In this example, we have shown how to use the `time` source to launch a task at a fixed rate. This pattern may be applied to any source to launch a task in response to any event. === Launching a Composed Task From a Stream A composed task can be launched with the `tasklauncher-dataflow` sink, as discussed <>. Since we use the `ComposedTaskRunner` directly, we need to set up the task definitions for the composed task runner itself, along with the composed tasks, 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 composed-task-runner --definition ""composed-task-runner"" task create AAA --definition ""timestamp"" task create BBB --definition ""timestamp"" ---- NOTE: Releases of `ComposedTaskRunner` can be found https://github.com/spring-cloud-task-app-starters/composed-task-runner/releases[here]. 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 * The `time` source customized to emit task launch requests, as shown <>. * The `tasklauncher-dataflow` sink that launches the `ComposedTaskRunner` The stream should resemble the following: [source] ---- stream create ctr-stream --definition ""time --fixed-delay=30 --task.launch.request.task-name=composed-task-launcher --task.launch.request.args=--graph=AAA&&BBB,--increment-instance-enabled=true | tasklauncher-dataflow"" ---- 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 https://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`. [[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 databases 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. ==== 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 Task Launcher Sink 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. When using the Cloud Foundry platform Spring Cloud Data Flow will use the https://www.cloudfoundry.org/the-foundry/scheduler/[PCF Scheduler]. When using Kubernetes, a https://kubernetes.io/docs/concepts/workloads/controllers/cron-jobs/[CronJob] will be used. NOTE: Scheduled tasks do not implement the continuous deployment feature. Any changes to application version or properties for a task definition via Spring Cloud Data Flow will not affect scheduled tasks. .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: * Spring Cloud Data Flow Shell * Spring Cloud Data Flow Dashboard * Spring Cloud Data Flow RESTful API ==== Scheduling a Task To schedule a task using the shell, use the `task schedule create` command to create the schedule as shown in the following example: ``` dataflow:>task schedule create --definitionName mytask --name mytaskschedule --expression '*/1 * * * *' Created schedule 'mytaskschedule' ``` In the example above we created a schedule `mytaskschedule` for the task definition `mytask`. This schedule will launch `mytask` once a minute. NOTE: If using Cloud Foundry the cron expression above would be: `*/1 * ? * *`. This is because Cloud Foundry uses the Quartz cron expression format. [[spring-cloud-data-flow-schedule-unscheduling]] ==== Deleting a Schedule You can delete a schedule via the: * Spring Cloud Data Flow Shell * Spring Cloud Data Flow Dashboard * Spring Cloud Data Flow RESTful API To delete a task schedule using the shell, use the `task schedule destroy` command as shown in the following example: ``` dataflow:>task schedule destroy --name mytaskschedule Deleted task schedule 'mytaskschedule' ``` [[spring-cloud-data-flow-schedule-list]] ==== Listing Schedules You can view the available schedules via the: * Spring Cloud Data Flow Shell * Spring Cloud Data Flow Dashboard * Spring Cloud Data Flow RESTful API To view your schedules via the shell use the `task schedule list` command as shown in the following example: [source,bas,options=""nowrap""h] ---- dataflow:>task schedule list ╔══════════════════════════╤════════════════════╤════════════════════════════════════════════════════╗ ║ Schedule Name │Task Definition Name│ Properties ║ ╠══════════════════════════╪════════════════════╪════════════════════════════════════════════════════╣ ║mytaskschedule │mytask │spring.cloud.scheduler.cron.expression = */1 * * * *║ ╚══════════════════════════╧════════════════════╧════════════════════════════════════════════════════╝ ---- NOTE: Instructions to create, delete and list schedules via the Spring Cloud Data Flow UI can be found https://dataflow.spring.io/docs/feature-guides/batch/scheduling/[here]. [[spring-cloud-dataflow-task-cd]] == Continuous Deployment As task applications evolve, you want to get your updates to production. This section walks through the capabilities that Spring Cloud Data Flow provides around being able to update task applications. When a task application is registered (<>), a version is associated with it. A task application can have multiple versions associated with it, with one selected as the default. The following image illustrates an application with multiple versions associated with it (see the timestamp entry). image::{dataflow-asciidoc}/images/dataflow-task-application-versions.png[Task Application Versions, scaledwidth=""50%""] Versions of an application are managed by registering multiple applications with the same name and coordinates, _except_ the version. For example, if you were to register an application with the following values, you would get one application registered with two versions (2.0.0.RELEASE and 2.1.0.RELEASE): * Application 1 ** Name: `timestamp` ** Type: `task` ** URI: `maven://org.springframework.cloud.task.app:timestamp-task:2.0.0.RELEASE` * Application 2 ** Name: `timestamp` ** Type: `task` ** URI: `maven://org.springframework.cloud.task.app:timestamp-task:2.1.0.RELEASE` Besides having multiple versions, Spring Cloud Data Flow needs to know which version to run on the next launch. This is indicated by setting a version to be the default version. Whatever version of a task application is configured as the default version is the one to be run on the next launch request. You can see which version is the default in the UI as this image shows: image::{dataflow-asciidoc}/images/dataflow-task-default-version.png[Task Application Default Version, scaledwidth=""50%""] === Task Launch Lifecycle In previous versions of Spring Cloud Data Flow, when the request to launch a task was received, Spring Cloud Data Flow would deploy the application (if needed) and run it. If the application was being run on a platform that did not need to have the application deployed every time (CloudFoundry for example), the previously deployed application was used. This flow has changed in 2.3. The following image shows what happens when a task launch request comes in now: image::{dataflow-asciidoc}/images/dataflow-task-launch-flow.png[Flow For Launching A Task, scaledwidth=""50%""] There are three main flows to consider in the preceding diagram. Launching the first time or launching with no changes is one. The other is launching when there are changes. We look at the flow with no changes first. ==== Launch a Task With No Changes 1. A launch request comes into to Data Flow. Data Flow determines that an upgrade is not required, since nothing has changed (no properties, deployment properites, or versions have changed since the last execution). [start=5] 5. On platforms that cache a deployed artifact (CloudFoundry at the writing of this documentation), Data Flow checks whether the application was previously deployed. 6. If the application needs to be deployed, Data Flow does the deployment of the task application. 7. Data Flow launches the application. That flow is the default behavior and occurs every time a request comes in if nothing has changed. It is important to note that this is the same flow that Data Flow has always executed for launching of tasks. ==== Launch a Task With Changes That Is Not Currently Running The second flow to consider when launching a task is whether there was a change in any of the task application version, application properties, or deployment properties. In this case, the following flow is executed: 1. A launch request comes into Data Flow. Data Flow determines that an upgrade is required since there was a change in either task application version, application properties, or deployment properties. 2. Data Flow checks to see whether another instance of the task definition is currently running. [start=4] 4. If there is not another instance of the task definition currently running, the old deployment is deleted. 5. On platforms that cache a deployed artifact (CloudFoundry at the writing of this documentation), Data Flow checks whether the application was previously deployed (this check will evaluate to `false` in this flow since the old deployment was deleted). 6. Data Flow does the deployment of the task application with the updated values (new application version, new merged properties, and new merged deployment properties). 7. Data Flow launches the application. This flow is what fundamentally enables continuous deployment for Spring Cloud Data Flow. ==== Launch a Task With Changes While Another Instance Is Running The last main flow is when a launch request comes to Spring Cloud Data Flow to do an upgrade but the task definition is currently running. In this case, the launch is blocked due to the requirement to delete the current application. On some platforms (CloudFoundry at the writing of this document), deleting the application causes all currently running applications to be shut down. This feature prevents that from happening. The following process describes what happens when a task changes while another instance is running: 1. A launch request comes into to Data Flow. Data Flow determines that an upgrade is required, since there was a change in either task application version, application properties, or deployment properties. 2. Data Flow checks to see whether another instance of the task definition is currently running. 3. Data Flow prevents the launch from happening because other instances of the task definition are running. NOTE: Any launch that requires an upgrade of a task definition that is running at the time of the request is blocked from executing due to the need to delete any currently running tasks. ",16205,True,2884.2465782564373,median "------------------------------------------------------------------------------ -- -- -- GNAT LIBRARY COMPONENTS -- -- -- -- G N A T . S P I T B O L . P A T T E R N S -- -- -- -- S p e c -- -- -- -- Copyright (C) 1997-2015, AdaCore -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- As a special exception under Section 7 of GPL version 3, you are granted -- -- additional permissions described in the GCC Runtime Library Exception, -- -- version 3.1, as published by the Free Software Foundation. -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- . -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ -- SPITBOL-like pattern construction and matching -- This child package of GNAT.SPITBOL provides a complete implementation -- of the SPITBOL-like pattern construction and matching operations. This -- package is based on Macro-SPITBOL created by Robert Dewar. ------------------------------------------------------------ -- Summary of Pattern Matching Packages in GNAT Hierarchy -- ------------------------------------------------------------ -- There are three related packages that perform pattern matching functions. -- the following is an outline of these packages, to help you determine -- which is best for your needs. -- GNAT.Regexp (files g-regexp.ads/g-regexp.adb) -- This is a simple package providing Unix-style regular expression -- matching with the restriction that it matches entire strings. It -- is particularly useful for file name matching, and in particular -- it provides ""globbing patterns"" that are useful in implementing -- unix or DOS style wild card matching for file names. -- GNAT.Regpat (files g-regpat.ads/g-regpat.adb) -- This is a more complete implementation of Unix-style regular -- expressions, copied from the original V7 style regular expression -- library written in C by Henry Spencer. It is functionally the -- same as this library, and uses the same internal data structures -- stored in a binary compatible manner. -- GNAT.Spitbol.Patterns (files g-spipat.ads/g-spipat.adb) -- This is a completely general patterm matching package based on the -- pattern language of SNOBOL4, as implemented in SPITBOL. The pattern -- language is modeled on context free grammars, with context sensitive -- extensions that provide full (type 0) computational capabilities. with Ada.Strings.Maps; use Ada.Strings.Maps; with Ada.Text_IO; use Ada.Text_IO; package GNAT.Spitbol.Patterns is pragma Elaborate_Body; ------------------------------- -- Pattern Matching Tutorial -- ------------------------------- -- A pattern matching operation (a call to one of the Match subprograms) -- takes a subject string and a pattern, and optionally a replacement -- string. The replacement string option is only allowed if the subject -- is a variable. -- The pattern is matched against the subject string, and either the -- match fails, or it succeeds matching a contiguous substring. If a -- replacement string is specified, then the subject string is modified -- by replacing the matched substring with the given replacement. -- Concatenation and Alternation -- ============================= -- A pattern consists of a series of pattern elements. The pattern is -- built up using either the concatenation operator: -- A & B -- which means match A followed immediately by matching B, or the -- alternation operator: -- A or B -- which means first attempt to match A, and then if that does not -- succeed, match B. -- There is full backtracking, which means that if a given pattern -- element fails to match, then previous alternatives are matched. -- For example if we have the pattern: -- (A or B) & (C or D) & (E or F) -- First we attempt to match A, if that succeeds, then we go on to try -- to match C, and if that succeeds, we go on to try to match E. If E -- fails, then we try F. If F fails, then we go back and try matching -- D instead of C. Let's make this explicit using a specific example, -- and introducing the simplest kind of pattern element, which is a -- literal string. The meaning of this pattern element is simply to -- match the characters that correspond to the string characters. Now -- let's rewrite the above pattern form with specific string literals -- as the pattern elements: -- (""ABC"" or ""AB"") & (""DEF"" or ""CDE"") & (""GH"" or ""IJ"") -- The following strings will be attempted in sequence: -- ABC . DEF . GH -- ABC . DEF . IJ -- ABC . CDE . GH -- ABC . CDE . IJ -- AB . DEF . GH -- AB . DEF . IJ -- AB . CDE . GH -- AB . CDE . IJ -- Here we use the dot simply to separate the pieces of the string -- matched by the three separate elements. -- Moving the Start Point -- ====================== -- A pattern is not required to match starting at the first character -- of the string, and is not required to match to the end of the string. -- The first attempt does indeed attempt to match starting at the first -- character of the string, trying all the possible alternatives. But -- if all alternatives fail, then the starting point of the match is -- moved one character, and all possible alternatives are attempted at -- the new anchor point. -- The entire match fails only when every possible starting point has -- been attempted. As an example, suppose that we had the subject -- string -- ""ABABCDEIJKL"" -- matched using the pattern in the previous example: -- (""ABC"" or ""AB"") & (""DEF"" or ""CDE"") & (""GH"" or ""IJ"") -- would succeed, after two anchor point moves: -- ""ABABCDEIJKL"" -- ^^^^^^^ -- matched -- section -- This mode of pattern matching is called the unanchored mode. It is -- also possible to put the pattern matcher into anchored mode by -- setting the global variable Anchored_Mode to True. This will cause -- all subsequent matches to be performed in anchored mode, where the -- match is required to start at the first character. -- We will also see later how the effect of an anchored match can be -- obtained for a single specified anchor point if this is desired. -- Other Pattern Elements -- ====================== -- In addition to strings (or single characters), there are many special -- pattern elements that correspond to special predefined alternations: -- Arb Matches any string. First it matches the null string, and -- then on a subsequent failure, matches one character, and -- then two characters, and so on. It only fails if the -- entire remaining string is matched. -- Bal Matches a non-empty string that is parentheses balanced -- with respect to ordinary () characters. Examples of -- balanced strings are ""ABC"", ""A((B)C)"", and ""A(B)C(D)E"". -- Bal matches the shortest possible balanced string on the -- first attempt, and if there is a subsequent failure, -- attempts to extend the string. -- Cancel Immediately aborts the entire pattern match, signalling -- failure. This is a specialized pattern element, which is -- useful in conjunction with some of the special pattern -- elements that have side effects. -- Fail The null alternation. Matches no possible strings, so it -- always signals failure. This is a specialized pattern -- element, which is useful in conjunction with some of the -- special pattern elements that have side effects. -- Fence Matches the null string at first, and then if a failure -- causes alternatives to be sought, aborts the match (like -- a Cancel). Note that using Fence at the start of a pattern -- has the same effect as matching in anchored mode. -- Rest Matches from the current point to the last character in -- the string. This is a specialized pattern element, which -- is useful in conjunction with some of the special pattern -- elements that have side effects. -- Succeed Repeatedly matches the null string (it is equivalent to -- the alternation ("""" or """" or """" ....). This is a special -- pattern element, which is useful in conjunction with some -- of the special pattern elements that have side effects. -- Pattern Construction Functions -- ============================== -- The following functions construct additional pattern elements -- Any(S) Where S is a string, matches a single character that is -- any one of the characters in S. Fails if the current -- character is not one of the given set of characters. -- Arbno(P) Where P is any pattern, matches any number of instances -- of the pattern, starting with zero occurrences. It is -- thus equivalent to ("""" or (P & ("""" or (P & ("""" ....)))). -- The pattern P may contain any number of pattern elements -- including the use of alternation and concatenation. -- Break(S) Where S is a string, matches a string of zero or more -- characters up to but not including a break character -- that is one of the characters given in the string S. -- Can match the null string, but cannot match the last -- character in the string, since a break character is -- required to be present. -- BreakX(S) Where S is a string, behaves exactly like Break(S) when -- it first matches, but if a string is successfully matched, -- then a subsequent failure causes an attempt to extend the -- matched string. -- Fence(P) Where P is a pattern, attempts to match the pattern P -- including trying all possible alternatives of P. If none -- of these alternatives succeeds, then the Fence pattern -- fails. If one alternative succeeds, then the pattern -- match proceeds, but on a subsequent failure, no attempt -- is made to search for alternative matches of P. The -- pattern P may contain any number of pattern elements -- including the use of alternation and concatenation. -- Len(N) Where N is a natural number, matches the given number of -- characters. For example, Len(10) matches any string that -- is exactly ten characters long. -- NotAny(S) Where S is a string, matches a single character that is -- not one of the characters of S. Fails if the current -- character is one of the given set of characters. -- NSpan(S) Where S is a string, matches a string of zero or more -- characters that is among the characters given in the -- string. Always matches the longest possible such string. -- Always succeeds, since it can match the null string. -- Pos(N) Where N is a natural number, matches the null string -- if exactly N characters have been matched so far, and -- otherwise fails. -- Rpos(N) Where N is a natural number, matches the null string -- if exactly N characters remain to be matched, and -- otherwise fails. -- Rtab(N) Where N is a natural number, matches characters from -- the current position until exactly N characters remain -- to be matched in the string. Fails if fewer than N -- unmatched characters remain in the string. -- Tab(N) Where N is a natural number, matches characters from -- the current position until exactly N characters have -- been matched in all. Fails if more than N characters -- have already been matched. -- Span(S) Where S is a string, matches a string of one or more -- characters that is among the characters given in the -- string. Always matches the longest possible such string. -- Fails if the current character is not one of the given -- set of characters. -- Recursive Pattern Matching -- ========================== -- The plus operator (+P) where P is a pattern variable, creates -- a recursive pattern that will, at pattern matching time, follow -- the pointer to obtain the referenced pattern, and then match this -- pattern. This may be used to construct recursive patterns. Consider -- for example: -- P := (""A"" or (""B"" & (+P))) -- On the first attempt, this pattern attempts to match the string ""A"". -- If this fails, then the alternative matches a ""B"", followed by an -- attempt to match P again. This second attempt first attempts to -- match ""A"", and so on. The result is a pattern that will match a -- string of B's followed by a single A. -- This particular example could simply be written as NSpan('B') & 'A', -- but the use of recursive patterns in the general case can construct -- complex patterns which could not otherwise be built. -- Pattern Assignment Operations -- ============================= -- In addition to the overall result of a pattern match, which indicates -- success or failure, it is often useful to be able to keep track of -- the pieces of the subject string that are matched by individual -- pattern elements, or subsections of the pattern. -- The pattern assignment operators allow this capability. The first -- form is the immediate assignment: -- P * S -- Here P is an arbitrary pattern, and S is a variable of type VString -- that will be set to the substring matched by P. This assignment -- happens during pattern matching, so if P matches more than once, -- then the assignment happens more than once. -- The deferred assignment operation: -- P ** S -- avoids these multiple assignments by deferring the assignment to the -- end of the match. If the entire match is successful, and if the -- pattern P was part of the successful match, then at the end of the -- matching operation the assignment to S of the string matching P is -- performed. -- The cursor assignment operation: -- Setcur(N'Access) -- assigns the current cursor position to the natural variable N. The -- cursor position is defined as the count of characters that have been -- matched so far (including any start point moves). -- Finally the operations * and ** may be used with values of type -- Text_IO.File_Access. The effect is to do a Put_Line operation of -- the matched substring. These are particularly useful in debugging -- pattern matches. -- Deferred Matching -- ================= -- The pattern construction functions (such as Len and Any) all permit -- the use of pointers to natural or string values, or functions that -- return natural or string values. These forms cause the actual value -- to be obtained at pattern matching time. This allows interesting -- possibilities for constructing dynamic patterns as illustrated in -- the examples section. -- In addition the (+S) operator may be used where S is a pointer to -- string or function returning string, with a similar deferred effect. -- A special use of deferred matching is the construction of predicate -- functions. The element (+P) where P is an access to a function that -- returns a Boolean value, causes the function to be called at the -- time the element is matched. If the function returns True, then the -- null string is matched, if the function returns False, then failure -- is signalled and previous alternatives are sought. -- Deferred Replacement -- ==================== -- The simple model given for pattern replacement (where the matched -- substring is replaced by the string given as the third argument to -- Match) works fine in simple cases, but this approach does not work -- in the case where the expression used as the replacement string is -- dependent on values set by the match. -- For example, suppose we want to find an instance of a parenthesized -- character, and replace the parentheses with square brackets. At first -- glance it would seem that: -- Match (Subject, '(' & Len (1) * Char & ')', '[' & Char & ']'); -- would do the trick, but that does not work, because the third -- argument to Match gets evaluated too early, before the call to -- Match, and before the pattern match has had a chance to set Char. -- To solve this problem we provide the deferred replacement capability. -- With this approach, which of course is only needed if the pattern -- involved has side effects, is to do the match in two stages. The -- call to Match sets a pattern result in a variable of the private -- type Match_Result, and then a subsequent Replace operation uses -- this Match_Result object to perform the required replacement. -- Using this approach, we can now write the above operation properly -- in a manner that will work: -- M : Match_Result; -- ... -- Match (Subject, '(' & Len (1) * Char & ')', M); -- Replace (M, '[' & Char & ']'); -- As with other Match cases, there is a function and procedure form -- of this match call. A call to Replace after a failed match has no -- effect. Note that Subject should not be modified between the calls. -- Examples of Pattern Matching -- ============================ -- First a simple example of the use of pattern replacement to remove -- a line number from the start of a string. We assume that the line -- number has the form of a string of decimal digits followed by a -- period, followed by one or more spaces. -- Digs : constant Pattern := Span(""0123456789""); -- Lnum : constant Pattern := Pos(0) & Digs & '.' & Span(' '); -- Now to use this pattern we simply do a match with a replacement: -- Match (Line, Lnum, """"); -- which replaces the line number by the null string. Note that it is -- also possible to use an Ada.Strings.Maps.Character_Set value as an -- argument to Span and similar functions, and in particular all the -- useful constants 'in Ada.Strings.Maps.Constants are available. This -- means that we could define Digs as: -- Digs : constant Pattern := Span(Decimal_Digit_Set); -- The style we use here, of defining constant patterns and then using -- them is typical. It is possible to build up patterns dynamically, -- but it is usually more efficient to build them in pieces in advance -- using constant declarations. Note in particular that although it is -- possible to construct a pattern directly as an argument for the -- Match routine, it is much more efficient to preconstruct the pattern -- as we did in this example. -- Now let's look at the use of pattern assignment to break a -- string into sections. Suppose that the input string has two -- unsigned decimal integers, separated by spaces or a comma, -- with spaces allowed anywhere. Then we can isolate the two -- numbers with the following pattern: -- Num1, Num2 : aliased VString; -- B : constant Pattern := NSpan(' '); -- N : constant Pattern := Span(""0123456789""); -- T : constant Pattern := -- NSpan(' ') & N * Num1 & Span("" ,"") & N * Num2; -- The match operation Match ("" 124, 257 "", T) would assign the -- string 124 to Num1 and the string 257 to Num2. -- Now let's see how more complex elements can be built from the -- set of primitive elements. The following pattern matches strings -- that have the syntax of Ada 95 based literals: -- Digs : constant Pattern := Span(Decimal_Digit_Set); -- UDigs : constant Pattern := Digs & Arbno('_' & Digs); -- Edig : constant Pattern := Span(Hexadecimal_Digit_Set); -- UEdig : constant Pattern := Edig & Arbno('_' & Edig); -- Bnum : constant Pattern := Udigs & '#' & UEdig & '#'; -- A match against Bnum will now match the desired strings, e.g. -- it will match 16#123_abc#, but not a#b#. However, this pattern -- is not quite complete, since it does not allow colons to replace -- the pound signs. The following is more complete: -- Bchar : constant Pattern := Any(""#:""); -- Bnum : constant Pattern := Udigs & Bchar & UEdig & Bchar; -- but that is still not quite right, since it allows # and : to be -- mixed, and they are supposed to be used consistently. We solve -- this by using a deferred match. -- Temp : aliased VString; -- Bnum : constant Pattern := -- Udigs & Bchar * Temp & UEdig & (+Temp) -- Here the first instance of the base character is stored in Temp, and -- then later in the pattern we rematch the value that was assigned. -- For an example of a recursive pattern, let's define a pattern -- that is like the built in Bal, but the string matched is balanced -- with respect to square brackets or curly brackets. -- The language for such strings might be defined in extended BNF as -- ELEMENT ::= -- | '[' BALANCED_STRING ']' -- | '{' BALANCED_STRING '}' -- BALANCED_STRING ::= ELEMENT {ELEMENT} -- Here we use {} to indicate zero or more occurrences of a term, as -- is common practice in extended BNF. Now we can translate the above -- BNF into recursive patterns as follows: -- Element, Balanced_String : aliased Pattern; -- . -- . -- . -- Element := NotAny (""[]{}"") -- or -- ('[' & (+Balanced_String) & ']') -- or -- ('{' & (+Balanced_String) & '}'); -- Balanced_String := Element & Arbno (Element); -- Note the important use of + here to refer to a pattern not yet -- defined. Note also that we use assignments precisely because we -- cannot refer to as yet undeclared variables in initializations. -- Now that this pattern is constructed, we can use it as though it -- were a new primitive pattern element, and for example, the match: -- Match (""xy[ab{cd}]"", Balanced_String * Current_Output & Fail); -- will generate the output: -- x -- xy -- xy[ab{cd}] -- y -- y[ab{cd}] -- [ab{cd}] -- a -- ab -- ab{cd} -- b -- b{cd} -- {cd} -- c -- cd -- d -- Note that the function of the fail here is simply to force the -- pattern Balanced_String to match all possible alternatives. Studying -- the operation of this pattern in detail is highly instructive. -- Finally we give a rather elaborate example of the use of deferred -- matching. The following declarations build up a pattern which will -- find the longest string of decimal digits in the subject string. -- Max, Cur : VString; -- Loc : Natural; -- function GtS return Boolean is -- begin -- return Length (Cur) > Length (Max); -- end GtS; -- Digit : constant Character_Set := Decimal_Digit_Set; -- Digs : constant Pattern := Span(Digit); -- Find : constant Pattern := -- """" * Max & Fence & -- initialize Max to null -- BreakX (Digit) & -- scan looking for digits -- ((Span(Digit) * Cur & -- assign next string to Cur -- (+GtS'Unrestricted_Access) & -- check size(Cur) > Size(Max) -- Setcur(Loc'Access)) -- if so, save location -- * Max) & -- and assign to Max -- Fail; -- seek all alternatives -- As we see from the comments here, complex patterns like this take -- on aspects of sequential programs. In fact they are sequential -- programs with general backtracking. In this pattern, we first use -- a pattern assignment that matches null and assigns it to Max, so -- that it is initialized for the new match. Now BreakX scans to the -- next digit. Arb would do here, but BreakX will be more efficient. -- Once we have found a digit, we scan out the longest string of -- digits with Span, and assign it to Cur. The deferred call to GtS -- tests if the string we assigned to Cur is the longest so far. If -- not, then failure is signalled, and we seek alternatives (this -- means that BreakX will extend and look for the next digit string). -- If the call to GtS succeeds then the matched string is assigned -- as the largest string so far into Max and its location is saved -- in Loc. Finally Fail forces the match to fail and seek alternatives, -- so that the entire string is searched. -- If the pattern Find is matched against a string, the variable Max -- at the end of the pattern will have the longest string of digits, -- and Loc will be the starting character location of the string. For -- example, Match(""ab123cd4657ef23"", Find) will assign ""4657"" to Max -- and 11 to Loc (indicating that the string ends with the eleventh -- character of the string). -- Note: the use of Unrestricted_Access to reference GtS will not -- be needed if GtS is defined at the outer level, but definitely -- will be necessary if GtS is a nested function (in which case of -- course the scope of the pattern Find will be restricted to this -- nested scope, and this cannot be checked, i.e. use of the pattern -- outside this scope is erroneous). Generally it is a good idea to -- define patterns and the functions they call at the outer level -- where possible, to avoid such problems. -- Correspondence with Pattern Matching in SPITBOL -- =============================================== -- Generally the Ada syntax and names correspond closely to SPITBOL -- syntax for pattern matching construction. -- The basic pattern construction operators are renamed as follows: -- Spitbol Ada -- (space) & -- | or -- $ * -- . ** -- The Ada operators were chosen so that the relative precedences of -- these operators corresponds to that of the Spitbol operators, but -- as always, the use of parentheses is advisable to clarify. -- The pattern construction operators all have similar names except for -- Spitbol Ada -- Abort Cancel -- Rem Rest -- where we have clashes with Ada reserved names -- Ada requires the use of 'Access to refer to functions used in the -- pattern match, and often the use of 'Unrestricted_Access may be -- necessary to get around the scope restrictions if the functions -- are not declared at the outer level. -- The actual pattern matching syntax is modified in Ada as follows: -- Spitbol Ada -- X Y Match (X, Y); -- X Y = Z Match (X, Y, Z); -- and pattern failure is indicated by returning a Boolean result from -- the Match function (True for success, False for failure). ----------------------- -- Type Declarations -- ----------------------- type Pattern is private; -- Type representing a pattern. This package provides a complete set of -- operations for constructing patterns that can be used in the pattern -- matching operations provided. type Boolean_Func is access function return Boolean; -- General Boolean function type. When this type is used as a formal -- parameter type in this package, it indicates a deferred predicate -- pattern. The function will be called when the pattern element is -- matched and failure signalled if False is returned. type Natural_Func is access function return Natural; -- General Natural function type. When this type is used as a formal -- parameter type in this package, it indicates a deferred pattern. -- The function will be called when the pattern element is matched -- to obtain the currently referenced Natural value. type VString_Func is access function return VString; -- General VString function type. When this type is used as a formal -- parameter type in this package, it indicates a deferred pattern. -- The function will be called when the pattern element is matched -- to obtain the currently referenced string value. subtype PString is String; -- This subtype is used in the remainder of the package to indicate a -- formal parameter that is converted to its corresponding pattern, -- i.e. a pattern that matches the characters of the string. subtype PChar is Character; -- Similarly, this subtype is used in the remainder of the package to -- indicate a formal parameter that is converted to its corresponding -- pattern, i.e. a pattern that matches this one character. subtype VString_Var is VString; subtype Pattern_Var is Pattern; -- These synonyms are used as formal parameter types to a function where, -- if the language allowed, we would use in out parameters, but we are -- not allowed to have in out parameters for functions. Instead we pass -- actuals which must be variables, and with a bit of trickery in the -- body, manage to interpret them properly as though they were indeed -- in out parameters. pragma Warnings (Off, VString_Var); pragma Warnings (Off, Pattern_Var); -- We turn off warnings for these two types so that when variables are used -- as arguments in this context, warnings about them not being assigned in -- the source program will be suppressed. -------------------------------- -- Basic Pattern Construction -- -------------------------------- function ""&"" (L : Pattern; R : Pattern) return Pattern; function ""&"" (L : PString; R : Pattern) return Pattern; function ""&"" (L : Pattern; R : PString) return Pattern; function ""&"" (L : PChar; R : Pattern) return Pattern; function ""&"" (L : Pattern; R : PChar) return Pattern; -- Pattern concatenation. Matches L followed by R function ""or"" (L : Pattern; R : Pattern) return Pattern; function ""or"" (L : PString; R : Pattern) return Pattern; function ""or"" (L : Pattern; R : PString) return Pattern; function ""or"" (L : PString; R : PString) return Pattern; function ""or"" (L : PChar; R : Pattern) return Pattern; function ""or"" (L : Pattern; R : PChar) return Pattern; function ""or"" (L : PChar; R : PChar) return Pattern; function ""or"" (L : PString; R : PChar) return Pattern; function ""or"" (L : PChar; R : PString) return Pattern; -- Pattern alternation. Creates a pattern that will first try to match -- L and then on a subsequent failure, attempts to match R instead. ---------------------------------- -- Pattern Assignment Functions -- ---------------------------------- function ""*"" (P : Pattern; Var : VString_Var) return Pattern; function ""*"" (P : PString; Var : VString_Var) return Pattern; function ""*"" (P : PChar; Var : VString_Var) return Pattern; -- Matches P, and if the match succeeds, assigns the matched substring -- to the given VString variable Var. This assignment happens as soon as -- the substring is matched, and if the pattern P1 is matched more than -- once during the course of the match, then the assignment will occur -- more than once. function ""**"" (P : Pattern; Var : VString_Var) return Pattern; function ""**"" (P : PString; Var : VString_Var) return Pattern; function ""**"" (P : PChar; Var : VString_Var) return Pattern; -- Like ""*"" above, except that the assignment happens at most once -- after the entire match is completed successfully. If the match -- fails, then no assignment takes place. ---------------------------------- -- Deferred Matching Operations -- ---------------------------------- function ""+"" (Str : VString_Var) return Pattern; -- Here Str must be a VString variable. This function constructs a -- pattern which at pattern matching time will access the current -- value of this variable, and match against these characters. function ""+"" (Str : VString_Func) return Pattern; -- Constructs a pattern which at pattern matching time calls the given -- function, and then matches against the string or character value -- that is returned by the call. function ""+"" (P : Pattern_Var) return Pattern; -- Here P must be a Pattern variable. This function constructs a -- pattern which at pattern matching time will access the current -- value of this variable, and match against the pattern value. function ""+"" (P : Boolean_Func) return Pattern; -- Constructs a predicate pattern function that at pattern matching time -- calls the given function. If True is returned, then the pattern matches. -- If False is returned, then failure is signalled. -------------------------------- -- Pattern Building Functions -- -------------------------------- function Arb return Pattern; -- Constructs a pattern that will match any string. On the first attempt, -- the pattern matches a null string, then on each successive failure, it -- matches one more character, and only fails if matching the entire rest -- of the string. function Arbno (P : Pattern) return Pattern; function Arbno (P : PString) return Pattern; function Arbno (P : PChar) return Pattern; -- Pattern repetition. First matches null, then on a subsequent failure -- attempts to match an additional instance of the given pattern. -- Equivalent to (but more efficient than) P & ("""" or (P & ("""" or ... function Any (Str : String) return Pattern; function Any (Str : VString) return Pattern; function Any (Str : Character) return Pattern; function Any (Str : Character_Set) return Pattern; function Any (Str : not null access VString) return Pattern; function Any (Str : VString_Func) return Pattern; -- Constructs a pattern that matches a single character that is one of -- the characters in the given argument. The pattern fails if the current -- character is not in Str. function Bal return Pattern; -- Constructs a pattern that will match any non-empty string that is -- parentheses balanced with respect to the normal parentheses characters. -- Attempts to extend the string if a subsequent failure occurs. function Break (Str : String) return Pattern; function Break (Str : VString) return Pattern; function Break (Str : Character) return Pattern; function Break (Str : Character_Set) return Pattern; function Break (Str : not null access VString) return Pattern; function Break (Str : VString_Func) return Pattern; -- Constructs a pattern that matches a (possibly null) string which -- is immediately followed by a character in the given argument. This -- character is not part of the matched string. The pattern fails if -- the remaining characters to be matched do not include any of the -- characters in Str. function BreakX (Str : String) return Pattern; function BreakX (Str : VString) return Pattern; function BreakX (Str : Character) return Pattern; function BreakX (Str : Character_Set) return Pattern; function BreakX (Str : not null access VString) return Pattern; function BreakX (Str : VString_Func) return Pattern; -- Like Break, but the pattern attempts to extend on a failure to find -- the next occurrence of a character in Str, and only fails when the -- last such instance causes a failure. function Cancel return Pattern; -- Constructs a pattern that immediately aborts the entire match function Fail return Pattern; -- Constructs a pattern that always fails function Fence return Pattern; -- Constructs a pattern that matches null on the first attempt, and then -- causes the entire match to be aborted if a subsequent failure occurs. function Fence (P : Pattern) return Pattern; -- Constructs a pattern that first matches P. If P fails, then the -- constructed pattern fails. If P succeeds, then the match proceeds, -- but if subsequent failure occurs, alternatives in P are not sought. -- The idea of Fence is that each time the pattern is matched, just -- one attempt is made to match P, without trying alternatives. function Len (Count : Natural) return Pattern; function Len (Count : not null access Natural) return Pattern; function Len (Count : Natural_Func) return Pattern; -- Constructs a pattern that matches exactly the given number of -- characters. The pattern fails if fewer than this number of characters -- remain to be matched in the string. function NotAny (Str : String) return Pattern; function NotAny (Str : VString) return Pattern; function NotAny (Str : Character) return Pattern; function NotAny (Str : Character_Set) return Pattern; function NotAny (Str : not null access VString) return Pattern; function NotAny (Str : VString_Func) return Pattern; -- Constructs a pattern that matches a single character that is not -- one of the characters in the given argument. The pattern Fails if -- the current character is in Str. function NSpan (Str : String) return Pattern; function NSpan (Str : VString) return Pattern; function NSpan (Str : Character) return Pattern; function NSpan (Str : Character_Set) return Pattern; function NSpan (Str : not null access VString) return Pattern; function NSpan (Str : VString_Func) return Pattern; -- Constructs a pattern that matches the longest possible string -- consisting entirely of characters from the given argument. The -- string may be empty, so this pattern always succeeds. function Pos (Count : Natural) return Pattern; function Pos (Count : not null access Natural) return Pattern; function Pos (Count : Natural_Func) return Pattern; -- Constructs a pattern that matches the null string if exactly Count -- characters have already been matched, and otherwise fails. function Rest return Pattern; -- Constructs a pattern that always succeeds, matching the remaining -- unmatched characters in the pattern. function Rpos (Count : Natural) return Pattern; function Rpos (Count : not null access Natural) return Pattern; function Rpos (Count : Natural_Func) return Pattern; -- Constructs a pattern that matches the null string if exactly Count -- characters remain to be matched in the string, and otherwise fails. function Rtab (Count : Natural) return Pattern; function Rtab (Count : not null access Natural) return Pattern; function Rtab (Count : Natural_Func) return Pattern; -- Constructs a pattern that matches from the current location until -- exactly Count characters remain to be matched in the string. The -- pattern fails if fewer than Count characters remain to be matched. function Setcur (Var : not null access Natural) return Pattern; -- Constructs a pattern that matches the null string, and assigns the -- current cursor position in the string. This value is the number of -- characters matched so far. So it is zero at the start of the match. function Span (Str : String) return Pattern; function Span (Str : VString) return Pattern; function Span (Str : Character) return Pattern; function Span (Str : Character_Set) return Pattern; function Span (Str : not null access VString) return Pattern; function Span (Str : VString_Func) return Pattern; -- Constructs a pattern that matches the longest possible string -- consisting entirely of characters from the given argument. The -- string cannot be empty, so the pattern fails if the current -- character is not one of the characters in Str. function Succeed return Pattern; -- Constructs a pattern that succeeds matching null, both on the first -- attempt, and on any rematch attempt, i.e. it is equivalent to an -- infinite alternation of null strings. function Tab (Count : Natural) return Pattern; function Tab (Count : not null access Natural) return Pattern; function Tab (Count : Natural_Func) return Pattern; -- Constructs a pattern that from the current location until Count -- characters have been matched. The pattern fails if more than Count -- characters have already been matched. --------------------------------- -- Pattern Matching Operations -- --------------------------------- -- The Match function performs an actual pattern matching operation. -- The versions with three parameters perform a match without modifying -- the subject string and return a Boolean result indicating if the -- match is successful or not. The Anchor parameter is set to True to -- obtain an anchored match in which the pattern is required to match -- the first character of the string. In an unanchored match, which is -- the default, successive attempts are made to match the given pattern -- at each character of the subject string until a match succeeds, or -- until all possibilities have failed. -- Note that pattern assignment functions in the pattern may generate -- side effects, so these functions are not necessarily pure. Anchored_Mode : Boolean := False; -- This global variable can be set True to cause all subsequent pattern -- matches to operate in anchored mode. In anchored mode, no attempt is -- made to move the anchor point, so that if the match succeeds it must -- succeed starting at the first character. Note that the effect of -- anchored mode may be achieved in individual pattern matches by using -- Fence or Pos(0) at the start of the pattern. Pattern_Stack_Overflow : exception; -- Exception raised if internal pattern matching stack overflows. This -- is typically the result of runaway pattern recursion. If there is a -- genuine case of stack overflow, then either the match must be broken -- down into simpler steps, or the stack limit must be reset. Stack_Size : constant Positive := 2000; -- Size used for internal pattern matching stack. Increase this size if -- complex patterns cause Pattern_Stack_Overflow to be raised. -- Simple match functions. The subject is matched against the pattern. -- Any immediate or deferred assignments or writes are executed, and -- the returned value indicates whether or not the match succeeded. function Match (Subject : VString; Pat : Pattern) return Boolean; function Match (Subject : VString; Pat : PString) return Boolean; function Match (Subject : String; Pat : Pattern) return Boolean; function Match (Subject : String; Pat : PString) return Boolean; -- Replacement functions. The subject is matched against the pattern. -- Any immediate or deferred assignments or writes are executed, and -- the returned value indicates whether or not the match succeeded. -- If the match succeeds, then the matched part of the subject string -- is replaced by the given Replace string. function Match (Subject : VString_Var; Pat : Pattern; Replace : VString) return Boolean; function Match (Subject : VString_Var; Pat : PString; Replace : VString) return Boolean; function Match (Subject : VString_Var; Pat : Pattern; Replace : String) return Boolean; function Match (Subject : VString_Var; Pat : PString; Replace : String) return Boolean; -- Simple match procedures. The subject is matched against the pattern. -- Any immediate or deferred assignments or writes are executed. No -- indication of success or failure is returned. procedure Match (Subject : VString; Pat : Pattern); procedure Match (Subject : VString; Pat : PString); procedure Match (Subject : String; Pat : Pattern); procedure Match (Subject : String; Pat : PString); -- Replacement procedures. The subject is matched against the pattern. -- Any immediate or deferred assignments or writes are executed. No -- indication of success or failure is returned. If the match succeeds, -- then the matched part of the subject string is replaced by the given -- Replace string. procedure Match (Subject : in out VString; Pat : Pattern; Replace : VString); procedure Match (Subject : in out VString; Pat : PString; Replace : VString); procedure Match (Subject : in out VString; Pat : Pattern; Replace : String); procedure Match (Subject : in out VString; Pat : PString; Replace : String); -- Deferred Replacement type Match_Result is private; -- Type used to record result of pattern match subtype Match_Result_Var is Match_Result; -- This synonyms is used as a formal parameter type to a function where, -- if the language allowed, we would use an in out parameter, but we are -- not allowed to have in out parameters for functions. Instead we pass -- actuals which must be variables, and with a bit of trickery in the -- body, manage to interpret them properly as though they were indeed -- in out parameters. function Match (Subject : VString_Var; Pat : Pattern; Result : Match_Result_Var) return Boolean; procedure Match (Subject : in out VString; Pat : Pattern; Result : out Match_Result); procedure Replace (Result : in out Match_Result; Replace : VString); -- Given a previous call to Match which set Result, performs a pattern -- replacement if the match was successful. Has no effect if the match -- failed. This call should immediately follow the Match call. ------------------------ -- Debugging Routines -- ------------------------ -- Debugging pattern matching operations can often be quite complex, -- since there is no obvious way to trace the progress of the match. -- The declarations in this section provide some debugging assistance. Debug_Mode : Boolean := False; -- This global variable can be set True to generate debugging on all -- subsequent calls to Match. The debugging output is a full trace of -- the actions of the pattern matcher, written to Standard_Output. The -- level of this information is intended to be comprehensible at the -- abstract level of this package declaration. However, note that the -- use of this switch often generates large amounts of output. function ""*"" (P : Pattern; Fil : File_Access) return Pattern; function ""*"" (P : PString; Fil : File_Access) return Pattern; function ""*"" (P : PChar; Fil : File_Access) return Pattern; function ""**"" (P : Pattern; Fil : File_Access) return Pattern; function ""**"" (P : PString; Fil : File_Access) return Pattern; function ""**"" (P : PChar; Fil : File_Access) return Pattern; -- These are similar to the corresponding pattern assignment operations -- except that instead of setting the value of a variable, the matched -- substring is written to the appropriate file. This can be useful in -- following the progress of a match without generating the full amount -- of information obtained by setting Debug_Mode to True. Terminal : constant File_Access := Standard_Error; Output : constant File_Access := Standard_Output; -- Two handy synonyms for use with the above pattern write operations -- Finally we have some routines that are useful for determining what -- patterns are in use, particularly if they are constructed dynamically. function Image (P : Pattern) return String; function Image (P : Pattern) return VString; -- This procedures yield strings that corresponds to the syntax needed -- to create the given pattern using the functions in this package. The -- form of this string is such that it could actually be compiled and -- evaluated to yield the required pattern except for references to -- variables and functions, which are output using one of the following -- forms: -- -- access Natural NP(16#...#) -- access Pattern PP(16#...#) -- access VString VP(16#...#) -- -- Natural_Func NF(16#...#) -- VString_Func VF(16#...#) -- -- where 16#...# is the hex representation of the integer address that -- corresponds to the given access value procedure Dump (P : Pattern); -- This procedure writes information about the pattern to Standard_Out. -- The format of this information is keyed to the internal data structures -- used to implement patterns. The information provided by Dump is thus -- more precise than that yielded by Image, but is also a bit more obscure -- (i.e. it cannot be interpreted solely in terms of this spec, you have -- to know something about the data structures). ------------------ -- Private Part -- ------------------ private type PE; -- Pattern element, a pattern is a complex structure of PE's. This type -- is defined and described in the body of this package. type PE_Ptr is access all PE; -- Pattern reference. PE's use PE_Ptr values to reference other PE's type Pattern is new Controlled with record Stk : Natural := 0; -- Maximum number of stack entries required for matching this -- pattern. See description of pattern history stack in body. P : PE_Ptr := null; -- Pointer to initial pattern element for pattern end record; pragma Finalize_Storage_Only (Pattern); procedure Adjust (Object : in out Pattern); -- Adjust routine used to copy pattern objects procedure Finalize (Object : in out Pattern); -- Finalization routine used to release storage allocated for a pattern type VString_Ptr is access all VString; type Match_Result is record Var : VString_Ptr; -- Pointer to subject string. Set to null if match failed Start : Natural := 1; -- Starting index position (1's origin) of matched section of -- subject string. Only valid if Var is non-null. Stop : Natural := 0; -- Ending index position (1's origin) of matched section of -- subject string. Only valid if Var is non-null. end record; pragma Volatile (Match_Result); -- This ensures that the Result parameter is passed by reference, so -- that we can play our games with the bogus Match_Result_Var parameter -- in the function case to treat it as though it were an in out parameter. end GNAT.Spitbol.Patterns; ",12364,False,2346.3494813158063,median "------------------------------------------------------------------------------ -- -- -- Copyright (C) 2015-2016, AdaCore -- -- -- -- 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. -- -- -- ------------------------------------------------------------------------------ -- MPU9250 I2C device class package with Interfaces; use Interfaces; with HAL; use HAL; with HAL.I2C; use HAL.I2C; with HAL.Time; package MPU9250 is type MPU9250_AD0_Pin_State is (High, Low); -- The MPU9250 has a pin that can be set to high or low level to change -- its I2C address. -- Types and subtypes type MPU9250_Device (Port : HAL.I2C.Any_I2C_Port; I2C_AD0_Pin : MPU9250_AD0_Pin_State; Time : not null HAL.Time.Any_Delays) is private; -- Type reprensnting all the different clock sources of the MPU9250. -- See the MPU9250 register map section 4.4 for more details. type MPU9250_Clock_Source is (Internal_Clk, X_Gyro_Clk, Y_Gyro_Clk, Z_Gyro_Clk, External_32K_Clk, External_19M_Clk, Reserved_Clk, Stop_Clk); for MPU9250_Clock_Source use (Internal_Clk => 16#00#, X_Gyro_Clk => 16#01#, Y_Gyro_Clk => 16#02#, Z_Gyro_Clk => 16#03#, External_32K_Clk => 16#04#, External_19M_Clk => 16#05#, Reserved_Clk => 16#06#, Stop_Clk => 16#07#); for MPU9250_Clock_Source'Size use 3; -- Type representing the allowed full scale ranges -- for MPU9250 gyroscope. type MPU9250_FS_Gyro_Range is (MPU9250_Gyro_FS_250, MPU9250_Gyro_FS_500, MPU9250_Gyro_FS_1000, MPU9250_Gyro_FS_2000); for MPU9250_FS_Gyro_Range use (MPU9250_Gyro_FS_250 => 16#00#, MPU9250_Gyro_FS_500 => 16#01#, MPU9250_Gyro_FS_1000 => 16#02#, MPU9250_Gyro_FS_2000 => 16#03#); for MPU9250_FS_Gyro_Range'Size use 2; -- Type representing the allowed full scale ranges -- for MPU9250 accelerometer. type MPU9250_FS_Accel_Range is (MPU9250_Accel_FS_2, MPU9250_Accel_FS_4, MPU9250_Accel_FS_8, MPU9250_Accel_FS_16); for MPU9250_FS_Accel_Range use (MPU9250_Accel_FS_2 => 16#00#, MPU9250_Accel_FS_4 => 16#01#, MPU9250_Accel_FS_8 => 16#02#, MPU9250_Accel_FS_16 => 16#03#); for MPU9250_FS_Accel_Range'Size use 2; type MPU9250_DLPF_Bandwidth_Mode is (MPU9250_DLPF_BW_256, MPU9250_DLPF_BW_188, MPU9250_DLPF_BW_98, MPU9250_DLPF_BW_42, MPU9250_DLPF_BW_20, MPU9250_DLPF_BW_10, MPU9250_DLPF_BW_5); for MPU9250_DLPF_Bandwidth_Mode use (MPU9250_DLPF_BW_256 => 16#00#, MPU9250_DLPF_BW_188 => 16#01#, MPU9250_DLPF_BW_98 => 16#02#, MPU9250_DLPF_BW_42 => 16#03#, MPU9250_DLPF_BW_20 => 16#04#, MPU9250_DLPF_BW_10 => 16#05#, MPU9250_DLPF_BW_5 => 16#06#); for MPU9250_DLPF_Bandwidth_Mode'Size use 3; -- Use to convert MPU9250 registers in degrees (gyro) and G (acc). MPU9250_DEG_PER_LSB_250 : constant := (2.0 * 250.0) / 65536.0; MPU9250_DEG_PER_LSB_500 : constant := (2.0 * 500.0) / 65536.0; MPU9250_DEG_PER_LSB_1000 : constant := (2.0 * 1000.0) / 65536.0; MPU9250_DEG_PER_LSB_2000 : constant := (2.0 * 2000.0) / 65536.0; MPU9250_G_PER_LSB_2 : constant := (2.0 * 2.0) / 65536.0; MPU9250_G_PER_LSB_4 : constant := (2.0 * 4.0) / 65536.0; MPU9250_G_PER_LSB_8 : constant := (2.0 * 8.0) / 65536.0; MPU9250_G_PER_LSB_16 : constant := (2.0 * 16.0) / 65536.0; -- Procedures and functions -- Initialize the MPU9250 Device via I2C. procedure MPU9250_Init (Device : in out MPU9250_Device); -- Test if the MPU9250 is initialized and connected. function MPU9250_Test (Device : MPU9250_Device) return Boolean; -- Test if we are connected to MPU9250 via I2C. function MPU9250_Test_Connection (Device : MPU9250_Device) return Boolean; type Test_Reporter is access procedure (Msg : String; Has_Succeeded : out Boolean); -- MPU9250 self test. function MPU9250_Self_Test (Device : in out MPU9250_Device; Do_Report : Boolean; Reporter : Test_Reporter) return Boolean; -- Reset the MPU9250 device. -- A small delay of ~50ms may be desirable after triggering a reset. procedure MPU9250_Reset (Device : in out MPU9250_Device); -- Get raw 6-axis motion sensor readings (accel/gyro). -- Retrieves all currently available motion sensor values. procedure MPU9250_Get_Motion_6 (Device : MPU9250_Device; Acc_X : out Integer_16; Acc_Y : out Integer_16; Acc_Z : out Integer_16; Gyro_X : out Integer_16; Gyro_Y : out Integer_16; Gyro_Z : out Integer_16); -- Set clock source setting. -- 3 bits allowed to choose the source. The different -- clock sources are enumerated in the MPU9250 register map. procedure MPU9250_Set_Clock_Source (Device : in out MPU9250_Device; Clock_Source : MPU9250_Clock_Source); -- Set digital low-pass filter configuration. procedure MPU9250_Set_DLPF_Mode (Device : in out MPU9250_Device; DLPF_Mode : MPU9250_DLPF_Bandwidth_Mode); -- Set full-scale gyroscope range. procedure MPU9250_Set_Full_Scale_Gyro_Range (Device : in out MPU9250_Device; FS_Range : MPU9250_FS_Gyro_Range); -- Set full-scale acceler range. procedure MPU9250_Set_Full_Scale_Accel_Range (Device : in out MPU9250_Device; FS_Range : MPU9250_FS_Accel_Range); -- Set I2C bypass enabled status. -- When this bit is equal to 1 and I2C_MST_EN (Register 106 bit[5]) is -- equal to 0, the host application processor -- will be able to directly access the -- auxiliary I2C bus of the MPU-60X0. When this bit is equal to 0, -- the host application processor will not be able to directly -- access the auxiliary I2C bus of the MPU-60X0 regardless of the state -- of I2C_MST_EN (Register 106 bit[5]). procedure MPU9250_Set_I2C_Bypass_Enabled (Device : in out MPU9250_Device; Value : Boolean); -- Set interrupts enabled status. procedure MPU9250_Set_Int_Enabled (Device : in out MPU9250_Device; Value : Boolean); -- Set gyroscope sample rate divider procedure MPU9250_Set_Rate (Device : in out MPU9250_Device; Rate_Div : UInt8); -- Set sleep mode status. procedure MPU9250_Set_Sleep_Enabled (Device : in out MPU9250_Device; Value : Boolean); -- Set temperature sensor enabled status. procedure MPU9250_Set_Temp_Sensor_Enabled (Device : in out MPU9250_Device; Value : Boolean); -- Get temperature sensor enabled status. function MPU9250_Get_Temp_Sensor_Enabled (Device : MPU9250_Device) return Boolean; private type MPU9250_Device (Port : HAL.I2C.Any_I2C_Port; I2C_AD0_Pin : MPU9250_AD0_Pin_State; Time : not null HAL.Time.Any_Delays) is record Is_Init : Boolean := False; Address : UInt10; end record; subtype T_Bit_Pos_8 is Natural range 0 .. 7; subtype T_Bit_Pos_16 is Natural range 0 .. 15; -- Global variables and constants -- MPU9250 Device ID. Use to test if we are connected via I2C MPU9250_DEVICE_ID : constant := 16#71#; -- Address pin low (GND), default for InvenSense evaluation board MPU9250_ADDRESS_AD0_LOW : constant := 16#68#; -- Address pin high (VCC) MPU9250_ADDRESS_AD0_HIGH : constant := 16#69#; MPU9250_STARTUP_TIME_MS : constant := 1_000; -- MPU9250 register adresses and other defines MPU9250_REV_C4_ES : constant := 16#14#; MPU9250_REV_C5_ES : constant := 16#15#; MPU9250_REV_D6_ES : constant := 16#16#; MPU9250_REV_D7_ES : constant := 16#17#; MPU9250_REV_D8_ES : constant := 16#18#; MPU9250_REV_C4 : constant := 16#54#; MPU9250_REV_C5 : constant := 16#55#; MPU9250_REV_D6 : constant := 16#56#; MPU9250_REV_D7 : constant := 16#57#; MPU9250_REV_D8 : constant := 16#58#; MPU9250_REV_D9 : constant := 16#59#; MPU9250_RA_ST_X_GYRO : constant := 16#00#; MPU9250_RA_ST_Y_GYRO : constant := 16#01#; MPU9250_RA_ST_Z_GYRO : constant := 16#02#; MPU9250_RA_ST_X_ACCEL : constant := 16#0D#; MPU9250_RA_ST_Y_ACCEL : constant := 16#0E#; MPU9250_RA_ST_Z_ACCEL : constant := 16#0F#; MPU9250_RA_XG_OFFS_USRH : constant := 16#13#; MPU9250_RA_XG_OFFS_USRL : constant := 16#14#; MPU9250_RA_YG_OFFS_USRH : constant := 16#15#; MPU9250_RA_YG_OFFS_USRL : constant := 16#16#; MPU9250_RA_ZG_OFFS_USRH : constant := 16#17#; MPU9250_RA_ZG_OFFS_USRL : constant := 16#18#; MPU9250_RA_SMPLRT_DIV : constant := 16#19#; MPU9250_RA_CONFIG : constant := 16#1A#; MPU9250_RA_GYRO_CONFIG : constant := 16#1B#; MPU9250_RA_ACCEL_CONFIG : constant := 16#1C#; MPU9250_RA_ACCEL_CONFIG_2 : constant := 16#1D#; MPU9250_RA_LP_ACCEL_ODR : constant := 16#1E#; MPU9250_RA_WOM_THR : constant := 16#1F#; MPU9250_RA_FIFO_EN : constant := 16#23#; MPU9250_RA_I2C_MST_CTRL : constant := 16#24#; MPU9250_RA_I2C_SLV0_ADDR : constant := 16#25#; MPU9250_RA_I2C_SLV0_REG : constant := 16#26#; MPU9250_RA_I2C_SLV0_CTRL : constant := 16#27#; MPU9250_RA_I2C_SLV1_ADDR : constant := 16#28#; MPU9250_RA_I2C_SLV1_REG : constant := 16#29#; MPU9250_RA_I2C_SLV1_CTRL : constant := 16#2A#; MPU9250_RA_I2C_SLV2_ADDR : constant := 16#2B#; MPU9250_RA_I2C_SLV2_REG : constant := 16#2C#; MPU9250_RA_I2C_SLV2_CTRL : constant := 16#2D#; MPU9250_RA_I2C_SLV3_ADDR : constant := 16#2E#; MPU9250_RA_I2C_SLV3_REG : constant := 16#2F#; MPU9250_RA_I2C_SLV3_CTRL : constant := 16#30#; MPU9250_RA_I2C_SLV4_ADDR : constant := 16#31#; MPU9250_RA_I2C_SLV4_REG : constant := 16#32#; MPU9250_RA_I2C_SLV4_DO : constant := 16#33#; MPU9250_RA_I2C_SLV4_CTRL : constant := 16#34#; MPU9250_RA_I2C_SLV4_DI : constant := 16#35#; MPU9250_RA_I2C_MST_STATUS : constant := 16#36#; MPU9250_RA_INT_PIN_CFG : constant := 16#37#; MPU9250_RA_INT_ENABLE : constant := 16#38#; MPU9250_RA_DMP_INT_STATUS : constant := 16#39#; MPU9250_RA_INT_STATUS : constant := 16#3A#; MPU9250_RA_ACCEL_XOUT_H : constant := 16#3B#; MPU9250_RA_ACCEL_XOUT_L : constant := 16#3C#; MPU9250_RA_ACCEL_YOUT_H : constant := 16#3D#; MPU9250_RA_ACCEL_YOUT_L : constant := 16#3E#; MPU9250_RA_ACCEL_ZOUT_H : constant := 16#3F#; MPU9250_RA_ACCEL_ZOUT_L : constant := 16#40#; MPU9250_RA_TEMP_OUT_H : constant := 16#41#; MPU9250_RA_TEMP_OUT_L : constant := 16#42#; MPU9250_RA_GYRO_XOUT_H : constant := 16#43#; MPU9250_RA_GYRO_XOUT_L : constant := 16#44#; MPU9250_RA_GYRO_YOUT_H : constant := 16#45#; MPU9250_RA_GYRO_YOUT_L : constant := 16#46#; MPU9250_RA_GYRO_ZOUT_H : constant := 16#47#; MPU9250_RA_GYRO_ZOUT_L : constant := 16#48#; MPU9250_RA_EXT_SENS_DATA_00 : constant := 16#49#; MPU9250_RA_EXT_SENS_DATA_01 : constant := 16#4A#; MPU9250_RA_EXT_SENS_DATA_02 : constant := 16#4B#; MPU9250_RA_EXT_SENS_DATA_03 : constant := 16#4C#; MPU9250_RA_EXT_SENS_DATA_04 : constant := 16#4D#; MPU9250_RA_EXT_SENS_DATA_05 : constant := 16#4E#; MPU9250_RA_EXT_SENS_DATA_06 : constant := 16#4F#; MPU9250_RA_EXT_SENS_DATA_07 : constant := 16#50#; MPU9250_RA_EXT_SENS_DATA_08 : constant := 16#51#; MPU9250_RA_EXT_SENS_DATA_09 : constant := 16#52#; MPU9250_RA_EXT_SENS_DATA_10 : constant := 16#53#; MPU9250_RA_EXT_SENS_DATA_11 : constant := 16#54#; MPU9250_RA_EXT_SENS_DATA_12 : constant := 16#55#; MPU9250_RA_EXT_SENS_DATA_13 : constant := 16#56#; MPU9250_RA_EXT_SENS_DATA_14 : constant := 16#57#; MPU9250_RA_EXT_SENS_DATA_15 : constant := 16#58#; MPU9250_RA_EXT_SENS_DATA_16 : constant := 16#59#; MPU9250_RA_EXT_SENS_DATA_17 : constant := 16#5A#; MPU9250_RA_EXT_SENS_DATA_18 : constant := 16#5B#; MPU9250_RA_EXT_SENS_DATA_19 : constant := 16#5C#; MPU9250_RA_EXT_SENS_DATA_20 : constant := 16#5D#; MPU9250_RA_EXT_SENS_DATA_21 : constant := 16#5E#; MPU9250_RA_EXT_SENS_DATA_22 : constant := 16#5F#; MPU9250_RA_EXT_SENS_DATA_23 : constant := 16#60#; MPU9250_RA_MOT_DETECT_STATUS : constant := 16#61#; MPU9250_RA_I2C_SLV0_DO : constant := 16#63#; MPU9250_RA_I2C_SLV1_DO : constant := 16#64#; MPU9250_RA_I2C_SLV2_DO : constant := 16#65#; MPU9250_RA_I2C_SLV3_DO : constant := 16#66#; MPU9250_RA_I2C_MST_DELAY_CTRL : constant := 16#67#; MPU9250_RA_SIGNAL_PATH_RESET : constant := 16#68#; MPU9250_RA_MOT_DETECT_CTRL : constant := 16#69#; MPU9250_RA_USER_CTRL : constant := 16#6A#; MPU9250_RA_PWR_MGMT_1 : constant := 16#6B#; MPU9250_RA_PWR_MGMT_2 : constant := 16#6C#; MPU9250_RA_BANK_SEL : constant := 16#6D#; MPU9250_RA_MEM_START_ADDR : constant := 16#6E#; MPU9250_RA_MEM_R_W : constant := 16#6F#; MPU9250_RA_DMP_CFG_1 : constant := 16#70#; MPU9250_RA_DMP_CFG_2 : constant := 16#71#; MPU9250_RA_FIFO_COUNTH : constant := 16#72#; MPU9250_RA_FIFO_COUNTL : constant := 16#73#; MPU9250_RA_FIFO_R_W : constant := 16#74#; MPU9250_RA_WHO_AM_I : constant := 16#75#; MPU9250_RA_XA_OFFSET_H : constant := 16#77#; MPU9250_RA_XA_OFFSET_L : constant := 16#78#; MPU9250_RA_YA_OFFSET_H : constant := 16#7A#; MPU9250_RA_YA_OFFSET_L : constant := 16#7B#; MPU9250_RA_ZA_OFFSET_H : constant := 16#7D#; MPU9250_RA_ZA_OFFSET_L : constant := 16#7E#; MPU9250_TC_PWR_MODE_BIT : constant := 7; MPU9250_TC_OFFSET_BIT : constant := 6; MPU9250_TC_OFFSET_LENGTH : constant := 6; MPU9250_TC_OTP_BNK_VLD_BIT : constant := 0; MPU9250_VDDIO_LEVEL_VLOGIC : constant := 0; MPU9250_VDDIO_LEVEL_VDD : constant := 1; MPU9250_CFG_EXT_SYNC_SET_BIT : constant := 5; MPU9250_CFG_EXT_SYNC_SET_LENGTH : constant := 3; MPU9250_CFG_DLPF_CFG_BIT : constant := 2; MPU9250_CFG_DLPF_CFG_LENGTH : constant := 3; MPU9250_EXT_SYNC_DISABLED : constant := 16#0#; MPU9250_EXT_SYNC_TEMP_OUT_L : constant := 16#1#; MPU9250_EXT_SYNC_GYRO_XOUT_L : constant := 16#2#; MPU9250_EXT_SYNC_GYRO_YOUT_L : constant := 16#3#; MPU9250_EXT_SYNC_GYRO_ZOUT_L : constant := 16#4#; MPU9250_EXT_SYNC_ACCEL_XOUT_L : constant := 16#5#; MPU9250_EXT_SYNC_ACCEL_YOUT_L : constant := 16#6#; MPU9250_EXT_SYNC_ACCEL_ZOUT_L : constant := 16#7#; MPU9250_GCONFIG_XG_ST_BIT : constant := 7; MPU9250_GCONFIG_YG_ST_BIT : constant := 6; MPU9250_GCONFIG_ZG_ST_BIT : constant := 5; MPU9250_GCONFIG_FS_SEL_BIT : constant := 4; MPU9250_GCONFIG_FS_SEL_LENGTH : constant := 2; MPU9250_ACONFIG_XA_ST_BIT : constant := 7; MPU9250_ACONFIG_YA_ST_BIT : constant := 6; MPU9250_ACONFIG_ZA_ST_BIT : constant := 5; MPU9250_ACONFIG_AFS_SEL_BIT : constant := 4; MPU9250_ACONFIG_AFS_SEL_LENGTH : constant := 2; MPU9250_ACONFIG_ACCEL_HPF_BIT : constant := 2; MPU9250_ACONFIG_ACCEL_HPF_LENGTH : constant := 3; MPU9250_DHPF_RESET : constant := 16#00#; MPU9250_DHPF_5 : constant := 16#01#; MPU9250_DHPF_2P5 : constant := 16#02#; MPU9250_DHPF_1P25 : constant := 16#03#; MPU9250_DHPF_0P63 : constant := 16#04#; MPU9250_DHPF_HOLD : constant := 16#07#; MPU9250_TEMP_FIFO_EN_BIT : constant := 7; MPU9250_XG_FIFO_EN_BIT : constant := 6; MPU9250_YG_FIFO_EN_BIT : constant := 5; MPU9250_ZG_FIFO_EN_BIT : constant := 4; MPU9250_ACCEL_FIFO_EN_BIT : constant := 3; MPU9250_SLV2_FIFO_EN_BIT : constant := 2; MPU9250_SLV1_FIFO_EN_BIT : constant := 1; MPU9250_SLV0_FIFO_EN_BIT : constant := 0; MPU9250_MULT_MST_EN_BIT : constant := 7; MPU9250_WAIT_FOR_ES_BIT : constant := 6; MPU9250_SLV_3_FIFO_EN_BIT : constant := 5; MPU9250_I2C_MST_P_NSR_BIT : constant := 4; MPU9250_I2C_MST_CLK_BIT : constant := 3; MPU9250_I2C_MST_CLK_LENGTH : constant := 4; MPU9250_CLOCK_DIV_348 : constant := 16#0#; MPU9250_CLOCK_DIV_333 : constant := 16#1#; MPU9250_CLOCK_DIV_320 : constant := 16#2#; MPU9250_CLOCK_DIV_308 : constant := 16#3#; MPU9250_CLOCK_DIV_296 : constant := 16#4#; MPU9250_CLOCK_DIV_286 : constant := 16#5#; MPU9250_CLOCK_DIV_276 : constant := 16#6#; MPU9250_CLOCK_DIV_267 : constant := 16#7#; MPU9250_CLOCK_DIV_258 : constant := 16#8#; MPU9250_CLOCK_DIV_500 : constant := 16#9#; MPU9250_CLOCK_DIV_471 : constant := 16#A#; MPU9250_CLOCK_DIV_444 : constant := 16#B#; MPU9250_CLOCK_DIV_421 : constant := 16#C#; MPU9250_CLOCK_DIV_400 : constant := 16#D#; MPU9250_CLOCK_DIV_381 : constant := 16#E#; MPU9250_CLOCK_DIV_364 : constant := 16#F#; MPU9250_I2C_SLV_RW_BIT : constant := 7; MPU9250_I2C_SLV_ADDR_BIT : constant := 6; MPU9250_I2C_SLV_ADDR_LENGTH : constant := 7; MPU9250_I2C_SLV_EN_BIT : constant := 7; MPU9250_I2C_SLV_UInt8_SW_BIT : constant := 6; MPU9250_I2C_SLV_REG_DIS_BIT : constant := 5; MPU9250_I2C_SLV_GRP_BIT : constant := 4; MPU9250_I2C_SLV_LEN_BIT : constant := 3; MPU9250_I2C_SLV_LEN_LENGTH : constant := 4; MPU9250_I2C_SLV4_RW_BIT : constant := 7; MPU9250_I2C_SLV4_ADDR_BIT : constant := 6; MPU9250_I2C_SLV4_ADDR_LENGTH : constant := 7; MPU9250_I2C_SLV4_EN_BIT : constant := 7; MPU9250_I2C_SLV4_INT_EN_BIT : constant := 6; MPU9250_I2C_SLV4_REG_DIS_BIT : constant := 5; MPU9250_I2C_SLV4_MST_DLY_BIT : constant := 4; MPU9250_I2C_SLV4_MST_DLY_LENGTH : constant := 5; MPU9250_MST_PASS_THROUGH_BIT : constant := 7; MPU9250_MST_I2C_SLV4_DONE_BIT : constant := 6; MPU9250_MST_I2C_LOST_ARB_BIT : constant := 5; MPU9250_MST_I2C_SLV4_NACK_BIT : constant := 4; MPU9250_MST_I2C_SLV3_NACK_BIT : constant := 3; MPU9250_MST_I2C_SLV2_NACK_BIT : constant := 2; MPU9250_MST_I2C_SLV1_NACK_BIT : constant := 1; MPU9250_MST_I2C_SLV0_NACK_BIT : constant := 0; MPU9250_INTCFG_INT_LEVEL_BIT : constant := 7; MPU9250_INTCFG_INT_OPEN_BIT : constant := 6; MPU9250_INTCFG_LATCH_INT_EN_BIT : constant := 5; MPU9250_INTCFG_INT_RD_CLEAR_BIT : constant := 4; MPU9250_INTCFG_FSYNC_INT_LEVEL_BIT : constant := 3; MPU9250_INTCFG_FSYNC_INT_EN_BIT : constant := 2; MPU9250_INTCFG_I2C_BYPASS_EN_BIT : constant := 1; MPU9250_INTCFG_CLKOUT_EN_BIT : constant := 0; MPU9250_INTMODE_ACTIVEHIGH : constant := 16#00#; MPU9250_INTMODE_ACTIVELOW : constant := 16#01#; MPU9250_INTDRV_PUSHPULL : constant := 16#00#; MPU9250_INTDRV_OPENDRAIN : constant := 16#01#; MPU9250_INTLATCH_50USPULSE : constant := 16#00#; MPU9250_INTLATCH_WAITCLEAR : constant := 16#01#; MPU9250_INTCLEAR_STATUSREAD : constant := 16#00#; MPU9250_INTCLEAR_ANYREAD : constant := 16#01#; MPU9250_INTERRUPT_FF_BIT : constant := 7; MPU9250_INTERRUPT_MOT_BIT : constant := 6; MPU9250_INTERRUPT_ZMOT_BIT : constant := 5; MPU9250_INTERRUPT_FIFO_OFLOW_BIT : constant := 4; MPU9250_INTERRUPT_I2C_MST_INT_BIT : constant := 3; MPU9250_INTERRUPT_PLL_RDY_INT_BIT : constant := 2; MPU9250_INTERRUPT_DMP_INT_BIT : constant := 1; MPU9250_INTERRUPT_DATA_RDY_BIT : constant := 0; MPU9250_DMPINT_5_BIT : constant := 5; MPU9250_DMPINT_4_BIT : constant := 4; MPU9250_DMPINT_3_BIT : constant := 3; MPU9250_DMPINT_2_BIT : constant := 2; MPU9250_DMPINT_1_BIT : constant := 1; MPU9250_DMPINT_0_BIT : constant := 0; MPU9250_MOTION_MOT_XNEG_BIT : constant := 7; MPU9250_MOTION_MOT_XPOS_BIT : constant := 6; MPU9250_MOTION_MOT_YNEG_BIT : constant := 5; MPU9250_MOTION_MOT_YPOS_BIT : constant := 4; MPU9250_MOTION_MOT_ZNEG_BIT : constant := 3; MPU9250_MOTION_MOT_ZPOS_BIT : constant := 2; MPU9250_MOTION_MOT_ZRMOT_BIT : constant := 0; MPU9250_DELAYCTRL_DELAY_ES_SHADOW_BIT : constant := 7; MPU9250_DELAYCTRL_I2C_SLV4_DLY_EN_BIT : constant := 4; MPU9250_DELAYCTRL_I2C_SLV3_DLY_EN_BIT : constant := 3; MPU9250_DELAYCTRL_I2C_SLV2_DLY_EN_BIT : constant := 2; MPU9250_DELAYCTRL_I2C_SLV1_DLY_EN_BIT : constant := 1; MPU9250_DELAYCTRL_I2C_SLV0_DLY_EN_BIT : constant := 0; MPU9250_PATHRESET_GYRO_RESET_BIT : constant := 2; MPU9250_PATHRESET_ACCEL_RESET_BIT : constant := 1; MPU9250_PATHRESET_TEMP_RESET_BIT : constant := 0; MPU9250_DETECT_ACCEL_ON_DELAY_BIT : constant := 5; MPU9250_DETECT_ACCEL_ON_DELAY_LENGTH : constant := 2; MPU9250_DETECT_FF_COUNT_BIT : constant := 3; MPU9250_DETECT_FF_COUNT_LENGTH : constant := 2; MPU9250_DETECT_MOT_COUNT_BIT : constant := 1; MPU9250_DETECT_MOT_COUNT_LENGTH : constant := 2; MPU9250_DETECT_DECREMENT_RESET : constant := 16#0#; MPU9250_DETECT_DECREMENT_1 : constant := 16#1#; MPU9250_DETECT_DECREMENT_2 : constant := 16#2#; MPU9250_DETECT_DECREMENT_4 : constant := 16#3#; MPU9250_USERCTRL_DMP_EN_BIT : constant := 7; MPU9250_USERCTRL_FIFO_EN_BIT : constant := 6; MPU9250_USERCTRL_I2C_MST_EN_BIT : constant := 5; MPU9250_USERCTRL_I2C_IF_DIS_BIT : constant := 4; MPU9250_USERCTRL_DMP_RESET_BIT : constant := 3; MPU9250_USERCTRL_FIFO_RESET_BIT : constant := 2; MPU9250_USERCTRL_I2C_MST_RESET_BIT : constant := 1; MPU9250_USERCTRL_SIG_COND_RESET_BIT : constant := 0; MPU9250_PWR1_DEVICE_RESET_BIT : constant := 7; MPU9250_PWR1_SLEEP_BIT : constant := 6; MPU9250_PWR1_CYCLE_BIT : constant := 5; MPU9250_PWR1_TEMP_DIS_BIT : constant := 3; MPU9250_PWR1_CLKSEL_BIT : constant := 2; MPU9250_PWR1_CLKSEL_LENGTH : constant := 3; MPU9250_CLOCK_INTERNAL : constant := 16#00#; MPU9250_CLOCK_PLL_XGYRO : constant := 16#01#; MPU9250_CLOCK_PLL_YGYRO : constant := 16#02#; MPU9250_CLOCK_PLL_ZGYRO : constant := 16#03#; MPU9250_CLOCK_PLL_EXT32K : constant := 16#04#; MPU9250_CLOCK_PLL_EXT19M : constant := 16#05#; MPU9250_CLOCK_KEEP_RESET : constant := 16#07#; MPU9250_PWR2_LP_WAKE_CTRL_BIT : constant := 7; MPU9250_PWR2_LP_WAKE_CTRL_LENGTH : constant := 2; MPU9250_PWR2_STBY_XA_BIT : constant := 5; MPU9250_PWR2_STBY_YA_BIT : constant := 4; MPU9250_PWR2_STBY_ZA_BIT : constant := 3; MPU9250_PWR2_STBY_XG_BIT : constant := 2; MPU9250_PWR2_STBY_YG_BIT : constant := 1; MPU9250_PWR2_STBY_ZG_BIT : constant := 0; MPU9250_WAKE_FREQ_1P25 : constant := 16#0#; MPU9250_WAKE_FREQ_2P5 : constant := 16#1#; MPU9250_WAKE_FREQ_5 : constant := 16#2#; MPU9250_WAKE_FREQ_10 : constant := 16#3#; MPU9250_BANKSEL_PRFTCH_EN_BIT : constant := 6; MPU9250_BANKSEL_CFG_USER_BANK_BIT : constant := 5; MPU9250_BANKSEL_MEM_SEL_BIT : constant := 4; MPU9250_BANKSEL_MEM_SEL_LENGTH : constant := 5; MPU9250_WHO_AM_I_BIT : constant := 6; MPU9250_WHO_AM_I_LENGTH : constant := 6; MPU9250_DMP_MEMORY_BANKS : constant := 8; MPU9250_DMP_MEMORY_BANK_SIZE : constant := 256; MPU9250_DMP_MEMORY_CHUNK_SIZE : constant := 16; MPU9250_ST_GYRO_LOW : constant := (-14.0); MPU9250_ST_GYRO_HIGH : constant := 14.0; MPU9250_ST_ACCEL_LOW : constant := (-14.0); MPU9250_ST_ACCEL_HIGH : constant := 14.0; -- Element n is 2620 * (1.01 ** n) MPU9250_ST_TB : constant array (0 .. 255) of UInt16 := ( 2620, 2646, 2672, 2699, 2726, 2753, 2781, 2808, 2837, 2865, 2894, 2923, 2952, 2981, 3011, 3041, 3072, 3102, 3133, 3165, 3196, 3228, 3261, 3293, 3326, 3359, 3393, 3427, 3461, 3496, 3531, 3566, 3602, 3638, 3674, 3711, 3748, 3786, 3823, 3862, 3900, 3939, 3979, 4019, 4059, 4099, 4140, 4182, 4224, 4266, 4308, 4352, 4395, 4439, 4483, 4528, 4574, 4619, 4665, 4712, 4759, 4807, 4855, 4903, 4953, 5002, 5052, 5103, 5154, 5205, 5257, 5310, 5363, 5417, 5471, 5525, 5581, 5636, 5693, 5750, 5807, 5865, 5924, 5983, 6043, 6104, 6165, 6226, 6289, 6351, 6415, 6479, 6544, 6609, 6675, 6742, 6810, 6878, 6946, 7016, 7086, 7157, 7229, 7301, 7374, 7448, 7522, 7597, 7673, 7750, 7828, 7906, 7985, 8065, 8145, 8227, 8309, 8392, 8476, 8561, 8647, 8733, 8820, 8909, 8998, 9088, 9178, 9270, 9363, 9457, 9551, 9647, 9743, 9841, 9939, 10038, 10139, 10240, 10343, 10446, 10550, 10656, 10763, 10870, 10979, 11089, 11200, 11312, 11425, 11539, 11654, 11771, 11889, 12008, 12128, 12249, 12371, 12495, 12620, 12746, 12874, 13002, 13132, 13264, 13396, 13530, 13666, 13802, 13940, 14080, 14221, 14363, 14506, 14652, 14798, 14946, 15096, 15247, 15399, 15553, 15709, 15866, 16024, 16184, 16346, 16510, 16675, 16842, 17010, 17180, 17352, 17526, 17701, 17878, 18057, 18237, 18420, 18604, 18790, 18978, 19167, 19359, 19553, 19748, 19946, 20145, 20347, 20550, 20756, 20963, 21173, 21385, 21598, 21814, 22033, 22253, 22475, 22700, 22927, 23156, 23388, 23622, 23858, 24097, 24338, 24581, 24827, 25075, 25326, 25579, 25835, 26093, 26354, 26618, 26884, 27153, 27424, 27699, 27976, 28255, 28538, 28823, 29112, 29403, 29697, 29994, 30294, 30597, 30903, 31212, 31524, 31839, 32157, 32479, 32804, 33132 ); -- Procedures and functions -- Read data to the specified MPU9250 register procedure MPU9250_Read_Register (Device : MPU9250_Device; Reg_Addr : UInt8; Data : in out I2C_Data); -- Read one UInt8 at the specified MPU9250 register procedure MPU9250_Read_UInt8_At_Register (Device : MPU9250_Device; Reg_Addr : UInt8; Data : out UInt8); -- Read one but at the specified MPU9250 register function MPU9250_Read_Bit_At_Register (Device : MPU9250_Device; Reg_Addr : UInt8; Bit_Pos : T_Bit_Pos_8) return Boolean; -- Write data to the specified MPU9250 register procedure MPU9250_Write_Register (Device : MPU9250_Device; Reg_Addr : UInt8; Data : I2C_Data); -- Write one UInt8 at the specified MPU9250 register procedure MPU9250_Write_UInt8_At_Register (Device : MPU9250_Device; Reg_Addr : UInt8; Data : UInt8); -- Write one bit at the specified MPU9250 register procedure MPU9250_Write_Bit_At_Register (Device : MPU9250_Device; Reg_Addr : UInt8; Bit_Pos : T_Bit_Pos_8; Bit_Value : Boolean); -- Write data in the specified register, starting from the -- bit specified in Start_Bit_Pos procedure MPU9250_Write_Bits_At_Register (Device : MPU9250_Device; Reg_Addr : UInt8; Start_Bit_Pos : T_Bit_Pos_8; Data : UInt8; Length : T_Bit_Pos_8); function Fuse_Low_And_High_Register_Parts (High : UInt8; Low : UInt8) return Integer_16; pragma Inline (Fuse_Low_And_High_Register_Parts); end MPU9250; ",12147,True,2576.3427868568433,median "------------------------------------------------------------------------------ -- -- -- GNAT LIBRARY COMPONENTS -- -- -- -- G N A T . S P I T B O L . P A T T E R N S -- -- -- -- S p e c -- -- -- -- Copyright (C) 1997-2020, AdaCore -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- As a special exception under Section 7 of GPL version 3, you are granted -- -- additional permissions described in the GCC Runtime Library Exception, -- -- version 3.1, as published by the Free Software Foundation. -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- . -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ -- SPITBOL-like pattern construction and matching -- This child package of GNAT.SPITBOL provides a complete implementation -- of the SPITBOL-like pattern construction and matching operations. This -- package is based on Macro-SPITBOL created by Robert Dewar. ------------------------------------------------------------ -- Summary of Pattern Matching Packages in GNAT Hierarchy -- ------------------------------------------------------------ -- There are three related packages that perform pattern matching functions. -- the following is an outline of these packages, to help you determine -- which is best for your needs. -- GNAT.Regexp (files g-regexp.ads/g-regexp.adb) -- This is a simple package providing Unix-style regular expression -- matching with the restriction that it matches entire strings. It -- is particularly useful for file name matching, and in particular -- it provides ""globbing patterns"" that are useful in implementing -- unix or DOS style wildcard matching for file names. -- GNAT.Regpat (files g-regpat.ads/g-regpat.adb) -- This is a more complete implementation of Unix-style regular -- expressions, copied from the original V7 style regular expression -- library written in C by Henry Spencer. It is functionally the -- same as this library, and uses the same internal data structures -- stored in a binary compatible manner. -- GNAT.Spitbol.Patterns (files g-spipat.ads/g-spipat.adb) -- This is a completely general patterm matching package based on the -- pattern language of SNOBOL4, as implemented in SPITBOL. The pattern -- language is modeled on context free grammars, with context sensitive -- extensions that provide full (type 0) computational capabilities. with Ada.Strings.Maps; use Ada.Strings.Maps; with Ada.Text_IO; use Ada.Text_IO; package GNAT.Spitbol.Patterns is pragma Elaborate_Body; ------------------------------- -- Pattern Matching Tutorial -- ------------------------------- -- A pattern matching operation (a call to one of the Match subprograms) -- takes a subject string and a pattern, and optionally a replacement -- string. The replacement string option is only allowed if the subject -- is a variable. -- The pattern is matched against the subject string, and either the -- match fails, or it succeeds matching a contiguous substring. If a -- replacement string is specified, then the subject string is modified -- by replacing the matched substring with the given replacement. -- Concatenation and Alternation -- ============================= -- A pattern consists of a series of pattern elements. The pattern is -- built up using either the concatenation operator: -- A & B -- which means match A followed immediately by matching B, or the -- alternation operator: -- A or B -- which means first attempt to match A, and then if that does not -- succeed, match B. -- There is full backtracking, which means that if a given pattern -- element fails to match, then previous alternatives are matched. -- For example if we have the pattern: -- (A or B) & (C or D) & (E or F) -- First we attempt to match A, if that succeeds, then we go on to try -- to match C, and if that succeeds, we go on to try to match E. If E -- fails, then we try F. If F fails, then we go back and try matching -- D instead of C. Let's make this explicit using a specific example, -- and introducing the simplest kind of pattern element, which is a -- literal string. The meaning of this pattern element is simply to -- match the characters that correspond to the string characters. Now -- let's rewrite the above pattern form with specific string literals -- as the pattern elements: -- (""ABC"" or ""AB"") & (""DEF"" or ""CDE"") & (""GH"" or ""IJ"") -- The following strings will be attempted in sequence: -- ABC . DEF . GH -- ABC . DEF . IJ -- ABC . CDE . GH -- ABC . CDE . IJ -- AB . DEF . GH -- AB . DEF . IJ -- AB . CDE . GH -- AB . CDE . IJ -- Here we use the dot simply to separate the pieces of the string -- matched by the three separate elements. -- Moving the Start Point -- ====================== -- A pattern is not required to match starting at the first character -- of the string, and is not required to match to the end of the string. -- The first attempt does indeed attempt to match starting at the first -- character of the string, trying all the possible alternatives. But -- if all alternatives fail, then the starting point of the match is -- moved one character, and all possible alternatives are attempted at -- the new anchor point. -- The entire match fails only when every possible starting point has -- been attempted. As an example, suppose that we had the subject -- string -- ""ABABCDEIJKL"" -- matched using the pattern in the previous example: -- (""ABC"" or ""AB"") & (""DEF"" or ""CDE"") & (""GH"" or ""IJ"") -- would succeed, after two anchor point moves: -- ""ABABCDEIJKL"" -- ^^^^^^^ -- matched -- section -- This mode of pattern matching is called the unanchored mode. It is -- also possible to put the pattern matcher into anchored mode by -- setting the global variable Anchored_Mode to True. This will cause -- all subsequent matches to be performed in anchored mode, where the -- match is required to start at the first character. -- We will also see later how the effect of an anchored match can be -- obtained for a single specified anchor point if this is desired. -- Other Pattern Elements -- ====================== -- In addition to strings (or single characters), there are many special -- pattern elements that correspond to special predefined alternations: -- Arb Matches any string. First it matches the null string, and -- then on a subsequent failure, matches one character, and -- then two characters, and so on. It only fails if the -- entire remaining string is matched. -- Bal Matches a non-empty string that is parentheses balanced -- with respect to ordinary () characters. Examples of -- balanced strings are ""ABC"", ""A((B)C)"", and ""A(B)C(D)E"". -- Bal matches the shortest possible balanced string on the -- first attempt, and if there is a subsequent failure, -- attempts to extend the string. -- Cancel Immediately aborts the entire pattern match, signalling -- failure. This is a specialized pattern element, which is -- useful in conjunction with some of the special pattern -- elements that have side effects. -- Fail The null alternation. Matches no possible strings, so it -- always signals failure. This is a specialized pattern -- element, which is useful in conjunction with some of the -- special pattern elements that have side effects. -- Fence Matches the null string at first, and then if a failure -- causes alternatives to be sought, aborts the match (like -- a Cancel). Note that using Fence at the start of a pattern -- has the same effect as matching in anchored mode. -- Rest Matches from the current point to the last character in -- the string. This is a specialized pattern element, which -- is useful in conjunction with some of the special pattern -- elements that have side effects. -- Succeed Repeatedly matches the null string (it is equivalent to -- the alternation ("""" or """" or """" ....). This is a special -- pattern element, which is useful in conjunction with some -- of the special pattern elements that have side effects. -- Pattern Construction Functions -- ============================== -- The following functions construct additional pattern elements -- Any(S) Where S is a string, matches a single character that is -- any one of the characters in S. Fails if the current -- character is not one of the given set of characters. -- Arbno(P) Where P is any pattern, matches any number of instances -- of the pattern, starting with zero occurrences. It is -- thus equivalent to ("""" or (P & ("""" or (P & ("""" ....)))). -- The pattern P may contain any number of pattern elements -- including the use of alternation and concatenation. -- Break(S) Where S is a string, matches a string of zero or more -- characters up to but not including a break character -- that is one of the characters given in the string S. -- Can match the null string, but cannot match the last -- character in the string, since a break character is -- required to be present. -- BreakX(S) Where S is a string, behaves exactly like Break(S) when -- it first matches, but if a string is successfully matched, -- then a subsequent failure causes an attempt to extend the -- matched string. -- Fence(P) Where P is a pattern, attempts to match the pattern P -- including trying all possible alternatives of P. If none -- of these alternatives succeeds, then the Fence pattern -- fails. If one alternative succeeds, then the pattern -- match proceeds, but on a subsequent failure, no attempt -- is made to search for alternative matches of P. The -- pattern P may contain any number of pattern elements -- including the use of alternation and concatenation. -- Len(N) Where N is a natural number, matches the given number of -- characters. For example, Len(10) matches any string that -- is exactly ten characters long. -- NotAny(S) Where S is a string, matches a single character that is -- not one of the characters of S. Fails if the current -- character is one of the given set of characters. -- NSpan(S) Where S is a string, matches a string of zero or more -- characters that is among the characters given in the -- string. Always matches the longest possible such string. -- Always succeeds, since it can match the null string. -- Pos(N) Where N is a natural number, matches the null string -- if exactly N characters have been matched so far, and -- otherwise fails. -- Rpos(N) Where N is a natural number, matches the null string -- if exactly N characters remain to be matched, and -- otherwise fails. -- Rtab(N) Where N is a natural number, matches characters from -- the current position until exactly N characters remain -- to be matched in the string. Fails if fewer than N -- unmatched characters remain in the string. -- Tab(N) Where N is a natural number, matches characters from -- the current position until exactly N characters have -- been matched in all. Fails if more than N characters -- have already been matched. -- Span(S) Where S is a string, matches a string of one or more -- characters that is among the characters given in the -- string. Always matches the longest possible such string. -- Fails if the current character is not one of the given -- set of characters. -- Recursive Pattern Matching -- ========================== -- The plus operator (+P) where P is a pattern variable, creates -- a recursive pattern that will, at pattern matching time, follow -- the pointer to obtain the referenced pattern, and then match this -- pattern. This may be used to construct recursive patterns. Consider -- for example: -- P := (""A"" or (""B"" & (+P))) -- On the first attempt, this pattern attempts to match the string ""A"". -- If this fails, then the alternative matches a ""B"", followed by an -- attempt to match P again. This second attempt first attempts to -- match ""A"", and so on. The result is a pattern that will match a -- string of B's followed by a single A. -- This particular example could simply be written as NSpan('B') & 'A', -- but the use of recursive patterns in the general case can construct -- complex patterns which could not otherwise be built. -- Pattern Assignment Operations -- ============================= -- In addition to the overall result of a pattern match, which indicates -- success or failure, it is often useful to be able to keep track of -- the pieces of the subject string that are matched by individual -- pattern elements, or subsections of the pattern. -- The pattern assignment operators allow this capability. The first -- form is the immediate assignment: -- P * S -- Here P is an arbitrary pattern, and S is a variable of type VString -- that will be set to the substring matched by P. This assignment -- happens during pattern matching, so if P matches more than once, -- then the assignment happens more than once. -- The deferred assignment operation: -- P ** S -- avoids these multiple assignments by deferring the assignment to the -- end of the match. If the entire match is successful, and if the -- pattern P was part of the successful match, then at the end of the -- matching operation the assignment to S of the string matching P is -- performed. -- The cursor assignment operation: -- Setcur(N'Access) -- assigns the current cursor position to the natural variable N. The -- cursor position is defined as the count of characters that have been -- matched so far (including any start point moves). -- Finally the operations * and ** may be used with values of type -- Text_IO.File_Access. The effect is to do a Put_Line operation of -- the matched substring. These are particularly useful in debugging -- pattern matches. -- Deferred Matching -- ================= -- The pattern construction functions (such as Len and Any) all permit -- the use of pointers to natural or string values, or functions that -- return natural or string values. These forms cause the actual value -- to be obtained at pattern matching time. This allows interesting -- possibilities for constructing dynamic patterns as illustrated in -- the examples section. -- In addition the (+S) operator may be used where S is a pointer to -- string or function returning string, with a similar deferred effect. -- A special use of deferred matching is the construction of predicate -- functions. The element (+P) where P is an access to a function that -- returns a Boolean value, causes the function to be called at the -- time the element is matched. If the function returns True, then the -- null string is matched, if the function returns False, then failure -- is signalled and previous alternatives are sought. -- Deferred Replacement -- ==================== -- The simple model given for pattern replacement (where the matched -- substring is replaced by the string given as the third argument to -- Match) works fine in simple cases, but this approach does not work -- in the case where the expression used as the replacement string is -- dependent on values set by the match. -- For example, suppose we want to find an instance of a parenthesized -- character, and replace the parentheses with square brackets. At first -- glance it would seem that: -- Match (Subject, '(' & Len (1) * Char & ')', '[' & Char & ']'); -- would do the trick, but that does not work, because the third -- argument to Match gets evaluated too early, before the call to -- Match, and before the pattern match has had a chance to set Char. -- To solve this problem we provide the deferred replacement capability. -- With this approach, which of course is only needed if the pattern -- involved has side effects, is to do the match in two stages. The -- call to Match sets a pattern result in a variable of the private -- type Match_Result, and then a subsequent Replace operation uses -- this Match_Result object to perform the required replacement. -- Using this approach, we can now write the above operation properly -- in a manner that will work: -- M : Match_Result; -- ... -- Match (Subject, '(' & Len (1) * Char & ')', M); -- Replace (M, '[' & Char & ']'); -- As with other Match cases, there is a function and procedure form -- of this match call. A call to Replace after a failed match has no -- effect. Note that Subject should not be modified between the calls. -- Examples of Pattern Matching -- ============================ -- First a simple example of the use of pattern replacement to remove -- a line number from the start of a string. We assume that the line -- number has the form of a string of decimal digits followed by a -- period, followed by one or more spaces. -- Digs : constant Pattern := Span(""0123456789""); -- Lnum : constant Pattern := Pos(0) & Digs & '.' & Span(' '); -- Now to use this pattern we simply do a match with a replacement: -- Match (Line, Lnum, """"); -- which replaces the line number by the null string. Note that it is -- also possible to use an Ada.Strings.Maps.Character_Set value as an -- argument to Span and similar functions, and in particular all the -- useful constants 'in Ada.Strings.Maps.Constants are available. This -- means that we could define Digs as: -- Digs : constant Pattern := Span(Decimal_Digit_Set); -- The style we use here, of defining constant patterns and then using -- them is typical. It is possible to build up patterns dynamically, -- but it is usually more efficient to build them in pieces in advance -- using constant declarations. Note in particular that although it is -- possible to construct a pattern directly as an argument for the -- Match routine, it is much more efficient to preconstruct the pattern -- as we did in this example. -- Now let's look at the use of pattern assignment to break a -- string into sections. Suppose that the input string has two -- unsigned decimal integers, separated by spaces or a comma, -- with spaces allowed anywhere. Then we can isolate the two -- numbers with the following pattern: -- Num1, Num2 : aliased VString; -- B : constant Pattern := NSpan(' '); -- N : constant Pattern := Span(""0123456789""); -- T : constant Pattern := -- NSpan(' ') & N * Num1 & Span("" ,"") & N * Num2; -- The match operation Match ("" 124, 257 "", T) would assign the -- string 124 to Num1 and the string 257 to Num2. -- Now let's see how more complex elements can be built from the -- set of primitive elements. The following pattern matches strings -- that have the syntax of Ada 95 based literals: -- Digs : constant Pattern := Span(Decimal_Digit_Set); -- UDigs : constant Pattern := Digs & Arbno('_' & Digs); -- Edig : constant Pattern := Span(Hexadecimal_Digit_Set); -- UEdig : constant Pattern := Edig & Arbno('_' & Edig); -- Bnum : constant Pattern := Udigs & '#' & UEdig & '#'; -- A match against Bnum will now match the desired strings, e.g. -- it will match 16#123_abc#, but not a#b#. However, this pattern -- is not quite complete, since it does not allow colons to replace -- the pound signs. The following is more complete: -- Bchar : constant Pattern := Any(""#:""); -- Bnum : constant Pattern := Udigs & Bchar & UEdig & Bchar; -- but that is still not quite right, since it allows # and : to be -- mixed, and they are supposed to be used consistently. We solve -- this by using a deferred match. -- Temp : aliased VString; -- Bnum : constant Pattern := -- Udigs & Bchar * Temp & UEdig & (+Temp) -- Here the first instance of the base character is stored in Temp, and -- then later in the pattern we rematch the value that was assigned. -- For an example of a recursive pattern, let's define a pattern -- that is like the built in Bal, but the string matched is balanced -- with respect to square brackets or curly brackets. -- The language for such strings might be defined in extended BNF as -- ELEMENT ::= -- | '[' BALANCED_STRING ']' -- | '{' BALANCED_STRING '}' -- BALANCED_STRING ::= ELEMENT {ELEMENT} -- Here we use {} to indicate zero or more occurrences of a term, as -- is common practice in extended BNF. Now we can translate the above -- BNF into recursive patterns as follows: -- Element, Balanced_String : aliased Pattern; -- . -- . -- . -- Element := NotAny (""[]{}"") -- or -- ('[' & (+Balanced_String) & ']') -- or -- ('{' & (+Balanced_String) & '}'); -- Balanced_String := Element & Arbno (Element); -- Note the important use of + here to refer to a pattern not yet -- defined. Note also that we use assignments precisely because we -- cannot refer to as yet undeclared variables in initializations. -- Now that this pattern is constructed, we can use it as though it -- were a new primitive pattern element, and for example, the match: -- Match (""xy[ab{cd}]"", Balanced_String * Current_Output & Fail); -- will generate the output: -- x -- xy -- xy[ab{cd}] -- y -- y[ab{cd}] -- [ab{cd}] -- a -- ab -- ab{cd} -- b -- b{cd} -- {cd} -- c -- cd -- d -- Note that the function of the fail here is simply to force the -- pattern Balanced_String to match all possible alternatives. Studying -- the operation of this pattern in detail is highly instructive. -- Finally we give a rather elaborate example of the use of deferred -- matching. The following declarations build up a pattern which will -- find the longest string of decimal digits in the subject string. -- Max, Cur : VString; -- Loc : Natural; -- function GtS return Boolean is -- begin -- return Length (Cur) > Length (Max); -- end GtS; -- Digit : constant Character_Set := Decimal_Digit_Set; -- Digs : constant Pattern := Span(Digit); -- Find : constant Pattern := -- """" * Max & Fence & -- initialize Max to null -- BreakX (Digit) & -- scan looking for digits -- ((Span(Digit) * Cur & -- assign next string to Cur -- (+GtS'Unrestricted_Access) & -- check size(Cur) > Size(Max) -- Setcur(Loc'Access)) -- if so, save location -- * Max) & -- and assign to Max -- Fail; -- seek all alternatives -- As we see from the comments here, complex patterns like this take -- on aspects of sequential programs. In fact they are sequential -- programs with general backtracking. In this pattern, we first use -- a pattern assignment that matches null and assigns it to Max, so -- that it is initialized for the new match. Now BreakX scans to the -- next digit. Arb would do here, but BreakX will be more efficient. -- Once we have found a digit, we scan out the longest string of -- digits with Span, and assign it to Cur. The deferred call to GtS -- tests if the string we assigned to Cur is the longest so far. If -- not, then failure is signalled, and we seek alternatives (this -- means that BreakX will extend and look for the next digit string). -- If the call to GtS succeeds then the matched string is assigned -- as the largest string so far into Max and its location is saved -- in Loc. Finally Fail forces the match to fail and seek alternatives, -- so that the entire string is searched. -- If the pattern Find is matched against a string, the variable Max -- at the end of the pattern will have the longest string of digits, -- and Loc will be the starting character location of the string. For -- example, Match(""ab123cd4657ef23"", Find) will assign ""4657"" to Max -- and 11 to Loc (indicating that the string ends with the eleventh -- character of the string). -- Note: the use of Unrestricted_Access to reference GtS will not -- be needed if GtS is defined at the outer level, but definitely -- will be necessary if GtS is a nested function (in which case of -- course the scope of the pattern Find will be restricted to this -- nested scope, and this cannot be checked, i.e. use of the pattern -- outside this scope is erroneous). Generally it is a good idea to -- define patterns and the functions they call at the outer level -- where possible, to avoid such problems. -- Correspondence with Pattern Matching in SPITBOL -- =============================================== -- Generally the Ada syntax and names correspond closely to SPITBOL -- syntax for pattern matching construction. -- The basic pattern construction operators are renamed as follows: -- Spitbol Ada -- (space) & -- | or -- $ * -- . ** -- The Ada operators were chosen so that the relative precedences of -- these operators corresponds to that of the Spitbol operators, but -- as always, the use of parentheses is advisable to clarify. -- The pattern construction operators all have similar names except for -- Spitbol Ada -- Abort Cancel -- Rem Rest -- where we have clashes with Ada reserved names -- Ada requires the use of 'Access to refer to functions used in the -- pattern match, and often the use of 'Unrestricted_Access may be -- necessary to get around the scope restrictions if the functions -- are not declared at the outer level. -- The actual pattern matching syntax is modified in Ada as follows: -- Spitbol Ada -- X Y Match (X, Y); -- X Y = Z Match (X, Y, Z); -- and pattern failure is indicated by returning a Boolean result from -- the Match function (True for success, False for failure). ----------------------- -- Type Declarations -- ----------------------- type Pattern is private; -- Type representing a pattern. This package provides a complete set of -- operations for constructing patterns that can be used in the pattern -- matching operations provided. type Boolean_Func is access function return Boolean; -- General Boolean function type. When this type is used as a formal -- parameter type in this package, it indicates a deferred predicate -- pattern. The function will be called when the pattern element is -- matched and failure signalled if False is returned. type Natural_Func is access function return Natural; -- General Natural function type. When this type is used as a formal -- parameter type in this package, it indicates a deferred pattern. -- The function will be called when the pattern element is matched -- to obtain the currently referenced Natural value. type VString_Func is access function return VString; -- General VString function type. When this type is used as a formal -- parameter type in this package, it indicates a deferred pattern. -- The function will be called when the pattern element is matched -- to obtain the currently referenced string value. subtype PString is String; -- This subtype is used in the remainder of the package to indicate a -- formal parameter that is converted to its corresponding pattern, -- i.e. a pattern that matches the characters of the string. subtype PChar is Character; -- Similarly, this subtype is used in the remainder of the package to -- indicate a formal parameter that is converted to its corresponding -- pattern, i.e. a pattern that matches this one character. subtype VString_Var is VString; subtype Pattern_Var is Pattern; -- These synonyms are used as formal parameter types to a function where, -- if the language allowed, we would use in out parameters, but we are -- not allowed to have in out parameters for functions. Instead we pass -- actuals which must be variables, and with a bit of trickery in the -- body, manage to interpret them properly as though they were indeed -- in out parameters. pragma Warnings (Off, VString_Var); pragma Warnings (Off, Pattern_Var); -- We turn off warnings for these two types so that when variables are used -- as arguments in this context, warnings about them not being assigned in -- the source program will be suppressed. -------------------------------- -- Basic Pattern Construction -- -------------------------------- function ""&"" (L : Pattern; R : Pattern) return Pattern; function ""&"" (L : PString; R : Pattern) return Pattern; function ""&"" (L : Pattern; R : PString) return Pattern; function ""&"" (L : PChar; R : Pattern) return Pattern; function ""&"" (L : Pattern; R : PChar) return Pattern; -- Pattern concatenation. Matches L followed by R function ""or"" (L : Pattern; R : Pattern) return Pattern; function ""or"" (L : PString; R : Pattern) return Pattern; function ""or"" (L : Pattern; R : PString) return Pattern; function ""or"" (L : PString; R : PString) return Pattern; function ""or"" (L : PChar; R : Pattern) return Pattern; function ""or"" (L : Pattern; R : PChar) return Pattern; function ""or"" (L : PChar; R : PChar) return Pattern; function ""or"" (L : PString; R : PChar) return Pattern; function ""or"" (L : PChar; R : PString) return Pattern; -- Pattern alternation. Creates a pattern that will first try to match -- L and then on a subsequent failure, attempts to match R instead. ---------------------------------- -- Pattern Assignment Functions -- ---------------------------------- function ""*"" (P : Pattern; Var : VString_Var) return Pattern; function ""*"" (P : PString; Var : VString_Var) return Pattern; function ""*"" (P : PChar; Var : VString_Var) return Pattern; -- Matches P, and if the match succeeds, assigns the matched substring -- to the given VString variable Var. This assignment happens as soon as -- the substring is matched, and if the pattern P1 is matched more than -- once during the course of the match, then the assignment will occur -- more than once. function ""**"" (P : Pattern; Var : VString_Var) return Pattern; function ""**"" (P : PString; Var : VString_Var) return Pattern; function ""**"" (P : PChar; Var : VString_Var) return Pattern; -- Like ""*"" above, except that the assignment happens at most once -- after the entire match is completed successfully. If the match -- fails, then no assignment takes place. ---------------------------------- -- Deferred Matching Operations -- ---------------------------------- function ""+"" (Str : VString_Var) return Pattern; -- Here Str must be a VString variable. This function constructs a -- pattern which at pattern matching time will access the current -- value of this variable, and match against these characters. function ""+"" (Str : VString_Func) return Pattern; -- Constructs a pattern which at pattern matching time calls the given -- function, and then matches against the string or character value -- that is returned by the call. function ""+"" (P : Pattern_Var) return Pattern; -- Here P must be a Pattern variable. This function constructs a -- pattern which at pattern matching time will access the current -- value of this variable, and match against the pattern value. function ""+"" (P : Boolean_Func) return Pattern; -- Constructs a predicate pattern function that at pattern matching time -- calls the given function. If True is returned, then the pattern matches. -- If False is returned, then failure is signalled. -------------------------------- -- Pattern Building Functions -- -------------------------------- function Arb return Pattern; -- Constructs a pattern that will match any string. On the first attempt, -- the pattern matches a null string, then on each successive failure, it -- matches one more character, and only fails if matching the entire rest -- of the string. function Arbno (P : Pattern) return Pattern; function Arbno (P : PString) return Pattern; function Arbno (P : PChar) return Pattern; -- Pattern repetition. First matches null, then on a subsequent failure -- attempts to match an additional instance of the given pattern. -- Equivalent to (but more efficient than) P & ("""" or (P & ("""" or ... function Any (Str : String) return Pattern; function Any (Str : VString) return Pattern; function Any (Str : Character) return Pattern; function Any (Str : Character_Set) return Pattern; function Any (Str : not null access VString) return Pattern; function Any (Str : VString_Func) return Pattern; -- Constructs a pattern that matches a single character that is one of -- the characters in the given argument. The pattern fails if the current -- character is not in Str. function Bal return Pattern; -- Constructs a pattern that will match any non-empty string that is -- parentheses balanced with respect to the normal parentheses characters. -- Attempts to extend the string if a subsequent failure occurs. function Break (Str : String) return Pattern; function Break (Str : VString) return Pattern; function Break (Str : Character) return Pattern; function Break (Str : Character_Set) return Pattern; function Break (Str : not null access VString) return Pattern; function Break (Str : VString_Func) return Pattern; -- Constructs a pattern that matches a (possibly null) string which -- is immediately followed by a character in the given argument. This -- character is not part of the matched string. The pattern fails if -- the remaining characters to be matched do not include any of the -- characters in Str. function BreakX (Str : String) return Pattern; function BreakX (Str : VString) return Pattern; function BreakX (Str : Character) return Pattern; function BreakX (Str : Character_Set) return Pattern; function BreakX (Str : not null access VString) return Pattern; function BreakX (Str : VString_Func) return Pattern; -- Like Break, but the pattern attempts to extend on a failure to find -- the next occurrence of a character in Str, and only fails when the -- last such instance causes a failure. function Cancel return Pattern; -- Constructs a pattern that immediately aborts the entire match function Fail return Pattern; -- Constructs a pattern that always fails function Fence return Pattern; -- Constructs a pattern that matches null on the first attempt, and then -- causes the entire match to be aborted if a subsequent failure occurs. function Fence (P : Pattern) return Pattern; -- Constructs a pattern that first matches P. If P fails, then the -- constructed pattern fails. If P succeeds, then the match proceeds, -- but if subsequent failure occurs, alternatives in P are not sought. -- The idea of Fence is that each time the pattern is matched, just -- one attempt is made to match P, without trying alternatives. function Len (Count : Natural) return Pattern; function Len (Count : not null access Natural) return Pattern; function Len (Count : Natural_Func) return Pattern; -- Constructs a pattern that matches exactly the given number of -- characters. The pattern fails if fewer than this number of characters -- remain to be matched in the string. function NotAny (Str : String) return Pattern; function NotAny (Str : VString) return Pattern; function NotAny (Str : Character) return Pattern; function NotAny (Str : Character_Set) return Pattern; function NotAny (Str : not null access VString) return Pattern; function NotAny (Str : VString_Func) return Pattern; -- Constructs a pattern that matches a single character that is not -- one of the characters in the given argument. The pattern Fails if -- the current character is in Str. function NSpan (Str : String) return Pattern; function NSpan (Str : VString) return Pattern; function NSpan (Str : Character) return Pattern; function NSpan (Str : Character_Set) return Pattern; function NSpan (Str : not null access VString) return Pattern; function NSpan (Str : VString_Func) return Pattern; -- Constructs a pattern that matches the longest possible string -- consisting entirely of characters from the given argument. The -- string may be empty, so this pattern always succeeds. function Pos (Count : Natural) return Pattern; function Pos (Count : not null access Natural) return Pattern; function Pos (Count : Natural_Func) return Pattern; -- Constructs a pattern that matches the null string if exactly Count -- characters have already been matched, and otherwise fails. function Rest return Pattern; -- Constructs a pattern that always succeeds, matching the remaining -- unmatched characters in the pattern. function Rpos (Count : Natural) return Pattern; function Rpos (Count : not null access Natural) return Pattern; function Rpos (Count : Natural_Func) return Pattern; -- Constructs a pattern that matches the null string if exactly Count -- characters remain to be matched in the string, and otherwise fails. function Rtab (Count : Natural) return Pattern; function Rtab (Count : not null access Natural) return Pattern; function Rtab (Count : Natural_Func) return Pattern; -- Constructs a pattern that matches from the current location until -- exactly Count characters remain to be matched in the string. The -- pattern fails if fewer than Count characters remain to be matched. function Setcur (Var : not null access Natural) return Pattern; -- Constructs a pattern that matches the null string, and assigns the -- current cursor position in the string. This value is the number of -- characters matched so far. So it is zero at the start of the match. function Span (Str : String) return Pattern; function Span (Str : VString) return Pattern; function Span (Str : Character) return Pattern; function Span (Str : Character_Set) return Pattern; function Span (Str : not null access VString) return Pattern; function Span (Str : VString_Func) return Pattern; -- Constructs a pattern that matches the longest possible string -- consisting entirely of characters from the given argument. The -- string cannot be empty, so the pattern fails if the current -- character is not one of the characters in Str. function Succeed return Pattern; -- Constructs a pattern that succeeds matching null, both on the first -- attempt, and on any rematch attempt, i.e. it is equivalent to an -- infinite alternation of null strings. function Tab (Count : Natural) return Pattern; function Tab (Count : not null access Natural) return Pattern; function Tab (Count : Natural_Func) return Pattern; -- Constructs a pattern that from the current location until Count -- characters have been matched. The pattern fails if more than Count -- characters have already been matched. --------------------------------- -- Pattern Matching Operations -- --------------------------------- -- The Match function performs an actual pattern matching operation. -- The versions with three parameters perform a match without modifying -- the subject string and return a Boolean result indicating if the -- match is successful or not. The Anchor parameter is set to True to -- obtain an anchored match in which the pattern is required to match -- the first character of the string. In an unanchored match, which is -- the default, successive attempts are made to match the given pattern -- at each character of the subject string until a match succeeds, or -- until all possibilities have failed. -- Note that pattern assignment functions in the pattern may generate -- side effects, so these functions are not necessarily pure. Anchored_Mode : Boolean := False; -- This global variable can be set True to cause all subsequent pattern -- matches to operate in anchored mode. In anchored mode, no attempt is -- made to move the anchor point, so that if the match succeeds it must -- succeed starting at the first character. Note that the effect of -- anchored mode may be achieved in individual pattern matches by using -- Fence or Pos(0) at the start of the pattern. Pattern_Stack_Overflow : exception; -- Exception raised if internal pattern matching stack overflows. This -- is typically the result of runaway pattern recursion. If there is a -- genuine case of stack overflow, then either the match must be broken -- down into simpler steps, or the stack limit must be reset. Stack_Size : constant Positive := 2000; -- Size used for internal pattern matching stack. Increase this size if -- complex patterns cause Pattern_Stack_Overflow to be raised. -- Simple match functions. The subject is matched against the pattern. -- Any immediate or deferred assignments or writes are executed, and -- the returned value indicates whether or not the match succeeded. function Match (Subject : VString; Pat : Pattern) return Boolean; function Match (Subject : VString; Pat : PString) return Boolean; function Match (Subject : String; Pat : Pattern) return Boolean; function Match (Subject : String; Pat : PString) return Boolean; -- Replacement functions. The subject is matched against the pattern. -- Any immediate or deferred assignments or writes are executed, and -- the returned value indicates whether or not the match succeeded. -- If the match succeeds, then the matched part of the subject string -- is replaced by the given Replace string. function Match (Subject : VString_Var; Pat : Pattern; Replace : VString) return Boolean; function Match (Subject : VString_Var; Pat : PString; Replace : VString) return Boolean; function Match (Subject : VString_Var; Pat : Pattern; Replace : String) return Boolean; function Match (Subject : VString_Var; Pat : PString; Replace : String) return Boolean; -- Simple match procedures. The subject is matched against the pattern. -- Any immediate or deferred assignments or writes are executed. No -- indication of success or failure is returned. procedure Match (Subject : VString; Pat : Pattern); procedure Match (Subject : VString; Pat : PString); procedure Match (Subject : String; Pat : Pattern); procedure Match (Subject : String; Pat : PString); -- Replacement procedures. The subject is matched against the pattern. -- Any immediate or deferred assignments or writes are executed. No -- indication of success or failure is returned. If the match succeeds, -- then the matched part of the subject string is replaced by the given -- Replace string. procedure Match (Subject : in out VString; Pat : Pattern; Replace : VString); procedure Match (Subject : in out VString; Pat : PString; Replace : VString); procedure Match (Subject : in out VString; Pat : Pattern; Replace : String); procedure Match (Subject : in out VString; Pat : PString; Replace : String); -- Deferred Replacement type Match_Result is private; -- Type used to record result of pattern match subtype Match_Result_Var is Match_Result; -- This synonyms is used as a formal parameter type to a function where, -- if the language allowed, we would use an in out parameter, but we are -- not allowed to have in out parameters for functions. Instead we pass -- actuals which must be variables, and with a bit of trickery in the -- body, manage to interpret them properly as though they were indeed -- in out parameters. function Match (Subject : VString_Var; Pat : Pattern; Result : Match_Result_Var) return Boolean; procedure Match (Subject : in out VString; Pat : Pattern; Result : out Match_Result); procedure Replace (Result : in out Match_Result; Replace : VString); -- Given a previous call to Match which set Result, performs a pattern -- replacement if the match was successful. Has no effect if the match -- failed. This call should immediately follow the Match call. ------------------------ -- Debugging Routines -- ------------------------ -- Debugging pattern matching operations can often be quite complex, -- since there is no obvious way to trace the progress of the match. -- The declarations in this section provide some debugging assistance. Debug_Mode : Boolean := False; -- This global variable can be set True to generate debugging on all -- subsequent calls to Match. The debugging output is a full trace of -- the actions of the pattern matcher, written to Standard_Output. The -- level of this information is intended to be comprehensible at the -- abstract level of this package declaration. However, note that the -- use of this switch often generates large amounts of output. function ""*"" (P : Pattern; Fil : File_Access) return Pattern; function ""*"" (P : PString; Fil : File_Access) return Pattern; function ""*"" (P : PChar; Fil : File_Access) return Pattern; function ""**"" (P : Pattern; Fil : File_Access) return Pattern; function ""**"" (P : PString; Fil : File_Access) return Pattern; function ""**"" (P : PChar; Fil : File_Access) return Pattern; -- These are similar to the corresponding pattern assignment operations -- except that instead of setting the value of a variable, the matched -- substring is written to the appropriate file. This can be useful in -- following the progress of a match without generating the full amount -- of information obtained by setting Debug_Mode to True. Terminal : constant File_Access := Standard_Error; Output : constant File_Access := Standard_Output; -- Two handy synonyms for use with the above pattern write operations -- Finally we have some routines that are useful for determining what -- patterns are in use, particularly if they are constructed dynamically. function Image (P : Pattern) return String; function Image (P : Pattern) return VString; -- This procedures yield strings that corresponds to the syntax needed -- to create the given pattern using the functions in this package. The -- form of this string is such that it could actually be compiled and -- evaluated to yield the required pattern except for references to -- variables and functions, which are output using one of the following -- forms: -- -- access Natural NP(16#...#) -- access Pattern PP(16#...#) -- access VString VP(16#...#) -- -- Natural_Func NF(16#...#) -- VString_Func VF(16#...#) -- -- where 16#...# is the hex representation of the integer address that -- corresponds to the given access value procedure Dump (P : Pattern); -- This procedure writes information about the pattern to Standard_Out. -- The format of this information is keyed to the internal data structures -- used to implement patterns. The information provided by Dump is thus -- more precise than that yielded by Image, but is also a bit more obscure -- (i.e. it cannot be interpreted solely in terms of this spec, you have -- to know something about the data structures). ------------------ -- Private Part -- ------------------ private type PE; -- Pattern element, a pattern is a complex structure of PE's. This type -- is defined and described in the body of this package. type PE_Ptr is access all PE; -- Pattern reference. PE's use PE_Ptr values to reference other PE's type Pattern is new Controlled with record Stk : Natural := 0; -- Maximum number of stack entries required for matching this -- pattern. See description of pattern history stack in body. P : PE_Ptr := null; -- Pointer to initial pattern element for pattern end record; pragma Finalize_Storage_Only (Pattern); procedure Adjust (Object : in out Pattern); -- Adjust routine used to copy pattern objects procedure Finalize (Object : in out Pattern); -- Finalization routine used to release storage allocated for a pattern type VString_Ptr is access all VString; type Match_Result is record Var : VString_Ptr; -- Pointer to subject string. Set to null if match failed Start : Natural := 1; -- Starting index position (1's origin) of matched section of -- subject string. Only valid if Var is non-null. Stop : Natural := 0; -- Ending index position (1's origin) of matched section of -- subject string. Only valid if Var is non-null. end record; pragma Volatile (Match_Result); -- This ensures that the Result parameter is passed by reference, so -- that we can play our games with the bogus Match_Result_Var parameter -- in the function case to treat it as though it were an in out parameter. end GNAT.Spitbol.Patterns; ",12363,False,2347.0121841030546,median "------------------------------------------------------------------------------ -- -- -- GNAT RUN-TIME COMPONENTS -- -- -- -- A D A . T E X T _ I O -- -- -- -- B o d y -- -- -- -- Copyright (C) 1992-2006, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 2, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNAT; see file COPYING. If not, write -- -- to the Free Software Foundation, 51 Franklin Street, Fifth Floor, -- -- Boston, MA 02110-1301, USA. -- -- -- -- As a special exception, if other files instantiate generics from this -- -- unit, or you link this unit with other files to produce an executable, -- -- this unit does not by itself cause the resulting executable to be -- -- covered by the GNU General Public License. This exception does not -- -- however invalidate any other reasons why the executable file might be -- -- covered by the GNU Public License. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ with Ada.Streams; use Ada.Streams; with Interfaces.C_Streams; use Interfaces.C_Streams; with System.File_IO; with System.CRTL; with Unchecked_Conversion; with Unchecked_Deallocation; pragma Elaborate_All (System.File_IO); -- Needed because of calls to Chain_File in package body elaboration package body Ada.Text_IO is package FIO renames System.File_IO; subtype AP is FCB.AFCB_Ptr; function To_FCB is new Unchecked_Conversion (File_Mode, FCB.File_Mode); function To_TIO is new Unchecked_Conversion (FCB.File_Mode, File_Mode); use type FCB.File_Mode; use type System.CRTL.size_t; ------------------- -- AFCB_Allocate -- ------------------- function AFCB_Allocate (Control_Block : Text_AFCB) return FCB.AFCB_Ptr is pragma Unreferenced (Control_Block); begin return new Text_AFCB; end AFCB_Allocate; ---------------- -- AFCB_Close -- ---------------- procedure AFCB_Close (File : access Text_AFCB) is begin -- If the file being closed is one of the current files, then close -- the corresponding current file. It is not clear that this action -- is required (RM A.10.3(23)) but it seems reasonable, and besides -- ACVC test CE3208A expects this behavior. if File_Type (File) = Current_In then Current_In := null; elsif File_Type (File) = Current_Out then Current_Out := null; elsif File_Type (File) = Current_Err then Current_Err := null; end if; Terminate_Line (File_Type (File)); end AFCB_Close; --------------- -- AFCB_Free -- --------------- procedure AFCB_Free (File : access Text_AFCB) is type FCB_Ptr is access all Text_AFCB; FT : FCB_Ptr := FCB_Ptr (File); procedure Free is new Unchecked_Deallocation (Text_AFCB, FCB_Ptr); begin Free (FT); end AFCB_Free; ----------- -- Close -- ----------- procedure Close (File : in out File_Type) is begin FIO.Close (AP (File)); end Close; --------- -- Col -- --------- -- Note: we assume that it is impossible in practice for the column -- to exceed the value of Count'Last, i.e. no check is required for -- overflow raising layout error. function Col (File : File_Type) return Positive_Count is begin FIO.Check_File_Open (AP (File)); return File.Col; end Col; function Col return Positive_Count is begin return Col (Current_Out); end Col; ------------ -- Create -- ------------ procedure Create (File : in out File_Type; Mode : File_Mode := Out_File; Name : String := """"; Form : String := """") is Dummy_File_Control_Block : Text_AFCB; pragma Warnings (Off, Dummy_File_Control_Block); -- Yes, we know this is never assigned a value, only the tag -- is used for dispatching purposes, so that's expected. begin FIO.Open (File_Ptr => AP (File), Dummy_FCB => Dummy_File_Control_Block, Mode => To_FCB (Mode), Name => Name, Form => Form, Amethod => 'T', Creat => True, Text => True); File.Self := File; end Create; ------------------- -- Current_Error -- ------------------- function Current_Error return File_Type is begin return Current_Err; end Current_Error; function Current_Error return File_Access is begin return Current_Err.Self'Access; end Current_Error; ------------------- -- Current_Input -- ------------------- function Current_Input return File_Type is begin return Current_In; end Current_Input; function Current_Input return File_Access is begin return Current_In.Self'Access; end Current_Input; -------------------- -- Current_Output -- -------------------- function Current_Output return File_Type is begin return Current_Out; end Current_Output; function Current_Output return File_Access is begin return Current_Out.Self'Access; end Current_Output; ------------ -- Delete -- ------------ procedure Delete (File : in out File_Type) is begin FIO.Delete (AP (File)); end Delete; ----------------- -- End_Of_File -- ----------------- function End_Of_File (File : File_Type) return Boolean is ch : int; begin FIO.Check_Read_Status (AP (File)); if File.Before_LM then if File.Before_LM_PM then return Nextc (File) = EOF; end if; else ch := Getc (File); if ch = EOF then return True; elsif ch /= LM then Ungetc (ch, File); return False; else -- ch = LM File.Before_LM := True; end if; end if; -- Here we are just past the line mark with Before_LM set so that we -- do not have to try to back up past the LM, thus avoiding the need -- to back up more than one character. ch := Getc (File); if ch = EOF then return True; elsif ch = PM and then File.Is_Regular_File then File.Before_LM_PM := True; return Nextc (File) = EOF; -- Here if neither EOF nor PM followed end of line else Ungetc (ch, File); return False; end if; end End_Of_File; function End_Of_File return Boolean is begin return End_Of_File (Current_In); end End_Of_File; ----------------- -- End_Of_Line -- ----------------- function End_Of_Line (File : File_Type) return Boolean is ch : int; begin FIO.Check_Read_Status (AP (File)); if File.Before_LM then return True; else ch := Getc (File); if ch = EOF then return True; else Ungetc (ch, File); return (ch = LM); end if; end if; end End_Of_Line; function End_Of_Line return Boolean is begin return End_Of_Line (Current_In); end End_Of_Line; ----------------- -- End_Of_Page -- ----------------- function End_Of_Page (File : File_Type) return Boolean is ch : int; begin FIO.Check_Read_Status (AP (File)); if not File.Is_Regular_File then return False; elsif File.Before_LM then if File.Before_LM_PM then return True; end if; else ch := Getc (File); if ch = EOF then return True; elsif ch /= LM then Ungetc (ch, File); return False; else -- ch = LM File.Before_LM := True; end if; end if; -- Here we are just past the line mark with Before_LM set so that we -- do not have to try to back up past the LM, thus avoiding the need -- to back up more than one character. ch := Nextc (File); return ch = PM or else ch = EOF; end End_Of_Page; function End_Of_Page return Boolean is begin return End_Of_Page (Current_In); end End_Of_Page; -------------- -- EOF_Char -- -------------- function EOF_Char return Integer is begin return EOF; end EOF_Char; ----------- -- Flush -- ----------- procedure Flush (File : File_Type) is begin FIO.Flush (AP (File)); end Flush; procedure Flush is begin Flush (Current_Out); end Flush; ---------- -- Form -- ---------- function Form (File : File_Type) return String is begin return FIO.Form (AP (File)); end Form; --------- -- Get -- --------- procedure Get (File : File_Type; Item : out Character) is ch : int; begin FIO.Check_Read_Status (AP (File)); if File.Before_LM then File.Before_LM := False; File.Col := 1; if File.Before_LM_PM then File.Line := 1; File.Page := File.Page + 1; File.Before_LM_PM := False; else File.Line := File.Line + 1; end if; end if; loop ch := Getc (File); if ch = EOF then raise End_Error; elsif ch = LM then File.Line := File.Line + 1; File.Col := 1; elsif ch = PM and then File.Is_Regular_File then File.Page := File.Page + 1; File.Line := 1; else Item := Character'Val (ch); File.Col := File.Col + 1; return; end if; end loop; end Get; procedure Get (Item : out Character) is begin Get (Current_In, Item); end Get; procedure Get (File : File_Type; Item : out String) is ch : int; J : Natural; begin FIO.Check_Read_Status (AP (File)); if File.Before_LM then File.Before_LM := False; File.Before_LM_PM := False; File.Col := 1; if File.Before_LM_PM then File.Line := 1; File.Page := File.Page + 1; File.Before_LM_PM := False; else File.Line := File.Line + 1; end if; end if; J := Item'First; while J <= Item'Last loop ch := Getc (File); if ch = EOF then raise End_Error; elsif ch = LM then File.Line := File.Line + 1; File.Col := 1; elsif ch = PM and then File.Is_Regular_File then File.Page := File.Page + 1; File.Line := 1; else Item (J) := Character'Val (ch); J := J + 1; File.Col := File.Col + 1; end if; end loop; end Get; procedure Get (Item : out String) is begin Get (Current_In, Item); end Get; ------------------- -- Get_Immediate -- ------------------- -- More work required here ??? procedure Get_Immediate (File : File_Type; Item : out Character) is ch : int; end_of_file : int; procedure getc_immediate (stream : FILEs; ch : out int; end_of_file : out int); pragma Import (C, getc_immediate, ""getc_immediate""); begin FIO.Check_Read_Status (AP (File)); if File.Before_LM then File.Before_LM := False; File.Before_LM_PM := False; ch := LM; else getc_immediate (File.Stream, ch, end_of_file); if ferror (File.Stream) /= 0 then raise Device_Error; elsif end_of_file /= 0 then raise End_Error; end if; end if; Item := Character'Val (ch); end Get_Immediate; procedure Get_Immediate (Item : out Character) is begin Get_Immediate (Current_In, Item); end Get_Immediate; procedure Get_Immediate (File : File_Type; Item : out Character; Available : out Boolean) is ch : int; end_of_file : int; avail : int; procedure getc_immediate_nowait (stream : FILEs; ch : out int; end_of_file : out int; avail : out int); pragma Import (C, getc_immediate_nowait, ""getc_immediate_nowait""); begin FIO.Check_Read_Status (AP (File)); -- If we are logically before an end of line, but physically after it, -- then we just return the end of line character, no I/O is necessary. if File.Before_LM then File.Before_LM := False; File.Before_LM_PM := False; Available := True; Item := Character'Val (LM); -- Normal case where a read operation is required else getc_immediate_nowait (File.Stream, ch, end_of_file, avail); if ferror (File.Stream) /= 0 then raise Device_Error; elsif end_of_file /= 0 then raise End_Error; elsif avail = 0 then Available := False; Item := ASCII.NUL; else Available := True; Item := Character'Val (ch); end if; end if; end Get_Immediate; procedure Get_Immediate (Item : out Character; Available : out Boolean) is begin Get_Immediate (Current_In, Item, Available); end Get_Immediate; -------------- -- Get_Line -- -------------- procedure Get_Line (File : File_Type; Item : out String; Last : out Natural) is ch : int; begin FIO.Check_Read_Status (AP (File)); Last := Item'First - 1; -- Immediate exit for null string, this is a case in which we do not -- need to test for end of file and we do not skip a line mark under -- any circumstances. if Last >= Item'Last then return; end if; -- Here we have at least one character, if we are immediately before -- a line mark, then we will just skip past it storing no characters. if File.Before_LM then File.Before_LM := False; File.Before_LM_PM := False; -- Otherwise we need to read some characters else ch := Getc (File); -- If we are at the end of file now, it means we are trying to -- skip a file terminator and we raise End_Error (RM A.10.7(20)) if ch = EOF then raise End_Error; end if; -- Loop through characters. Don't bother if we hit a page mark, -- since in normal files, page marks can only follow line marks -- in any case and we only promise to treat the page nonsense -- correctly in the absense of such rogue page marks. loop -- Exit the loop if read is terminated by encountering line mark exit when ch = LM; -- Otherwise store the character, note that we know that ch is -- something other than LM or EOF. It could possibly be a page -- mark if there is a stray page mark in the middle of a line, -- but this is not an official page mark in any case, since -- official page marks can only follow a line mark. The whole -- page business is pretty much nonsense anyway, so we do not -- want to waste time trying to make sense out of non-standard -- page marks in the file! This means that the behavior of -- Get_Line is different from repeated Get of a character, but -- that's too bad. We only promise that page numbers etc make -- sense if the file is formatted in a standard manner. -- Note: we do not adjust the column number because it is quicker -- to adjust it once at the end of the operation than incrementing -- it each time around the loop. Last := Last + 1; Item (Last) := Character'Val (ch); -- All done if the string is full, this is the case in which -- we do not skip the following line mark. We need to adjust -- the column number in this case. if Last = Item'Last then File.Col := File.Col + Count (Item'Length); return; end if; -- Otherwise read next character. We also exit from the loop if -- we read an end of file. This is the case where the last line -- is not terminated with a line mark, and we consider that there -- is an implied line mark in this case (this is a non-standard -- file, but it is nice to treat it reasonably). ch := Getc (File); exit when ch = EOF; end loop; end if; -- We have skipped past, but not stored, a line mark. Skip following -- page mark if one follows, but do not do this for a non-regular -- file (since otherwise we get annoying wait for an extra character) File.Line := File.Line + 1; File.Col := 1; if File.Before_LM_PM then File.Line := 1; File.Before_LM_PM := False; File.Page := File.Page + 1; elsif File.Is_Regular_File then ch := Getc (File); if ch = PM and then File.Is_Regular_File then File.Line := 1; File.Page := File.Page + 1; else Ungetc (ch, File); end if; end if; end Get_Line; procedure Get_Line (Item : out String; Last : out Natural) is begin Get_Line (Current_In, Item, Last); end Get_Line; function Get_Line (File : File_Type) return String is Buffer : String (1 .. 500); Last : Natural; function Get_Rest (S : String) return String; -- This is a recursive function that reads the rest of the line and -- returns it. S is the part read so far. -------------- -- Get_Rest -- -------------- function Get_Rest (S : String) return String is -- Each time we allocate a buffer the same size as what we have -- read so far. This limits us to a logarithmic number of calls -- to Get_Rest and also ensures only a linear use of stack space. Buffer : String (1 .. S'Length); Last : Natural; begin Get_Line (File, Buffer, Last); declare R : constant String := S & Buffer (1 .. Last); begin if Last < Buffer'Last then return R; else return Get_Rest (R); end if; end; end Get_Rest; -- Start of processing for Get_Line begin Get_Line (File, Buffer, Last); if Last < Buffer'Last then return Buffer (1 .. Last); else return Get_Rest (Buffer (1 .. Last)); end if; end Get_Line; function Get_Line return String is begin return Get_Line (Current_In); end Get_Line; ---------- -- Getc -- ---------- function Getc (File : File_Type) return int is ch : int; begin ch := fgetc (File.Stream); if ch = EOF and then ferror (File.Stream) /= 0 then raise Device_Error; else return ch; end if; end Getc; ------------- -- Is_Open -- ------------- function Is_Open (File : File_Type) return Boolean is begin return FIO.Is_Open (AP (File)); end Is_Open; ---------- -- Line -- ---------- -- Note: we assume that it is impossible in practice for the line -- to exceed the value of Count'Last, i.e. no check is required for -- overflow raising layout error. function Line (File : File_Type) return Positive_Count is begin FIO.Check_File_Open (AP (File)); return File.Line; end Line; function Line return Positive_Count is begin return Line (Current_Out); end Line; ----------------- -- Line_Length -- ----------------- function Line_Length (File : File_Type) return Count is begin FIO.Check_Write_Status (AP (File)); return File.Line_Length; end Line_Length; function Line_Length return Count is begin return Line_Length (Current_Out); end Line_Length; ---------------- -- Look_Ahead -- ---------------- procedure Look_Ahead (File : File_Type; Item : out Character; End_Of_Line : out Boolean) is ch : int; begin FIO.Check_Read_Status (AP (File)); if File.Before_LM then End_Of_Line := True; Item := ASCII.NUL; else ch := Nextc (File); if ch = LM or else ch = EOF or else (ch = PM and then File.Is_Regular_File) then End_Of_Line := True; Item := ASCII.NUL; else End_Of_Line := False; Item := Character'Val (ch); end if; end if; end Look_Ahead; procedure Look_Ahead (Item : out Character; End_Of_Line : out Boolean) is begin Look_Ahead (Current_In, Item, End_Of_Line); end Look_Ahead; ---------- -- Mode -- ---------- function Mode (File : File_Type) return File_Mode is begin return To_TIO (FIO.Mode (AP (File))); end Mode; ---------- -- Name -- ---------- function Name (File : File_Type) return String is begin return FIO.Name (AP (File)); end Name; -------------- -- New_Line -- -------------- procedure New_Line (File : File_Type; Spacing : Positive_Count := 1) is begin -- Raise Constraint_Error if out of range value. The reason for this -- explicit test is that we don't want junk values around, even if -- checks are off in the caller. if not Spacing'Valid then raise Constraint_Error; end if; FIO.Check_Write_Status (AP (File)); for K in 1 .. Spacing loop Putc (LM, File); File.Line := File.Line + 1; if File.Page_Length /= 0 and then File.Line > File.Page_Length then Putc (PM, File); File.Line := 1; File.Page := File.Page + 1; end if; end loop; File.Col := 1; end New_Line; procedure New_Line (Spacing : Positive_Count := 1) is begin New_Line (Current_Out, Spacing); end New_Line; -------------- -- New_Page -- -------------- procedure New_Page (File : File_Type) is begin FIO.Check_Write_Status (AP (File)); if File.Col /= 1 or else File.Line = 1 then Putc (LM, File); end if; Putc (PM, File); File.Page := File.Page + 1; File.Line := 1; File.Col := 1; end New_Page; procedure New_Page is begin New_Page (Current_Out); end New_Page; ----------- -- Nextc -- ----------- function Nextc (File : File_Type) return int is ch : int; begin ch := fgetc (File.Stream); if ch = EOF then if ferror (File.Stream) /= 0 then raise Device_Error; end if; else if ungetc (ch, File.Stream) = EOF then raise Device_Error; end if; end if; return ch; end Nextc; ---------- -- Open -- ---------- procedure Open (File : in out File_Type; Mode : File_Mode; Name : String; Form : String := """") is Dummy_File_Control_Block : Text_AFCB; pragma Warnings (Off, Dummy_File_Control_Block); -- Yes, we know this is never assigned a value, only the tag -- is used for dispatching purposes, so that's expected. begin FIO.Open (File_Ptr => AP (File), Dummy_FCB => Dummy_File_Control_Block, Mode => To_FCB (Mode), Name => Name, Form => Form, Amethod => 'T', Creat => False, Text => True); File.Self := File; end Open; ---------- -- Page -- ---------- -- Note: we assume that it is impossible in practice for the page -- to exceed the value of Count'Last, i.e. no check is required for -- overflow raising layout error. function Page (File : File_Type) return Positive_Count is begin FIO.Check_File_Open (AP (File)); return File.Page; end Page; function Page return Positive_Count is begin return Page (Current_Out); end Page; ----------------- -- Page_Length -- ----------------- function Page_Length (File : File_Type) return Count is begin FIO.Check_Write_Status (AP (File)); return File.Page_Length; end Page_Length; function Page_Length return Count is begin return Page_Length (Current_Out); end Page_Length; --------- -- Put -- --------- procedure Put (File : File_Type; Item : Character) is begin FIO.Check_Write_Status (AP (File)); if File.Line_Length /= 0 and then File.Col > File.Line_Length then New_Line (File); end if; if fputc (Character'Pos (Item), File.Stream) = EOF then raise Device_Error; end if; File.Col := File.Col + 1; end Put; procedure Put (Item : Character) is begin FIO.Check_Write_Status (AP (Current_Out)); if Current_Out.Line_Length /= 0 and then Current_Out.Col > Current_Out.Line_Length then New_Line (Current_Out); end if; if fputc (Character'Pos (Item), Current_Out.Stream) = EOF then raise Device_Error; end if; Current_Out.Col := Current_Out.Col + 1; end Put; --------- -- Put -- --------- procedure Put (File : File_Type; Item : String) is begin FIO.Check_Write_Status (AP (File)); if Item'Length > 0 then -- If we have bounded lines, then do things character by -- character (this seems a rare case anyway!) if File.Line_Length /= 0 then for J in Item'Range loop Put (File, Item (J)); end loop; -- Otherwise we can output the entire string at once. Note that if -- there are LF or FF characters in the string, we do not bother to -- count them as line or page terminators. else FIO.Write_Buf (AP (File), Item'Address, Item'Length); File.Col := File.Col + Item'Length; end if; end if; end Put; procedure Put (Item : String) is begin Put (Current_Out, Item); end Put; -------------- -- Put_Line -- -------------- procedure Put_Line (File : File_Type; Item : String) is Ilen : Natural := Item'Length; Istart : Natural := Item'First; begin FIO.Check_Write_Status (AP (File)); -- If we have bounded lines, then just do a put and a new line. In -- this case we will end up doing things character by character in -- any case, and it is a rare situation. if File.Line_Length /= 0 then Put (File, Item); New_Line (File); return; end if; -- We setup a single string that has the necessary terminators and -- then write it with a single call. The reason for doing this is -- that it gives better behavior for the use of Put_Line in multi- -- tasking programs, since often the OS will treat the entire put -- operation as an atomic operation. -- We only do this if the message is 512 characters or less in length, -- since otherwise Put_Line would use an unbounded amount of stack -- space and could cause undetected stack overflow. If we have a -- longer string, then output the first part separately to avoid this. if Ilen > 512 then FIO.Write_Buf (AP (File), Item'Address, size_t (Ilen - 512)); Istart := Istart + Ilen - 512; Ilen := 512; end if; -- Now prepare the string with its terminator declare Buffer : String (1 .. Ilen + 2); Plen : size_t; begin Buffer (1 .. Ilen) := Item (Istart .. Item'Last); Buffer (Ilen + 1) := Character'Val (LM); if File.Page_Length /= 0 and then File.Line > File.Page_Length then Buffer (Ilen + 2) := Character'Val (PM); Plen := size_t (Ilen) + 2; File.Line := 1; File.Page := File.Page + 1; else Plen := size_t (Ilen) + 1; File.Line := File.Line + 1; end if; FIO.Write_Buf (AP (File), Buffer'Address, Plen); File.Col := 1; end; end Put_Line; procedure Put_Line (Item : String) is begin Put_Line (Current_Out, Item); end Put_Line; ---------- -- Putc -- ---------- procedure Putc (ch : int; File : File_Type) is begin if fputc (ch, File.Stream) = EOF then raise Device_Error; end if; end Putc; ---------- -- Read -- ---------- -- This is the primitive Stream Read routine, used when a Text_IO file -- is treated directly as a stream using Text_IO.Streams.Stream. procedure Read (File : in out Text_AFCB; Item : out Stream_Element_Array; Last : out Stream_Element_Offset) is Discard_ch : int; pragma Warnings (Off, Discard_ch); begin if File.Mode /= FCB.In_File then raise Mode_Error; end if; -- Deal with case where our logical and physical position do not match -- because of being after an LM or LM-PM sequence when in fact we are -- logically positioned before it. if File.Before_LM then -- If we are before a PM, then it is possible for a stream read -- to leave us after the LM and before the PM, which is a bit -- odd. The easiest way to deal with this is to unget the PM, -- so we are indeed positioned between the characters. This way -- further stream read operations will work correctly, and the -- effect on text processing is a little weird, but what can -- be expected if stream and text input are mixed this way? if File.Before_LM_PM then Discard_ch := ungetc (PM, File.Stream); File.Before_LM_PM := False; end if; File.Before_LM := False; Item (Item'First) := Stream_Element (Character'Pos (ASCII.LF)); if Item'Length = 1 then Last := Item'Last; else Last := Item'First + Stream_Element_Offset (fread (buffer => Item'Address, index => size_t (Item'First + 1), size => 1, count => Item'Length - 1, stream => File.Stream)); end if; return; end if; -- Now we do the read. Since this is a text file, it is normally in -- text mode, but stream data must be read in binary mode, so we -- temporarily set binary mode for the read, resetting it after. -- These calls have no effect in a system (like Unix) where there is -- no distinction between text and binary files. set_binary_mode (fileno (File.Stream)); Last := Item'First + Stream_Element_Offset (fread (Item'Address, 1, Item'Length, File.Stream)) - 1; if Last < Item'Last then if ferror (File.Stream) /= 0 then raise Device_Error; end if; end if; set_text_mode (fileno (File.Stream)); end Read; ----------- -- Reset -- ----------- procedure Reset (File : in out File_Type; Mode : File_Mode) is begin -- Don't allow change of mode for current file (RM A.10.2(5)) if (File = Current_In or else File = Current_Out or else File = Current_Error) and then To_FCB (Mode) /= File.Mode then raise Mode_Error; end if; Terminate_Line (File); FIO.Reset (AP (File), To_FCB (Mode)); File.Page := 1; File.Line := 1; File.Col := 1; File.Line_Length := 0; File.Page_Length := 0; File.Before_LM := False; File.Before_LM_PM := False; end Reset; procedure Reset (File : in out File_Type) is begin Terminate_Line (File); FIO.Reset (AP (File)); File.Page := 1; File.Line := 1; File.Col := 1; File.Line_Length := 0; File.Page_Length := 0; File.Before_LM := False; File.Before_LM_PM := False; end Reset; ------------- -- Set_Col -- ------------- procedure Set_Col (File : File_Type; To : Positive_Count) is ch : int; begin -- Raise Constraint_Error if out of range value. The reason for this -- explicit test is that we don't want junk values around, even if -- checks are off in the caller. if not To'Valid then raise Constraint_Error; end if; FIO.Check_File_Open (AP (File)); -- Output case if Mode (File) >= Out_File then -- Error if we attempt to set Col to a value greater than the -- maximum permissible line length. if File.Line_Length /= 0 and then To > File.Line_Length then raise Layout_Error; end if; -- If we are behind current position, then go to start of new line if To < File.Col then New_Line (File); end if; -- Loop to output blanks till we are at the required column while File.Col < To loop Put (File, ' '); end loop; -- Input case else -- If we are logically before a LM, but physically after it, the -- file position still reflects the position before the LM, so eat -- it now and adjust the file position appropriately. if File.Before_LM then File.Before_LM := False; File.Before_LM_PM := False; File.Line := File.Line + 1; File.Col := 1; end if; -- Loop reading characters till we get one at the required Col value loop -- Read next character. The reason we have to read ahead is to -- skip formatting characters, the effect of Set_Col is to set -- us to a real character with the right Col value, and format -- characters don't count. ch := Getc (File); -- Error if we hit an end of file if ch = EOF then raise End_Error; -- If line mark, eat it and adjust file position elsif ch = LM then File.Line := File.Line + 1; File.Col := 1; -- If recognized page mark, eat it, and adjust file position elsif ch = PM and then File.Is_Regular_File then File.Page := File.Page + 1; File.Line := 1; File.Col := 1; -- Otherwise this is the character we are looking for, so put it -- back in the input stream (we have not adjusted the file -- position yet, so everything is set right after this ungetc). elsif To = File.Col then Ungetc (ch, File); return; -- Keep skipping characters if we are not there yet, updating the -- file position past the skipped character. else File.Col := File.Col + 1; end if; end loop; end if; end Set_Col; procedure Set_Col (To : Positive_Count) is begin Set_Col (Current_Out, To); end Set_Col; --------------- -- Set_Error -- --------------- procedure Set_Error (File : File_Type) is begin FIO.Check_Write_Status (AP (File)); Current_Err := File; end Set_Error; --------------- -- Set_Input -- --------------- procedure Set_Input (File : File_Type) is begin FIO.Check_Read_Status (AP (File)); Current_In := File; end Set_Input; -------------- -- Set_Line -- -------------- procedure Set_Line (File : File_Type; To : Positive_Count) is begin -- Raise Constraint_Error if out of range value. The reason for this -- explicit test is that we don't want junk values around, even if -- checks are off in the caller. if not To'Valid then raise Constraint_Error; end if; FIO.Check_File_Open (AP (File)); if To = File.Line then return; end if; if Mode (File) >= Out_File then if File.Page_Length /= 0 and then To > File.Page_Length then raise Layout_Error; end if; if To < File.Line then New_Page (File); end if; while File.Line < To loop New_Line (File); end loop; else while To /= File.Line loop Skip_Line (File); end loop; end if; end Set_Line; procedure Set_Line (To : Positive_Count) is begin Set_Line (Current_Out, To); end Set_Line; --------------------- -- Set_Line_Length -- --------------------- procedure Set_Line_Length (File : File_Type; To : Count) is begin -- Raise Constraint_Error if out of range value. The reason for this -- explicit test is that we don't want junk values around, even if -- checks are off in the caller. if not To'Valid then raise Constraint_Error; end if; FIO.Check_Write_Status (AP (File)); File.Line_Length := To; end Set_Line_Length; procedure Set_Line_Length (To : Count) is begin Set_Line_Length (Current_Out, To); end Set_Line_Length; ---------------- -- Set_Output -- ---------------- procedure Set_Output (File : File_Type) is begin FIO.Check_Write_Status (AP (File)); Current_Out := File; end Set_Output; --------------------- -- Set_Page_Length -- --------------------- procedure Set_Page_Length (File : File_Type; To : Count) is begin -- Raise Constraint_Error if out of range value. The reason for this -- explicit test is that we don't want junk values around, even if -- checks are off in the caller. if not To'Valid then raise Constraint_Error; end if; FIO.Check_Write_Status (AP (File)); File.Page_Length := To; end Set_Page_Length; procedure Set_Page_Length (To : Count) is begin Set_Page_Length (Current_Out, To); end Set_Page_Length; --------------- -- Skip_Line -- --------------- procedure Skip_Line (File : File_Type; Spacing : Positive_Count := 1) is ch : int; begin -- Raise Constraint_Error if out of range value. The reason for this -- explicit test is that we don't want junk values around, even if -- checks are off in the caller. if not Spacing'Valid then raise Constraint_Error; end if; FIO.Check_Read_Status (AP (File)); for L in 1 .. Spacing loop if File.Before_LM then File.Before_LM := False; File.Before_LM_PM := False; else ch := Getc (File); -- If at end of file now, then immediately raise End_Error. Note -- that we can never be positioned between a line mark and a page -- mark, so if we are at the end of file, we cannot logically be -- before the implicit page mark that is at the end of the file. -- For the same reason, we do not need an explicit check for a -- page mark. If there is a FF in the middle of a line, the file -- is not in canonical format and we do not care about the page -- numbers for files other than ones in canonical format. if ch = EOF then raise End_Error; end if; -- If not at end of file, then loop till we get to an LM or EOF. -- The latter case happens only in non-canonical files where the -- last line is not terminated by LM, but we don't want to blow -- up for such files, so we assume an implicit LM in this case. loop exit when ch = LM or ch = EOF; ch := Getc (File); end loop; end if; -- We have got past a line mark, now, for a regular file only, -- see if a page mark immediately follows this line mark and -- if so, skip past the page mark as well. We do not do this -- for non-regular files, since it would cause an undesirable -- wait for an additional character. File.Col := 1; File.Line := File.Line + 1; if File.Before_LM_PM then File.Page := File.Page + 1; File.Line := 1; File.Before_LM_PM := False; elsif File.Is_Regular_File then ch := Getc (File); -- Page mark can be explicit, or implied at the end of the file if (ch = PM or else ch = EOF) and then File.Is_Regular_File then File.Page := File.Page + 1; File.Line := 1; else Ungetc (ch, File); end if; end if; end loop; end Skip_Line; procedure Skip_Line (Spacing : Positive_Count := 1) is begin Skip_Line (Current_In, Spacing); end Skip_Line; --------------- -- Skip_Page -- --------------- procedure Skip_Page (File : File_Type) is ch : int; begin FIO.Check_Read_Status (AP (File)); -- If at page mark already, just skip it if File.Before_LM_PM then File.Before_LM := False; File.Before_LM_PM := False; File.Page := File.Page + 1; File.Line := 1; File.Col := 1; return; end if; -- This is a bit tricky, if we are logically before an LM then -- it is not an error if we are at an end of file now, since we -- are not really at it. if File.Before_LM then File.Before_LM := False; File.Before_LM_PM := False; ch := Getc (File); -- Otherwise we do raise End_Error if we are at the end of file now else ch := Getc (File); if ch = EOF then raise End_Error; end if; end if; -- Now we can just rumble along to the next page mark, or to the -- end of file, if that comes first. The latter case happens when -- the page mark is implied at the end of file. loop exit when ch = EOF or else (ch = PM and then File.Is_Regular_File); ch := Getc (File); end loop; File.Page := File.Page + 1; File.Line := 1; File.Col := 1; end Skip_Page; procedure Skip_Page is begin Skip_Page (Current_In); end Skip_Page; -------------------- -- Standard_Error -- -------------------- function Standard_Error return File_Type is begin return Standard_Err; end Standard_Error; function Standard_Error return File_Access is begin return Standard_Err'Access; end Standard_Error; -------------------- -- Standard_Input -- -------------------- function Standard_Input return File_Type is begin return Standard_In; end Standard_Input; function Standard_Input return File_Access is begin return Standard_In'Access; end Standard_Input; --------------------- -- Standard_Output -- --------------------- function Standard_Output return File_Type is begin return Standard_Out; end Standard_Output; function Standard_Output return File_Access is begin return Standard_Out'Access; end Standard_Output; -------------------- -- Terminate_Line -- -------------------- procedure Terminate_Line (File : File_Type) is begin FIO.Check_File_Open (AP (File)); -- For file other than In_File, test for needing to terminate last line if Mode (File) /= In_File then -- If not at start of line definition need new line if File.Col /= 1 then New_Line (File); -- For files other than standard error and standard output, we -- make sure that an empty file has a single line feed, so that -- it is properly formatted. We avoid this for the standard files -- because it is too much of a nuisance to have these odd line -- feeds when nothing has been written to the file. -- We also avoid this for files opened in append mode, in -- accordance with (RM A.8.2(10)) elsif (File /= Standard_Err and then File /= Standard_Out) and then (File.Line = 1 and then File.Page = 1) and then Mode (File) = Out_File then New_Line (File); end if; end if; end Terminate_Line; ------------ -- Ungetc -- ------------ procedure Ungetc (ch : int; File : File_Type) is begin if ch /= EOF then if ungetc (ch, File.Stream) = EOF then raise Device_Error; end if; end if; end Ungetc; ----------- -- Write -- ----------- -- This is the primitive Stream Write routine, used when a Text_IO file -- is treated directly as a stream using Text_IO.Streams.Stream. procedure Write (File : in out Text_AFCB; Item : Stream_Element_Array) is function Has_Translated_Characters return Boolean; -- return True if Item array contains a character which will be -- translated under the text file mode. There is only one such -- character under DOS based systems which is character 10. text_translation_required : Boolean; pragma Import (C, text_translation_required, ""__gnat_text_translation_required""); Siz : constant size_t := Item'Length; function Has_Translated_Characters return Boolean is begin for K in Item'Range loop if Item (K) = 10 then return True; end if; end loop; return False; end Has_Translated_Characters; Needs_Binary_Write : constant Boolean := text_translation_required and then Has_Translated_Characters; begin if File.Mode = FCB.In_File then raise Mode_Error; end if; -- Now we do the write. Since this is a text file, it is normally in -- text mode, but stream data must be written in binary mode, so we -- temporarily set binary mode for the write, resetting it after. This -- is done only if needed (i.e. there is some characters in Item which -- needs to be written using the binary mode). -- These calls have no effect in a system (like Unix) where there is -- no distinction between text and binary files. -- Since the character translation is done at the time the buffer is -- written (this is true under Windows) we first flush current buffer -- with text mode if needed. if Needs_Binary_Write then if fflush (File.Stream) = -1 then raise Device_Error; end if; set_binary_mode (fileno (File.Stream)); end if; if fwrite (Item'Address, 1, Siz, File.Stream) /= Siz then raise Device_Error; end if; -- At this point we need to flush the buffer using the binary mode then -- we reset to text mode. if Needs_Binary_Write then if fflush (File.Stream) = -1 then raise Device_Error; end if; set_text_mode (fileno (File.Stream)); end if; end Write; -- Use ""preallocated"" strings to avoid calling ""new"" during the -- elaboration of the run time. This is needed in the tasking case to -- avoid calling Task_Lock too early. A filename is expected to end with a -- null character in the runtime, here the null characters are added just -- to have a correct filename length. Err_Name : aliased String := ""*stderr"" & ASCII.Nul; In_Name : aliased String := ""*stdin"" & ASCII.Nul; Out_Name : aliased String := ""*stdout"" & ASCII.Nul; begin ------------------------------- -- Initialize Standard Files -- ------------------------------- -- Note: the names in these files are bogus, and probably it would be -- better for these files to have no names, but the ACVC test insist! -- We use names that are bound to fail in open etc. Standard_Err.Stream := stderr; Standard_Err.Name := Err_Name'Access; Standard_Err.Form := Null_Str'Unrestricted_Access; Standard_Err.Mode := FCB.Out_File; Standard_Err.Is_Regular_File := is_regular_file (fileno (stderr)) /= 0; Standard_Err.Is_Temporary_File := False; Standard_Err.Is_System_File := True; Standard_Err.Is_Text_File := True; Standard_Err.Access_Method := 'T'; Standard_Err.Self := Standard_Err; Standard_In.Stream := stdin; Standard_In.Name := In_Name'Access; Standard_In.Form := Null_Str'Unrestricted_Access; Standard_In.Mode := FCB.In_File; Standard_In.Is_Regular_File := is_regular_file (fileno (stdin)) /= 0; Standard_In.Is_Temporary_File := False; Standard_In.Is_System_File := True; Standard_In.Is_Text_File := True; Standard_In.Access_Method := 'T'; Standard_In.Self := Standard_In; Standard_Out.Stream := stdout; Standard_Out.Name := Out_Name'Access; Standard_Out.Form := Null_Str'Unrestricted_Access; Standard_Out.Mode := FCB.Out_File; Standard_Out.Is_Regular_File := is_regular_file (fileno (stdout)) /= 0; Standard_Out.Is_Temporary_File := False; Standard_Out.Is_System_File := True; Standard_Out.Is_Text_File := True; Standard_Out.Access_Method := 'T'; Standard_Out.Self := Standard_Out; FIO.Chain_File (AP (Standard_In)); FIO.Chain_File (AP (Standard_Out)); FIO.Chain_File (AP (Standard_Err)); FIO.Make_Unbuffered (AP (Standard_Out)); FIO.Make_Unbuffered (AP (Standard_Err)); end Ada.Text_IO; ",12457,True,2718.5980171768583,median "----------------------------------------------------------------------- -- AWA.Events.Models -- AWA.Events.Models ----------------------------------------------------------------------- -- File generated by ada-gen DO NOT MODIFY -- Template used: templates/model/package-body.xhtml -- Ada Generator: https://ada-gen.googlecode.com/svn/trunk Revision 1095 ----------------------------------------------------------------------- -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the ""License""); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an ""AS IS"" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Beans.Objects.Time; package body AWA.Events.Models is use type ADO.Objects.Object_Record_Access; use type ADO.Objects.Object_Ref; use type ADO.Objects.Object_Record; function Message_Type_Key (Id : in ADO.Identifier) return ADO.Objects.Object_Key is Result : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => MESSAGE_TYPE_DEF'Access); begin ADO.Objects.Set_Value (Result, Id); return Result; end Message_Type_Key; function Message_Type_Key (Id : in String) return ADO.Objects.Object_Key is Result : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => MESSAGE_TYPE_DEF'Access); begin ADO.Objects.Set_Value (Result, Id); return Result; end Message_Type_Key; function ""="" (Left, Right : Message_Type_Ref'Class) return Boolean is begin return ADO.Objects.Object_Ref'Class (Left) = ADO.Objects.Object_Ref'Class (Right); end ""=""; procedure Set_Field (Object : in out Message_Type_Ref'Class; Impl : out Message_Type_Access) is Result : ADO.Objects.Object_Record_Access; begin Object.Prepare_Modify (Result); Impl := Message_Type_Impl (Result.all)'Access; end Set_Field; -- Internal method to allocate the Object_Record instance procedure Allocate (Object : in out Message_Type_Ref) is Impl : Message_Type_Access; begin Impl := new Message_Type_Impl; ADO.Objects.Set_Object (Object, Impl.all'Access); end Allocate; -- ---------------------------------------- -- Data object: Message_Type -- ---------------------------------------- procedure Set_Id (Object : in out Message_Type_Ref; Value : in ADO.Identifier) is Impl : Message_Type_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Key_Value (Impl.all, 1, Value); end Set_Id; function Get_Id (Object : in Message_Type_Ref) return ADO.Identifier is Impl : constant Message_Type_Access := Message_Type_Impl (Object.Get_Object.all)'Access; begin return Impl.Get_Key_Value; end Get_Id; procedure Set_Name (Object : in out Message_Type_Ref; Value : in String) is Impl : Message_Type_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_String (Impl.all, 2, Impl.Name, Value); end Set_Name; procedure Set_Name (Object : in out Message_Type_Ref; Value : in Ada.Strings.Unbounded.Unbounded_String) is Impl : Message_Type_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Unbounded_String (Impl.all, 2, Impl.Name, Value); end Set_Name; function Get_Name (Object : in Message_Type_Ref) return String is begin return Ada.Strings.Unbounded.To_String (Object.Get_Name); end Get_Name; function Get_Name (Object : in Message_Type_Ref) return Ada.Strings.Unbounded.Unbounded_String is Impl : constant Message_Type_Access := Message_Type_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Name; end Get_Name; -- Copy of the object. procedure Copy (Object : in Message_Type_Ref; Into : in out Message_Type_Ref) is Result : Message_Type_Ref; begin if not Object.Is_Null then declare Impl : constant Message_Type_Access := Message_Type_Impl (Object.Get_Load_Object.all)'Access; Copy : constant Message_Type_Access := new Message_Type_Impl; begin ADO.Objects.Set_Object (Result, Copy.all'Access); Copy.Copy (Impl.all); Copy.Name := Impl.Name; end; end if; Into := Result; end Copy; procedure Find (Object : in out Message_Type_Ref; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean) is Impl : constant Message_Type_Access := new Message_Type_Impl; begin Impl.Find (Session, Query, Found); if Found then ADO.Objects.Set_Object (Object, Impl.all'Access); else ADO.Objects.Set_Object (Object, null); Destroy (Impl); end if; end Find; procedure Load (Object : in out Message_Type_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier) is Impl : constant Message_Type_Access := new Message_Type_Impl; Found : Boolean; Query : ADO.SQL.Query; begin Query.Bind_Param (Position => 1, Value => Id); Query.Set_Filter (""id = ?""); Impl.Find (Session, Query, Found); if not Found then Destroy (Impl); raise ADO.Objects.NOT_FOUND; end if; ADO.Objects.Set_Object (Object, Impl.all'Access); end Load; procedure Load (Object : in out Message_Type_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier; Found : out Boolean) is Impl : constant Message_Type_Access := new Message_Type_Impl; Query : ADO.SQL.Query; begin Query.Bind_Param (Position => 1, Value => Id); Query.Set_Filter (""id = ?""); Impl.Find (Session, Query, Found); if not Found then Destroy (Impl); else ADO.Objects.Set_Object (Object, Impl.all'Access); end if; end Load; procedure Save (Object : in out Message_Type_Ref; Session : in out ADO.Sessions.Master_Session'Class) is Impl : ADO.Objects.Object_Record_Access := Object.Get_Object; begin if Impl = null then Impl := new Message_Type_Impl; ADO.Objects.Set_Object (Object, Impl); end if; if not ADO.Objects.Is_Created (Impl.all) then Impl.Create (Session); else Impl.Save (Session); end if; end Save; procedure Delete (Object : in out Message_Type_Ref; Session : in out ADO.Sessions.Master_Session'Class) is Impl : constant ADO.Objects.Object_Record_Access := Object.Get_Object; begin if Impl /= null then Impl.Delete (Session); end if; end Delete; -- -------------------- -- Free the object -- -------------------- procedure Destroy (Object : access Message_Type_Impl) is type Message_Type_Impl_Ptr is access all Message_Type_Impl; procedure Unchecked_Free is new Ada.Unchecked_Deallocation (Message_Type_Impl, Message_Type_Impl_Ptr); pragma Warnings (Off, ""*redundant conversion*""); Ptr : Message_Type_Impl_Ptr := Message_Type_Impl (Object.all)'Access; pragma Warnings (On, ""*redundant conversion*""); begin Unchecked_Free (Ptr); end Destroy; procedure Find (Object : in out Message_Type_Impl; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean) is Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query, MESSAGE_TYPE_DEF'Access); begin Stmt.Execute; if Stmt.Has_Elements then Object.Load (Stmt, Session); Stmt.Next; Found := not Stmt.Has_Elements; else Found := False; end if; end Find; overriding procedure Load (Object : in out Message_Type_Impl; Session : in out ADO.Sessions.Session'Class) is Found : Boolean; Query : ADO.SQL.Query; Id : constant ADO.Identifier := Object.Get_Key_Value; begin Query.Bind_Param (Position => 1, Value => Id); Query.Set_Filter (""id = ?""); Object.Find (Session, Query, Found); if not Found then raise ADO.Objects.NOT_FOUND; end if; end Load; procedure Save (Object : in out Message_Type_Impl; Session : in out ADO.Sessions.Master_Session'Class) is Stmt : ADO.Statements.Update_Statement := Session.Create_Statement (MESSAGE_TYPE_DEF'Access); begin if Object.Is_Modified (1) then Stmt.Save_Field (Name => COL_0_1_NAME, -- id Value => Object.Get_Key); Object.Clear_Modified (1); end if; if Object.Is_Modified (2) then Stmt.Save_Field (Name => COL_1_1_NAME, -- name Value => Object.Name); Object.Clear_Modified (2); end if; if Stmt.Has_Save_Fields then Stmt.Set_Filter (Filter => ""id = ?""); Stmt.Add_Param (Value => Object.Get_Key); declare Result : Integer; begin Stmt.Execute (Result); if Result /= 1 then if Result /= 0 then raise ADO.Objects.UPDATE_ERROR; end if; end if; end; end if; end Save; procedure Create (Object : in out Message_Type_Impl; Session : in out ADO.Sessions.Master_Session'Class) is Query : ADO.Statements.Insert_Statement := Session.Create_Statement (MESSAGE_TYPE_DEF'Access); Result : Integer; begin Session.Allocate (Id => Object); Query.Save_Field (Name => COL_0_1_NAME, -- id Value => Object.Get_Key); Query.Save_Field (Name => COL_1_1_NAME, -- name Value => Object.Name); Query.Execute (Result); if Result /= 1 then raise ADO.Objects.INSERT_ERROR; end if; ADO.Objects.Set_Created (Object); end Create; procedure Delete (Object : in out Message_Type_Impl; Session : in out ADO.Sessions.Master_Session'Class) is Stmt : ADO.Statements.Delete_Statement := Session.Create_Statement (MESSAGE_TYPE_DEF'Access); begin Stmt.Set_Filter (Filter => ""id = ?""); Stmt.Add_Param (Value => Object.Get_Key); Stmt.Execute; end Delete; function Get_Value (From : in Message_Type_Ref; Name : in String) return Util.Beans.Objects.Object is Obj : constant ADO.Objects.Object_Record_Access := From.Get_Load_Object; Impl : access Message_Type_Impl; begin if Obj = null then return Util.Beans.Objects.Null_Object; end if; Impl := Message_Type_Impl (Obj.all)'Access; if Name = ""id"" then return ADO.Objects.To_Object (Impl.Get_Key); elsif Name = ""name"" then return Util.Beans.Objects.To_Object (Impl.Name); end if; return Util.Beans.Objects.Null_Object; end Get_Value; procedure List (Object : in out Message_Type_Vector; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class) is Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query, MESSAGE_TYPE_DEF'Access); begin Stmt.Execute; Message_Type_Vectors.Clear (Object); while Stmt.Has_Elements loop declare Item : Message_Type_Ref; Impl : constant Message_Type_Access := new Message_Type_Impl; begin Impl.Load (Stmt, Session); ADO.Objects.Set_Object (Item, Impl.all'Access); Object.Append (Item); end; Stmt.Next; end loop; end List; -- ------------------------------ -- Load the object from current iterator position -- ------------------------------ procedure Load (Object : in out Message_Type_Impl; Stmt : in out ADO.Statements.Query_Statement'Class; Session : in out ADO.Sessions.Session'Class) is pragma Unreferenced (Session); begin Object.Set_Key_Value (Stmt.Get_Identifier (0)); Object.Name := Stmt.Get_Unbounded_String (1); ADO.Objects.Set_Created (Object); end Load; function Queue_Key (Id : in ADO.Identifier) return ADO.Objects.Object_Key is Result : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => QUEUE_DEF'Access); begin ADO.Objects.Set_Value (Result, Id); return Result; end Queue_Key; function Queue_Key (Id : in String) return ADO.Objects.Object_Key is Result : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => QUEUE_DEF'Access); begin ADO.Objects.Set_Value (Result, Id); return Result; end Queue_Key; function ""="" (Left, Right : Queue_Ref'Class) return Boolean is begin return ADO.Objects.Object_Ref'Class (Left) = ADO.Objects.Object_Ref'Class (Right); end ""=""; procedure Set_Field (Object : in out Queue_Ref'Class; Impl : out Queue_Access) is Result : ADO.Objects.Object_Record_Access; begin Object.Prepare_Modify (Result); Impl := Queue_Impl (Result.all)'Access; end Set_Field; -- Internal method to allocate the Object_Record instance procedure Allocate (Object : in out Queue_Ref) is Impl : Queue_Access; begin Impl := new Queue_Impl; Impl.Server_Id := 0; ADO.Objects.Set_Object (Object, Impl.all'Access); end Allocate; -- ---------------------------------------- -- Data object: Queue -- ---------------------------------------- procedure Set_Id (Object : in out Queue_Ref; Value : in ADO.Identifier) is Impl : Queue_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Key_Value (Impl.all, 1, Value); end Set_Id; function Get_Id (Object : in Queue_Ref) return ADO.Identifier is Impl : constant Queue_Access := Queue_Impl (Object.Get_Object.all)'Access; begin return Impl.Get_Key_Value; end Get_Id; procedure Set_Server_Id (Object : in out Queue_Ref; Value : in Integer) is Impl : Queue_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Integer (Impl.all, 2, Impl.Server_Id, Value); end Set_Server_Id; function Get_Server_Id (Object : in Queue_Ref) return Integer is Impl : constant Queue_Access := Queue_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Server_Id; end Get_Server_Id; procedure Set_Name (Object : in out Queue_Ref; Value : in String) is Impl : Queue_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_String (Impl.all, 3, Impl.Name, Value); end Set_Name; procedure Set_Name (Object : in out Queue_Ref; Value : in Ada.Strings.Unbounded.Unbounded_String) is Impl : Queue_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Unbounded_String (Impl.all, 3, Impl.Name, Value); end Set_Name; function Get_Name (Object : in Queue_Ref) return String is begin return Ada.Strings.Unbounded.To_String (Object.Get_Name); end Get_Name; function Get_Name (Object : in Queue_Ref) return Ada.Strings.Unbounded.Unbounded_String is Impl : constant Queue_Access := Queue_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Name; end Get_Name; -- Copy of the object. procedure Copy (Object : in Queue_Ref; Into : in out Queue_Ref) is Result : Queue_Ref; begin if not Object.Is_Null then declare Impl : constant Queue_Access := Queue_Impl (Object.Get_Load_Object.all)'Access; Copy : constant Queue_Access := new Queue_Impl; begin ADO.Objects.Set_Object (Result, Copy.all'Access); Copy.Copy (Impl.all); Copy.Server_Id := Impl.Server_Id; Copy.Name := Impl.Name; end; end if; Into := Result; end Copy; procedure Find (Object : in out Queue_Ref; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean) is Impl : constant Queue_Access := new Queue_Impl; begin Impl.Find (Session, Query, Found); if Found then ADO.Objects.Set_Object (Object, Impl.all'Access); else ADO.Objects.Set_Object (Object, null); Destroy (Impl); end if; end Find; procedure Load (Object : in out Queue_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier) is Impl : constant Queue_Access := new Queue_Impl; Found : Boolean; Query : ADO.SQL.Query; begin Query.Bind_Param (Position => 1, Value => Id); Query.Set_Filter (""id = ?""); Impl.Find (Session, Query, Found); if not Found then Destroy (Impl); raise ADO.Objects.NOT_FOUND; end if; ADO.Objects.Set_Object (Object, Impl.all'Access); end Load; procedure Load (Object : in out Queue_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier; Found : out Boolean) is Impl : constant Queue_Access := new Queue_Impl; Query : ADO.SQL.Query; begin Query.Bind_Param (Position => 1, Value => Id); Query.Set_Filter (""id = ?""); Impl.Find (Session, Query, Found); if not Found then Destroy (Impl); else ADO.Objects.Set_Object (Object, Impl.all'Access); end if; end Load; procedure Save (Object : in out Queue_Ref; Session : in out ADO.Sessions.Master_Session'Class) is Impl : ADO.Objects.Object_Record_Access := Object.Get_Object; begin if Impl = null then Impl := new Queue_Impl; ADO.Objects.Set_Object (Object, Impl); end if; if not ADO.Objects.Is_Created (Impl.all) then Impl.Create (Session); else Impl.Save (Session); end if; end Save; procedure Delete (Object : in out Queue_Ref; Session : in out ADO.Sessions.Master_Session'Class) is Impl : constant ADO.Objects.Object_Record_Access := Object.Get_Object; begin if Impl /= null then Impl.Delete (Session); end if; end Delete; -- -------------------- -- Free the object -- -------------------- procedure Destroy (Object : access Queue_Impl) is type Queue_Impl_Ptr is access all Queue_Impl; procedure Unchecked_Free is new Ada.Unchecked_Deallocation (Queue_Impl, Queue_Impl_Ptr); pragma Warnings (Off, ""*redundant conversion*""); Ptr : Queue_Impl_Ptr := Queue_Impl (Object.all)'Access; pragma Warnings (On, ""*redundant conversion*""); begin Unchecked_Free (Ptr); end Destroy; procedure Find (Object : in out Queue_Impl; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean) is Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query, QUEUE_DEF'Access); begin Stmt.Execute; if Stmt.Has_Elements then Object.Load (Stmt, Session); Stmt.Next; Found := not Stmt.Has_Elements; else Found := False; end if; end Find; overriding procedure Load (Object : in out Queue_Impl; Session : in out ADO.Sessions.Session'Class) is Found : Boolean; Query : ADO.SQL.Query; Id : constant ADO.Identifier := Object.Get_Key_Value; begin Query.Bind_Param (Position => 1, Value => Id); Query.Set_Filter (""id = ?""); Object.Find (Session, Query, Found); if not Found then raise ADO.Objects.NOT_FOUND; end if; end Load; procedure Save (Object : in out Queue_Impl; Session : in out ADO.Sessions.Master_Session'Class) is Stmt : ADO.Statements.Update_Statement := Session.Create_Statement (QUEUE_DEF'Access); begin if Object.Is_Modified (1) then Stmt.Save_Field (Name => COL_0_2_NAME, -- id Value => Object.Get_Key); Object.Clear_Modified (1); end if; if Object.Is_Modified (2) then Stmt.Save_Field (Name => COL_1_2_NAME, -- server_id Value => Object.Server_Id); Object.Clear_Modified (2); end if; if Object.Is_Modified (3) then Stmt.Save_Field (Name => COL_2_2_NAME, -- name Value => Object.Name); Object.Clear_Modified (3); end if; if Stmt.Has_Save_Fields then Stmt.Set_Filter (Filter => ""id = ?""); Stmt.Add_Param (Value => Object.Get_Key); declare Result : Integer; begin Stmt.Execute (Result); if Result /= 1 then if Result /= 0 then raise ADO.Objects.UPDATE_ERROR; end if; end if; end; end if; end Save; procedure Create (Object : in out Queue_Impl; Session : in out ADO.Sessions.Master_Session'Class) is Query : ADO.Statements.Insert_Statement := Session.Create_Statement (QUEUE_DEF'Access); Result : Integer; begin Session.Allocate (Id => Object); Query.Save_Field (Name => COL_0_2_NAME, -- id Value => Object.Get_Key); Query.Save_Field (Name => COL_1_2_NAME, -- server_id Value => Object.Server_Id); Query.Save_Field (Name => COL_2_2_NAME, -- name Value => Object.Name); Query.Execute (Result); if Result /= 1 then raise ADO.Objects.INSERT_ERROR; end if; ADO.Objects.Set_Created (Object); end Create; procedure Delete (Object : in out Queue_Impl; Session : in out ADO.Sessions.Master_Session'Class) is Stmt : ADO.Statements.Delete_Statement := Session.Create_Statement (QUEUE_DEF'Access); begin Stmt.Set_Filter (Filter => ""id = ?""); Stmt.Add_Param (Value => Object.Get_Key); Stmt.Execute; end Delete; function Get_Value (From : in Queue_Ref; Name : in String) return Util.Beans.Objects.Object is Obj : constant ADO.Objects.Object_Record_Access := From.Get_Load_Object; Impl : access Queue_Impl; begin if Obj = null then return Util.Beans.Objects.Null_Object; end if; Impl := Queue_Impl (Obj.all)'Access; if Name = ""id"" then return ADO.Objects.To_Object (Impl.Get_Key); elsif Name = ""server_id"" then return Util.Beans.Objects.To_Object (Long_Long_Integer (Impl.Server_Id)); elsif Name = ""name"" then return Util.Beans.Objects.To_Object (Impl.Name); end if; return Util.Beans.Objects.Null_Object; end Get_Value; -- ------------------------------ -- Load the object from current iterator position -- ------------------------------ procedure Load (Object : in out Queue_Impl; Stmt : in out ADO.Statements.Query_Statement'Class; Session : in out ADO.Sessions.Session'Class) is pragma Unreferenced (Session); begin Object.Set_Key_Value (Stmt.Get_Identifier (0)); Object.Server_Id := Stmt.Get_Integer (1); Object.Name := Stmt.Get_Unbounded_String (2); ADO.Objects.Set_Created (Object); end Load; function Message_Key (Id : in ADO.Identifier) return ADO.Objects.Object_Key is Result : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => MESSAGE_DEF'Access); begin ADO.Objects.Set_Value (Result, Id); return Result; end Message_Key; function Message_Key (Id : in String) return ADO.Objects.Object_Key is Result : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => MESSAGE_DEF'Access); begin ADO.Objects.Set_Value (Result, Id); return Result; end Message_Key; function ""="" (Left, Right : Message_Ref'Class) return Boolean is begin return ADO.Objects.Object_Ref'Class (Left) = ADO.Objects.Object_Ref'Class (Right); end ""=""; procedure Set_Field (Object : in out Message_Ref'Class; Impl : out Message_Access) is Result : ADO.Objects.Object_Record_Access; begin Object.Prepare_Modify (Result); Impl := Message_Impl (Result.all)'Access; end Set_Field; -- Internal method to allocate the Object_Record instance procedure Allocate (Object : in out Message_Ref) is Impl : Message_Access; begin Impl := new Message_Impl; Impl.Create_Date := ADO.DEFAULT_TIME; Impl.Priority := 0; Impl.Count := 0; Impl.Server_Id := 0; Impl.Task_Id := 0; Impl.Status := AWA.Events.Models.Message_Status_Type'First; Impl.Processing_Date.Is_Null := True; Impl.Version := 0; Impl.Entity_Id := ADO.NO_IDENTIFIER; Impl.Entity_Type := 0; Impl.Finish_Date.Is_Null := True; ADO.Objects.Set_Object (Object, Impl.all'Access); end Allocate; -- ---------------------------------------- -- Data object: Message -- ---------------------------------------- procedure Set_Id (Object : in out Message_Ref; Value : in ADO.Identifier) is Impl : Message_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Key_Value (Impl.all, 1, Value); end Set_Id; function Get_Id (Object : in Message_Ref) return ADO.Identifier is Impl : constant Message_Access := Message_Impl (Object.Get_Object.all)'Access; begin return Impl.Get_Key_Value; end Get_Id; procedure Set_Create_Date (Object : in out Message_Ref; Value : in Ada.Calendar.Time) is Impl : Message_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Time (Impl.all, 2, Impl.Create_Date, Value); end Set_Create_Date; function Get_Create_Date (Object : in Message_Ref) return Ada.Calendar.Time is Impl : constant Message_Access := Message_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Create_Date; end Get_Create_Date; procedure Set_Priority (Object : in out Message_Ref; Value : in Integer) is Impl : Message_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Integer (Impl.all, 3, Impl.Priority, Value); end Set_Priority; function Get_Priority (Object : in Message_Ref) return Integer is Impl : constant Message_Access := Message_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Priority; end Get_Priority; procedure Set_Count (Object : in out Message_Ref; Value : in Integer) is Impl : Message_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Integer (Impl.all, 4, Impl.Count, Value); end Set_Count; function Get_Count (Object : in Message_Ref) return Integer is Impl : constant Message_Access := Message_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Count; end Get_Count; procedure Set_Parameters (Object : in out Message_Ref; Value : in String) is Impl : Message_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_String (Impl.all, 5, Impl.Parameters, Value); end Set_Parameters; procedure Set_Parameters (Object : in out Message_Ref; Value : in Ada.Strings.Unbounded.Unbounded_String) is Impl : Message_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Unbounded_String (Impl.all, 5, Impl.Parameters, Value); end Set_Parameters; function Get_Parameters (Object : in Message_Ref) return String is begin return Ada.Strings.Unbounded.To_String (Object.Get_Parameters); end Get_Parameters; function Get_Parameters (Object : in Message_Ref) return Ada.Strings.Unbounded.Unbounded_String is Impl : constant Message_Access := Message_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Parameters; end Get_Parameters; procedure Set_Server_Id (Object : in out Message_Ref; Value : in Integer) is Impl : Message_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Integer (Impl.all, 6, Impl.Server_Id, Value); end Set_Server_Id; function Get_Server_Id (Object : in Message_Ref) return Integer is Impl : constant Message_Access := Message_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Server_Id; end Get_Server_Id; procedure Set_Task_Id (Object : in out Message_Ref; Value : in Integer) is Impl : Message_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Integer (Impl.all, 7, Impl.Task_Id, Value); end Set_Task_Id; function Get_Task_Id (Object : in Message_Ref) return Integer is Impl : constant Message_Access := Message_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Task_Id; end Get_Task_Id; procedure Set_Status (Object : in out Message_Ref; Value : in AWA.Events.Models.Message_Status_Type) is procedure Set_Field_Enum is new ADO.Objects.Set_Field_Operation (Message_Status_Type); Impl : Message_Access; begin Set_Field (Object, Impl); Set_Field_Enum (Impl.all, 8, Impl.Status, Value); end Set_Status; function Get_Status (Object : in Message_Ref) return AWA.Events.Models.Message_Status_Type is Impl : constant Message_Access := Message_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Status; end Get_Status; procedure Set_Processing_Date (Object : in out Message_Ref; Value : in ADO.Nullable_Time) is Impl : Message_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Time (Impl.all, 9, Impl.Processing_Date, Value); end Set_Processing_Date; function Get_Processing_Date (Object : in Message_Ref) return ADO.Nullable_Time is Impl : constant Message_Access := Message_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Processing_Date; end Get_Processing_Date; function Get_Version (Object : in Message_Ref) return Integer is Impl : constant Message_Access := Message_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Version; end Get_Version; procedure Set_Entity_Id (Object : in out Message_Ref; Value : in ADO.Identifier) is Impl : Message_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Identifier (Impl.all, 11, Impl.Entity_Id, Value); end Set_Entity_Id; function Get_Entity_Id (Object : in Message_Ref) return ADO.Identifier is Impl : constant Message_Access := Message_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Entity_Id; end Get_Entity_Id; procedure Set_Entity_Type (Object : in out Message_Ref; Value : in ADO.Entity_Type) is Impl : Message_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Entity_Type (Impl.all, 12, Impl.Entity_Type, Value); end Set_Entity_Type; function Get_Entity_Type (Object : in Message_Ref) return ADO.Entity_Type is Impl : constant Message_Access := Message_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Entity_Type; end Get_Entity_Type; procedure Set_Finish_Date (Object : in out Message_Ref; Value : in ADO.Nullable_Time) is Impl : Message_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Time (Impl.all, 13, Impl.Finish_Date, Value); end Set_Finish_Date; function Get_Finish_Date (Object : in Message_Ref) return ADO.Nullable_Time is Impl : constant Message_Access := Message_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Finish_Date; end Get_Finish_Date; procedure Set_Queue (Object : in out Message_Ref; Value : in AWA.Events.Models.Queue_Ref'Class) is Impl : Message_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Object (Impl.all, 14, Impl.Queue, Value); end Set_Queue; function Get_Queue (Object : in Message_Ref) return AWA.Events.Models.Queue_Ref'Class is Impl : constant Message_Access := Message_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Queue; end Get_Queue; procedure Set_Message_Type (Object : in out Message_Ref; Value : in AWA.Events.Models.Message_Type_Ref'Class) is Impl : Message_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Object (Impl.all, 15, Impl.Message_Type, Value); end Set_Message_Type; function Get_Message_Type (Object : in Message_Ref) return AWA.Events.Models.Message_Type_Ref'Class is Impl : constant Message_Access := Message_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Message_Type; end Get_Message_Type; procedure Set_User (Object : in out Message_Ref; Value : in AWA.Users.Models.User_Ref'Class) is Impl : Message_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Object (Impl.all, 16, Impl.User, Value); end Set_User; function Get_User (Object : in Message_Ref) return AWA.Users.Models.User_Ref'Class is Impl : constant Message_Access := Message_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.User; end Get_User; procedure Set_Session (Object : in out Message_Ref; Value : in AWA.Users.Models.Session_Ref'Class) is Impl : Message_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Object (Impl.all, 17, Impl.Session, Value); end Set_Session; function Get_Session (Object : in Message_Ref) return AWA.Users.Models.Session_Ref'Class is Impl : constant Message_Access := Message_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Session; end Get_Session; -- Copy of the object. procedure Copy (Object : in Message_Ref; Into : in out Message_Ref) is Result : Message_Ref; begin if not Object.Is_Null then declare Impl : constant Message_Access := Message_Impl (Object.Get_Load_Object.all)'Access; Copy : constant Message_Access := new Message_Impl; begin ADO.Objects.Set_Object (Result, Copy.all'Access); Copy.Copy (Impl.all); Copy.Create_Date := Impl.Create_Date; Copy.Priority := Impl.Priority; Copy.Count := Impl.Count; Copy.Parameters := Impl.Parameters; Copy.Server_Id := Impl.Server_Id; Copy.Task_Id := Impl.Task_Id; Copy.Status := Impl.Status; Copy.Processing_Date := Impl.Processing_Date; Copy.Version := Impl.Version; Copy.Entity_Id := Impl.Entity_Id; Copy.Entity_Type := Impl.Entity_Type; Copy.Finish_Date := Impl.Finish_Date; Copy.Queue := Impl.Queue; Copy.Message_Type := Impl.Message_Type; Copy.User := Impl.User; Copy.Session := Impl.Session; end; end if; Into := Result; end Copy; procedure Find (Object : in out Message_Ref; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean) is Impl : constant Message_Access := new Message_Impl; begin Impl.Find (Session, Query, Found); if Found then ADO.Objects.Set_Object (Object, Impl.all'Access); else ADO.Objects.Set_Object (Object, null); Destroy (Impl); end if; end Find; procedure Load (Object : in out Message_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier) is Impl : constant Message_Access := new Message_Impl; Found : Boolean; Query : ADO.SQL.Query; begin Query.Bind_Param (Position => 1, Value => Id); Query.Set_Filter (""id = ?""); Impl.Find (Session, Query, Found); if not Found then Destroy (Impl); raise ADO.Objects.NOT_FOUND; end if; ADO.Objects.Set_Object (Object, Impl.all'Access); end Load; procedure Load (Object : in out Message_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier; Found : out Boolean) is Impl : constant Message_Access := new Message_Impl; Query : ADO.SQL.Query; begin Query.Bind_Param (Position => 1, Value => Id); Query.Set_Filter (""id = ?""); Impl.Find (Session, Query, Found); if not Found then Destroy (Impl); else ADO.Objects.Set_Object (Object, Impl.all'Access); end if; end Load; procedure Save (Object : in out Message_Ref; Session : in out ADO.Sessions.Master_Session'Class) is Impl : ADO.Objects.Object_Record_Access := Object.Get_Object; begin if Impl = null then Impl := new Message_Impl; ADO.Objects.Set_Object (Object, Impl); end if; if not ADO.Objects.Is_Created (Impl.all) then Impl.Create (Session); else Impl.Save (Session); end if; end Save; procedure Delete (Object : in out Message_Ref; Session : in out ADO.Sessions.Master_Session'Class) is Impl : constant ADO.Objects.Object_Record_Access := Object.Get_Object; begin if Impl /= null then Impl.Delete (Session); end if; end Delete; -- -------------------- -- Free the object -- -------------------- procedure Destroy (Object : access Message_Impl) is type Message_Impl_Ptr is access all Message_Impl; procedure Unchecked_Free is new Ada.Unchecked_Deallocation (Message_Impl, Message_Impl_Ptr); pragma Warnings (Off, ""*redundant conversion*""); Ptr : Message_Impl_Ptr := Message_Impl (Object.all)'Access; pragma Warnings (On, ""*redundant conversion*""); begin Unchecked_Free (Ptr); end Destroy; procedure Find (Object : in out Message_Impl; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean) is Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query, MESSAGE_DEF'Access); begin Stmt.Execute; if Stmt.Has_Elements then Object.Load (Stmt, Session); Stmt.Next; Found := not Stmt.Has_Elements; else Found := False; end if; end Find; overriding procedure Load (Object : in out Message_Impl; Session : in out ADO.Sessions.Session'Class) is Found : Boolean; Query : ADO.SQL.Query; Id : constant ADO.Identifier := Object.Get_Key_Value; begin Query.Bind_Param (Position => 1, Value => Id); Query.Set_Filter (""id = ?""); Object.Find (Session, Query, Found); if not Found then raise ADO.Objects.NOT_FOUND; end if; end Load; procedure Save (Object : in out Message_Impl; Session : in out ADO.Sessions.Master_Session'Class) is Stmt : ADO.Statements.Update_Statement := Session.Create_Statement (MESSAGE_DEF'Access); begin if Object.Is_Modified (1) then Stmt.Save_Field (Name => COL_0_3_NAME, -- id Value => Object.Get_Key); Object.Clear_Modified (1); end if; if Object.Is_Modified (2) then Stmt.Save_Field (Name => COL_1_3_NAME, -- create_date Value => Object.Create_Date); Object.Clear_Modified (2); end if; if Object.Is_Modified (3) then Stmt.Save_Field (Name => COL_2_3_NAME, -- priority Value => Object.Priority); Object.Clear_Modified (3); end if; if Object.Is_Modified (4) then Stmt.Save_Field (Name => COL_3_3_NAME, -- count Value => Object.Count); Object.Clear_Modified (4); end if; if Object.Is_Modified (5) then Stmt.Save_Field (Name => COL_4_3_NAME, -- parameters Value => Object.Parameters); Object.Clear_Modified (5); end if; if Object.Is_Modified (6) then Stmt.Save_Field (Name => COL_5_3_NAME, -- server_id Value => Object.Server_Id); Object.Clear_Modified (6); end if; if Object.Is_Modified (7) then Stmt.Save_Field (Name => COL_6_3_NAME, -- task_id Value => Object.Task_Id); Object.Clear_Modified (7); end if; if Object.Is_Modified (8) then Stmt.Save_Field (Name => COL_7_3_NAME, -- status Value => Integer (Message_Status_Type'Pos (Object.Status))); Object.Clear_Modified (8); end if; if Object.Is_Modified (9) then Stmt.Save_Field (Name => COL_8_3_NAME, -- processing_date Value => Object.Processing_Date); Object.Clear_Modified (9); end if; if Object.Is_Modified (11) then Stmt.Save_Field (Name => COL_10_3_NAME, -- entity_id Value => Object.Entity_Id); Object.Clear_Modified (11); end if; if Object.Is_Modified (12) then Stmt.Save_Field (Name => COL_11_3_NAME, -- entity_type Value => Object.Entity_Type); Object.Clear_Modified (12); end if; if Object.Is_Modified (13) then Stmt.Save_Field (Name => COL_12_3_NAME, -- finish_date Value => Object.Finish_Date); Object.Clear_Modified (13); end if; if Object.Is_Modified (14) then Stmt.Save_Field (Name => COL_13_3_NAME, -- queue_id Value => Object.Queue); Object.Clear_Modified (14); end if; if Object.Is_Modified (15) then Stmt.Save_Field (Name => COL_14_3_NAME, -- message_type_id Value => Object.Message_Type); Object.Clear_Modified (15); end if; if Object.Is_Modified (16) then Stmt.Save_Field (Name => COL_15_3_NAME, -- user_id Value => Object.User); Object.Clear_Modified (16); end if; if Object.Is_Modified (17) then Stmt.Save_Field (Name => COL_16_3_NAME, -- session_id Value => Object.Session); Object.Clear_Modified (17); end if; if Stmt.Has_Save_Fields then Object.Version := Object.Version + 1; Stmt.Save_Field (Name => ""version"", Value => Object.Version); Stmt.Set_Filter (Filter => ""id = ? and version = ?""); Stmt.Add_Param (Value => Object.Get_Key); Stmt.Add_Param (Value => Object.Version - 1); declare Result : Integer; begin Stmt.Execute (Result); if Result /= 1 then if Result /= 0 then raise ADO.Objects.UPDATE_ERROR; else raise ADO.Objects.LAZY_LOCK; end if; end if; end; end if; end Save; procedure Create (Object : in out Message_Impl; Session : in out ADO.Sessions.Master_Session'Class) is Query : ADO.Statements.Insert_Statement := Session.Create_Statement (MESSAGE_DEF'Access); Result : Integer; begin Object.Version := 1; Session.Allocate (Id => Object); Query.Save_Field (Name => COL_0_3_NAME, -- id Value => Object.Get_Key); Query.Save_Field (Name => COL_1_3_NAME, -- create_date Value => Object.Create_Date); Query.Save_Field (Name => COL_2_3_NAME, -- priority Value => Object.Priority); Query.Save_Field (Name => COL_3_3_NAME, -- count Value => Object.Count); Query.Save_Field (Name => COL_4_3_NAME, -- parameters Value => Object.Parameters); Query.Save_Field (Name => COL_5_3_NAME, -- server_id Value => Object.Server_Id); Query.Save_Field (Name => COL_6_3_NAME, -- task_id Value => Object.Task_Id); Query.Save_Field (Name => COL_7_3_NAME, -- status Value => Integer (Message_Status_Type'Pos (Object.Status))); Query.Save_Field (Name => COL_8_3_NAME, -- processing_date Value => Object.Processing_Date); Query.Save_Field (Name => COL_9_3_NAME, -- version Value => Object.Version); Query.Save_Field (Name => COL_10_3_NAME, -- entity_id Value => Object.Entity_Id); Query.Save_Field (Name => COL_11_3_NAME, -- entity_type Value => Object.Entity_Type); Query.Save_Field (Name => COL_12_3_NAME, -- finish_date Value => Object.Finish_Date); Query.Save_Field (Name => COL_13_3_NAME, -- queue_id Value => Object.Queue); Query.Save_Field (Name => COL_14_3_NAME, -- message_type_id Value => Object.Message_Type); Query.Save_Field (Name => COL_15_3_NAME, -- user_id Value => Object.User); Query.Save_Field (Name => COL_16_3_NAME, -- session_id Value => Object.Session); Query.Execute (Result); if Result /= 1 then raise ADO.Objects.INSERT_ERROR; end if; ADO.Objects.Set_Created (Object); end Create; procedure Delete (Object : in out Message_Impl; Session : in out ADO.Sessions.Master_Session'Class) is Stmt : ADO.Statements.Delete_Statement := Session.Create_Statement (MESSAGE_DEF'Access); begin Stmt.Set_Filter (Filter => ""id = ?""); Stmt.Add_Param (Value => Object.Get_Key); Stmt.Execute; end Delete; function Get_Value (From : in Message_Ref; Name : in String) return Util.Beans.Objects.Object is Obj : constant ADO.Objects.Object_Record_Access := From.Get_Load_Object; Impl : access Message_Impl; begin if Obj = null then return Util.Beans.Objects.Null_Object; end if; Impl := Message_Impl (Obj.all)'Access; if Name = ""id"" then return ADO.Objects.To_Object (Impl.Get_Key); elsif Name = ""create_date"" then return Util.Beans.Objects.Time.To_Object (Impl.Create_Date); elsif Name = ""priority"" then return Util.Beans.Objects.To_Object (Long_Long_Integer (Impl.Priority)); elsif Name = ""count"" then return Util.Beans.Objects.To_Object (Long_Long_Integer (Impl.Count)); elsif Name = ""parameters"" then return Util.Beans.Objects.To_Object (Impl.Parameters); elsif Name = ""server_id"" then return Util.Beans.Objects.To_Object (Long_Long_Integer (Impl.Server_Id)); elsif Name = ""task_id"" then return Util.Beans.Objects.To_Object (Long_Long_Integer (Impl.Task_Id)); elsif Name = ""status"" then return Message_Status_Type_Objects.To_Object (Impl.Status); elsif Name = ""processing_date"" then if Impl.Processing_Date.Is_Null then return Util.Beans.Objects.Null_Object; else return Util.Beans.Objects.Time.To_Object (Impl.Processing_Date.Value); end if; elsif Name = ""entity_id"" then return Util.Beans.Objects.To_Object (Long_Long_Integer (Impl.Entity_Id)); elsif Name = ""entity_type"" then return Util.Beans.Objects.To_Object (Long_Long_Integer (Impl.Entity_Type)); elsif Name = ""finish_date"" then if Impl.Finish_Date.Is_Null then return Util.Beans.Objects.Null_Object; else return Util.Beans.Objects.Time.To_Object (Impl.Finish_Date.Value); end if; end if; return Util.Beans.Objects.Null_Object; end Get_Value; procedure List (Object : in out Message_Vector; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class) is Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query, MESSAGE_DEF'Access); begin Stmt.Execute; Message_Vectors.Clear (Object); while Stmt.Has_Elements loop declare Item : Message_Ref; Impl : constant Message_Access := new Message_Impl; begin Impl.Load (Stmt, Session); ADO.Objects.Set_Object (Item, Impl.all'Access); Object.Append (Item); end; Stmt.Next; end loop; end List; -- ------------------------------ -- Load the object from current iterator position -- ------------------------------ procedure Load (Object : in out Message_Impl; Stmt : in out ADO.Statements.Query_Statement'Class; Session : in out ADO.Sessions.Session'Class) is begin Object.Set_Key_Value (Stmt.Get_Identifier (0)); Object.Create_Date := Stmt.Get_Time (1); Object.Priority := Stmt.Get_Integer (2); Object.Count := Stmt.Get_Integer (3); Object.Parameters := Stmt.Get_Unbounded_String (4); Object.Server_Id := Stmt.Get_Integer (5); Object.Task_Id := Stmt.Get_Integer (6); Object.Status := Message_Status_Type'Val (Stmt.Get_Integer (7)); Object.Processing_Date := Stmt.Get_Time (8); Object.Entity_Id := Stmt.Get_Identifier (10); Object.Entity_Type := ADO.Entity_Type (Stmt.Get_Integer (11)); Object.Finish_Date := Stmt.Get_Time (12); if not Stmt.Is_Null (13) then Object.Queue.Set_Key_Value (Stmt.Get_Identifier (13), Session); end if; if not Stmt.Is_Null (14) then Object.Message_Type.Set_Key_Value (Stmt.Get_Identifier (14), Session); end if; if not Stmt.Is_Null (15) then Object.User.Set_Key_Value (Stmt.Get_Identifier (15), Session); end if; if not Stmt.Is_Null (16) then Object.Session.Set_Key_Value (Stmt.Get_Identifier (16), Session); end if; Object.Version := Stmt.Get_Integer (9); ADO.Objects.Set_Created (Object); end Load; end AWA.Events.Models; ",12156,True,3426.9796793006994,median "-- This file was generated by bmp2ada with Giza.Image; with Giza.Image.DMA2D; use Giza.Image.DMA2D; package cancel_80x80 is pragma Style_Checks (Off); CLUT : aliased constant L4_CLUT_T := ( (R => 255, G => 0, B => 0), (R => 255, G => 255, B => 255), others => (0, 0, 0)); Data : aliased constant L4_Data_T := ( 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 16, 17, 17, 17, 17, 17, 17, 1, 0, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 17, 17, 17, 17, 17, 17, 0, 0, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 16, 17, 17, 17, 17, 17, 1, 0, 0, 0, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 16, 17, 17, 17, 17, 17, 0, 0, 0, 0, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 17, 17, 17, 17, 17, 1, 0, 0, 0, 0, 0, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 16, 17, 17, 17, 17, 17, 1, 0, 0, 0, 0, 0, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 17, 17, 17, 17, 17, 17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 16, 17, 17, 17, 17, 17, 17, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 17, 17, 17, 17, 17, 17, 1, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 17, 17, 17, 17, 17, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 17, 17, 17, 17, 1, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 17, 17, 17, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 17, 17, 1, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 17, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 16, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 17, 17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 16, 17, 17, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 17, 17, 17, 17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 16, 17, 17, 17, 17, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 17, 17, 17, 17, 17, 17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 16, 17, 17, 17, 17, 17, 17, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 17, 17, 17, 17, 17, 17, 1, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 0, 0, 0, 0, 0, 16, 17, 17, 17, 17, 17, 17, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 0, 0, 0, 0, 0, 16, 17, 17, 17, 17, 17, 1, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 0, 0, 0, 0, 17, 17, 17, 17, 17, 17, 0, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 0, 0, 0, 16, 17, 17, 17, 17, 17, 1, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 0, 0, 17, 17, 17, 17, 17, 17, 1, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 0, 16, 17, 17, 17, 17, 17, 17, 0, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0, 17, 17, 17, 17, 17, 17, 17, 1, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17 ); Image : constant Giza.Image.Ref := new Giza.Image.DMA2D.Instance' (Mode => L4, W => 80, H => 80, Length => 3200, L4_CLUT => CLUT'Access, L4_Data => Data'Access); pragma Style_Checks (On); end cancel_80x80; ",12243,True,5108.121224495144,median "------------------------------------------------------------------------------ -- -- -- ASIS-for-GNAT IMPLEMENTATION COMPONENTS -- -- -- -- A 4 G . C O N T T . D P -- -- -- -- B o d y -- -- -- -- Copyright (C) 1995-2012, Free Software Foundation, Inc. -- -- -- -- ASIS-for-GNAT is free software; you can redistribute it and/or modify it -- -- under terms of the GNU General Public License as published by the Free -- -- Software Foundation; either version 2, or (at your option) any later -- -- version. ASIS-for-GNAT is distributed in the hope that it will be use- -- -- ful, but WITHOUT ANY WARRANTY; without even the implied warranty of MER- -- -- CHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General -- -- Public License for more details. You should have received a copy of the -- -- GNU General Public License distributed with ASIS-for-GNAT; see file -- -- COPYING. If not, write to the Free Software Foundation, 51 Franklin -- -- Street, Fifth Floor, Boston, MA 02110-1301, USA. -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- ASIS-for-GNAT was originally developed by the ASIS-for-GNAT team at the -- -- Software Engineering Laboratory of the Swiss Federal Institute of -- -- Technology (LGL-EPFL) in Lausanne, Switzerland, in cooperation with the -- -- Scientific Research Computer Center of Moscow State University (SRCC -- -- MSU), Russia, with funding partially provided by grants from the Swiss -- -- National Science Foundation and the Swiss Academy of Engineering -- -- Sciences. ASIS-for-GNAT is now maintained by AdaCore -- -- (http://www.adacore.com). -- -- -- ------------------------------------------------------------------------------ pragma Ada_2005; with Ada.Containers.Ordered_Sets; with Ada.Unchecked_Deallocation; with Asis.Set_Get; use Asis.Set_Get; with A4G.Contt.UT; use A4G.Contt.UT; with A4G.Get_Unit; use A4G.Get_Unit; with Atree; use Atree; with Nlists; use Nlists; with Namet; use Namet; with Sinfo; use Sinfo; with Lib; use Lib; package body A4G.Contt.Dp is ----------------------- -- Local Subprograms -- ----------------------- function Get_First_Stub (Body_Node : Node_Id) return Node_Id; function Get_Next_Stub (Stub_Node : Node_Id) return Node_Id; -- these two functions implement the iterator through the body stubs -- contained in the given compilation unit. The iterator should -- be started from calling Get_First_Stub for the node pointed to -- the body (that is, for the node of ..._Body kind). The Empty node -- is returned if there is no first/next body stub node procedure Set_All_Unit_Dependencies (U : Unit_Id); -- Computes the full lists of supporters and dependents of U in the current -- Context from the list of direct supporters of U and sets these lists as -- values of Supporters and Dependents lists in the Unit Table procedure Add_Unit_Supporters (U : Unit_Id; L : in out Elist_Id); -- Add all the supporters of U, excluding U itself to L. This procedure -- traverses all the transitive semantic dependencies. procedure Fix_Direct_Supporters (Unit : Unit_Id); -- This procedure adds missed direct dependencies to the unit. It is -- supposed that before the call the list of direct supporters contains -- only units extracted from the unit context clause. So, if U is a body, -- this procedure adds the spec to the list of direct supporters, if it is -- a subunit - the parent body is added, if it is a child unit - the -- parent spec is added etc. The procedure adds these supporters in a -- transitive manner - that is, in case of a subunit, it adds the parent -- body, its spec (if any), its parent (if any) etc. -- This function supposes that Current Context is correctly set before -- the call. function In_List (U : Unit_Id; L : Unit_Id_List; Up_To : Natural) return Boolean; -- Checks if U is a member of the first Up_To components of L. (If -- Up_To is 0, False is returned procedure CU_To_Unit_Id_List (CU_List : Compilation_Unit_List; Result_Unit_Id_List : in out Unit_Id_List; Result_List_Len : out Natural); -- Converts the ASIS Compilation Unit list into the list of Unit Ids and -- places this list into Result_Unit_Id_List. (Probably, we should replace -- this routine with a function...) -- For each ASIS Compilation Unit from CU_List the Result_Unit_Id_List -- contains exactly one Id for the corresponding unit. Result_List_Len is -- set to represent the index of the last Unit Id in Result_List_Len (0 -- in case if Result_List_Len is empty). This routine expects that -- Result_Unit_Id_List'Length >= CU_List'Length -------------------------------------- -- Dynamic Unit_Id list abstraction -- -------------------------------------- -- All the subprograms implementing Unit_Id list abstraction do not -- reset Context -- Is this package body the right place for defining this abstraction? -- May be, we should move it into A4G.A_Types??? type Unit_Id_List_Access is access Unit_Id_List; Tmp_Unit_Id_List_Access : Unit_Id_List_Access; procedure Free is new Ada.Unchecked_Deallocation (Unit_Id_List, Unit_Id_List_Access); function In_Unit_Id_List (U : Unit_Id; L : Unit_Id_List_Access) return Boolean; -- Checks if U is a member of L. procedure Append_Unit_To_List (U : Unit_Id; L : in out Unit_Id_List_Access); -- (Unconditionally) appends U to L. procedure Add_To_Unit_Id_List (U : Unit_Id; L : in out Unit_Id_List_Access); -- If not In_Unit_Id_List (U, L), U is appended to L (if L is null, -- new Unit_Id_List value is created) procedure Reorder_Sem_Dependencies (Units : Unit_Id_List_Access); -- This procedure takes the unit list with is supposed to be the result of -- one of the Set_All_ functions above (that is, its parameter -- is not supposed to be null and it contains only existing units). It -- reorders it in the way required by -- Asis.Compilation_Units.Relations.Semantic_Dependence_Order - that is, -- with no forward semantic dependencies. ------------------- -- Add_To_Parent -- ------------------- procedure Add_To_Parent (C : Context_Id; U : Unit_Id) is Parent_Id : Unit_Id; Unit_Kind : constant Unit_Kinds := Kind (C, U); begin if U = Standard_Id then return; end if; Reset_Context (C); -- ??? Get_Name_String (U, Norm_Ada_Name); if Not_Root then Form_Parent_Name; if Unit_Kind in A_Subunit then A_Name_Buffer (A_Name_Len) := 'b'; end if; Parent_Id := Name_Find (C); -- Parent_Id cannot be Nil_Unit here Append_Elmt (Unit => U, To => Unit_Table.Table (Parent_Id).Subunits_Or_Childs); else Append_Elmt (Unit => U, To => Unit_Table.Table (Standard_Id).Subunits_Or_Childs); end if; end Add_To_Parent; ------------------------- -- Add_Unit_Supporters -- ------------------------- procedure Add_Unit_Supporters (U : Unit_Id; L : in out Elist_Id) is Supporters : Elist_Id renames Unit_Table.Table (U).Supporters; Direct_Supporters : Elist_Id renames Unit_Table.Table (U).Direct_Supporters; Next_Support_Elmt : Elmt_Id; Next_Support_Unit : Unit_Id; begin if Is_Empty_Elmt_List (Direct_Supporters) then -- end of the recursion return; elsif not Is_Empty_Elmt_List (Supporters) then -- no need to traverse indirect dependencies Next_Support_Elmt := First_Elmt (Supporters); while Present (Next_Support_Elmt) loop Next_Support_Unit := Unit (Next_Support_Elmt); Add_To_Elmt_List (Unit => Next_Support_Unit, List => L); Next_Support_Elmt := Next_Elmt (Next_Support_Elmt); end loop; else -- And here we have to traverse the recursive dependencies: Next_Support_Elmt := First_Elmt (Direct_Supporters); while Present (Next_Support_Elmt) loop Next_Support_Unit := Unit (Next_Support_Elmt); -- The old code currently commented out caused a huge delay -- when opening one tree context (8326-002). We will keep it -- till the new code is tested for queries from -- Asis.Compilation_Units.Relations -- ???Old code start -- Here we can not be sure, that if Next_Support_Unit already -- is in the list, all its supporters also are in the list -- Add_To_Elmt_List -- (Unit => Next_Support_Unit, -- List => L); -- Add_Unit_Supporters (Next_Support_Unit, L); -- ???Old code end -- ???New code start if not In_Elmt_List (Next_Support_Unit, L) then Append_Elmt (Unit => Next_Support_Unit, To => L); Add_Unit_Supporters (Next_Support_Unit, L); end if; -- ???New code end Next_Support_Elmt := Next_Elmt (Next_Support_Elmt); end loop; end if; end Add_Unit_Supporters; ------------------------- -- Append_Subunit_Name -- ------------------------- procedure Append_Subunit_Name (Def_S_Name : Node_Id) is begin -- Here we need unqualified name, because the name -- which comes from the stub is qualified by parent body -- name Get_Unqualified_Decoded_Name_String (Chars (Def_S_Name)); A_Name_Buffer (A_Name_Len - 1) := '.'; A_Name_Buffer (A_Name_Len .. A_Name_Len + Name_Len - 1) := Name_Buffer (1 .. Name_Len); A_Name_Len := A_Name_Len + Name_Len + 1; A_Name_Buffer (A_Name_Len - 1) := '%'; A_Name_Buffer (A_Name_Len) := 'b'; end Append_Subunit_Name; ------------------------ -- CU_To_Unit_Id_List -- ------------------------ procedure CU_To_Unit_Id_List (CU_List : Compilation_Unit_List; Result_Unit_Id_List : in out Unit_Id_List; Result_List_Len : out Natural) is Next_Unit : Unit_Id; begin Result_List_Len := 0; for I in CU_List'Range loop Next_Unit := Get_Unit_Id (CU_List (I)); if not In_List (Next_Unit, Result_Unit_Id_List, Result_List_Len) then Result_List_Len := Result_List_Len + 1; Result_Unit_Id_List (Result_List_Len) := Next_Unit; end if; end loop; end CU_To_Unit_Id_List; --------------------------- -- Fix_Direct_Supporters -- --------------------------- procedure Fix_Direct_Supporters (Unit : Unit_Id) is function Next_Supporter (U : Unit_Id) return Unit_Id; -- Computes the next supporter to be added (from subunit to the parent -- body, from body to the spec, from child to the parent etc). Ends up -- with Standard and then with Nil_Unit as its parent Next_Supporter_Id : Unit_Id; function Next_Supporter (U : Unit_Id) return Unit_Id is C : constant Context_Id := Current_Context; Arg_Unit_Kind : constant Unit_Kinds := Kind (C, U); Result_Id : Unit_Id := Nil_Unit; begin case Arg_Unit_Kind is when A_Procedure | A_Function | A_Package | A_Generic_Procedure | A_Generic_Function | A_Generic_Package | A_Procedure_Instance | A_Function_Instance | A_Package_Instance | A_Procedure_Renaming | A_Function_Renaming | A_Package_Renaming | A_Generic_Procedure_Renaming | A_Generic_Function_Renaming | A_Generic_Package_Renaming => Result_Id := Get_Parent_Unit (C, U); when A_Procedure_Body | A_Function_Body => if Class (C, U) = A_Public_Declaration_And_Body then Result_Id := Get_Parent_Unit (C, U); else Result_Id := Get_Declaration (C, U); end if; when A_Package_Body => Result_Id := Get_Declaration (C, U); when A_Procedure_Body_Subunit | A_Function_Body_Subunit | A_Package_Body_Subunit | A_Task_Body_Subunit | A_Protected_Body_Subunit => Result_Id := Get_Subunit_Parent_Body (C, U); when others => pragma Assert (False); null; end case; return Result_Id; end Next_Supporter; begin Next_Supporter_Id := Next_Supporter (Unit); while Present (Next_Supporter_Id) loop Append_Elmt (Unit => Next_Supporter_Id, To => Unit_Table.Table (Unit).Direct_Supporters); Next_Supporter_Id := Next_Supporter (Next_Supporter_Id); end loop; end Fix_Direct_Supporters; -------------------- -- Get_First_Stub -- -------------------- function Get_First_Stub (Body_Node : Node_Id) return Node_Id is Decls : List_Id; Decl : Node_Id; begin Decls := Declarations (Body_Node); if No (Decls) then return Empty; else Decl := Nlists.First (Decls); while Present (Decl) loop if Nkind (Decl) in N_Body_Stub then return Decl; end if; Decl := Next (Decl); end loop; return Empty; end if; end Get_First_Stub; ------------------- -- Get_Next_Stub -- ------------------- function Get_Next_Stub (Stub_Node : Node_Id) return Node_Id is Next_Decl : Node_Id; begin Next_Decl := Next (Stub_Node); while Present (Next_Decl) loop if Nkind (Next_Decl) in N_Body_Stub then return Next_Decl; end if; Next_Decl := Next (Next_Decl); end loop; return Empty; end Get_Next_Stub; ------------- -- In_List -- ------------- function In_List (U : Unit_Id; L : Unit_Id_List; Up_To : Natural) return Boolean is Len : constant Natural := Natural'Min (Up_To, L'Length); Result : Boolean := False; begin for I in 1 .. Len loop if L (I) = U then Result := True; exit; end if; end loop; return Result; end In_List; ------------------ -- Process_Stub -- ------------------ procedure Process_Stub (C : Context_Id; U : Unit_Id; Stub : Node_Id) is Def_S_Name : Node_Id; Subunit_Id : Unit_Id; begin -- We should save (and then restore) the content of A_Name_Buffer in -- case when more than one stub is to be processed. (A_Name_Buffer -- contains the Ada name of the parent body) NB_Save; if Nkind (Stub) = N_Subprogram_Body_Stub then Def_S_Name := Defining_Unit_Name (Specification (Stub)); else Def_S_Name := Defining_Identifier (Stub); end if; Append_Subunit_Name (Def_S_Name); Subunit_Id := Name_Find (C); if No (Subunit_Id) then Subunit_Id := Allocate_Nonexistent_Unit_Entry (C); Append_Elmt (Unit => Subunit_Id, To => Unit_Table.Table (U).Subunits_Or_Childs); end if; NB_Restore; end Process_Stub; ------------------------------ -- Reorder_Sem_Dependencies -- ------------------------------ procedure Reorder_Sem_Dependencies (Units : Unit_Id_List_Access) is More_Inversion : Boolean := True; Tmp_Unit : Unit_Id; begin if Units'Length = 0 then return; end if; -- The idea is simple: for all the units in Units list we have the -- lists of all the unit's supporters already computed. If we order -- units so that the lengths of supporter lists will increase we will -- get the order in which there will be no forward semantic -- dependencies: if unit A depends on unit B, then A also depends on -- all the supporters of B, so it has the list of supporters longer -- then B has while More_Inversion loop More_Inversion := False; for J in Units'First .. Units'Last - 1 loop if List_Length (Unit_Table.Table (Units (J)).Supporters) > List_Length (Unit_Table.Table (Units (J + 1)).Supporters) then Tmp_Unit := Units (J + 1); Units (J + 1) := Units (J); Units (J) := Tmp_Unit; More_Inversion := True; end if; end loop; end loop; end Reorder_Sem_Dependencies; -------------------------- -- Set_All_Dependencies -- -------------------------- procedure Set_All_Dependencies (Use_First_New_Unit : Boolean := False) is Starting_Unit : Unit_Id; begin if Use_First_New_Unit then Starting_Unit := First_New_Unit; if No (Starting_Unit) then -- This may happen, when, for the incremental Context, we -- process the tree which is the main tree for some body unit, -- and this body unit has been already included in the Context -- (See Lib (spec, (h)) return; end if; else Starting_Unit := Config_Comp_Id + 1; -- Config_Comp_Id corresponds to last predefined unit set in the -- unit table end if; for U in Starting_Unit .. Last_Unit loop Set_All_Unit_Dependencies (U); end loop; end Set_All_Dependencies; ------------------------------- -- Set_All_Unit_Dependencies -- ------------------------------- procedure Set_All_Unit_Dependencies (U : Unit_Id) is Supporters : Elist_Id renames Unit_Table.Table (U).Supporters; Direct_Supporters : Elist_Id renames Unit_Table.Table (U).Direct_Supporters; Next_Support_Elmt : Elmt_Id; Next_Support_Unit : Unit_Id; begin Fix_Direct_Supporters (U); -- Setting all the unit supporters Next_Support_Elmt := First_Elmt (Direct_Supporters); while Present (Next_Support_Elmt) loop Next_Support_Unit := Unit (Next_Support_Elmt); -- If Next_Support_Unit already is in Supporters list, -- all its supporters also are already included in Supporters. if not In_Elmt_List (Next_Support_Unit, Supporters) then Append_Elmt (Unit => Next_Support_Unit, To => Supporters); Add_Unit_Supporters (Next_Support_Unit, Supporters); end if; Next_Support_Elmt := Next_Elmt (Next_Support_Elmt); end loop; -- And now - adding U as depended unit to the list of Dependents for -- all its supporters Next_Support_Elmt := First_Elmt (Supporters); while Present (Next_Support_Elmt) loop Next_Support_Unit := Unit (Next_Support_Elmt); Append_Elmt (Unit => U, To => Unit_Table.Table (Next_Support_Unit).Dependents); Next_Support_Elmt := Next_Elmt (Next_Support_Elmt); end loop; end Set_All_Unit_Dependencies; --------------------------- -- Set_Direct_Dependents -- --------------------------- procedure Set_Direct_Dependents (U : Unit_Id) is Next_Support_Elmt : Elmt_Id; Next_Support_Unit : Unit_Id; begin Next_Support_Elmt := First_Elmt (Unit_Table.Table (U).Direct_Supporters); while Present (Next_Support_Elmt) loop Next_Support_Unit := Unit (Next_Support_Elmt); Append_Elmt (Unit => U, To => Unit_Table.Table (Next_Support_Unit).Direct_Dependents); Next_Support_Elmt := Next_Elmt (Next_Support_Elmt); end loop; end Set_Direct_Dependents; ----------------------- -- Set_All_Ancestors -- ----------------------- procedure Set_All_Ancestors (Compilation_Units : Asis.Compilation_Unit_List; Result : in out Compilation_Unit_List_Access) is Cont : constant Context_Id := Current_Context; Arg_List : Unit_Id_List (1 .. Compilation_Units'Length) := (others => Nil_Unit); Arg_List_Len : Natural := 0; Result_List : Unit_Id_List_Access := null; Next_Ancestor_Unit : Unit_Id; begin -- For the current version, we are supposing, that we have only one -- Context opened at a time CU_To_Unit_Id_List (Compilation_Units, Arg_List, Arg_List_Len); -- Standard is an ancestor of any unit, and if we are here, -- Compilation_Units can not be Nil_Compilation_Unit_List. So we set -- it as the first element of the result list: Append_Unit_To_List (Standard_Id, Result_List); for I in 1 .. Arg_List_Len loop Next_Ancestor_Unit := Arg_List (I); if Next_Ancestor_Unit /= Standard_Id then while Kind (Cont, Next_Ancestor_Unit) in A_Subunit loop Next_Ancestor_Unit := Get_Subunit_Parent_Body (Cont, Next_Ancestor_Unit); end loop; if Class (Cont, Next_Ancestor_Unit) = A_Public_Body or else Class (Cont, Next_Ancestor_Unit) = A_Private_Body then Next_Ancestor_Unit := Get_Declaration (Cont, Next_Ancestor_Unit); end if; while Next_Ancestor_Unit /= Standard_Id loop if not In_Unit_Id_List (Next_Ancestor_Unit, Result_List) then Append_Unit_To_List (Next_Ancestor_Unit, Result_List); Next_Ancestor_Unit := Get_Parent_Unit (Cont, Next_Ancestor_Unit); else exit; end if; end loop; end if; end loop; -- And here we have to order Result_List to eliminate forward -- semantic dependencies -- Result_List can not be null - it contains at least Standard_Id Reorder_Sem_Dependencies (Result_List); Result := new Compilation_Unit_List' (Get_Comp_Unit_List (Result_List.all, Cont)); Free (Result_List); end Set_All_Ancestors; ------------------------ -- Set_All_Dependents -- ------------------------ procedure Set_All_Dependents (Compilation_Units : Asis.Compilation_Unit_List; Dependent_Units : Asis.Compilation_Unit_List; Result : in out Compilation_Unit_List_Access) is Cont : constant Context_Id := Current_Context; Arg_List : Unit_Id_List (1 .. Compilation_Units'Length) := (others => Nil_Unit); Arg_List_Len : Natural := 0; Dep_List : Unit_Id_List (1 .. Dependent_Units'Length) := (others => Nil_Unit); Dep_List_Len : Natural := 0; Result_List : Unit_Id_List_Access := null; Next_Dependent_Elmt : Elmt_Id; Next_Dependent_Unit : Unit_Id; begin -- For the current version, we are supposing, that we have only one -- Context opened at a time CU_To_Unit_Id_List (Compilation_Units, Arg_List, Arg_List_Len); CU_To_Unit_Id_List (Dependent_Units, Dep_List, Dep_List_Len); -- Now, collecting all the dependents for Compilation_Units for I in 1 .. Arg_List_Len loop Next_Dependent_Elmt := First_Elmt (Unit_Table.Table (Arg_List (I)).Dependents); while Present (Next_Dependent_Elmt) loop Next_Dependent_Unit := Unit (Next_Dependent_Elmt); if Dep_List_Len = 0 or else In_List (Next_Dependent_Unit, Dep_List, Dep_List_Len) then Add_To_Unit_Id_List (Next_Dependent_Unit, Result_List); end if; Next_Dependent_Elmt := Next_Elmt (Next_Dependent_Elmt); end loop; end loop; -- And here we have to order Result_List to eliminate forward -- semantic dependencies if Result_List /= null then Reorder_Sem_Dependencies (Result_List); Result := new Compilation_Unit_List' (Get_Comp_Unit_List (Result_List.all, Cont)); Free (Result_List); else Result := new Compilation_Unit_List (1 .. 0); end if; end Set_All_Dependents; ------------------------- -- Set_All_Descendants -- ------------------------- procedure Set_All_Descendants (Compilation_Units : Asis.Compilation_Unit_List; Result : in out Compilation_Unit_List_Access) is Cont : constant Context_Id := Current_Context; Arg_List : Unit_Id_List (1 .. Compilation_Units'Length) := (others => Nil_Unit); Arg_List_Len : Natural := 0; Result_List : Unit_Id_List_Access := null; Next_Descendant_Elmt : Elmt_Id; Next_Unit : Unit_Id; procedure Add_All_Descendants (Desc_Unit : Unit_Id; Result_List : in out Unit_Id_List_Access); -- If Desc_Unit is not in Result_List, this procedure adds it and -- (recursively) all its descendants which are not in Result_List to -- the list. procedure Add_All_Descendants (Desc_Unit : Unit_Id; Result_List : in out Unit_Id_List_Access) is Child_Elmt : Elmt_Id; Child_Unit : Unit_Id; begin if not In_Unit_Id_List (Desc_Unit, Result_List) then Append_Unit_To_List (Desc_Unit, Result_List); if Kind (Cont, Desc_Unit) = A_Package or else Kind (Cont, Desc_Unit) = A_Generic_Package or else Kind (Cont, Desc_Unit) = A_Package_Renaming or else Kind (Cont, Desc_Unit) = A_Generic_Package_Renaming then Child_Elmt := First_Elmt (Unit_Table.Table (Desc_Unit).Subunits_Or_Childs); while Present (Child_Elmt) loop Child_Unit := Unit (Child_Elmt); Add_All_Descendants (Child_Unit, Result_List); Child_Elmt := Next_Elmt (Child_Elmt); end loop; end if; end if; end Add_All_Descendants; begin -- We can not use CU_To_Unit_Id_List routine, because we have to -- filter out subunits, nonexistent units (?) and bodies for which the -- Context does not contain a spec - such units can not have -- descendants. For bodies, only the corresponding specs contain the -- lists of descendants. for I in Compilation_Units'Range loop Next_Unit := Get_Unit_Id (Compilation_Units (I)); if Kind (Cont, Next_Unit) not in A_Procedure_Body_Subunit .. A_Nonexistent_Body then if Kind (Cont, Next_Unit) in A_Library_Unit_Body then Next_Unit := Get_Declaration (Cont, Next_Unit); end if; if Present (Next_Unit) and then (not In_List (Next_Unit, Arg_List, Arg_List_Len)) then Arg_List_Len := Arg_List_Len + 1; Arg_List (Arg_List_Len) := Next_Unit; end if; end if; end loop; for J in 1 .. Arg_List_Len loop Next_Descendant_Elmt := First_Elmt (Unit_Table.Table (Arg_List (J)).Subunits_Or_Childs); while Present (Next_Descendant_Elmt) loop Next_Unit := Unit (Next_Descendant_Elmt); Add_All_Descendants (Next_Unit, Result_List); Next_Descendant_Elmt := Next_Elmt (Next_Descendant_Elmt); end loop; end loop; if Result_List /= null then Reorder_Sem_Dependencies (Result_List); Result := new Compilation_Unit_List' (Get_Comp_Unit_List (Result_List.all, Cont)); Free (Result_List); else Result := new Compilation_Unit_List (1 .. 0); end if; end Set_All_Descendants; ---------------------- -- Set_All_Families -- ---------------------- procedure Set_All_Families (Compilation_Units : Asis.Compilation_Unit_List; Result : in out Compilation_Unit_List_Access) is Cont : constant Context_Id := Current_Context; Arg_List : Unit_Id_List (1 .. Compilation_Units'Length) := (others => Nil_Unit); Arg_List_Len : Natural := 0; Result_List : Unit_Id_List_Access := null; procedure Collect_Spec_Family (Spec_Unit : Unit_Id; Result_List : in out Unit_Id_List_Access); -- If Spec_Unit is not in Result_List, this procedure adds it and -- (recursively) all members of its family which are not in Result_List -- to the list. In case of a spec, the corresponding body's family is -- also added procedure Collect_Body_Family (Body_Unit : Unit_Id; Result_List : in out Unit_Id_List_Access); -- If Body_Unit is not in Result_List, this procedure adds it and -- (recursively) all members of its family which are not in Result_List -- to the list. In case of a body, only the subunit tree rooted by this -- body may be added procedure Collect_Spec_Family (Spec_Unit : Unit_Id; Result_List : in out Unit_Id_List_Access) is Child_Elmt : Elmt_Id; Child_Unit : Unit_Id; begin if not In_Unit_Id_List (Spec_Unit, Result_List) then Append_Unit_To_List (Spec_Unit, Result_List); -- We have to add all descendants (if any) and their families if Kind (Cont, Spec_Unit) = A_Package or else Kind (Cont, Spec_Unit) = A_Generic_Package or else Kind (Cont, Spec_Unit) = A_Package_Renaming or else Kind (Cont, Spec_Unit) = A_Generic_Package_Renaming then Child_Elmt := First_Elmt (Unit_Table.Table (Spec_Unit).Subunits_Or_Childs); while Present (Child_Elmt) loop Child_Unit := Unit (Child_Elmt); if Kind (Cont, Child_Unit) in A_Procedure .. A_Generic_Package_Renaming then Collect_Spec_Family (Child_Unit, Result_List); elsif Kind (Cont, Child_Unit) in A_Procedure_Body .. A_Protected_Body_Subunit then Collect_Body_Family (Child_Unit, Result_List); end if; Child_Elmt := Next_Elmt (Child_Elmt); end loop; end if; end if; end Collect_Spec_Family; procedure Collect_Body_Family (Body_Unit : Unit_Id; Result_List : in out Unit_Id_List_Access) is Child_Elmt : Elmt_Id; Child_Unit : Unit_Id; begin if not In_Unit_Id_List (Body_Unit, Result_List) then Append_Unit_To_List (Body_Unit, Result_List); -- We have to add all descendants (if any) and their families if Kind (Cont, Body_Unit) in A_Procedure_Body .. A_Protected_Body_Subunit then Child_Elmt := First_Elmt (Unit_Table.Table (Body_Unit).Subunits_Or_Childs); while Present (Child_Elmt) loop Child_Unit := Unit (Child_Elmt); Collect_Body_Family (Child_Unit, Result_List); Child_Elmt := Next_Elmt (Child_Elmt); end loop; end if; end if; end Collect_Body_Family; begin CU_To_Unit_Id_List (Compilation_Units, Arg_List, Arg_List_Len); for J in 1 .. Arg_List_Len loop case Class (Cont, Arg_List (J)) is when A_Public_Declaration | A_Private_Declaration => Collect_Spec_Family (Arg_List (J), Result_List); when Not_A_Class => -- This should never happen, so just in case we -- raise an exception null; pragma Assert (False); when others => -- Here we can have only a body or a separate body Collect_Body_Family (Arg_List (J), Result_List); end case; end loop; -- And here we have to order Result_List to eliminate forward -- semantic dependencies if Result_List /= null then Reorder_Sem_Dependencies (Result_List); Result := new Compilation_Unit_List' (Get_Comp_Unit_List (Result_List.all, Cont)); Free (Result_List); else Result := new Compilation_Unit_List (1 .. 0); end if; end Set_All_Families; ------------------------ -- Set_All_Supporters -- ------------------------ package Unit_Container is new Ada.Containers.Ordered_Sets (Element_Type => Unit_Id); procedure Unit_List_To_Set (Unit_List : Elist_Id; Unit_Set : in out Unit_Container.Set); -- Assuming that Unit_List does not contain repeating elements, creates -- Unit_Set as the set containing Unit IDs from Unit_List. If Unit_Set is -- non-empty before the call, the old content of the set is lost. function Unit_Set_To_List (Unit_Set : Unit_Container.Set) return Unit_Id_List; -- Converts the unit id set into array Result_Set : Unit_Container.Set; New_Set : Unit_Container.Set; Newer_Set : Unit_Container.Set; Next_Direct_Supporter : Unit_Container.Cursor; procedure Unit_List_To_Set (Unit_List : Elist_Id; Unit_Set : in out Unit_Container.Set) is Next_El : Elmt_Id; begin Unit_Container.Clear (Unit_Set); Next_El := First_Elmt (Unit_List); while Present (Next_El) loop Unit_Container.Insert (Unit_Set, Unit (Next_El)); Next_El := Next_Elmt (Next_El); end loop; end Unit_List_To_Set; function Unit_Set_To_List (Unit_Set : Unit_Container.Set) return Unit_Id_List is Next_Unit : Unit_Container.Cursor; Result : Unit_Id_List (1 .. Natural (Unit_Container.Length (Unit_Set))); Next_Idx : Natural := Result'First; begin Next_Unit := Unit_Container.First (Unit_Set); while Unit_Container.Has_Element (Next_Unit) loop Result (Next_Idx) := Unit_Container.Element (Next_Unit); Next_Idx := Next_Idx + 1; Next_Unit := Unit_Container.Next (Next_Unit); end loop; return Result; end Unit_Set_To_List; procedure Set_All_Supporters (Compilation_Units : Asis.Compilation_Unit_List; Result : in out Compilation_Unit_List_Access) is Cont : constant Context_Id := Current_Context; Arg_List : Unit_Id_List (1 .. Compilation_Units'Length) := (others => Nil_Unit); Result_List : Unit_Id_List_Access := null; Arg_List_Len : Natural := 0; pragma Unreferenced (Arg_List_Len); procedure Collect_Supporters (U : Unit_Id); -- If U is not presented in Result, adds (recursively) all its -- supporters to Result_List -- Uses workpile algorithm to avoid cycling (cycling is possible because -- of limited with) procedure Collect_Supporters (U : Unit_Id) is Next_Supporter : Elmt_Id; begin Unit_Container.Clear (New_Set); Unit_Container.Clear (Newer_Set); Unit_List_To_Set (Unit_List => Unit_Table.Table (U).Supporters, Unit_Set => New_Set); Unit_Container.Union (Target => Result_Set, Source => New_Set); while not Unit_Container.Is_Empty (New_Set) loop Next_Direct_Supporter := Unit_Container.First (New_Set); Next_Supporter := First_Elmt (Unit_Table.Table (Unit_Container.Element (Next_Direct_Supporter)).Supporters); while Present (Next_Supporter) loop if not Unit_Container.Contains (Result_Set, Unit (Next_Supporter)) then Unit_Container.Insert (Newer_Set, Unit (Next_Supporter)); end if; Next_Supporter := Next_Elmt (Next_Supporter); end loop; Unit_Container.Delete_First (New_Set); if not Unit_Container.Is_Empty (Newer_Set) then Unit_Container.Union (Result_Set, Newer_Set); Unit_Container.Union (New_Set, Newer_Set); Unit_Container.Clear (Newer_Set); end if; end loop; end Collect_Supporters; begin Unit_Container.Clear (Result_Set); Unit_Container.Insert (Result_Set, Standard_Id); -- For the current version, we are supposing, that we have only one -- Context opened at a time CU_To_Unit_Id_List (Compilation_Units, Arg_List, Arg_List_Len); -- Now, collecting all the supporters for Compilation_Units -- Standard is a supporter of any unit, and if we are here, -- Compilation_Units can not be Nil_Compilation_Unit_List. So we set -- it as the first element of the result list: for J in Compilation_Units'Range loop Collect_Supporters (Get_Unit_Id (Compilation_Units (J))); end loop; Result_List := new Unit_Id_List'(Unit_Set_To_List (Result_Set)); -- And here we have to order Result_List to eliminate forward -- semantic dependencies -- Result_List can not be null - it contains at least Standard_Id Reorder_Sem_Dependencies (Result_List); Result := new Compilation_Unit_List' (Get_Comp_Unit_List (Result_List.all, Cont)); Free (Result_List); end Set_All_Supporters; -------------------------- -- Set_All_Needed_Units -- -------------------------- procedure Set_All_Needed_Units (Compilation_Units : Asis.Compilation_Unit_List; Result : in out Compilation_Unit_List_Access; Missed : in out Compilation_Unit_List_Access) is Cont : constant Context_Id := Current_Context; Cont_Tree_Mode : constant Tree_Mode := Tree_Processing_Mode (Cont); Arg_List : Unit_Id_List (1 .. Compilation_Units'Length) := (others => Nil_Unit); Arg_List_Len : Natural := 0; Result_List : Unit_Id_List_Access := null; Missed_List : Unit_Id_List_Access := null; procedure Set_One_Unit (U : Unit_Id); -- Provided that U is an (existing) unit which is not in the -- Result_List, this procedure adds this unit and all the units -- needed by it to result lists. procedure Add_Needed_By_Spec (Spec_Unit : Unit_Id); -- Provided that Spec_Unit denotes an (existing) spec, this procedure -- adds to the result lists units which are needed by this unit only, -- that is, excluding this unit (it is supposed to be already added at -- the moment of the call), its body and units needed by the body (if -- any, they are processed separately) procedure Add_Needed_By_Body (Body_Unit : Unit_Id); -- Provided that Body_Unit denotes an (existing) body, this procedure -- adds to the result lists units which are needed by this unit, -- excluding the unit itself (it is supposed to be already added at -- the moment of the call). That is, the spec of this unit and units -- which are needed by the spec (if any) are also needed, if they have -- not been added before ------------------------ -- Add_Needed_By_Body -- ------------------------ procedure Add_Needed_By_Body (Body_Unit : Unit_Id) is Spec_Unit : Unit_Id; Subunit_List : constant Unit_Id_List := Subunits (Cont, Body_Unit); Next_Support_Elmt : Elmt_Id; Next_Support_Unit : Unit_Id; begin -- First, check if there is a separate spec then it has to be -- processed if Class (Cont, Body_Unit) /= A_Public_Declaration_And_Body then Spec_Unit := Body_Unit; while Class (Cont, Spec_Unit) = A_Separate_Body loop Spec_Unit := Get_Subunit_Parent_Body (Cont, Spec_Unit); end loop; Spec_Unit := Get_Declaration (Cont, Spec_Unit); -- We can not get Nil or nonexistent unit here if not In_Unit_Id_List (Spec_Unit, Result_List) then Add_Needed_By_Spec (Spec_Unit); end if; end if; -- Now process body's supporters: Next_Support_Elmt := First_Elmt (Unit_Table.Table (Body_Unit).Supporters); while Present (Next_Support_Elmt) loop Next_Support_Unit := Unit (Next_Support_Elmt); if not In_Unit_Id_List (Next_Support_Unit, Result_List) then Set_One_Unit (Next_Support_Unit); end if; Next_Support_Elmt := Next_Elmt (Next_Support_Elmt); end loop; -- And, finally, subunits: for J in Subunit_List'Range loop if Kind (Cont, Subunit_List (J)) = A_Nonexistent_Body then Append_Unit_To_List (Subunit_List (J), Missed_List); elsif not In_Unit_Id_List (Subunit_List (J), Result_List) then Append_Unit_To_List (Subunit_List (J), Result_List); Add_Needed_By_Body (Subunit_List (J)); end if; end loop; end Add_Needed_By_Body; ------------------------ -- Add_Needed_By_Spec -- ------------------------ procedure Add_Needed_By_Spec (Spec_Unit : Unit_Id) is Next_Support_Elmt : Elmt_Id; Next_Support_Unit : Unit_Id; begin Next_Support_Elmt := First_Elmt (Unit_Table.Table (Spec_Unit).Supporters); while Present (Next_Support_Elmt) loop Next_Support_Unit := Unit (Next_Support_Elmt); if not In_Unit_Id_List (Next_Support_Unit, Result_List) then Set_One_Unit (Next_Support_Unit); end if; Next_Support_Elmt := Next_Elmt (Next_Support_Elmt); end loop; end Add_Needed_By_Spec; ------------------ -- Set_One_Unit -- ------------------ procedure Set_One_Unit (U : Unit_Id) is U_Body : Unit_Id; begin Append_Unit_To_List (U, Result_List); case Class (Cont, U) is when A_Public_Declaration | A_Private_Declaration => Add_Needed_By_Spec (U); if Is_Body_Required (Cont, U) then U_Body := Get_Body (Cont, U); if No (U_Body) and then (Cont_Tree_Mode = On_The_Fly or else Cont_Tree_Mode = Mixed) then -- Is it a correct thing to compile something on the fly -- Inside the query from Relations??? U_Body := Get_One_Unit (Name => To_Program_Text (Unit_Name (Get_Comp_Unit (U, Cont))), Context => Cont, Spec => False); end if; if Present (U_Body) then if Kind (Cont, U_Body) in A_Nonexistent_Declaration .. A_Nonexistent_Body then Add_To_Unit_Id_List (U_Body, Missed_List); elsif not In_Unit_Id_List (U_Body, Result_List) then Append_Unit_To_List (U_Body, Result_List); Add_Needed_By_Body (U_Body); end if; else U_Body := Get_Nonexistent_Unit (Cont); Append_Unit_To_List (U_Body, Missed_List); end if; end if; when Not_A_Class => -- This should never happen, so just in case we -- raise an exception null; pragma Assert (False); when others => Add_Needed_By_Body (U); end case; end Set_One_Unit; begin -- Set_All_Needed_Units CU_To_Unit_Id_List (Compilation_Units, Arg_List, Arg_List_Len); -- Standard is a supporter of any unit, and if we are here, -- Compilation_Units can not be Nil_Compilation_Unit_List. So we set -- it as the first element of the result list: Append_Unit_To_List (Standard_Id, Result_List); for J in 1 .. Arg_List_Len loop if not In_Unit_Id_List (Arg_List (J), Result_List) then Set_One_Unit (Arg_List (J)); end if; end loop; -- Result_List can not be null - it contains at least Standard_Id Reorder_Sem_Dependencies (Result_List); Result := new Compilation_Unit_List' (Get_Comp_Unit_List (Result_List.all, Cont)); Free (Result_List); if Missed_List /= null then Missed := new Compilation_Unit_List' (Get_Comp_Unit_List (Missed_List.all, Cont)); Free (Missed_List); else Missed := new Compilation_Unit_List (1 .. 0); end if; end Set_All_Needed_Units; ------------------ -- Set_Subunits -- ------------------ procedure Set_Subunits (C : Context_Id; U : Unit_Id; Top : Node_Id) is Body_Node : Node_Id; Stub_Node : Node_Id; begin Get_Name_String (U, Norm_Ada_Name); Body_Node := Unit (Top); if Nkind (Body_Node) = N_Subunit then Body_Node := Proper_Body (Body_Node); end if; Stub_Node := Get_First_Stub (Body_Node); if No (Stub_Node) then return; end if; while Present (Stub_Node) loop Process_Stub (C, U, Stub_Node); Stub_Node := Get_Next_Stub (Stub_Node); end loop; Unit_Table.Table (U).Subunits_Computed := True; end Set_Subunits; -------------------- -- Set_Supporters -- -------------------- procedure Set_Supporters (C : Context_Id; U : Unit_Id; Top : Node_Id) is begin Set_Withed_Units (C, U, Top); Set_Direct_Dependents (U); end Set_Supporters; ---------------------- -- Set_Withed_Units -- ---------------------- procedure Set_Withed_Units (C : Context_Id; U : Unit_Id; Top : Node_Id) is With_Clause_Node : Node_Id; Cunit_Node : Node_Id; Cunit_Number : Unit_Number_Type; Current_Supporter : Unit_Id; Tmp : Unit_Id; Include_Unit : Boolean := False; begin -- the maim control structure - cycle through the with clauses -- in the tree if No (Context_Items (Top)) then return; end if; With_Clause_Node := First_Non_Pragma (Context_Items (Top)); while Present (With_Clause_Node) loop -- here we simply get the name of the next supporting unit from -- the GNAT Units Table (defined in Lib) Cunit_Node := Library_Unit (With_Clause_Node); Cunit_Number := Get_Cunit_Unit_Number (Cunit_Node); Get_Decoded_Name_String (Unit_Name (Cunit_Number)); Set_Norm_Ada_Name_String_With_Check (Cunit_Number, Include_Unit); if Include_Unit then Current_Supporter := Name_Find (C); if A_Name_Buffer (A_Name_Len) = 'b' then A_Name_Buffer (A_Name_Len) := 's'; Tmp := Name_Find (C); if Present (Tmp) then -- OPEN PROBLEM: is this the best solution for this problem? -- -- Here we are in the potentially hard-to-report-about and -- definitely involving inconsistent unit set situation. -- The last version of U depends on subprogram body at least -- in one of the consistent trees, but the Context contains -- a spec (that is, a library_unit_declaration or a -- library_unit_renaming_declaration) for the same full -- expanded Ada name. The current working decision is -- to set this dependency as if U depends on the spec. -- -- Another (crazy!) problem: in one consistent tree -- U depends on the package P (and P does not require a -- body), and in another consistent tree U depends on -- the procedure P which is presented by its body only. -- It may be quite possible, if these trees were created -- with different search paths. Is our decision reasonable -- for this crazy situation :-[ ??!!?? Current_Supporter := Tmp; end if; end if; -- and now we store this dependency - we have to use -- Add_To_Elmt_List instead of Append_Elmt - some units -- may be mentioned several times in the context clause: if Implicit_With (With_Clause_Node) then Add_To_Elmt_List (Unit => Current_Supporter, List => Unit_Table.Table (U).Implicit_Supporters); else Add_To_Elmt_List (Unit => Current_Supporter, List => Unit_Table.Table (U).Direct_Supporters); end if; end if; With_Clause_Node := Next_Non_Pragma (With_Clause_Node); while Present (With_Clause_Node) and then Nkind (With_Clause_Node) /= N_With_Clause loop With_Clause_Node := Next_Non_Pragma (With_Clause_Node); end loop; end loop; end Set_Withed_Units; ------------------------------------------------------- -- Dynamic Unit_Id list abstraction (implementation) -- ------------------------------------------------------- ---------------------- -- In_Unit_Id_List -- ---------------------- function In_Unit_Id_List (U : Unit_Id; L : Unit_Id_List_Access) return Boolean is begin if L /= null then for I in L'Range loop if U = L (I) then return True; end if; end loop; end if; return False; end In_Unit_Id_List; -------------------------- -- Add_To_Unit_Id_List -- -------------------------- procedure Add_To_Unit_Id_List (U : Unit_Id; L : in out Unit_Id_List_Access) is begin if not In_Unit_Id_List (U, L) then Append_Unit_To_List (U, L); end if; end Add_To_Unit_Id_List; ------------------------- -- Append_Unit_To_List -- ------------------------- procedure Append_Unit_To_List (U : Unit_Id; L : in out Unit_Id_List_Access) is begin if L = null then L := new Unit_Id_List'(1 => U); else Free (Tmp_Unit_Id_List_Access); Tmp_Unit_Id_List_Access := new Unit_Id_List'(L.all & U); Free (L); L := new Unit_Id_List'(Tmp_Unit_Id_List_Access.all); end if; end Append_Unit_To_List; end A4G.Contt.Dp; ",12526,True,2695.6676547101556,median "= bpftrace(8) :doctype: manpage :toc: true //// Style guide: - one sentence per line //// == Name bpftrace - a high-level tracing language == Synopsis *bpftrace* [_OPTIONS_] _FILENAME_ + *bpftrace* [_OPTIONS_] -e 'program code' == Description bpftrace is a high-level tracing language and runtime for Linux based on BPF. It supports static and dynamic tracing for both the kernel and user-space. When _FILENAME_ is ""_-_"", read from stdin. == Examples List all probes with ""sleep"" in their name:: ---- # bpftrace -l '*sleep*' ---- Trace processes calling sleep:: ---- # bpftrace -e 'kprobe:do_nanosleep { printf(""%d sleeping\\n"", pid); }' ---- Trace processes calling sleep while spawning `sleep 5` as a child process:: ---- # bpftrace -e 'kprobe:do_nanosleep { printf(""%d sleeping\\n"", pid); }' -c 'sleep 5' ---- == Supported architectures x86_64, arm64 and s390x == Options //// Custom prefix to easily link section //// :idprefix: flags_ === Output format *-B* _MODE_:: Set the buffer mode for stdout. Valid values are:: *none* No buffering. Each I/O is written as soon as possible + *line* Data is written on the first newline or when the buffer is full. This is the default mode. + *full* Data is written once the buffer is full. *-f* _FORMAT_:: Set the output format. Valid values are:: *json* + *text* *-o* _FILENAME_:: Write bpftrace tracing output to _FILENAME_ instead of stdout. This doesn't include child process (*-c* option) output. Errors are still written to stderr. *--no-warnings*:: Suppress all warning messages created by bpftrace. === Tracing *-e* _PROGRAM_:: Execute _PROGRAM_ instead of reading the program from a file *-I* _DIR_:: Add the directory _DIR_ to the search path for C headers. This option can be used multiple times. *--include* _FILENAME_:: Add _FILENAME_ as an include for the pre-processor. This is equal to adding '#include _FILENAME_' to the start bpftrace program. This option can be used multiple times. *-l* [_SEARCH_]:: List all probes that match the _SEARCH_ pattern. If the pattern is omitted all probes will be listed. This pattern supports wildcards in the same way that probes do. E.g. '-l kprobe:*file*' to list all 'kprobes' with 'file' in the name. For more details see the <

    > section. *--unsafe*:: Some calls, like 'system', are marked as unsafe as they can have dangerous side effects ('system(""rm -rf"")') and are disabled by default. This flag allows their use. *-k*:: Errors from bpf-helpers(7) are silently ignored by default which can lead to strange results. This flag enables the detection of errors (except for errors from 'probe_read_*'). When errors occurs bpftrace will log an error containing the source location and the error code: ---- stdin:48-57: WARNING: Failed to probe_read_user_str: Bad address (-14) u:lib.so:""fn(char const*)"" { printf(""arg0:%s\\n"", str(arg0));} ~~~~~~~~~ ---- *-kk*:: Same as '-k' but also includes the errors from 'probe_read_*' helpers. === Process management *-p* _PID_:: Attach to the process with _PID_. If the process terminates, bpftrace will also terminate. When using USDT probes they will be attached to only this process. *-c* _COMMAND_:: Run _COMMAND_ as a child process. When the child terminates bpftrace stops as well, as if 'exit()' has been called. If bpftrace terminates before the child process does the child process will be terminated with a SIGTERM. If used, 'USDT' probes these will only be attached to the child process. To avoid a race condition when using 'USDTs' the child is stopped after 'execve' using 'ptrace(2)' and continued when all 'USDT' probes are attached. + The child PID is available to programs as the 'cpid' builtin. + The child process runs with the same privileges as bpftrace itself (usually root). *--usdt-file-activation*:: activate usdt semaphores based on file path === Miscellaneous *--info*:: Print detailed information about features supported by the kernel and the bpftrace build. *-h, --help*:: Print the help summary *-V, --version*:: Print bpftrace version information *-v*:: verbose messages *-d*:: debug mode *-dd*:: verbose debug mode //// ! ! ! This prefix reset must be at the end of the section, else cross references break ! ! //// == Environment Variables Some behavior can only be controlled through environment variables. This section lists all those variables. //// Custom prefix to easily link section //// :idprefix: envvar_ === BPFTRACE_STRLEN Default: 64 Number of bytes allocated on the BPF stack for the string returned by `str()`. Make this larger if you wish to read bigger strings with str(). Beware that the BPF stack is small (512 bytes). Support for even larger strings is [being discussed](https://github.com/iovisor/bpftrace/issues/305). === BPFTRACE_NO_CPP_DEMANGLE Default: 0 C++ symbol demangling in user space stack traces is enabled by default. This feature can be turned off by setting the value of this environment variable to `1`. === BPFTRACE_MAP_KEYS_MAX Default: 4096 This is the maximum number of keys that can be stored in a map. Increasing the value will consume more memory and increase startup times. There are some cases where you will want to: for example, sampling stack traces, recording timestamps for each page, etc. === BPFTRACE_MAX_PROBES Default: 512 This is the maximum number of probes that bpftrace can attach to. Increasing the value will consume more memory, increase startup times and can incur high performance overhead or even freeze or crash the system. === BPFTRACE_CACHE_USER_SYMBOLS Default: 0 if ASLR is enabled on system and `-c` option is not given; otherwise 1 By default, bpftrace caches the results of symbols resolutions only when ASLR (Address Space Layout Randomization) is disabled. This is because the symbol addresses change with each execution with ASLR. However, disabling caching may incur some performance penalty. Set this env variable to 1 to force bpftrace to cache. === BPFTRACE_VMLINUX Default: None This specifies the vmlinux path used for kernel symbol resolution when attaching kprobe to offset. If this value is not given, bpftrace searches vmlinux from pre defined locations. See src/attached_probe.cpp:find_vmlinux() for details. === BPFTRACE_BTF Default: None The path to a BTF file. By default, bpftrace searches several locations to find a BTF file. See src/btf.cpp for the details. === BPFTRACE_PERF_RB_PAGES Default: 64 Number of pages to allocate per CPU for perf ring buffer. The value must be a power of 2. If you're getting a lot of dropped events bpftrace may not be processing events in the ring buffer fast enough. It may be useful to bump the value higher so more events can be queued up. The tradeoff is that bpftrace will use more memory. === BPFTRACE_MAX_BPF_PROGS Default: 512 This is the maximum number of BPF programs (functions) that bpftrace can generate. The main purpose of this limit is to prevent bpftrace from hanging since generating a lot of probes takes a lot of resources (and it should not happen often). //// ! ! ! This prefix reset must be at the end of the section, else cross references break ! ! //// :idprefix: _ //// Custom prefix to easily link to a section //// :idprefix: language_ == bpftrace Language === Overview The `bpftrace` (`bt`) language is inspired by the D language used by `dtrace` and uses the same program structure. Each script consists of an preamble and one or more action blocks. ---- preamble actionblock1 actionblock2 ---- Preprocessor and type definitions take place in the preamble: ---- #include #define RED ""\\033[31m"" struct S { int x; } ---- Each action block consists of three parts: ---- probe[,probe] /predicate/ { action } ---- Probes:: A probe specifies the event and event type to attach too. Predicate:: The predicate is optional condition that must be met for the action to be executed. Action:: Actions are the programs that run when an event fires (and the predicate is met). An action is a semicolon (`;`) separated list of statements and always enclosed by brackets `{}` A basic script that traces the `open(2)` and `openat(2)` system calls can be written as follows: ---- BEGIN { printf(""Tracing open syscalls... Hit Ctrl-C to end.\\n""); } tracepoint:syscalls:sys_enter_open, tracepoint:syscalls:sys_enter_openat { printf(""%-6d %-16s %s\\n"", pid, comm, str(args->filename)); } ---- This script has two action blocks and a total of 3 probes. The first action block uses the special `BEGIN` probe, which fires once during `bpftrace` startup. This probe is used to print a header, indicating that the tracing has started. The second action block uses two probes, one for `open` and one for `openat`, and defines an action that prints the file being `open` ed as well as the `pid` and `comm` of the process that execute the syscall. See the <> section for details on the available probe types. === Identifiers Identifiers must match the following regular expression: `[_a-zA-Z][_a-zA-Z0-9]*` === Comments Both single line and multi line comments are supported. ---- // A single line comment i:s:1 { // can also be used to comment inline /* a multi line comment */ print(/* inline comment block */ 1); } ---- === Data Types The following fundamental integer types are provided by the language. [cols=""~,~""] |=== |*Type* |*Description* |uint8 |Unsigned 8 bit integer |int8 |Signed 8 bit integer |uint16 |Unsigned 16 bit integer |int16 |Signed 16 bit integer |uint32 |Unsigned 32 bit integer |int32 |Signed 32 bit integer |uint64 |Unsigned 64 bit integer |int64 |Signed 64 bit integer |=== ==== Floating-point Floating-point numbers are not supported by BPF and therefore not by bpftrace. === Constants Integers constants can be defined in the following formats: - decimal (base 10) - octal (base 8) - hexadecimal (base 16) - scientific (base 10) Octal constants have to be prefixed with a `0`, e.g. `0123`. Hexadecimal constants start with either `0x` or `0X`, e.g. `0x10`. Scientific are written in the `e` format which is a shorthand for `m*10^n`, e.g. `$i = 2e3;`. Note that scientific literals are integer only due to the lack of floating point support, `1e-3` is not valid. To improve the readability of big literals a underscore `_` can be used as field separator, e.g. 1_000_123_000. Integer suffixes as found in the C language are parsed by bpftrace to ensure compatibility with C headers/definitions but they're not used as size specifiers. `123UL`, `123U` and `123LL` all result in the same integer type with a value of `123`. Character constants can be defined by enclosing the character in single quotes, e.g. `$c = 'c';`. String constants can be defined by enclosing the character string in double quotes, e.g. `$str = ""Hello world"";`. Characters and strings support the following escape sequences: [cols=""~,~""] |=== | \\n |Newline | \\t |Tab | \\0nn |Octal value nn | \\xnn |Hexadecimal value nn |=== === Type conversion Integer and pointer types can be converted using explicit type conversion with an expression like: ---- $y = (uint32) $z; $py = (int16 *) $pz; ---- Integer casts to a higher rank are sign extended. Conversion to a lower rank is done by zeroing leading bits. === Operators and Expressions ==== Arithmetic Operators The following operators are available for integer arithmetic: [cols=""~,~""] |=== | + |integer addition | - |integer subtraction | * |integer multiplication | / |integer division | % |integer modulo |=== // TODO: Words about integer conversion when types mismatch ==== Logical Operators [cols=""~,~""] |=== | && | Logical AND | \\|\\| | Logical OR | ! | Logical NOT |=== ==== Bitwise Operators [cols=""~,~""] |=== | & | AND | \\| | OR | ^ | XOR | << | Left shift the left-hand operand by the number of bits specified by the right-hand expression value | >> | Right shift the left-hand operand by the number of bits specified by the right-hand expression value |=== ==== Relational Operators The following relational operators are defined for integers and pointers. [cols=""~,~""] |=== | < | left-hand expression is less than right-hand | \\<= | left-hand expression is less than or equal to right-hand | > | left-hand expression is bigger than right-hand | >= | left-hand expression is bigger or equal to than right-hand | == | left-hand expression equal to right-hand | != | left-hand expression not equal to right-hand |=== The following relation operators are available for comparing strings. [cols=""~,~""] |=== | == | left-hand string equal to right-hand | != | left-hand string not equal to right-hand |=== ==== Assignment Operators The following assignment operators can be used on both `map` and `scratch` variables: [cols=""~,~""] |=== | = | Assignment, assign the right-hand expression to the left-hand variable | <\\<= | Update the variable with its value left shifted by the number of bits specified by the right-hand expression value | >>= | Update the variable with its value right shifted by the number of bits specified by the right-hand expression value | += | Increment the variable by the right-hand expression value | -= | Decrement the variable by the right-hand expression value | *= | Multiple the variable by the right-hand expression value | /= | Divide the variable by the right-hand expression value | %= | Modulo the variable by the right-hand expression value | &= | Bitwise AND the variable by the right-hand expression value | \\|= | Bitwise OR the variable by the right-hand expression value | ^= | Bitwise XOR the variable by the right-hand expression value |=== All these operators are syntactic sugar for combining assignment with the specified operator. `@ -= 5` is equal to `@ = @ - 5`. ==== Increment and Decrement Operators The increment (`\\++`) and decrement (`--`) operators can be used on integer and pointer variables to increment their value by one. They can only be used on variables and can either be applied as prefix or suffix. The difference is that the expression `x++` returns the original value of `x`, before it got incremented while `++x` returns the value of `x` post increment. E.g. ---- $x = 10; $y = $x--; // y = 10; x = 9 $a = 10; $b = --$a; // a = 9; b = 9 ---- Note that maps will be implicitly declared and initialized to 0 if not already declared or defined. Scratch variables must be initialized before using these operators. === Variables and Maps bpftrace knows two types of variables, `scratch` and `map`. 'scratch' variables are kept on the BPF stack and only exists during the execution of the action block and cannot be accessed outside of the program. Scratch variable names always start with a `$`, e.g. `$myvar`. 'map' variables use BPF 'maps'. These exist for the lifetime of `bpftrace` itself and can be accessed from all action blocks and user-space. Map names always start with a `@`, e.g. `@mymap`. All valid identifiers can be used as `name`. The data type of a variable is automatically determined during first assignment and cannot be changed afterwards. ==== Associative Arrays Associative arrays are a collection of elements indexed by a key, similar to the hash tables found in languages like C++ (`std::map`) and Python (`dict`). They're a variant of 'map' variables. ---- @name[key] = expression @name[key1,key2] = expression ---- Just like with any variable the type is determined on first use and cannot be modified afterwards. This applies to both the key(s) and the value type. The following snippet creates a map with key signature `[int64, string[16]]` and a value type of `int64`: ---- @[pid, comm]++ ---- === Variable scoping // TODO === Pointers Pointers in bpftrace are similar to those found in `C`. // TODO, not true yet === Tuples bpftrace has support for immutable N-tuples (`n > 1`). A tuple is a sequence type (like an array) where, unlike an array, every element can have a different type. Tuples are a comma separated list of expressions, enclosed in brackets, `(1,2)` Individual fields can be accessed with the `.` operator. Tuples are zero indexed like arrays are. ---- i:s:1 { $a = (1,2); $b = (3,4, $a); print($a); print($b); print($b.0); } ---- Prints: ---- (1, 2) (3, 4, (1, 2)) 3 ---- ==== Arrays bpftrace supports accessing one-dimensional arrays like those found in `C`. Constructing arrays from scratch, like `int a[] = {1,2,3}` in `C`, is not supported. They can only be read into a variable from a pointer. The `[]` operator is used to access elements. ---- struct MyStruct { int y[4]; } kprobe:dummy { $s = (struct MyStruct *) arg0; print($s->y[0]); } ---- === Structs `C` like structs are supported by bpftrace. Fields are accessed with the `.` operator. Fields of a pointer to a struct can be accessed with the `\\->` operator. Custom struct can be defined in the preamble Constructing structs from scratch, like `struct X var = {.f1 = 1}` in `C`, is not supported. They can only be read into a variable from a pointer. ---- struct MyStruct { int a; } kprobe:dummy { $ptr = (struct MyStruct *) arg0; $st = *$ptr; print($st.a); print($ptr->a); } ---- === Conditionals Conditional expressions are supported in the form of if/else statements and the ternary operator. The ternary operator consists of three operands: a condition followed by a `?`, the expression to execute when the condition is true followed by a `:` and the expression to execute if the condition is false. ---- condition ? ifTrue : ifFalse ---- Both the `ifTrue` and `ifFalse` expressions must be of the same type, mixing types is not allowed. The ternary operator can be used as part of an assignment. ---- $a == 1 ? print(""true"") : print(""false""); $b = $a > 0 ? $a : -1; ---- If/else statements, like the one in `C`, are supported. ---- if (condition) { ifblock } else if (condition) { if2block } else { elseblock } ---- === Loops Since kernel 5.3 BPF supports loops as long as the verifier can prove they're bounded and fit within the instruction limit. In bpftrace loops are available through the `while` statement. ---- while (condition) { block; } ---- Within a while-loop the following control flow statements can be used: [cols=""~,~""] |=== | continue | skip processing of the rest of the block and jump back to the evaluation of the conditional | break | Terminate the loop |=== ---- i:s:1 { $i = 0; while ($i <= 100) { printf(""%d "", $i); if ($i > 5) { break; } $i++ } printf(""\\n""); } ---- Loop unrolling is also supported with the `unroll` statement. ---- unroll(n) { block; } ---- The compiler will evaluate the block `n` times and generate the BPF code for the block `n` times. As this happens at compile time `n` must be a constant greater than 0 (`n > 0`). The following two probes compile into the same code: ---- i:s:1 { unroll(3) { print(""Unrolled"") } } i:s:1 { print(""Unrolled"") print(""Unrolled"") print(""Unrolled"") } ---- //// ! ! ! This prefix reset must be at the end of the section, else cross references break ! ! //// :idprefix: _ == Sync and Async While BPF in the kernel can do a lot there are still things that can only be done from user space, like the outputting (printing) of data. The way bpftrace handles this is by sending events from the BPF program which user-space will pick up some time in the future (usually in milliseconds). Operations that happen in the kernel are 'synchronous' ('sync') and those that are handled in user space are 'asynchronous' ('async') The async behaviour can lead to some unexpected behavior as updates can happen before user space had time to process the event. One example is updating a map value in a tight loop: ---- BEGIN { @=0; unroll(10) { print(@); @++; } exit() } ---- Maps are printed by reference not by value and as the value gets updated right after the print user-space will likely only see the final value once it processes the event: ---- @: 10 @: 10 @: 10 @: 10 @: 10 @: 10 @: 10 @: 10 @: 10 @: 10 ---- == Address-spaces Kernel and user pointers live in different address spaces which, depending on the CPU architecture, might overlap. Trying to read a pointer that is in the wrong address space results in a runtime error. This error is hidden by default but can be enabled with the `-kk` flag: ---- stdin:1:9-12: WARNING: Failed to probe_read_user: Bad address (-14) BEGIN { @=*uptr(kaddr(""do_poweroff"")) } ~~~ ---- bpftrace tries to automatically set the correct address space for a pointer based on the probe type, but might fail in cases where it is unclear. The address space can be changed with the `kptr()` and `uptr()` functions. == Builtins Builtins are special variables built into the language. Unlike the scratch and map variable they don't need a `$` or `@` as prefix (except for the positional parameters). [%header,cols=""~,~,~,~,~""] |=== | Variable | Type | Kernel | BPF Helper | Description | `$1`, `$2`, `...$n` | int64 | n/a | n/a | The nth positional parameter passed to the bpftrace program. If less than n parameters are passed this evaluates to `0`. For string arguments use the `str()` call to retrieve the value. | `$#` | int64 | n/a | n/a | Total amount of positional parameters passed. | `arg0`, `arg1`, `...argn` | int64 | n/a | n/a | nth argument passed to the function being traced. These are extracted from the CPU registers. The amount of args passed in registers depends on the CPU architecture. (kprobes, uprobes, usdt). | cgroup | uint64 | 4.18 | get_current_cgroup_id | ID of the cgroup the current task is in. Only works with cgroupv2. | comm | string[16] | 4.2 | get_current_com | `comm` of the current task. Equal to the value in `/proc//comm` | cpid | uint32 | n/a | n/a | PID of the child process | cpu | uint32 | 4.1 | raw_smp_processor_id | ID of the processor executing the BPF program | curtask | uint64 | 4.8 | get_current_task | Pointer to `struct task_struct` of the current task | elapsed | uint64 | (see nsec) | ktime_get_ns / ktime_get_boot_ns | Nanoseconds elapsed since bpftrace initialization, based on `nsecs` | func | string | n/a | n/a | Name of the current function being traced (kprobes,uprobes) | gid | uint64 | 4.2 | get_current_uid_gid | GID of current task | kstack | kstack | | get_stackid | Kernel stack trace | nsecs | uint64 | 4.1 / 5.7 | ktime_get_ns / ktime_get_boot_ns | nanoseconds since kernel boot. On kernels that support `ktime_get_boot_ns` this includes the time spent suspended, on older kernels it does not. | pid | uint64 | 4.2 | get_current_pid_tgid | Process ID (or thread group ID) of the current task. | probe | string | n/na | n/a | Name of the current probe | rand | uint32 | 4.1 | get_prandom_u32 | Random number | retval | int64 | n/a | n/a | Value returned by the function being traced (kretprobe, uretprobe, kretfunc) | `sarg0`, `sarg1`, `...sargn` | int64 | n/a | n/a | nth stack value of the function being traced. (kprobes, uprobes). | tid | uint64 | 4.2 | get_current_pid_tgid | Thread ID of the current task. | uid | uint64 | 4.2 | get_current_uid_gid | UID of current task | ustack | ustack | 4.6 | get_stackid | Userspace stack trace |=== //// Custom prefix to easily link to a function //// :idprefix: functions_ == Map Functions Map functions are built-in functions who's return value can only be assigned to maps. The data type associated with these functions are only for internal use and are not compatible with the (integer) operators. Functions that are marked *async* are asynchronous which can lead to unexpected behavior, see the <> section for more information. === avg .variants * `avg(int64 n)` Calculate the running average of `n` between consecutive calls. ---- i:s:1 { @x++; @y = avg(@x); print(@x); print(@y); } ---- Internally this keeps two values in the map: value count and running total. The average is computed in user-space when printing by dividing the total by the count. === clear .variants * `clear(map m)` *async* Clear all keys/values from map `m`. ---- i:ms:100 { @[rand % 10] = count(); } i:s:10 { print(@); clear(@); } ---- === count .variants * `count()` Count how often this function is called. Using `@=count()` is conceptually similar to `@++`. The difference is that the `count()` function uses a map type optimized for this (PER_CPU), increasing performance. Due to this the map cannot be accessed as a regular integer. ---- i:ms:100 { @ = count(); } i:s:10 { print(@); clear(@); } ---- === delete .variants * `delete(mapkey k)` Delete a single key from a map. For a single value map this deletes the only element. For an associative-array the key to delete has to be specified. ``` k:dummy { @scalar = 1; @associative[1,2] = 1; delete(@scalar); delete(@associative[1,2]); delete(@associative); // error } ``` === hist .variants * `hist(int64 n)` Create a log2 histogram of `n`. ---- kretprobe:vfs_read { @bytes = hist(retval); } ---- Results in: ---- @: [1M, 2M) 3 | | [2M, 4M) 2 | | [4M, 8M) 2 | | [8M, 16M) 6 | | [16M, 32M) 16 | | [32M, 64M) 27 | | [64M, 128M) 48 |@ | [128M, 256M) 98 |@@@ | [256M, 512M) 191 |@@@@@@ | [512M, 1G) 394 |@@@@@@@@@@@@@ | [1G, 2G) 820 |@@@@@@@@@@@@@@@@@@@@@@@@@@@ | ---- === lhist .variants * `lhist(int64 n, int64 min, int64 max, int64 step)` Create a linear histogram of `n`. `lhist` creates `M` (`(max - min) / step`) buckets in the range `[min,max)` where each bucket is `step` in size. Values in the range `(-inf, min)` and `(max, inf)` get their get their own bucket too, bringing the total amount of buckets created to `M+2`. ---- i:ms:1 { @ = lhist(rand %10, 0, 10, 1); } i:s:5 { exit(); } ---- Prints: ---- @: [0, 1) 306 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ | [1, 2) 284 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ | [2, 3) 294 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ | [3, 4) 318 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ | [4, 5) 311 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ | [5, 6) 362 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@| [6, 7) 336 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ | [7, 8) 326 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ | [8, 9) 328 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ | [9, 10) 318 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ | ---- === max .variants * `max(int64 n)` Update the map with `n` if `n` is bigger than the current value held. === min .variants * `min(int64 n)` Update the map with `n` if `n` is smaller than the current value held. === stats .variants * `stats(int64 n)` `stats` combines the `count`, `avg` and `sum` calls into one. ---- kprobe:vfs_read { @bytes[comm] = stats(arg2); } ---- ---- @bytes[bash]: count 7, average 1, total 7 @bytes[sleep]: count 5, average 832, total 4160 @bytes[ls]: count 7, average 886, total 6208 @ ---- === sum .variants * `sum(int64 n)` Calculate the sum of all `n` passed. === zero .variants * `zero(map m)` *async* Set all values for all keys to zero. == Functions Functions that are marked *async* are asynchronous which can lead to unexpected behaviour, see the <> section for more information. *compile time* functions are evaluated at compile time, a static value will be compiled into the program. *unsafe* functions can have dangerous side effects and should be used with care, the `--unsafe` flag is required for use. === bswap .variants * `uint8 bswap(uint8 n)` * `uint16 bswap(uint16 n)` * `uint32 bswap(uint32 n)` * `uint64 bswap(uint64 n)` `bswap` reverses the order of the bytes in integer `n`. In case of 8 bit integers, `n` is returned without being modified. The return type is an unsigned integer of the same width as `n`. === buf .variants * `buf_t buf(void * data, [int64 length])` `buf` reads `length` amount of bytes from address `data`. The maximum value of `length` is limited to the `BPFTRACE_STRLEN` variable. For arrays the `length` is optional, it is automatically inferred from the signature. `buf` is address space aware and will call the correct helper based on the address space associated with `data`. The `buf_t` object returned by `buf` can safely be printed as a hex encoded string with the `%r` format specifier. Bytes with values >=32 and \\<=126 are printed using their ASCII character, other bytes are printed in hex form (e.g. `\\x00`). The `%rx` format specifier can be used to print everything in hex form, including ASCII characters. ---- i:s:1 { printf(""%r\\n"", buf(kaddr(""avenrun""), 8)); } ---- ---- \\x00\\x03\\x00\\x00\\x00\\x00\\x00\\x00 \\xc2\\x02\\x00\\x00\\x00\\x00\\x00\\x00 ---- === cat .variants * `void cat(string namefmt, [...args])` *async* Dump the contents of the named file to stdout. `cat` supports the same format string and arguments that `printf` does. If the file cannot be opened or read an error is printed to stderr. ---- t:syscalls:sys_enter_execve { cat(""/proc/%d/maps"", pid); } ---- ---- 55f683ebd000-55f683ec1000 r--p 00000000 08:01 1843399 /usr/bin/ls 55f683ec1000-55f683ed6000 r-xp 00004000 08:01 1843399 /usr/bin/ls 55f683ed6000-55f683edf000 r--p 00019000 08:01 1843399 /usr/bin/ls 55f683edf000-55f683ee2000 rw-p 00021000 08:01 1843399 /usr/bin/ls 55f683ee2000-55f683ee3000 rw-p 00000000 00:00 0 ---- === cgroup_path .variants * `cgroup_path cgroup_path(int cgroupid, string filter)` Convert cgroup id to cgroup path. This is done asynchronously in userspace when the cgroup_path value is printed, therefore it can resolve to a different value if the cgroup id gets reassigned. This also means that the returned value can only be used for printing. A string literal may be passed as an optional second argument to filter cgroup hierarchies in which the cgroup id is looked up by a wildcard expression (cgroup2 is always represented by ""unified"", regardless of where it is mounted). The currently mounted hierarchy at /sys/fs/cgroup is used to do the lookup. If the cgroup with the given id isn't present here (e.g. when running in a Docker container), the cgroup path won't be found (unlike when looking up the cgroup path of a process via /proc/.../cgroup). ---- BEGIN { $cgroup_path = cgroup_path(3436); print($cgroup_path); print($cgroup_path); /* This may print a different path */ printf(""%s %s"", $cgroup_path, $cgroup_path); /* This may print two different paths */ } ---- === cgroupid .variants * `uint64 cgroupid(const string path)` *compile time* `cgroupid` retrieves the cgroupv2 ID of the cgroup available at `path`. ---- BEGIN { print(cgroupid(""/sys/fs/cgroup/system.slice"")); } ---- === exit .variants * `void exit()` *async* Terminate bpftrace, as if a `SIGTERM` was received. The `END` probe will still trigger (if specified) and maps will be printed. === join .variants * `void join(char *arr[], [char * sep = ' '])` *async* `join` joins all the string array `arr` with `sep` as separator into one string. This string will be printed to stdout directly, it cannot be used as string value. The concatenation of the array members is done in BPF and the printing happens in userspace. ---- tracepoint:syscalls:sys_enter_execve { join(args->argv); } ---- === kaddr .variants * `uint64 kaddr(const string name)` *compile time* Get the address of the kernel symbol `name`. The following script: === kptr .variants * `T * kptr(T * ptr)` Marks `ptr` as a kernel address space pointer. See the address-spaces section for more information on address-spaces. The pointer type is left unchanged. === ksym .variants * `ksym_t ksym(uint64 addr)` *async* Retrieve the name of the function that contains address `addr`. The address to name mapping happens in user-space. The `ksym_t` type can be printed with the `%s` format specifier. ---- kprobe:do_nanosleep { printf(""%s\\n"", ksym(reg(""ip""))); } ---- Prints: ---- do_nanosleep ---- === macaddr .variants * `macaddr_t macaddr(char [6] mac)` Create a buffer that holds a macaddress as read from `mac` This buffer can be printed in the canonical string format using the `%s` format specifier. ---- kprobe:arp_create { printf(""SRC %s, DST %s\\n"", macaddr(sarg0), macaddr(sarg1)); } ---- Prints: ---- SRC 18:C0:4D:08:2E:BB, DST 74:83:C2:7F:8C:FF ---- === ntop .variants * `inet_t ntop([int64 af, ] int addr)` * `inet_t ntop([int64 af, ] char addr[4])` * `inet_t ntop([int64 af, ] char addr[16])` `ntop` returns the string representation of an IPv4 or IPv6 address. `ntop` will infer the address type (IPv4 or IPv6) based on the `addr` type and size. If an integer or `char[4]` is given, ntop assumes IPv4, if a `char[16]` is given, ntop assumes IPv6. You can also pass the address type (e.g. AF_INET) explicitly as the first parameter. === override .variants * `override(uint64 rc)` *unsafe* *Kernel* 4.16 *Helper* `bpf_override` .Supported probes * kprobe When using `override` the probed function will not be executed and instead `rc` will be returned. ---- k:__x64_sys_getuid /comm == ""id""/ { override(2<<21); } ---- ---- uid=4194304 gid=0(root) euid=0(root) groups=0(root) ---- This feature only works on kernels compiled with `CONFIG_BPF_KPROBE_OVERRIDE` and only works on functions tagged `ALLOW_ERROR_INJECTION`. bpftrace does not test whether error injection is allowed for the probed function, instead if will fail to load the program into the kernel: ---- ioctl(PERF_EVENT_IOC_SET_BPF): Invalid argument Error attaching probe: 'kprobe:vfs_read' ---- === reg .variants * `reg(const string name)` .Supported probes * kprobe * uprobe Get the contents of the register identified by `name`. Valid names depend on the CPU architecture. === signal .variants * `signal(const string sig)` * `signal(uint32 signum)` *unsafe* *Kernel* 5.3 *Helper* `bpf_send_signal` Probe types: k(ret)probe, u(ret)probe, USDT, profile Send a signal to the process being traced. The signal can either be identified by name, e.g. `SIGSTOP` or by ID, e.g. `19` as found in `kill -l`. ---- kprobe:__x64_sys_execve /comm == ""bash""/ { signal(5); } ---- ---- $ ls Trace/breakpoint trap (core dumped) ---- === sizeof .variants * `sizeof(TYPE)` * `sizeof(EXPRESSION)` *compile time* Returns size of the argument in bytes. Similar to C/C++ `sizeof` operator. Note that the expression does not get evaluated. === str .variants * `str(char * data [, uint32 length)` *Helper* `probe_read_str, probe_read_{kernel,user}_str` `str` reads a NULL terminated (`\\0`) string from `data`. The maximum string length is limited by the `BPFTRACE_STR_LEN` env variable, unless `length` is specified and shorter than the maximum. In case the string is longer than the specified length only `length - 1` bytes are copied and a NULL byte is appended at the end. When available (starting from kernel 5.5, see the `--info` flag) bpftrace will automatically use the `kernel` or `user` variant of `probe_read_{kernel,user}_str` based on the address space of `data`, see <> for more information. === strftime .variants * `strtime_t strftime(const string fmt, int64 timestamp_ns)` *async* Format the nanoseconds since boot timestamp `timestamp_ns` according to the format specified by `fmt`. The time conversion and formatting happens in user space, therefore the `timestr_t` value returned can only be used for printing using the `%s` format specifier. bpftrace uses the `strftime(3)` function for formatting time and supports the same format specifiers. ---- i:s:1 { printf(""%s\\n"", strftime(""%H:%M:%S"", nsecs)); } ---- bpftrace also supports the following format string extensions: [%header,cols=""~,~""] |=== | Specifier | Description | `%f` | Microsecond as a decimal number, zero-padded on the left |=== === strncmp .variants * `int64 strncmp(char * s1, char * s2, int64 n)` `strncmp` compares up to `n` characters string `s1` and string `s2`. If they're equal `0` is returned, else a non-zero value is returned. bpftrace doesn't read past the length of the shortest string. The use of the `==` and `!=` operators is recommended over calling `strncmp` directly. === system .variants * `void system(string namefmt [, ...args])` *unsafe* *async* `system` lets bpftrace run the specified command (`fork` and `exec`) until it completes and print its stdout. The `command` is run with the same privileges as bpftrace and it blocks execution of the processing threads which can lead to missed events and delays processing of async events. ---- i:s:1 { time(""%H:%M:%S: ""); printf(""%d\\n"", @++); } i:s:10 { system(""/bin/sleep 10""); } i:s:30 { exit(); } ---- Note how the async `time` and `printf` first print every second until the `i:s:10` probe hits, then they print every 10 seconds due to bpftrace blocking on `sleep`. ---- Attaching 3 probes... 08:50:37: 0 08:50:38: 1 08:50:39: 2 08:50:40: 3 08:50:41: 4 08:50:42: 5 08:50:43: 6 08:50:44: 7 08:50:45: 8 08:50:46: 9 08:50:56: 10 08:50:56: 11 08:50:56: 12 08:50:56: 13 08:50:56: 14 08:50:56: 15 08:50:56: 16 08:50:56: 17 08:50:56: 18 08:50:56: 19 ---- `system` supports the same format string and arguments that `printf` does. ---- t:syscalls:sys_enter_execve { system(""/bin/grep %s /proc/%d/status"", ""vmswap"", pid); } ---- === time .variants * `void time(const string fmt)` *async* Format the current wall time according to the format specifier `fmt` and print it to stdout. Unlike `strftime()` `time()` doesn't send a timestamp from the probe, instead it is the time at which user-space processes the event. bpftrace uses the `strftime(3)` function for formatting time and supports the same format specifiers. === uaddr .variants * `T * uaddr(const string sym)` .Supported probes * uprobes * uretprobes * USDT **Does not work with ASLR, see issue link:https://github.com/iovisor/bpftrace/issues/75[#75]** The `uaddr` function returns the address of the specified symbol. This lookup happens during program compilation and cannot be used dynamically. The default return type is `uint64*`. If the ELF object size matches a known integer size (1, 2, 4 or 8 bytes) the return type is modified to match the width (`uint8*`, `uint16*`, `uint32*` or `uint64*` resp.). As ELF does not contain type info the type is always assumed to be unsigned. ---- uprobe:/bin/bash:readline { printf(""PS1: %s\\n"", str(*uaddr(""ps1_prompt""))); } ---- === uptr .variants * `T * uptr(T * ptr)` Marks `ptr` as a user address space pointer. See the address-spaces section for more information on address-spaces. The pointer type is left unchanged. === usym .variants * `usym_t usym(uint64 * addr)` *async* .Supported probes * uprobes * uretprobes Equal to <> but resolves user space symbols ---- uprobe:/bin/bash:readline { printf(""%s\\n"", usym(reg(""ip""))); } ---- Prints: ---- readline ---- === path .variants * `char * path(struct path * path)` *Kernel* 5.10 *Helper* bpf_d_path Return full path referenced by struct path pointer in argument. This function can only be used by functions that are allowed to, these functions are contained in the `btf_allowlist_d_path` set in the kernel. === unwatch .variants * `void unwatch(void * addr)` *async* Removes a watchpoint == Output formatting === print .variants * `void print(T val)` *async* .variants * `void print(T val)` * `void print(@map)` * `void print(@map, uint64 top)` * `void print(@map, uint64 top, uint64 div)` `print` prints a the value, which can be a map or a scalar value, with the default formatting for the type. ---- i:ms:10 { @=hist(rand); } i:s:1 { print(@); print(123); print(""abc""); exit(); } ---- Prints: ---- @: [16M, 32M) 3 |@@@ | [32M, 64M) 2 |@@ | [64M, 128M) 1 |@ | [128M, 256M) 4 |@@@@ | [256M, 512M) 3 |@@@ | [512M, 1G) 14 |@@@@@@@@@@@@@@ | [1G, 2G) 22 |@@@@@@@@@@@@@@@@@@@@@@ | [2G, 4G) 51 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@| 123 abc ---- Note that maps are printed by reference while scalar values are copied. This means that updating and printing maps in a fast loop will likely result in bogus map values as the map will be updated before userspace gets the time to dump and print it. The printing of maps supports the optional `top` and `div` arguments. `top` limits the printing to the top N entries with the highest integer values ---- BEGIN { $i = 11; while($i) { @[$i] = --$i; } print(@, 2); clear(@); exit() } ---- ---- @[9]: 9 @[10]: 10 ---- The `div` argument scales the values prior to printing them. Scaling values before storing them can result in rounding errors. Consider the following program: ---- k:f { @[func] += arg0/10; } ---- With the following sequence as numbers for arg0: `134, 377, 111, 99`. The total is `721` which rounds to `72` when scaled by 10 but the program would print `70` due to the rounding of individual values. Changing the print call to `print(@, 5, 2)` will take the top 5 values and scale them by 2: ---- @[6]: 3 @[7]: 3 @[8]: 4 @[9]: 4 @[10]: 5 ---- === printf .variants * `void printf(const string fmt, args...)` *async* `printf()` formats and prints data. It behaves similar to `printf()` found in `C` and many other languages. The format string has to be a constant, it cannot be modified at runtime. The formatting of the string happens in user space. Values are copied and passed by value. bpftrace supports all the typical format specifiers like `%llx` and `%hhu`. The non-standard ones can be found in the table below: [%header,cols=""~,~,~""] |=== | Specifier | Type | Description | r | buffer | Hex-formatted string to print arbitrary binary content returned by the buf (<>) function. |=== Supported escape sequences Colors are supported too, using standard terminal escape sequences: ---- print(""\\033[31mRed\\t\\033[33mYellow\\033[0m\\n"") ---- //// ! ! ! This prefix reset must be at the end of the section, else cross references break ! ! //// :idprefix: _ == Probes bpftrace supports various probe types which allow the user to attach BPF programs to different types of events. Each probe starts with a provider (e.g. `kprobe`) followed by a colon (`:`) separated list of options. The amount of options and their meaning depend on the provider and are detailed below. The valid values for options can depend on the system or binary being traced, e.g. for uprobes it depends on the binary. Also see <> It is possible to associate multiple probes with a single action as long as the action is valid for all specified probes. Multiple probes can be specified as a comma (`,`) separated list: ---- kprobe:tcp_reset,kprobe:tcp_v4_rcv { printf(""Entered: %s\\n"", probe); } ---- Wildcards are supported too: ---- kprobe:tcp_* { printf(""Entered: %s\\n"", probe); } ---- Both can be combined: ---- kprobe:tcp_reset,kprobe:*socket* { printf(""Entered: %s\\n"", probe); } ---- Most providers also support a short name which can be used instead of the full name, e.g. `kprobe:f` and `k:f` are identical. [#probes-begin-end] === BEGIN and END These are special built-in events provided by the bpftrace runtime. `BEGIN` is triggered before all other probes are attached. `END` is triggered after all other probes are detached. Note that specifying an `END` probe doesn't override the printing of 'non-empty' maps at exit. To prevent the printing all used maps need be cleared, which can be done in the `END` probe: ---- END { clear(@map1); clear(@map2); } ---- [#probes-hardware] === hardware .variants * `hardware:event_name:` * `hardware:event_name:count` .shortname * `h` The `hardware` probe attaches to pre-defined hardware events provided by the kernel. They are implemented using performance monitoring counters (PMCs): hardware resources on the processor. There are about ten of these, and they are documented in the `perf_event_open(2)` man page. The event names are: - `cpu-cycles` or `cycles` - `instructions` - `cache-references` - `cache-misses` - `branch-instructions` or `branches` - `branch-misses` - `bus-cycles` - `frontend-stalls` - `backend-stalls` - `ref-cycles` The `count` option specifies how many events must happen before the probe fires. If `count` is left unspecified a default value is used. ---- hardware:cache-misses:1e6 { @[pid] = count(); } ---- [#probes-interval] === interval .variants * `interval:us:count` * `interval:ms:count` * `interval:s:count` * `interval:hz:rate` .shortnames * `i` The interval probe fires at a fixed interval as specified by its time spec. Interval fire on one CPU at the time, unlike <> probes. [#probes-iterator] === iterator .variants * `iter:task` * `iter:task:pin` * `iter:task_file` * `iter:task_file:pin` .shortnames * `it` These are eBPF iterator probes, that allow iteration over kernel objects. Iterator probe can't be mixed with any other probe, not even other iterator. Each iterator probe provides set of fields that could be accessed with ctx pointer. User can display set of available fields for iterator via -lv options as described below. Examples: ``` # bpftrace -e 'iter:task { printf(""%s:%d\\n"", ctx->task->comm, ctx->task->pid); }' Attaching 1 probe... systemd:1 kthreadd:2 rcu_gp:3 rcu_par_gp:4 kworker/0:0H:6 mm_percpu_wq:8 ... # bpftrace -e 'iter:task_file { printf(""%s:%d %d:%s\\n"", ctx->task->comm, ctx->task->pid, ctx->fd, path(ctx->file->f_path)); }' Attaching 1 probe... systemd:1 1:/dev/null systemd:1 2:/dev/null systemd:1 3:/dev/kmsg ... su:1622 1:/dev/pts/1 su:1622 2:/dev/pts/1 su:1622 3:/var/lib/sss/mc/passwd ... bpftrace:1892 1:pipe:[35124] bpftrace:1892 2:/dev/pts/1 bpftrace:1892 3:anon_inode:bpf-map bpftrace:1892 4:anon_inode:bpf-map bpftrace:1892 5:anon_inode:bpf_link bpftrace:1892 6:anon_inode:bpf-prog bpftrace:1892 7:anon_inode:bpf_iter ``` It's possible to pin iterator with specifying optional probe ':pin' part, that defines the pin file. It can be specified as absolute path or relative to /sys/fs/bpf. .relative pin ---- # bpftrace -e 'iter:task:list { printf(""%s:%d\\n"", ctx->task->comm, ctx->task->pid); }' Program pinned to /sys/fs/bpf/list ---- ---- # cat /sys/fs/bpf/list systemd:1 kthreadd:2 rcu_gp:3 rcu_par_gp:4 kworker/0:0H:6 mm_percpu_wq:8 rcu_tasks_kthre:9 ... ---- Examples with absolute pin file: .absolute pin ---- # bpftrace -e ' iter:task_file:/sys/fs/bpf/files { printf(""%s:%d %s\\n"", ctx->task->comm, ctx->task->pid, path(ctx->file->f_path)); }' Program pinned to /sys/fs/bpf/files ---- ---- # cat /sys/fs/bpf/files systemd:1 anon_inode:inotify systemd:1 anon_inode:[timerfd] ... systemd-journal:849 /dev/kmsg systemd-journal:849 anon_inode:[eventpoll] ... sssd:1146 /var/log/sssd/sssd.log sssd:1146 anon_inode:[eventpoll] ... NetworkManager:1155 anon_inode:[eventfd] NetworkManager:1155 /var/lib/sss/mc/passwd (deleted) ---- [#probes-kfunc] === kfunc and kretfunc .variants * `kfunc:fn` * `kretfunc:fn` .shortnames * `f` (`kfunc`) * `fr` (`kretfunc`) .requires (`--info`) * Kernel features:BTF * Probe types:kfunc ``kfunc``s attach to kernel function similar to <>. They make use of eBPF trampolines which allows kernel code to call into BPF programs with near zero overhead. `kfunc` s make use of BTF type information to derive the type of function arguments at compile time. This removes the need for manual type casting and makes the code more resilient against small signature changes in the kernel. The function arguments are available in the `args` struct which can be inspected by doing verbose listing (see <>). These arguments are also available in the return probe (`kretfunc`). ---- # bpftrace -lv 'kfunc:tcp_reset' kfunc:tcp_reset struct sock * sk struct sk_buff * skb ---- ---- kfunc:x86_pmu_stop { printf(""pmu %s stop\\n"", str(args->event->pmu->name)); } ---- ---- kretfunc:fget { printf(""fd %d name %s\\n"", args->fd, str(retval->f_path.dentry->d_name.name)); } ---- ---- fd 3 name ld.so.cache fd 3 name libselinux.so.1 fd 3 name libselinux.so.1 ... ---- [#probes-kprobe] === kprobe and kretprobe .variants * `kprobe:fn` * `kprobe:fn+offset` * `kretprobe:fn` .shortnames * `k` * `kr` `kprobe` s allow for dynamic instrumentation of kernel functions. Each time the specified kernel function is executed the attached BPF programs are ran. ---- kprobe:tcp_reset { @tcp_resets = count() } ---- Function arguments are available through the `argX` and `sargX` builtins, for register args and stack args respectively. Whether arguments passed on stack or in a register depends on the architecture and the number or arguments in used, e.g. on x86_64 the first non-floating point 6 arguments are passed in registers, all following arguments are passed on the stack. Note that floating point arguments are typically passed in special registers which don't count as `argX` arguments which can cause confusion. Consider a function with the following signature: ---- void func(int a, double d, int x) ---- Due to `d` being a floating point `x` is accessed through `arg1` where one might expect `arg2`. bpftrace does not detect the function signature so it is not aware of the argument count or their type. It is up to the user to perform <> when needed, e.g. ---- kprobe:tcp_connect { $sk = ((struct sock *) arg0); ... } ---- `kprobe` s are not limited to function entry, they can be attached to any instruction in a function by specifying an offset from the start of the function. `kretprobe` s trigger on the return from a kernel function. Return probes do not have access to the function (input) arguments, only to the return value (through `retval`). A common pattern to work around this is by storing the arguments in a map on function entry and retrieving in the return probe: ---- kprobe:d_lookup { $name = (struct qstr *)arg1; @fname[tid] = $name->name; } kretprobe:d_lookup /@fname[tid]/ { printf(""%-8d %-6d %-16s M %s\\n"", elapsed / 1e6, pid, comm, str(@fname[tid])); } ---- [#probes-profile] === profile .variants * `profile:us:count` * `profile:ms:count` * `profile:s:count` * `profile:hz:rate` .shortnames * `p` Profile probes fire on each CPU on the specified interval. [#probes-software] === software .variants * `software:event:` * `software:event:count` .shortnames * `s` The `software` probe attaches to pre-defined software events provided by the kernel. Event details can be found in the `perf_event_open(2)` man page. The event names are: - `cpu-clock` or `cpu` - `task-clock` - `page-faults` or `faults` - `context-switches` or `cs` - `cpu-migrations` - `minor-faults` - `major-faults` - `alignment-faults` - `emulation-faults` - `dummy` - `bpf-output` [#probes-tracepoint] === tracepoint .variants * `tracepoint:subsys:event` .shortnames * `t` Tracepoints are hooks into events in the kernel. Tracepoints are defined in the kernel source and compiled into the kernel binary which makes them a form of static tracing. Which means that unlike `kprobe` s new tracepoints cannot be added without modifying the kernel. The advantage of tracepoints is that they generally provide a more stable interface than `kprobe` s do, they do not depend on the existence of a kernel function. Tracepoint arguments are available in the `args` struct which can be inspected with verbose listing, see the <> section for more details. ---- tracepoint:syscalls:sys_enter_openat { printf(""%s %s\\n"", comm, str(args->filename)); } ---- ---- irqbalance /proc/interrupts irqbalance /proc/stat snmpd /proc/diskstats snmpd /proc/stat snmpd /proc/vmstat snmpd /proc/net/dev [...] ---- .Additional information * https://www.kernel.org/doc/html/latest/trace/tracepoints.html [#probes-uprobe] === uprobe, uretprobe .variants * `uprobe:binary:func` * `uprobe:binary:func+offset` * `uretprobe:binary:func` .shortnames * `u` * `ur` `uprobe` s or user-space probes are the user-space equivalent of `kprobe` s. The same limitations that apply <> also apply to `uprobe` s and `uretprobe` s. When tracing libraries, it is sufficient to specify the library name instead of a full path. The path will be then automatically resolved using `/etc/ld.so.cache`: ---- # bpftrace -e 'uprobe:libc:malloc { printf(""Allocated %d bytes\\n"", arg0); }' Allocated 4 bytes ... ---- If the traced binary has DWARF included, function arguments are available in the `args` struct which can be inspected with verbose listing, see the <> section for more details. It is important to note that for `uretprobe` s to work the kernel runs a special helper on user-space function entry which overrides the return address on the stack. This can cause issues with languages that have their own runtime like Golang: .example.go ---- func myprint(s string) { fmt.Printf(""Input: %s\\n"", s) } func main() { ss := []string{""a"", ""b"", ""c""} for _, s := range ss { go myprint(s) } time.Sleep(1*time.Second) } ---- .bpftrace ---- # bpftrace -e 'uretprobe:./test:main.myprint { @=count(); }' -c ./test runtime: unexpected return pc for main.myprint called from 0x7fffffffe000 stack: frame={sp:0xc00008cf60, fp:0xc00008cfd0} stack=[0xc00008c000,0xc00008d000) fatal error: unknown caller pc ---- [#probes-usdt] === usdt .variants * `usdt:binary:name` .shortnames * `U` [#probes-watchpoint] === watchpoint and asyncwatchpoint .variants * `watchpoint:absolute_address:length:mode` * `watchpoint:function+argN:length:mode` .shortnames * `w` * `aw` These are memory watchpoints provided by the kernel. Whenever a memory address is written to (`w`), read from (`r`), or executed (`x`), the kernel can generate an event. In the first form, an absolute address is monitored. If a pid (`-p`) or a command (`-c`) is provided, bpftrace takes the address as a userspace address and monitors the appropriate process. If not, bpftrace takes the address as a kernel space address. In the second form, the address present in `argN` when `function` is entered is monitored. A pid or command must be provided for this form. If synchronous (`watchpoint`), a `SIGSTOP` is sent to the tracee upon function entry. The tracee will be ``SIGCONT``ed after the watchpoint is attached. This is to ensure events are not missed. If you want to avoid the `SIGSTOP` + `SIGCONT` use `asyncwatchpoint`. Note that on most architectures you may not monitor for execution while monitoring read or write. Examples Print `hit` when a read from or write to `0x10000000` happens: ``` # bpftrace -e 'watchpoint:0x10000000:8:rw { printf(""hit!\\n""); exit(); }' -c ./testprogs/watchpoint ``` Print the call stack every time the `jiffies` variable is updated: ``` # bpftrace -e ""watchpoint:0x$(awk '$3 == ""jiffies"" {print $1}' /proc/kallsyms):8:w { @[kstack] = count(); } i:s:1 { exit(); }"" ...... @[ do_timer+12 tick_do_update_jiffies64.part.22+89 tick_sched_do_timer+103 tick_sched_timer+39 __hrtimer_run_queues+256 hrtimer_interrupt+256 smp_apic_timer_interrupt+106 apic_timer_interrupt+15 cpuidle_enter_state+188 cpuidle_enter+41 do_idle+536 cpu_startup_entry+25 start_secondary+355 secondary_startup_64+164 ]: 319 ``` ""hit"" and exit when the memory pointed to by `arg1` of `increment` is written to. ``` # cat wpfunc.c #include #include #include __attribute__((noinline)) void increment(__attribute__((unused)) int _, int *i) { (*i)++; } int main() { int *i = malloc(sizeof(int)); while (1) { increment(0, i); (*i)++; usleep(1000); } } # bpftrace -e 'watchpoint:increment+arg1:4:w { printf(""hit!\\n""); exit() }' -c ./wpfunc ``` == Listing Probes Probe listing is the method to discover which probes are supported by the current system. Listing supports the same syntax as normal attachment does: ---- # bpftrace -l 'kprobe:*' # bpftrace -l 't:syscalls:*openat* # bpftrace -l 'kprobe:tcp*,trace # bpftrace -l 'k:*socket*,tracepoint:syscalls:*tcp*' ---- The verbose flag (`-v`) can be specified to inspect arguments (`args`) for providers that support it: ---- # bpftrace -l 'fr:tcp_reset,t:syscalls:sys_enter_openat' -v kretfunc:tcp_reset struct sock * sk struct sk_buff * skb tracepoint:syscalls:sys_enter_openat int __syscall_nr int dfd const char * filename int flags umode_t mode # bpftrace -l 'uprobe:/bin/bash:rl_set_prompt' -v # works only if /bin/bash has DWARF uprobe:/bin/bash:rl_set_prompt const char *prompt ---- ",16236,True,2902.6668857624095,median " -1 erode_0_0_2160_3840_0_3_3_1_1_s 0 4 0 1 1 imgHelper1_4101 0 0 0 FIFO_SRL 49 8 0 3 0 0 0 1 2 imgHelper2_4102 0 0 0 FIFO_SRL 49 8 1 3 0 0 0 1 3 p_src_rows 0 0 0 FIFO_SRL 52 32 0 3 0 0 0 1 4 p_src_cols 0 0 0 FIFO_SRL 49 32 0 3 0 0 0 6 0 0 11 p_src_rows_read /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip/vitis_lib/vision/L1/include/imgproc/xf_erosion.hpp .. 344 erode&lt;0, 0, 2160, 3840, 0, 3, 3, 1, 1&gt; erode_0_0_2160_3840_0_3_3_1_1_s 1 0 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip 1 0 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip/vitis_lib/vision/L1/include/imgproc/xf_erosion.hpp erode&lt;0, 0, 2160, 3840, 0, 3, 3, 1, 1&gt; 344 auto fifo srl FIFO_SRL 81 32 2 0 19 20 read 0 0 0 0 3.24 1 -1 0 12 p_src_cols_read /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip/vitis_lib/vision/L1/include/imgproc/xf_erosion.hpp .. 345 erode&lt;0, 0, 2160, 3840, 0, 3, 3, 1, 1&gt; erode_0_0_2160_3840_0_3_3_1_1_s 1 0 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip 1 0 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip/vitis_lib/vision/L1/include/imgproc/xf_erosion.hpp erode&lt;0, 0, 2160, 3840, 0, 3, 3, 1, 1&gt; 345 auto fifo srl FIFO_SRL 81 32 2 0 21 22 read 0 0 0 0 3.24 2 -1 0 13 trunc_ln344 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip/vitis_lib/vision/L1/include/imgproc/xf_erosion.hpp .. 344 erode&lt;0, 0, 2160, 3840, 0, 3, 3, 1, 1&gt; erode_0_0_2160_3840_0_3_3_1_1_s 1 0 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip 1 0 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip/vitis_lib/vision/L1/include/imgproc/xf_erosion.hpp erode&lt;0, 0, 2160, 3840, 0, 3, 3, 1, 1&gt; 344 trunc_ln344_fu_52_p1 49 16 1 0 23 trunc 0 0 0 0 0.00 3 -1 0 14 trunc_ln345 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip/vitis_lib/vision/L1/include/imgproc/xf_erosion.hpp .. 345 erode&lt;0, 0, 2160, 3840, 0, 3, 3, 1, 1&gt; erode_0_0_2160_3840_0_3_3_1_1_s 1 0 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip 1 0 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip/vitis_lib/vision/L1/include/imgproc/xf_erosion.hpp erode&lt;0, 0, 2160, 3840, 0, 3, 3, 1, 1&gt; 345 trunc_ln345_fu_57_p1 225 16 1 0 24 trunc 0 0 0 0 0.00 4 -1 0 15 _ln365 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip/vitis_lib/vision/L1/include/imgproc/xf_erosion.hpp .. 365 erode&lt;0, 0, 2160, 3840, 0, 3, 3, 1, 1&gt; erode_0_0_2160_3840_0_3_3_1_1_s 1 0 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip 1 0 /home/willychiang/Desktop/PYNQ-HelloWorld/boards/ip/vitis_lib/vision/L1/include/imgproc/xf_erosion.hpp erode&lt;0, 0, 2160, 3840, 0, 3, 3, 1, 1&gt; 365 grp_xferode_2160_3840_1_0_1_0_3841_3_3_s_fu_42 113 0 5 0 26 27 28 29 30 call 0 0 0 0 0.00 5 -1 0 16 _ln0 0 0 0 113 0 0 0 ret 0 0 0 0 0.00 6 -1 1 0 2 25 xferode_2160_3840_1_0_1_0_3841_3_3_s 0 0 0 177 0 6 <constant:xferode<2160, 3840, 1, 0, 1, 0, 3841, 3, 3>> 1 0 3 17 erode<0, 0, 2160, 3840, 0, 3, 3, 1, 1> 0 0 0 1768189039 6 0 11 12 13 14 15 16 9 0 20 1 3 11 0 22 1 4 12 0 23 1 11 13 0 24 1 12 14 0 26 1 25 15 0 27 1 1 15 0 28 1 2 15 0 29 1 13 15 0 30 1 14 15 0 1 0 1 erode<0, 0, 2160, 3840, 0, 3, 3, 1, 1> erode_0_0_2160_3840_0_3_3_1_1_s 0 0 0 1 0 17 -1 -1 -1 -1 13 8319373 0 2 0 1 5 0 11 1 1 12 1 1 13 1 1 14 1 1 15 2 2 2 8 0 5 1 1 6 1 1 7 1 1 8 1 1 9 1 1 10 1 1 15 1 2 16 1 1 1 0 1 2 -1 1 0 0 0 1 0 grp_xferode_2160_3840_1_0_1_0_3841_3_3_s_fu_42 (xferode_2160_3840_1_0_1_0_3841_3_3_s) 3 0 BRAM 6 FF 611 LUT 819 1 0 ap_block_state1 ( or ) 4 0 (0P0) 1 (1P1) 1 FF 0 LUT 1 0 0 0 0 6 0 ap_NS_fsm 4 0 (0Size) 3 (1Bits) 1 (2Count) 3 LUT 13 ap_done 4 0 (0Size) 2 (1Bits) 1 (2Count) 2 LUT 9 imgHelper1_4101_read 4 0 (0Size) 2 (1Bits) 1 (2Count) 2 LUT 9 imgHelper2_4102_write 4 0 (0Size) 2 (1Bits) 1 (2Count) 2 LUT 9 p_src_cols_blk_n 4 0 (0Size) 2 (1Bits) 1 (2Count) 2 LUT 9 p_src_rows_blk_n 4 0 (0Size) 2 (1Bits) 1 (2Count) 2 LUT 9 5 0 ap_CS_fsm 3 0 (Bits) 2 (Consts) 0 FF 2 ap_done_reg 3 0 (Bits) 1 (Consts) 0 FF 1 grp_xferode_2160_3840_1_0_1_0_3841_3_3_s_fu_42_ap_start_reg 3 0 (Bits) 1 (Consts) 0 FF 1 trunc_ln344_reg_62 3 0 (Bits) 16 (Consts) 0 FF 16 trunc_ln345_reg_67 3 0 (Bits) 16 (Consts) 0 FF 16 1 0 grp_xferode_2160_3840_1_0_1_0_3841_3_3_s_fu_42 0 0 1 0 grp_xferode_2160_3840_1_0_1_0_3841_3_3_s_fu_42 (xferode_2160_3840_1_0_1_0_3841_3_3_s) 1 0 15 0 0 0 0 0 0 6 0 11 0 0 12 0 0 13 0 0 14 0 0 15 0 1 16 1 0 1 0 17 0 1 0 0 5 0 30 1 0 11 36 1 0 12 42 2 0 15 15 52 1 0 13 57 1 0 14 2 0 trunc_ln344_fu_52 1 0 13 trunc_ln345_fu_57 1 0 14 1 0 grp_xferode_2160_3840_1_0_1_0_3841_3_3_s_fu_42 2 0 15 15 2 0 p_src_cols_read_read_fu_36 1 0 12 p_src_rows_read_read_fu_30 1 0 11 0 0 0 0 2 0 62 1 0 13 67 1 0 14 2 0 trunc_ln344_reg_62 1 0 13 trunc_ln345_reg_67 1 0 14 0 0 0 0 4 0 imgHelper1_4101 1 0 call 1 0 15 imgHelper2_4102 1 0 call 1 0 15 p_src_cols 1 0 read 1 0 12 p_src_rows 1 0 read 1 0 11 4 0 1 1150 10 2 1150 10 3 1150 10 4 1150 10 3 0 11 1150 10 12 1150 10 15 -1 -1 ",12518,False,2207.775651382175,median "[[plannerConfiguration]] = OptaPlanner configuration :doctype: book :imagesdir: .. :sectnums: :toc: left :icons: font :experimental: [[plannerConfigurationOverview]] == Overview Solving a planning problem with OptaPlanner consists of the following steps: . *Model your planning problem* as a class annotated with the ``@PlanningSolution`` annotation, for example the ``NQueens`` class. . **Configure a ``**Solver**``**, for example a First Fit and Tabu Search solver for any `NQueens` instance. . *Load a problem data set* from your data layer, for example a Four Queens instance. That is the planning problem. . *Solve it* with `Solver.solve(problem)` which returns the best solution found. image::PlannerConfiguration/inputOutputOverview.png[align=""center""] [[solverConfiguration]] == Solver configuration [[solverConfigurationByXML]] === Solver configuration by XML Build a `Solver` instance with the ``SolverFactory``. Configure the `SolverFactory` with a solver configuration XML file, provided as a classpath resource (as defined by ``ClassLoader.getResource()``): [source,java,options=""nowrap""] ---- SolverFactory solverFactory = SolverFactory.createFromXmlResource( ""org/optaplanner/examples/nqueens/solver/nqueensSolverConfig.xml""); Solver solver = solverFactory.buildSolver(); ---- In a typical project (following the Maven directory structure), that solverConfig XML file would be located at ``$PROJECT_DIR/src/main/resources/org/optaplanner/examples/nqueens/solver/nqueensSolverConfig.xml``. Alternatively, a `SolverFactory` can be created from a ``File`` with ``SolverFactory.createFromXmlFile()``. However, for portability reasons, a classpath resource is recommended. [NOTE] ==== On some environments (<>, <>, ...), classpath resources (the solver config, domain classes, etc.) in your jars might not be available to the default `ClassLoader` of the `optaplanner-core` jar. In those cases, provide the `ClassLoader` of your classes as a parameter: [source,java,options=""nowrap""] ---- SolverFactory solverFactory = SolverFactory.createFromXmlResource( "".../nqueensSolverConfig.xml"", getClass().getClassLoader()); ---- ==== Both a `Solver` and a `SolverFactory` have a generic type called ``Solution_``, which is the class representing a <>. A solver configuration XML file looks like this: [source,xml,options=""nowrap""] ---- org.optaplanner.examples.nqueens.domain.NQueens org.optaplanner.examples.nqueens.domain.Queen org.optaplanner.examples.nqueens.score.NQueensConstraintProvider ... ... ... ---- Notice the three parts in it: * Define the model. * Define the score function. * Optionally configure the optimization algorithm(s). These various parts of a configuration are explained further in this manual. *OptaPlanner makes it relatively easy to switch optimization algorithm(s) just by changing the configuration.* There is even a <> which allows you to play out different configurations against each other and report the most appropriate configuration for your use case. [[solverConfigurationByJavaAPI]] === Solver configuration by Java API A solver configuration can also be configured with the `SolverConfig` API. This is especially useful to change some values dynamically at runtime. For example, to change the running time based on system property, before building the ``Solver``: [source,java,options=""nowrap""] ---- SolverConfig solverConfig = SolverConfig.createFromXmlResource( ""org/optaplanner/examples/nqueens/solver/nqueensSolverConfig.xml""); solverConfig.withTerminationConfig(new TerminationConfig() .withMinutesSpentLimit(userInput)); SolverFactory solverFactory = SolverFactory.create(solverConfig); Solver solver = solverFactory.buildSolver(); ---- Every element in the solver configuration XML is available as a `$$*$$Config` class or a property on a `$$*$$Config` class in the package namespace ``org.optaplanner.core.config``. These `$$*$$Config` classes are the Java representation of the XML format. They build the runtime components (of the package namespace ``org.optaplanner.core.impl``) and assemble them into an efficient ``Solver``. [NOTE] ==== To configure a `SolverFactory` dynamically for each user request, build a template `SolverConfig` during initialization and copy it with the copy constructor for each user request: [source,java,options=""nowrap""] ---- private SolverConfig template; public void init() { template = SolverConfig.createFromXmlResource( ""org/optaplanner/examples/nqueens/solver/nqueensSolverConfig.xml""); template.setTerminationConfig(new TerminationConfig()); } // Called concurrently from different threads public void userRequest(..., long userInput) { SolverConfig solverConfig = new SolverConfig(template); // Copy it solverConfig.getTerminationConfig().setMinutesSpentLimit(userInput); SolverFactory solverFactory = SolverFactory.create(solverConfig); Solver solver = solverFactory.buildSolver(); ... } ---- ==== [[annotationAlternatives]] === Annotation alternatives OptaPlanner needs to be told which classes in your domain model are planning entities, which properties are planning variables, etc. There are several ways to deliver this information: * Add class annotations and JavaBean property annotations on the domain model (recommended). The property annotations must be on the getter method, not on the setter method. Such a getter does not need to be public. * Add class annotations and field annotations on the domain model. Such a field does not need to be public. * No annotations: externalize the domain configuration in an XML file. This is https://issues.redhat.com/browse/PLANNER-151[not yet supported]. This manual focuses on the first manner, but every feature supports all three manners, even if it's not explicitly mentioned. [[domainAccess]] === Domain access OptaPlanner by default accesses your domain using reflection, which will always work, but is slow compared to direct access. Alternatively, you can configure OptaPlanner to access your domain using Gizmo, which will generate bytecode that directly access the fields/methods of your domain without reflection. However, it comes with some restrictions: * The planning annotations can only be on public fields and public getters. * io.quarkus.gizmo:gizmo must be on the classpath. These restrictions do not apply when using OptaPlanner with Quarkus, where Gizmo is the default domain access type. To use Gizmo outside of Quarkus, set the `domainAccessType` in the Solver Configuration: [source,xml,options=""nowrap""] ---- GIZMO ---- [[customPropertiesConfiguration]] === Custom properties configuration Solver configuration elements, that instantiate classes and explicitly mention it, support custom properties. Custom properties are useful to tweak dynamic values through the <>. For example, presume your `EasyScoreCalculator` has heavy calculations (which are cached) and you want to increase the cache size in one benchmark: [source,xml,options=""nowrap""] ---- ...MyEasyScoreCalculator ---- Add a public setter for each custom property, which is called when a `Solver` is built. [source,java,options=""nowrap""] ---- public class MyEasyScoreCalculator extends EasyScoreCalculator { private int myCacheSize = 500; // Default value @SuppressWarnings(""unused"") public void setMyCacheSize(int myCacheSize) { this.myCacheSize = myCacheSize; } ... } ---- Most value types are supported (including `boolean`, `int`, `double`, `BigDecimal`, `String` and enums). [[modelAPlanningProblem]] == Model a planning problem [[isThisClassAProblemFactOrPlanningEntity]] === Is this class a problem fact or planning entity? Look at a dataset of your planning problem. You will recognize domain classes in there, each of which can be categorized as one of the following: * An unrelated class: not used by any of the score constraints. From a planning standpoint, this data is obsolete. * A *problem fact* class: used by the score constraints, but does NOT change during planning (as long as the problem stays the same). For example: ``Bed``, ``Room``, ``Shift``, ``Employee``, ``Topic``, ``Period``, ... All the properties of a problem fact class are problem properties. * A *planning entity* class: used by the score constraints and changes during planning. For example: ``BedDesignation``, ``ShiftAssignment``, ``Exam``, ... The properties that change during planning are planning variables. The other properties are problem properties. Ask yourself: __What class changes during planning?__ __Which class has variables that I want the ``__Solver__`` to change for me?__ That class is a planning entity. Most use cases have only one planning entity class. Most use cases also have only one planning variable per planning entity class. [NOTE] ==== In <>, even though the problem itself changes, problem facts do not really change during planning, instead they change between planning (because the Solver temporarily stops to apply the problem fact changes). ==== To create a good domain model, read the <>. *In OptaPlanner, all problem facts and planning entities are plain old JavaBeans (POJOs).* Load them from a database, an XML file, a data repository, a REST service, a noSQL cloud, ... (see <>): it doesn't matter. [[problemFact]] === Problem fact A problem fact is any JavaBean (POJO) with getters that does not change during planning. For example in n queens, the columns and rows are problem facts: [source,java,options=""nowrap""] ---- public class Column { private int index; // ... getters } ---- [source,java,options=""nowrap""] ---- public class Row { private int index; // ... getters } ---- A problem fact can reference other problem facts of course: [source,java,options=""nowrap""] ---- public class Course { private String code; private Teacher teacher; // Other problem fact private int lectureSize; private int minWorkingDaySize; private List curriculumList; // Other problem facts private int studentSize; // ... getters } ---- A problem fact class does _not_ require any OptaPlanner specific code. For example, you can reuse your domain classes, which might have JPA annotations. [NOTE] ==== Generally, better designed domain classes lead to simpler and more efficient score constraints. Therefore, when dealing with a messy (denormalized) legacy system, it can sometimes be worthwhile to convert the messy domain model into a OptaPlanner specific model first. For example: if your domain model has two `Teacher` instances for the same teacher that teaches at two different departments, it is harder to write a correct score constraint that constrains a teacher's spare time on the original model than on an adjusted model. Alternatively, you can sometimes also introduce <> to enrich the domain model for planning only. ==== [[planningEntity]] === Planning entity [[planningEntityAnnotation]] ==== Planning entity annotation A planning entity is a JavaBean (POJO) that changes during solving, for example a `Queen` that changes to another row. A planning problem has multiple planning entities, for example for a single n queens problem, each `Queen` is a planning entity. But there is usually only one planning entity class, for example the `Queen` class. A planning entity class needs to be annotated with the `@PlanningEntity` annotation. Each planning entity class has one or more _planning variables_ (which can be <> or <>). It should also have one or more _defining_ properties. For example in n queens, a `Queen` is defined by its `Column` and has a planning variable ``Row``. This means that a Queen's column never changes during solving, while its row does change. [source,java,options=""nowrap""] ---- @PlanningEntity public class Queen { private Column column; // Planning variables: changes during planning, between score calculations. private Row row; // ... getters and setters } ---- A planning entity class can have multiple planning variables. For example, a `Lecture` is defined by its `Course` and its index in that course (because one course has multiple lectures). Each `Lecture` needs to be scheduled into a `Period` and a `Room` so it has two planning variables (period and room). For example: the course Mathematics has eight lectures per week, of which the first lecture is Monday morning at 08:00 in room 212. [source,java,options=""nowrap""] ---- @PlanningEntity public class Lecture { private Course course; private int lectureIndexInCourse; // Planning variables: changes during planning, between score calculations. private Period period; private Room room; // ... } ---- The solver configuration needs to declare each planning entity class: [source,java,options=""nowrap""] ---- ... org.optaplanner.examples.nqueens.domain.Queen ... ---- Some uses cases have multiple planning entity classes. For example: route freight and trains into railway network arcs, where each freight can use multiple trains over its journey and each train can carry multiple freights per arc. Having multiple planning entity classes directly raises the implementation complexity of your use case. [NOTE] ==== _Do not create unnecessary planning entity classes._ This leads to difficult `Move` implementations and slower score calculation. For example, do not create a planning entity class to hold the total free time of a teacher, which needs to be kept up to date as the `Lecture` planning entities change. Instead, calculate the free time in the score constraints (or as a <>) and put the result per teacher into a logically inserted score object. If historic data needs to be considered too, then create problem fact to hold the total of the historic assignments up to, but __not including__, the planning window (so that it does not change when a planning entity changes) and let the score constraints take it into account. ==== [NOTE] ==== Planning entity `hashCode()` implementations must remain constant. Therefore entity `hashCode()` must not depend on any planning variables. Pay special attention when using data structures with auto-generated `hashCode()` as entities, such as Java records or Kotlin data classes. ==== [[planningEntityDifficulty]] ==== Planning entity difficulty Some optimization algorithms work more efficiently if they have an estimation of which planning entities are more difficult to plan. For example: in bin packing bigger items are harder to fit, in course scheduling lectures with more students are more difficult to schedule, and in n queens the middle queens are more difficult to fit on the board. [NOTE] ==== *Do not try to use planning entity difficulty to implement a business constraint.* It will not affect the score function: if we have infinite solving time, the returned solution will be the same. To attain a schedule in which certain entities are scheduled earlier in the schedule, <> to change the score function so it prefers such solutions. Only consider adding planning entity difficulty too if it can make the solver more efficient. ==== To allow the heuristics to take advantage of that domain specific information, set a `difficultyComparatorClass` to the `@PlanningEntity` annotation: [source,java,options=""nowrap""] ---- @PlanningEntity(difficultyComparatorClass = CloudProcessDifficultyComparator.class) public class CloudProcess { // ... } ---- [source,java,options=""nowrap""] ---- public class CloudProcessDifficultyComparator implements Comparator { public int compare(CloudProcess a, CloudProcess b) { return new CompareToBuilder() .append(a.getRequiredMultiplicand(), b.getRequiredMultiplicand()) .append(a.getId(), b.getId()) .toComparison(); } } ---- Alternatively, you can also set a `difficultyWeightFactoryClass` to the `@PlanningEntity` annotation, so that you have access to the rest of the problem facts from the solution too: [source,java,options=""nowrap""] ---- @PlanningEntity(difficultyWeightFactoryClass = QueenDifficultyWeightFactory.class) public class Queen { // ... } ---- See <> for more information. [IMPORTANT] ==== Difficulty should be implemented ascending: easy entities are lower, difficult entities are higher. For example, in bin packing: small item < medium item < big item. Although most algorithms start with the more difficult entities first, they just reverse the ordering. ==== _None of the current planning variable states should be used to compare planning entity difficulty._ During Construction Heuristics, those variables are likely to be `null` anyway. For example, a ``Queen``'s `row` variable should not be used. [[planningVariable]] === Planning variable (genuine) [[planningVariableAnnotation]] ==== Planning variable annotation A planning variable is a JavaBean property (so a getter and setter) on a planning entity. It points to a planning value, which changes during planning. For example, a ``Queen``'s `row` property is a genuine planning variable. Note that even though a ``Queen``'s `row` property changes to another `Row` during planning, no `Row` instance itself is changed. Normally planning variables are genuine, but advanced cases can also have <>. A genuine planning variable getter needs to be annotated with the `@PlanningVariable` annotation, which needs a non-empty `valueRangeProviderRefs` property. [source,java,options=""nowrap""] ---- @PlanningEntity public class Queen { ... private Row row; @PlanningVariable(valueRangeProviderRefs = {""rowRange""}) public Row getRow() { return row; } public void setRow(Row row) { this.row = row; } } ---- The `valueRangeProviderRefs` property defines what are the possible planning values for this planning variable. It references one or more ``@ValueRangeProvider`` ``id``'s. [NOTE] ==== A @PlanningVariable annotation needs to be on a member in a class with a @PlanningEntity annotation. It is ignored on parent classes or subclasses without that annotation. ==== <> instead of the property works too: [source,java,options=""nowrap""] ---- @PlanningEntity public class Queen { ... @PlanningVariable(valueRangeProviderRefs = {""rowRange""}) private Row row; } ---- [[nullablePlanningVariable]] ==== Nullable planning variable By default, an initialized planning variable cannot be ``null``, so an initialized solution will never use `null` for any of its planning variables. In an over-constrained use case, this can be counterproductive. For example: in task assignment with too many tasks for the workforce, we would rather leave low priority tasks unassigned instead of assigning them to an overloaded worker. To allow an initialized planning variable to be ``null``, set `nullable` to ``true``: [source,java,options=""nowrap""] ---- @PlanningVariable(..., nullable = true) public Worker getWorker() { return worker; } ---- [NOTE] ==== Constraint Streams filter out planning entities with a `null` planning variable by default. Use <> to avoid such unwanted behaviour. ==== OptaPlanner will automatically add the value `null` to the value range. There is no need to add `null` in a collection provided by a ``ValueRangeProvider``. [NOTE] ==== Using a nullable planning variable implies that your score calculation is responsible for punishing (or even rewarding) variables with a `null` value. ==== [WARNING] ==== Currently <> planning variables are not compatible with `nullable`. ==== <> (especially <>) does not mix well with a nullable planning variable. Every time the Solver starts or a problem fact change is made, the <> will try to initialize all the `null` variables again, which can be a huge waste of time. One way to deal with this is to filter the entity selector of the placer in the construction heuristic. [source,xml,options=""nowrap""] ---- ... ... ... ... ... ---- [[whenIsAPlanningVariableInitialized]] ==== When is a planning variable considered initialized? A planning variable is considered initialized if its value is not `null` or if the variable is ``nullable``. So a nullable variable is always considered initialized. A planning entity is initialized if all of its planning variables are initialized. A solution is initialized if all of its planning entities are initialized. [[planningValueAndPlanningValueRange]] === Planning value and planning value range [[planningValue]] ==== Planning value A planning value is a possible value for a genuine planning variable. Usually, a planning value is a problem fact, but it can also be any object, for example a ``double``. It can even be another planning entity or even an interface implemented by both a planning entity and a problem fact. A planning value range is the set of possible planning values for a planning variable. This set can be a countable (for example row ``1``, ``2``, `3` or ``4``) or uncountable (for example any `double` between `0.0` and ``1.0``). [[planningValueRangeProvider]] ==== Planning value range provider [[planningValueRangeProviderOverview]] ===== Overview The value range of a planning variable is defined with the `@ValueRangeProvider` annotation. A `@ValueRangeProvider` annotation always has a property ``id``, which is referenced by the ``@PlanningVariable``'s property ``valueRangeProviderRefs``. This annotation can be located on two types of methods: * On the Solution: All planning entities share the same value range. * On the planning entity: The value range differs per planning entity. This is less common. [NOTE] ==== A @ValueRangeProvider annotation needs to be on a member in a class with a @PlanningSolution or a @PlanningEntity annotation. It is ignored on parent classes or subclasses without those annotations. ==== The return type of that method can be three types: * ``Collection``: The value range is defined by a `Collection` (usually a ``List``) of its possible values. * Array: The value range is defined by an array of its possible values. * ``ValueRange``: The value range is defined by its bounds. This is less common. [[valueRangeProviderOnSolution]] ===== `ValueRangeProvider` on the solution All instances of the same planning entity class share the same set of possible planning values for that planning variable. This is the most common way to configure a value range. The `@PlanningSolution` implementation has method that returns a `Collection` (or a ``ValueRange``). Any value from that `Collection` is a possible planning value for this planning variable. [source,java,options=""nowrap""] ---- @PlanningVariable(valueRangeProviderRefs = {""rowRange""}) public Row getRow() { return row; } ---- [source,java,options=""nowrap""] ---- @PlanningSolution public class NQueens { ... @ValueRangeProvider(id = ""rowRange"") public List getRowList() { return rowList; } } ---- [IMPORTANT] ==== That `Collection` (or ``ValueRange``) must not contain the value ``null``, not even for a <>. ==== <> instead of the property works too: [source,java,options=""nowrap""] ---- @PlanningSolution public class NQueens { ... @ValueRangeProvider(id = ""rowRange"") private List rowList; } ---- [[valueRangeProviderOnPlanningEntity]] ===== `ValueRangeProvider` on the Planning Entity Each planning entity has its own value range (a set of possible planning values) for the planning variable. For example, if a teacher can *never* teach in a room that does not belong to his department, lectures of that teacher can limit their room value range to the rooms of his department. [source,java,options=""nowrap""] ---- @PlanningVariable(valueRangeProviderRefs = {""departmentRoomRange""}) public Room getRoom() { return room; } @ValueRangeProvider(id = ""departmentRoomRange"") public List getPossibleRoomList() { return getCourse().getTeacher().getDepartment().getRoomList(); } ---- Never use this to enforce a soft constraint (or even a hard constraint when the problem might not have a feasible solution). For example: __Unless there is no other way__, a teacher cannot teach in a room that does not belong to his department. In this case, the teacher should _not_ be limited in his room value range (because sometimes there is no other way). [NOTE] ==== By limiting the value range specifically of one planning entity, you are effectively creating a __built-in hard constraint__. This can have the benefit of severely lowering the number of possible solutions; however, it can also take away the freedom of the optimization algorithms to temporarily break that constraint in order to escape from a local optimum. ==== A planning entity should _not_ use other planning entities to determine its value range. That would only try to make the planning entity solve the planning problem itself and interfere with the optimization algorithms. Every entity has its own `List` instance, unless multiple entities have the same value range. For example, if teacher A and B belong to the same department, they use the same `List` instance. Furthermore, each `List` contains a subset of the same set of planning value instances. For example, if department A and B can both use room X, then their `List` instances contain the same `Room` instance. [NOTE] ==== A `ValueRangeProvider` on the planning entity consumes more memory than `ValueRangeProvider` on the Solution and disables certain automatic performance optimizations. ==== [WARNING] ==== A `ValueRangeProvider` on the planning entity is not currently compatible with a <> variable. ==== [[valueRangeFactory]] ===== `ValueRangeFactory` Instead of a ``Collection``, you can also return a `ValueRange` or ``CountableValueRange``, build by the ``ValueRangeFactory``: [source,java,options=""nowrap""] ---- @ValueRangeProvider(id = ""delayRange"") public CountableValueRange getDelayRange() { return ValueRangeFactory.createIntValueRange(0, 5000); } ---- A `ValueRange` uses far less memory, because it only holds the bounds. In the example above, a `Collection` would need to hold all `5000` ints, instead of just the two bounds. Furthermore, an `incrementUnit` can be specified, for example if you have to buy stocks in units of 200 pieces: [source,java,options=""nowrap""] ---- @ValueRangeProvider(id = ""stockAmountRange"") public CountableValueRange getStockAmountRange() { // Range: 0, 200, 400, 600, ..., 9999600, 9999800, 10000000 return ValueRangeFactory.createIntValueRange(0, 10000000, 200); } ---- [NOTE] ==== Return `CountableValueRange` instead of `ValueRange` whenever possible (so OptaPlanner knows that it's countable). ==== The `ValueRangeFactory` has creation methods for several value class types: * ``boolean``: A boolean range. * ``int``: A 32bit integer range. * ``long``: A 64bit integer range. * ``double``: A 64bit floating point range which only supports random selection (because it does not implement ``CountableValueRange``). * ``BigInteger``: An arbitrary-precision integer range. * ``BigDecimal``: A decimal point range. By default, the increment unit is the lowest non-zero value in the scale of the bounds. * `Temporal` (such as ``LocalDate``, ``LocalDateTime``, ...): A time range. [[combineValueRangeProviders]] ===== Combine `ValueRangeProviders` Value range providers can be combined, for example: [source,java,options=""nowrap""] ---- @PlanningVariable(valueRangeProviderRefs = {""companyCarRange"", ""personalCarRange""}) public Car getCar() { return car; } ---- [source,java,options=""nowrap""] ---- @ValueRangeProvider(id = ""companyCarRange"") public List getCompanyCarList() { return companyCarList; } @ValueRangeProvider(id = ""personalCarRange"") public List getPersonalCarList() { return personalCarList; } ---- [[planningValueStrength]] ==== Planning value strength Some optimization algorithms work a bit more efficiently if they have an estimation of which planning values are stronger, which means they are more likely to satisfy a planning entity. For example: in bin packing bigger containers are more likely to fit an item and in course scheduling bigger rooms are less likely to break the student capacity constraint. Usually, the efficiency gain of planning value strength is far less than that of <>. [NOTE] ==== *Do not try to use planning value strength to implement a business constraint.* It will not affect the score function: if we have infinite solving time, the returned solution will be the same. To affect the score function, <>. Only consider adding planning value strength too if it can make the solver more efficient. ==== To allow the heuristics to take advantage of that domain specific information, set a `strengthComparatorClass` to the `@PlanningVariable` annotation: [source,java,options=""nowrap""] ---- @PlanningVariable(..., strengthComparatorClass = CloudComputerStrengthComparator.class) public CloudComputer getComputer() { return computer; } ---- [source,java,options=""nowrap""] ---- public class CloudComputerStrengthComparator implements Comparator { public int compare(CloudComputer a, CloudComputer b) { return new CompareToBuilder() .append(a.getMultiplicand(), b.getMultiplicand()) .append(b.getCost(), a.getCost()) // Descending (but this is debatable) .append(a.getId(), b.getId()) .toComparison(); } } ---- [NOTE] ==== If you have multiple planning value classes in the _same_ value range, the `strengthComparatorClass` needs to implement a `Comparator` of a common superclass (for example ``Comparator``) and be able to handle comparing instances of those different classes. ==== Alternatively, you can also set a `strengthWeightFactoryClass` to the `@PlanningVariable` annotation, so you have access to the rest of the problem facts from the solution too: [source,java,options=""nowrap""] ---- @PlanningVariable(..., strengthWeightFactoryClass = RowStrengthWeightFactory.class) public Row getRow() { return row; } ---- See <> for more information. [IMPORTANT] ==== Strength should be implemented ascending: weaker values are lower, stronger values are higher. For example in bin packing: small container < medium container < big container. ==== _None of the current planning variable state in any of the planning entities should be used to compare planning values._ During construction heuristics, those variables are likely to be ``null``. For example, none of the `row` variables of any `Queen` may be used to determine the strength of a ``Row``. [[chainedPlanningVariable]] ==== Chained planning variable (TSP, VRP, ...) Some use cases, such as TSP and Vehicle Routing, require __chaining__. This means the planning entities point to each other and form a chain. By modeling the problem as a set of chains (instead of a set of trees/loops), the search space is heavily reduced. A planning variable that is chained either: * Directly points to a problem fact (or planning entity), which is called an __anchor__. * Points to another planning entity with the same planning variable, which recursively points to an anchor. Here are some examples of valid and invalid chains: image::PlannerConfiguration/chainPrinciples.png[align=""center""] *Every initialized planning entity is part of an open-ended chain that begins from an anchor.* A valid model means that: * A chain is never a loop. The tail is always open. * Every chain always has exactly one anchor. The anchor is never an instance of the planning entity class that contains the chained planning variable. * A chain is never a tree, it is always a line. Every anchor or planning entity has at most one trailing planning entity. * Every initialized planning entity is part of a chain. * An anchor with no planning entities pointing to it, is also considered a chain. [WARNING] ==== A planning problem instance given to the `Solver` must be valid. ==== [NOTE] ==== If your constraints dictate a closed chain, model it as an open-ended chain (which is easier to persist in a database) and implement a score constraint for the last entity back to the anchor. ==== The optimization algorithms and built-in ``Move``s do chain correction to guarantee that the model stays valid: image::PlannerConfiguration/chainCorrection.png[align=""center""] [WARNING] ==== A custom `Move` implementation must leave the model in a valid state. ==== For example, in TSP the anchor is a `Domicile` (in vehicle routing it is ``Vehicle``): [source,java,options=""nowrap""] ---- public class Domicile ... implements Standstill { ... public City getCity() {...} } ---- The anchor (which is a problem fact) and the planning entity implement a common interface, for example TSP's ``Standstill``: [source,java,options=""nowrap""] ---- public interface Standstill { City getCity(); } ---- That interface is the return type of the planning variable. Furthermore, the planning variable is chained. For example TSP's `Visit` (in vehicle routing it is ``Customer``): [source,java,options=""nowrap""] ---- @PlanningEntity public class Visit ... implements Standstill { ... public City getCity() {...} @PlanningVariable(graphType = PlanningVariableGraphType.CHAINED, valueRangeProviderRefs = {""domicileRange"", ""visitRange""}) public Standstill getPreviousStandstill() { return previousStandstill; } public void setPreviousStandstill(Standstill previousStandstill) { this.previousStandstill = previousStandstill; } } ---- Notice how two value range providers are usually combined: * The value range provider that holds the anchors, for example ``domicileList``. * The value range provider that holds the initialized planning entities, for example ``visitList``. [[planningProblemAndPlanningSolution]] === Planning problem and planning solution [[planningProblemInstance]] ==== Planning problem instance A dataset for a planning problem needs to be wrapped in a class for the `Solver` to solve. That solution class represents both the planning problem and (if solved) a solution. It is annotated with a `@PlanningSolution` annotation. For example in n queens, the solution class is the `NQueens` class, which contains a `Column` list, a `Row` list, and a `Queen` list. A planning problem is actually an unsolved planning solution or - stated differently - an uninitialized solution. For example in n queens, that `NQueens` class has the `@PlanningSolution` annotation, yet every `Queen` in an unsolved `NQueens` class is not yet assigned to a `Row` (their `row` property is ``null``). That's not a feasible solution. It's not even a possible solution. It's an uninitialized solution. [[solutionClass]] ==== Solution class A solution class holds all problem facts, planning entities and a score. It is annotated with a `@PlanningSolution` annotation. For example, an `NQueens` instance holds a list of all columns, all rows and all `Queen` instances: [source,java,options=""nowrap""] ---- @PlanningSolution public class NQueens { // Problem facts private int n; private List columnList; private List rowList; // Planning entities private List queenList; private SimpleScore score; ... } ---- The solver configuration needs to declare the planning solution class: [source,java,options=""nowrap""] ---- ... org.optaplanner.examples.nqueens.domain.NQueens ... ---- [[planningEntitiesOfASolution]] ==== Planning entities of a solution (`@PlanningEntityCollectionProperty`) OptaPlanner needs to extract the entity instances from the solution instance. It gets those collection(s) by calling every getter (or field) that is annotated with ``@PlanningEntityCollectionProperty``: [source,java,options=""nowrap""] ---- @PlanningSolution public class NQueens { ... private List queenList; @PlanningEntityCollectionProperty public List getQueenList() { return queenList; } } ---- There can be multiple `@PlanningEntityCollectionProperty` annotated members. Those can even return a `Collection` with the same entity class type. Instead of `Collection`, it can also return an array. [NOTE] ==== A `@PlanningEntityCollectionProperty` annotation needs to be on a member in a class with a `@PlanningSolution` annotation. It is ignored on parent classes or subclasses without that annotation. ==== In rare cases, a planning entity might be a singleton: use `@PlanningEntityProperty` on its getter (or field) instead. Both annotations can also be <> if enabled. [[scoreOfASolution]] ==== `Score` of asSolution (`@PlanningScore`) A `@PlanningSolution` class requires a score property (or field), which is annotated with a `@PlanningScore` annotation. The score property is `null` if the score hasn't been calculated yet. The `score` property is typed to the specific `Score` implementation of your use case. For example, `NQueens` uses a <>: [source,java,options=""nowrap""] ---- @PlanningSolution public class NQueens { ... private SimpleScore score; @PlanningScore public SimpleScore getScore() { return score; } public void setScore(SimpleScore score) { this.score = score; } } ---- Most use cases use a <> instead: [source,java,options=""nowrap""] ---- @PlanningSolution public class CloudBalance { ... private HardSoftScore score; @PlanningScore public HardSoftScore getScore() { return score; } public void setScore(HardSoftScore score) { this.score = score; } } ---- Some use cases use <>. This annotation can also be <> if enabled. [[problemFacts]] ==== Problem facts of a solution (`@ProblemFactCollectionProperty`) For <> and <>, OptaPlanner needs to extract the problem fact instances from the solution instance. It gets those collection(s) by calling every method (or field) that is annotated with ``@ProblemFactCollectionProperty``. All objects returned by those methods are available to use by Constraint Streams or Drools rules. For example in `NQueens` all `Column` and `Row` instances are problem facts. [source,java,options=""nowrap""] ---- @PlanningSolution public class NQueens { ... private List columnList; private List rowList; @ProblemFactCollectionProperty public List getColumnList() { return columnList; } @ProblemFactCollectionProperty public List getRowList() { return rowList; } } ---- All planning entities are automatically inserted into the working memory. Do note add an annotation on their properties. [NOTE] ==== The problem facts methods are not called often: at most only once per solver phase per solver thread. ==== There can be multiple `@ProblemFactCollectionProperty` annotated members. Those can even return a `Collection` with the same class type, but they shouldn't return the same instance twice. Instead of `Collection`, it can also return an array. [NOTE] ==== A @ProblemFactCollectionProperty annotation needs to be on a member in a class with a @PlanningSolution annotation. It is ignored on parent classes or subclasses without that annotation. ==== In rare cases, a problem fact might be a singleton: use `@ProblemFactProperty` on its method (or field) instead. Both annotations can also be <> if enabled. [[cachedProblemFact]] ===== Cached problem fact A cached problem fact is a problem fact that does not exist in the real domain model, but is calculated before the `Solver` really starts solving. The problem facts methods have the opportunity to enrich the domain model with such cached problem facts, which can lead to simpler and faster score constraints. For example in examination, a cached problem fact `TopicConflict` is created for every two ``Topic``s which share at least one ``Student``. [source,java,options=""nowrap""] ---- @ProblemFactCollectionProperty private List calculateTopicConflictList() { List topicConflictList = new ArrayList(); for (Topic leftTopic : topicList) { for (Topic rightTopic : topicList) { if (leftTopic.getId() < rightTopic.getId()) { int studentSize = 0; for (Student student : leftTopic.getStudentList()) { if (rightTopic.getStudentList().contains(student)) { studentSize++; } } if (studentSize > 0) { topicConflictList.add(new TopicConflict(leftTopic, rightTopic, studentSize)); } } } } return topicConflictList; } ---- Where a score constraint needs to check that no two exams with a topic that shares a student are scheduled close together (depending on the constraint: at the same time, in a row, or in the same day), the `TopicConflict` instance can be used as a problem fact, rather than having to combine every two `Student` instances. [[autoDiscoverSolutionProperties]] ==== Auto discover solution properties Instead of configuring each property (or field) annotation explicitly, some can also be deduced automatically by OptaPlanner. For example, on the cloud balancing example: [source,java,options=""nowrap""] ---- @PlanningSolution(autoDiscoverMemberType = AutoDiscoverMemberType.FIELD) public class CloudBalance { // Auto discovered as @ProblemFactCollectionProperty @ValueRangeProvider(id = ""computerRange"") // Not (yet) auto discovered private List computerList; // Auto discovered as @PlanningEntityCollectionProperty private List processList; // Auto discovered as @PlanningScore private HardSoftScore score; ... } ---- The `AutoDiscoverMemberType` can be: * `NONE`: No auto discovery. * `FIELD`: Auto discover all fields on the `@PlanningSolution` class * `GETTER`: Auto discover all getters on the `@PlanningSolution` class The automatic annotation is based on the field type (or getter return type): * `@ProblemFactProperty`: when it isn't a `Collection`, an array, a `@PlanningEntity` class or a `Score` * `@ProblemFactCollectionProperty`: when it's a `Collection` (or array) of a type that isn't a `@PlanningEntity` class * `@PlanningEntityProperty`: when it is a configured `@PlanningEntity` class or subclass * `@PlanningEntityCollectionProperty`: when it's a `Collection` (or array) of a type that is a configured `@PlanningEntity` class or subclass * `@PlanningScore`: when it is a `Score` or subclass These automatic annotation can still be overwritten per field (or getter). Specifically, a <> always needs to override with an explicit `@PlanningScore` annotation to define the number of hard and soft levels. [[cloningASolution]] ==== Cloning a solution Most (if not all) optimization algorithms clone the solution each time they encounter a new best solution (so they can recall it later) or to work with multiple solutions in parallel. [NOTE] ==== There are many ways to clone, such as a shallow clone, deep clone, ... This context focuses on __a planning clone__. ==== A planning clone of a solution must fulfill these requirements: * The clone must represent the same planning problem. Usually it reuses the same instances of the problem facts and problem fact collections as the original. * The clone must use different, cloned instances of the entities and entity collections. Changes to an original solution entity's variables must not affect its clone. image::PlannerConfiguration/solutionCloning.png[align=""center""] *Implementing a planning clone method is hard, therefore you do not need to implement it.* [[fieldAccessingSolutionCloner]] ===== `FieldAccessingSolutionCloner` This `SolutionCloner` is used by default. It works well for most use cases. [WARNING] ==== When the `FieldAccessingSolutionCloner` clones one of your collections or maps, it may not recognize the implementation and replace it with `ArrayList`, `LinkedHashSet`, `TreeSet`, `LinkedHashMap` or `TreeMap` (whichever is more applicable) . It recognizes most of the common JDK collection and map implementations. ==== The `FieldAccessingSolutionCloner` does not clone problem facts by default. If any of your problem facts needs to be deep cloned for a planning clone, for example if the problem fact references a planning entity or the planning solution, mark its class with a `@DeepPlanningClone` annotation: [source,java,options=""nowrap""] ---- @DeepPlanningClone public class SeatDesignationDependency { private SeatDesignation leftSeatDesignation; // planning entity private SeatDesignation rightSeatDesignation; // planning entity ... } ---- In the example above, because `SeatDesignationDependency` references the planning entity `SeatDesignation` (which is deep planning cloned automatically), it should also be deep planning cloned. Alternatively, the `@DeepPlanningClone` annotation also works on a getter method or a field to planning clone it. If that property is a `Collection` or a `Map`, it will shallow clone it and deep planning clone any element thereof that is an instance of a class that has a `@DeepPlanningClone` annotation. [[customCloning]] ===== Custom cloning with a `SolutionCloner` To use a custom cloner, configure it on the planning solution: [source,java,options=""nowrap""] ---- @PlanningSolution(solutionCloner = NQueensSolutionCloner.class) public class NQueens { ... } ---- For example, a `NQueens` planning clone only deep clones all `Queen` instances. So when the original solution changes (later on during planning) and one or more ``Queen`` instances change, the planning clone isn't affected. [source,java,options=""nowrap""] ---- public class NQueensSolutionCloner implements SolutionCloner { @Override public NQueens cloneSolution(CloneLedger ledger, NQueens original) { NQueens clone = new NQueens(); ledger.registerClone(original, clone); clone.setId(original.getId()); clone.setN(original.getN()); clone.setColumnList(original.getColumnList()); clone.setRowList(original.getRowList()); List queenList = original.getQueenList(); List clonedQueenList = new ArrayList(queenList.size()); for (Queen originalQueen : queenList) { Queen cloneQueen = new Queen(); ledger.registerClone(originalQueen, cloneQueen); cloneQueen.setId(originalQueen.getId()); cloneQueen.setColumn(originalQueen.getColumn()); cloneQueen.setRow(originalQueen.getRow()); clonedQueenList.add(cloneQueen); } clone.setQueenList(clonedQueenList); clone.setScore(original.getScore()); return clone; } } ---- _The `cloneSolution()` method should only deep clone the planning entities._ Notice that the problem facts, such as `Column` and `Row` are normally _not_ cloned: even their `List` instances are _not_ cloned. If the problem facts were cloned too, then you would have to make sure that the new planning entity clones also refer to the new problem facts clones used by the cloned solution. For example, if you were to clone all `Row` instances, then each `Queen` clone and the `NQueens` clone itself should refer to those new `Row` clones. [WARNING] ==== Cloning an entity with a <> variable is devious: a variable of an entity A might point to another entity B. If A is cloned, then its variable must point to the clone of B, not the original B. ==== [[createAnUninitializedSolution]] ==== Create an uninitialized solution Create a `@PlanningSolution` instance to represent your planning problem's dataset, so it can be set on the `Solver` as the planning problem to solve. For example in n queens, an `NQueens` instance is created with the required `Column` and `Row` instances and every `Queen` set to a different `column` and every `row` set to ``null``. [source,java,options=""nowrap""] ---- private NQueens createNQueens(int n) { NQueens nQueens = new NQueens(); nQueens.setId(0L); nQueens.setN(n); nQueens.setColumnList(createColumnList(nQueens)); nQueens.setRowList(createRowList(nQueens)); nQueens.setQueenList(createQueenList(nQueens)); return nQueens; } private List createQueenList(NQueens nQueens) { int n = nQueens.getN(); List queenList = new ArrayList(n); long id = 0L; for (Column column : nQueens.getColumnList()) { Queen queen = new Queen(); queen.setId(id); id++; queen.setColumn(column); // Notice that we leave the PlanningVariable properties on null queenList.add(queen); } return queenList; } ---- .Uninitialized Solution for the Four Queens Puzzle image::PlannerConfiguration/uninitializedNQueens04.png[align=""left""] Usually, most of this data comes from your data layer, and your solution implementation just aggregates that data and creates the uninitialized planning entity instances to plan: [source,java,options=""nowrap""] ---- private void createLectureList(CourseSchedule schedule) { List courseList = schedule.getCourseList(); List lectureList = new ArrayList(courseList.size()); long id = 0L; for (Course course : courseList) { for (int i = 0; i < course.getLectureSize(); i++) { Lecture lecture = new Lecture(); lecture.setId(id); id++; lecture.setCourse(course); lecture.setLectureIndexInCourse(i); // Notice that we leave the PlanningVariable properties (period and room) on null lectureList.add(lecture); } } schedule.setLectureList(lectureList); } ---- [[useTheSolver]] == Use the `Solver` [[theSolverInterface]] === The `Solver` interface A `Solver` solves your planning problem. [source,java,options=""nowrap""] ---- public interface Solver { Solution_ solve(Solution_ problem); ... } ---- A `Solver` can only solve one planning problem instance at a time. It is built with a ``SolverFactory``, there is no need to implement it yourself. A `Solver` should only be accessed from a single thread, except for the methods that are specifically documented in javadoc as being thread-safe. The `solve()` method hogs the current thread. This can cause HTTP timeouts for REST services and it requires extra code to solve multiple datasets in parallel. To avoid such issues, use a <> instead. [[solvingAProblem]] === Solving a problem Solving a problem is quite easy once you have: * A `Solver` built from a solver configuration * A `@PlanningSolution` that represents the planning problem instance Just provide the planning problem as argument to the `solve()` method and it will return the best solution found: [source,java,options=""nowrap""] ---- NQueens problem = ...; NQueens bestSolution = solver.solve(problem); ---- For example in n queens, the `solve()` method will return an `NQueens` instance with every `Queen` assigned to a ``Row``. .Best Solution for the Four Queens Puzzle in 8ms (Also an Optimal Solution) image::PlannerConfiguration/solvedNQueens04.png[align=""left""] The `solve(Solution)` method can take a long time (depending on the problem size and the solver configuration). The `Solver` intelligently wades through <> of possible solutions and remembers the best solution it encounters during solving. Depending on a number of factors (including problem size, how much time the `Solver` has, the solver configuration, ...), <>. [NOTE] ==== The solution instance given to the method `solve(solution)` is changed by the ``Solver``, but do not mistake it for the best solution. The solution instance returned by the methods `solve(solution)` or `getBestSolution()` is most likely <> of the instance given to the method ``solve(solution)``, which implies it is a different instance. ==== [NOTE] ==== The solution instance given to the `solve(Solution)` method does not need to be uninitialized. It can be partially or fully initialized, which is often the case in <>. ==== [[environmentMode]] === Environment mode: are there bugs in my code? The environment mode allows you to detect common bugs in your implementation. It does not affect the <>. You can set the environment mode in the solver configuration XML file: [source,xml,options=""nowrap""] ---- FAST_ASSERT ... ---- A solver has a single `Random` instance. Some solver configurations use the `Random` instance a lot more than others. For example, Simulated Annealing depends highly on random numbers, while Tabu Search only depends on it to deal with score ties. The environment mode influences the seed of that `Random` instance. These are the environment modes: [[environmentModeFullAssert]] ==== `FULL_ASSERT` The FULL_ASSERT mode turns on all assertions (such as assert that the incremental score calculation is uncorrupted for each move) to fail-fast on a bug in a Move implementation, a constraint, the engine itself, ... This mode is reproducible (see the reproducible mode). It is also intrusive because it calls the method `calculateScore()` more frequently than a non-assert mode. The FULL_ASSERT mode is horribly slow (because it does not rely on incremental score calculation). [[environmentModeNonIntrusiveFullAssert]] ==== `NON_INTRUSIVE_FULL_ASSERT` The NON_INTRUSIVE_FULL_ASSERT turns on several assertions to fail-fast on a bug in a Move implementation, a constraint, the engine itself, ... This mode is reproducible (see the reproducible mode). It is non-intrusive because it does not call the method `calculateScore()` more frequently than a non assert mode. The NON_INTRUSIVE_FULL_ASSERT mode is horribly slow (because it does not rely on incremental score calculation). [[environmentModeFastAssert]] ==== `FAST_ASSERT` The FAST_ASSERT mode turns on most assertions (such as assert that an undoMove's score is the same as before the Move) to fail-fast on a bug in a Move implementation, a constraint, the engine itself, ... This mode is reproducible (see the reproducible mode). It is also intrusive because it calls the method `calculateScore()` more frequently than a non assert mode. The FAST_ASSERT mode is slow. It is recommended to write a test case that does a short run of your planning problem with the FAST_ASSERT mode on. [[environmentModeReproducible]] ==== `REPRODUCIBLE` (default) The reproducible mode is the default mode because it is recommended during development. In this mode, two runs in the same OptaPlanner version will execute the same code in the same order. **Those two runs will have the same result at every step**, except if the note below applies. This enables you to reproduce bugs consistently. It also allows you to benchmark certain refactorings (such as a score constraint performance optimization) fairly across runs. [NOTE] ==== Despite the reproducible mode, your application might still not be fully reproducible because of: * Use of `HashSet` (or another `Collection` which has an inconsistent order between JVM runs) for collections of planning entities or planning values (but not normal problem facts), especially in the solution implementation. Replace it with ``LinkedHashSet``. * Combining a time gradient dependent algorithms (most notably Simulated Annealing) together with time spent termination. A sufficiently large difference in allocated CPU time will influence the time gradient values. Replace Simulated Annealing with Late Acceptance. Or instead, replace time spent termination with step count termination. ==== The reproducible mode can be slightly slower than the non-reproducible mode. If your production environment can benefit from reproducibility, use this mode in production. In practice, this mode uses the default, fixed <> if no seed is specified, and it also disables certain concurrency optimizations (such as work stealing). [[environmentModeProduction]] ==== `NON_REPRODUCIBLE` The non-reproducible mode can be slightly faster than the reproducible mode. Avoid using it during development as it makes debugging and bug fixing painful. If your production environment doesn't care about reproducibility, use this mode in production. In practice, this mode uses no fixed <> if no seed is specified. [[logging]] === Logging level: what is the `Solver` doing? The best way to illuminate the black box that is a ``Solver``, is to play with the logging level: * **error**: Log errors, except those that are thrown to the calling code as a ``RuntimeException``. + [NOTE] ==== **If an error happens, OptaPlanner normally fails fast**: it throws a subclass of `RuntimeException` with a detailed message to the calling code. It does not log it as an error itself to avoid duplicate log messages. Except if the calling code explicitly catches and eats that ``RuntimeException``, a ``Thread``'s default `ExceptionHandler` will log it as an error anyway. Meanwhile, the code is disrupted from doing further harm or obfuscating the error. ==== * **warn**: Log suspicious circumstances. * **info**: Log every phase and the solver itself. See <>. * **debug**: Log every step of every phase. See <>. * **trace**: Log every move of every step of every phase. See <>. [NOTE] ==== Turning on `trace` logging, will slow down performance considerably: it is often four times slower. However, it is invaluable during development to discover a bottleneck. Even `debug` logging can slow down performance considerably for fast stepping algorithms (such as Late Acceptance and Simulated Annealing), but not for slow stepping algorithms (such as Tabu Search). Both cause congestion in <> with most appenders, see below. In Eclipse, `debug` logging to the console tends to cause congestion with a score calculation speeds above 10 000 per second. Nor IntelliJ, nor the Maven command line suffer from this problem. ==== For example, set it to `debug` logging, to see when the phases end and how fast steps are taken: [source,options=""nowrap""] ---- INFO Solving started: time spent (3), best score (-4init/0), random (JDK with seed 0). DEBUG CH step (0), time spent (5), score (-3init/0), selected move count (1), picked move (Queen-2 {null -> Row-0}). DEBUG CH step (1), time spent (7), score (-2init/0), selected move count (3), picked move (Queen-1 {null -> Row-2}). DEBUG CH step (2), time spent (10), score (-1init/0), selected move count (4), picked move (Queen-3 {null -> Row-3}). DEBUG CH step (3), time spent (12), score (-1), selected move count (4), picked move (Queen-0 {null -> Row-1}). INFO Construction Heuristic phase (0) ended: time spent (12), best score (-1), score calculation speed (9000/sec), step total (4). DEBUG LS step (0), time spent (19), score (-1), best score (-1), accepted/selected move count (12/12), picked move (Queen-1 {Row-2 -> Row-3}). DEBUG LS step (1), time spent (24), score (0), new best score (0), accepted/selected move count (9/12), picked move (Queen-3 {Row-3 -> Row-2}). INFO Local Search phase (1) ended: time spent (24), best score (0), score calculation speed (4000/sec), step total (2). INFO Solving ended: time spent (24), best score (0), score calculation speed (7000/sec), phase total (2), environment mode (REPRODUCIBLE). ---- All time spent values are in milliseconds. Everything is logged to http://www.slf4j.org/[SLF4J], which is a simple logging facade which delegates every log message to Logback, Apache Commons Logging, Log4j or java.util.logging. Add a dependency to the logging adaptor for your logging framework of choice. If you are not using any logging framework yet, use Logback by adding this Maven dependency (there is no need to add an extra bridge dependency): [source,xml,options=""nowrap""] ---- ch.qos.logback logback-classic 1.x ---- Configure the logging level on the `org.optaplanner` package in your `logback.xml` file: [source,xml,options=""nowrap""] ---- ... ---- If it isn't picked up, temporarily add the system property `-Dlogback.debug=true` to figure out why. [NOTE] ==== When running multiple solvers or one <>, most appenders (including the console) cause congestion with `debug` and `trace` logging. Switch to an async appender to avoid this problem or turn off `debug` logging. ==== If instead, you are still using Log4J 1.x (and you do not want to switch to its faster successor, Logback), add the bridge dependency: [source,xml,options=""nowrap""] ---- org.slf4j slf4j-log4j12 1.x ---- And configure the logging level on the package `org.optaplanner` in your `log4j.xml` file: [source,xml,options=""nowrap""] ---- ... ---- [NOTE] ==== In a multitenant application, multiple `Solver` instances might be running at the same time. To separate their logging into distinct files, surround the `solve()` call with an http://logback.qos.ch/manual/mdc.html[MDC]: [source,java,options=""nowrap""] ---- MDC.put(""tenant.name"",tenantName); MySolution bestSolution = solver.solve(problem); MDC.remove(""tenant.name""); ---- Then configure your logger to use different files for each ``${tenant.name}``. For example in Logback, use a `SiftingAppender` in ``logback.xml``: [source,xml,options=""nowrap""] ---- tenant.name unknown local/log/optaplanner-${tenant.name}.log ... ---- ==== [[randomNumberGenerator]] === Random number generator Many heuristics and metaheuristics depend on a pseudorandom number generator for move selection, to resolve score ties, probability based move acceptance, ... During solving, the same `Random` instance is reused to improve reproducibility, performance and uniform distribution of random values. To change the random seed of that `Random` instance, specify a ``randomSeed``: [source,xml,options=""nowrap""] ---- 0 ... ---- To change the pseudorandom number generator implementation, specify a ``randomType``: [source,xml,options=""nowrap""] ---- MERSENNE_TWISTER ... ---- The following types are supported: * `JDK` (default): Standard implementation (``java.util.Random``). * ``MERSENNE_TWISTER``: Implementation by http://commons.apache.org/proper/commons-math/userguide/random.html[Commons Math]. * ``WELL512A``, ``WELL1024A``, ``WELL19937A``, ``WELL19937C``, `WELL44497A` and ``WELL44497B``: Implementation by http://commons.apache.org/proper/commons-math/userguide/random.html[Commons Math]. For most use cases, the randomType has no significant impact on the average quality of the best solution on multiple datasets. If you want to confirm this on your use case, use the <>. [[solverManager]] == SolverManager A `SolverManager` is a facade for one or more `Solver` instances to simplify solving planning problems in REST and other enterprise services. Unlike the `Solver.solve(...)` method: * *`SolverManager.solve(...)` returns immediately*: it schedules a problem for asynchronous solving without blocking the calling thread. This avoids timeout issues of HTTP and other technologies. * *`SolverManager.solve(...)` solves multiple planning problems* of the same domain, in parallel. Internally a `SolverManager` manages a thread pool of solver threads, which call `Solver.solve(...)`, and a thread pool of consumer threads, which handle best solution changed events. In <> and <>, the `SolverManager` instance is automatically injected in your code. Otherwise, build a `SolverManager` instance with the `create(...)` method: [source,java,options=""nowrap""] ---- SolverConfig solverConfig = SolverConfig.createFromXmlResource("".../cloudBalancingSolverConfig.xml""); SolverManager solverManager = SolverManager.create(solverConfig, new SolverManagerConfig()); ---- Each problem submitted to the `SolverManager.solve(...)` methods needs a unique problem ID. Later calls to `getSolverStatus(problemId)` or `terminateEarly(problemId)` use that problem ID to distinguish between the planning problems. The problem ID must be an immutable class, such as `Long`, `String` or `java.util.UUID`. The `SolverManagerConfig` class has a `parallelSolverCount` property, that controls how many solvers are run in parallel. For example, if set to `4`, submitting five problems has four problems solving immediately, and the fifth one starts when another one ends. If those problems solve for 5 minutes each, the fifth problem takes 10 minutes to finish. By default, `parallelSolverCount` is set to `AUTO`, which resolves to half the CPU cores, regardless of the <> of the solvers. To retrieve the best solution, after solving terminates normally, use `SolverJob.getFinalBestSolution()`: [source,java,options=""nowrap""] ---- CloudBalance problem1 = ...; UUID problemId = UUID.randomUUID(); // Returns immediately SolverJob solverJob = solverManager.solve(problemId, problem1); ... CloudBalance solution1; try { // Returns only after solving terminates solution1 = solverJob.getFinalBestSolution(); } catch (InterruptedException | ExecutionException e) { throw ...; } ---- However, there are better approaches, both for solving batch problems before an end-user needs the solution as well as for live solving while an end-user is actively waiting for the solution, as explained below. The current `SolverManager` implementation runs on a single computer node, but future work aims to distribute solver loads across a cloud. [[solverManagerSolveBatch]] === Solve batch problems At night, batch solving is a great approach to deliver solid plans by breakfast, because: * There are typically few or no problem changes in the middle of the night. Some organizations even enforce a deadline, for example, _submit all day off requests before midnight_. * The solvers can run for much longer, often hours, because nobody's waiting for it and CPU resources are often cheaper. To solve a multiple datasets in parallel (limited by `parallelSolverCount`), call `solve(...)` for each dataset: [source,java,options=""nowrap""] ---- public class TimeTableService { private SolverManager solverManager; // Returns immediately, call it for every dataset public void solveBatch(Long timeTableId) { solverManager.solve(timeTableId, // Called once, when solving starts this::findById, // Called once, when solving ends this::save); } public TimeTable findById(Long timeTableId) {...} public void save(TimeTable timeTable) {...} } ---- A solid plan delivered by breakfast is great, even if you need to react on problem changes during the day. [[solverManagerSolveAndListen]] === Solve and listen to show progress to the end-user When a solver is running while an end-user is waiting for that solution, the user might need to wait for several minutes or hours before receiving a result. To assure the user that everything is going well, show progress by displaying the best solution and best score attained so far. To handle intermediate best solutions, use `solveAndListen(...)`: [source,java,options=""nowrap""] ---- public class TimeTableService { private SolverManager solverManager; // Returns immediately public void solveLive(Long timeTableId) { solverManager.solveAndListen(timeTableId, // Called once, when solving starts this::findById, // Called multiple times, for every best solution change this::save); } public TimeTable findById(Long timeTableId) {...} public void save(TimeTable timeTable) {...} public void stopSolving(Long timeTableId) { solverManager.terminateEarly(timeTableId); } } ---- This implementation is using the database to communicate with the UI, which polls the database. More advanced implementations push the best solutions directly to the UI or a messaging queue. If the user is satisfied with the intermediate best solution and does not want to wait any longer for a better one, call `SolverManager.terminateEarly(problemId)`. ",16318,True,2839.9260181956097,median "------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- N A M E T -- -- -- -- B o d y -- -- -- -- Copyright (C) 1992-2016, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- As a special exception under Section 7 of GPL version 3, you are granted -- -- additional permissions described in the GCC Runtime Library Exception, -- -- version 3.1, as published by the Free Software Foundation. -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- . -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ -- WARNING: There is a C version of this package. Any changes to this -- source file must be properly reflected in the C header file namet.h -- which is created manually from namet.ads and namet.adb. with Debug; use Debug; with Opt; use Opt; with Output; use Output; with Tree_IO; use Tree_IO; with Widechar; use Widechar; with Interfaces; use Interfaces; package body Namet is Name_Chars_Reserve : constant := 5000; Name_Entries_Reserve : constant := 100; -- The names table is locked during gigi processing, since gigi assumes -- that the table does not move. After returning from gigi, the names -- table is unlocked again, since writing library file information needs -- to generate some extra names. To avoid the inefficiency of always -- reallocating during this second unlocked phase, we reserve a bit of -- extra space before doing the release call. Hash_Num : constant Int := 2**16; -- Number of headers in the hash table. Current hash algorithm is closely -- tailored to this choice, so it can only be changed if a corresponding -- change is made to the hash algorithm. Hash_Max : constant Int := Hash_Num - 1; -- Indexes in the hash header table run from 0 to Hash_Num - 1 subtype Hash_Index_Type is Int range 0 .. Hash_Max; -- Range of hash index values Hash_Table : array (Hash_Index_Type) of Name_Id; -- The hash table is used to locate existing entries in the names table. -- The entries point to the first names table entry whose hash value -- matches the hash code. Then subsequent names table entries with the -- same hash code value are linked through the Hash_Link fields. ----------------------- -- Local Subprograms -- ----------------------- function Hash (Buf : Bounded_String) return Hash_Index_Type; pragma Inline (Hash); -- Compute hash code for name stored in Buf procedure Strip_Qualification_And_Suffixes (Buf : in out Bounded_String); -- Given an encoded entity name in Buf, remove package body -- suffix as described for Strip_Package_Body_Suffix, and also remove -- all qualification, i.e. names followed by two underscores. ----------------------------- -- Add_Char_To_Name_Buffer -- ----------------------------- procedure Add_Char_To_Name_Buffer (C : Character) is begin Append (Global_Name_Buffer, C); end Add_Char_To_Name_Buffer; ---------------------------- -- Add_Nat_To_Name_Buffer -- ---------------------------- procedure Add_Nat_To_Name_Buffer (V : Nat) is begin Append (Global_Name_Buffer, V); end Add_Nat_To_Name_Buffer; ---------------------------- -- Add_Str_To_Name_Buffer -- ---------------------------- procedure Add_Str_To_Name_Buffer (S : String) is begin Append (Global_Name_Buffer, S); end Add_Str_To_Name_Buffer; ------------ -- Append -- ------------ procedure Append (Buf : in out Bounded_String; C : Character) is begin if Buf.Length >= Buf.Chars'Last then raise Program_Error; end if; Buf.Length := Buf.Length + 1; Buf.Chars (Buf.Length) := C; end Append; procedure Append (Buf : in out Bounded_String; V : Nat) is begin if V >= 10 then Append (Buf, V / 10); end if; Append (Buf, Character'Val (Character'Pos ('0') + V rem 10)); end Append; procedure Append (Buf : in out Bounded_String; S : String) is begin for J in S'Range loop Append (Buf, S (J)); end loop; end Append; procedure Append (Buf : in out Bounded_String; Buf2 : Bounded_String) is begin Append (Buf, Buf2.Chars (1 .. Buf2.Length)); end Append; procedure Append (Buf : in out Bounded_String; Id : Name_Id) is pragma Assert (Id in Name_Entries.First .. Name_Entries.Last); S : constant Int := Name_Entries.Table (Id).Name_Chars_Index; begin for J in 1 .. Natural (Name_Entries.Table (Id).Name_Len) loop Append (Buf, Name_Chars.Table (S + Int (J))); end loop; end Append; -------------------- -- Append_Decoded -- -------------------- procedure Append_Decoded (Buf : in out Bounded_String; Id : Name_Id) is C : Character; P : Natural; Temp : Bounded_String; begin Append (Temp, Id); -- Skip scan if we already know there are no encodings if Name_Entries.Table (Id).Name_Has_No_Encodings then goto Done; end if; -- Quick loop to see if there is anything special to do P := 1; loop if P = Temp.Length then Name_Entries.Table (Id).Name_Has_No_Encodings := True; goto Done; else C := Temp.Chars (P); exit when C = 'U' or else C = 'W' or else C = 'Q' or else C = 'O'; P := P + 1; end if; end loop; -- Here we have at least some encoding that we must decode Decode : declare New_Len : Natural; Old : Positive; New_Buf : String (1 .. Temp.Chars'Last); procedure Copy_One_Character; -- Copy a character from Temp.Chars to New_Buf. Includes case -- of copying a Uhh,Whhhh,WWhhhhhhhh sequence and decoding it. function Hex (N : Natural) return Word; -- Scans past N digits using Old pointer and returns hex value procedure Insert_Character (C : Character); -- Insert a new character into output decoded name ------------------------ -- Copy_One_Character -- ------------------------ procedure Copy_One_Character is C : Character; begin C := Temp.Chars (Old); -- U (upper half insertion case) if C = 'U' and then Old < Temp.Length and then Temp.Chars (Old + 1) not in 'A' .. 'Z' and then Temp.Chars (Old + 1) /= '_' then Old := Old + 1; -- If we have upper half encoding, then we have to set an -- appropriate wide character sequence for this character. if Upper_Half_Encoding then Widechar.Set_Wide (Char_Code (Hex (2)), New_Buf, New_Len); -- For other encoding methods, upper half characters can -- simply use their normal representation. else Insert_Character (Character'Val (Hex (2))); end if; -- WW (wide wide character insertion) elsif C = 'W' and then Old < Temp.Length and then Temp.Chars (Old + 1) = 'W' then Old := Old + 2; Widechar.Set_Wide (Char_Code (Hex (8)), New_Buf, New_Len); -- W (wide character insertion) elsif C = 'W' and then Old < Temp.Length and then Temp.Chars (Old + 1) not in 'A' .. 'Z' and then Temp.Chars (Old + 1) /= '_' then Old := Old + 1; Widechar.Set_Wide (Char_Code (Hex (4)), New_Buf, New_Len); -- Any other character is copied unchanged else Insert_Character (C); Old := Old + 1; end if; end Copy_One_Character; --------- -- Hex -- --------- function Hex (N : Natural) return Word is T : Word := 0; C : Character; begin for J in 1 .. N loop C := Temp.Chars (Old); Old := Old + 1; pragma Assert (C in '0' .. '9' or else C in 'a' .. 'f'); if C <= '9' then T := 16 * T + Character'Pos (C) - Character'Pos ('0'); else -- C in 'a' .. 'f' T := 16 * T + Character'Pos (C) - (Character'Pos ('a') - 10); end if; end loop; return T; end Hex; ---------------------- -- Insert_Character -- ---------------------- procedure Insert_Character (C : Character) is begin New_Len := New_Len + 1; New_Buf (New_Len) := C; end Insert_Character; -- Start of processing for Decode begin New_Len := 0; Old := 1; -- Loop through characters of name while Old <= Temp.Length loop -- Case of character literal, put apostrophes around character if Temp.Chars (Old) = 'Q' and then Old < Temp.Length then Old := Old + 1; Insert_Character ('''); Copy_One_Character; Insert_Character ('''); -- Case of operator name elsif Temp.Chars (Old) = 'O' and then Old < Temp.Length and then Temp.Chars (Old + 1) not in 'A' .. 'Z' and then Temp.Chars (Old + 1) /= '_' then Old := Old + 1; declare -- This table maps the 2nd and 3rd characters of the name -- into the required output. Two blanks means leave the -- name alone Map : constant String := ""ab "" & -- Oabs => ""abs"" ""ad+ "" & -- Oadd => ""+"" ""an "" & -- Oand => ""and"" ""co& "" & -- Oconcat => ""&"" ""di/ "" & -- Odivide => ""/"" ""eq= "" & -- Oeq => ""="" ""ex**"" & -- Oexpon => ""**"" ""gt> "" & -- Ogt => "">"" ""ge>="" & -- Oge => "">="" ""le<="" & -- Ole => ""<="" ""lt< "" & -- Olt => ""<"" ""mo "" & -- Omod => ""mod"" ""mu* "" & -- Omutliply => ""*"" ""ne/="" & -- One => ""/="" ""no "" & -- Onot => ""not"" ""or "" & -- Oor => ""or"" ""re "" & -- Orem => ""rem"" ""su- "" & -- Osubtract => ""-"" ""xo ""; -- Oxor => ""xor"" J : Integer; begin Insert_Character ('""'); -- Search the map. Note that this loop must terminate, if -- not we have some kind of internal error, and a constraint -- error may be raised. J := Map'First; loop exit when Temp.Chars (Old) = Map (J) and then Temp.Chars (Old + 1) = Map (J + 1); J := J + 4; end loop; -- Special operator name if Map (J + 2) /= ' ' then Insert_Character (Map (J + 2)); if Map (J + 3) /= ' ' then Insert_Character (Map (J + 3)); end if; Insert_Character ('""'); -- Skip past original operator name in input while Old <= Temp.Length and then Temp.Chars (Old) in 'a' .. 'z' loop Old := Old + 1; end loop; -- For other operator names, leave them in lower case, -- surrounded by apostrophes else -- Copy original operator name from input to output while Old <= Temp.Length and then Temp.Chars (Old) in 'a' .. 'z' loop Copy_One_Character; end loop; Insert_Character ('""'); end if; end; -- Else copy one character and keep going else Copy_One_Character; end if; end loop; -- Copy new buffer as result Temp.Length := New_Len; Temp.Chars (1 .. New_Len) := New_Buf (1 .. New_Len); end Decode; <> Append (Buf, Temp); end Append_Decoded; ---------------------------------- -- Append_Decoded_With_Brackets -- ---------------------------------- procedure Append_Decoded_With_Brackets (Buf : in out Bounded_String; Id : Name_Id) is P : Natural; begin -- Case of operator name, normal decoding is fine if Buf.Chars (1) = 'O' then Append_Decoded (Buf, Id); -- For character literals, normal decoding is fine elsif Buf.Chars (1) = 'Q' then Append_Decoded (Buf, Id); -- Only remaining issue is U/W/WW sequences else declare Temp : Bounded_String; begin Append (Temp, Id); P := 1; while P < Temp.Length loop if Temp.Chars (P + 1) in 'A' .. 'Z' then P := P + 1; -- Uhh encoding elsif Temp.Chars (P) = 'U' then for J in reverse P + 3 .. P + Temp.Length loop Temp.Chars (J + 3) := Temp.Chars (J); end loop; Temp.Length := Temp.Length + 3; Temp.Chars (P + 3) := Temp.Chars (P + 2); Temp.Chars (P + 2) := Temp.Chars (P + 1); Temp.Chars (P) := '['; Temp.Chars (P + 1) := '""'; Temp.Chars (P + 4) := '""'; Temp.Chars (P + 5) := ']'; P := P + 6; -- WWhhhhhhhh encoding elsif Temp.Chars (P) = 'W' and then P + 9 <= Temp.Length and then Temp.Chars (P + 1) = 'W' and then Temp.Chars (P + 2) not in 'A' .. 'Z' and then Temp.Chars (P + 2) /= '_' then Temp.Chars (P + 12 .. Temp.Length + 2) := Temp.Chars (P + 10 .. Temp.Length); Temp.Chars (P) := '['; Temp.Chars (P + 1) := '""'; Temp.Chars (P + 10) := '""'; Temp.Chars (P + 11) := ']'; Temp.Length := Temp.Length + 2; P := P + 12; -- Whhhh encoding elsif Temp.Chars (P) = 'W' and then P < Temp.Length and then Temp.Chars (P + 1) not in 'A' .. 'Z' and then Temp.Chars (P + 1) /= '_' then Temp.Chars (P + 8 .. P + Temp.Length + 3) := Temp.Chars (P + 5 .. Temp.Length); Temp.Chars (P + 2 .. P + 5) := Temp.Chars (P + 1 .. P + 4); Temp.Chars (P) := '['; Temp.Chars (P + 1) := '""'; Temp.Chars (P + 6) := '""'; Temp.Chars (P + 7) := ']'; Temp.Length := Temp.Length + 3; P := P + 8; else P := P + 1; end if; end loop; Append (Buf, Temp); end; end if; end Append_Decoded_With_Brackets; -------------------- -- Append_Encoded -- -------------------- procedure Append_Encoded (Buf : in out Bounded_String; C : Char_Code) is procedure Set_Hex_Chars (C : Char_Code); -- Stores given value, which is in the range 0 .. 255, as two hex -- digits (using lower case a-f) in Buf.Chars, incrementing Buf.Length. ------------------- -- Set_Hex_Chars -- ------------------- procedure Set_Hex_Chars (C : Char_Code) is Hexd : constant String := ""0123456789abcdef""; N : constant Natural := Natural (C); begin Buf.Chars (Buf.Length + 1) := Hexd (N / 16 + 1); Buf.Chars (Buf.Length + 2) := Hexd (N mod 16 + 1); Buf.Length := Buf.Length + 2; end Set_Hex_Chars; -- Start of processing for Append_Encoded begin Buf.Length := Buf.Length + 1; if In_Character_Range (C) then declare CC : constant Character := Get_Character (C); begin if CC in 'a' .. 'z' or else CC in '0' .. '9' then Buf.Chars (Buf.Length) := CC; else Buf.Chars (Buf.Length) := 'U'; Set_Hex_Chars (C); end if; end; elsif In_Wide_Character_Range (C) then Buf.Chars (Buf.Length) := 'W'; Set_Hex_Chars (C / 256); Set_Hex_Chars (C mod 256); else Buf.Chars (Buf.Length) := 'W'; Buf.Length := Buf.Length + 1; Buf.Chars (Buf.Length) := 'W'; Set_Hex_Chars (C / 2 ** 24); Set_Hex_Chars ((C / 2 ** 16) mod 256); Set_Hex_Chars ((C / 256) mod 256); Set_Hex_Chars (C mod 256); end if; end Append_Encoded; ------------------------ -- Append_Unqualified -- ------------------------ procedure Append_Unqualified (Buf : in out Bounded_String; Id : Name_Id) is Temp : Bounded_String; begin Append (Temp, Id); Strip_Qualification_And_Suffixes (Temp); Append (Buf, Temp); end Append_Unqualified; -------------------------------- -- Append_Unqualified_Decoded -- -------------------------------- procedure Append_Unqualified_Decoded (Buf : in out Bounded_String; Id : Name_Id) is Temp : Bounded_String; begin Append_Decoded (Temp, Id); Strip_Qualification_And_Suffixes (Temp); Append (Buf, Temp); end Append_Unqualified_Decoded; -------------- -- Finalize -- -------------- procedure Finalize is F : array (Int range 0 .. 50) of Int; -- N'th entry is the number of chains of length N, except last entry, -- which is the number of chains of length F'Last or more. Max_Chain_Length : Nat := 0; -- Maximum length of all chains Probes : Nat := 0; -- Used to compute average number of probes Nsyms : Nat := 0; -- Number of symbols in table Verbosity : constant Int range 1 .. 3 := 1; pragma Warnings (Off, Verbosity); -- This constant indicates the level of verbosity in the output from -- this procedure. Currently this can only be changed by editing the -- declaration above and recompiling. That's good enough in practice, -- since we very rarely need to use this debug option. Settings are: -- -- 1 => print basic summary information -- 2 => in addition print number of entries per hash chain -- 3 => in addition print content of entries Zero : constant Int := Character'Pos ('0'); begin if not Debug_Flag_H then return; end if; for J in F'Range loop F (J) := 0; end loop; for J in Hash_Index_Type loop if Hash_Table (J) = No_Name then F (0) := F (0) + 1; else declare C : Nat; N : Name_Id; S : Int; begin C := 0; N := Hash_Table (J); while N /= No_Name loop N := Name_Entries.Table (N).Hash_Link; C := C + 1; end loop; Nsyms := Nsyms + 1; Probes := Probes + (1 + C) * 100; if C > Max_Chain_Length then Max_Chain_Length := C; end if; if Verbosity >= 2 then Write_Str (""Hash_Table (""); Write_Int (J); Write_Str ("") has ""); Write_Int (C); Write_Str ("" entries""); Write_Eol; end if; if C < F'Last then F (C) := F (C) + 1; else F (F'Last) := F (F'Last) + 1; end if; if Verbosity >= 3 then N := Hash_Table (J); while N /= No_Name loop S := Name_Entries.Table (N).Name_Chars_Index; Write_Str ("" ""); for J in 1 .. Name_Entries.Table (N).Name_Len loop Write_Char (Name_Chars.Table (S + Int (J))); end loop; Write_Eol; N := Name_Entries.Table (N).Hash_Link; end loop; end if; end; end if; end loop; Write_Eol; for J in F'Range loop if F (J) /= 0 then Write_Str (""Number of hash chains of length ""); if J < 10 then Write_Char (' '); end if; Write_Int (J); if J = F'Last then Write_Str ("" or greater""); end if; Write_Str ("" = ""); Write_Int (F (J)); Write_Eol; end if; end loop; -- Print out average number of probes, in the case where Name_Find is -- called for a string that is already in the table. Write_Eol; Write_Str (""Average number of probes for lookup = ""); Probes := Probes / Nsyms; Write_Int (Probes / 200); Write_Char ('.'); Probes := (Probes mod 200) / 2; Write_Char (Character'Val (Zero + Probes / 10)); Write_Char (Character'Val (Zero + Probes mod 10)); Write_Eol; Write_Str (""Max_Chain_Length = ""); Write_Int (Max_Chain_Length); Write_Eol; Write_Str (""Name_Chars'Length = ""); Write_Int (Name_Chars.Last - Name_Chars.First + 1); Write_Eol; Write_Str (""Name_Entries'Length = ""); Write_Int (Int (Name_Entries.Last - Name_Entries.First + 1)); Write_Eol; Write_Str (""Nsyms = ""); Write_Int (Nsyms); Write_Eol; end Finalize; ----------------------------- -- Get_Decoded_Name_String -- ----------------------------- procedure Get_Decoded_Name_String (Id : Name_Id) is begin Global_Name_Buffer.Length := 0; Append_Decoded (Global_Name_Buffer, Id); end Get_Decoded_Name_String; ------------------------------------------- -- Get_Decoded_Name_String_With_Brackets -- ------------------------------------------- procedure Get_Decoded_Name_String_With_Brackets (Id : Name_Id) is begin Global_Name_Buffer.Length := 0; Append_Decoded_With_Brackets (Global_Name_Buffer, Id); end Get_Decoded_Name_String_With_Brackets; ------------------------ -- Get_Last_Two_Chars -- ------------------------ procedure Get_Last_Two_Chars (N : Name_Id; C1 : out Character; C2 : out Character) is NE : Name_Entry renames Name_Entries.Table (N); NEL : constant Int := Int (NE.Name_Len); begin if NEL >= 2 then C1 := Name_Chars.Table (NE.Name_Chars_Index + NEL - 1); C2 := Name_Chars.Table (NE.Name_Chars_Index + NEL - 0); else C1 := ASCII.NUL; C2 := ASCII.NUL; end if; end Get_Last_Two_Chars; --------------------- -- Get_Name_String -- --------------------- procedure Get_Name_String (Id : Name_Id) is begin Global_Name_Buffer.Length := 0; Append (Global_Name_Buffer, Id); end Get_Name_String; function Get_Name_String (Id : Name_Id) return String is Buf : Bounded_String; begin Append (Buf, Id); return +Buf; end Get_Name_String; -------------------------------- -- Get_Name_String_And_Append -- -------------------------------- procedure Get_Name_String_And_Append (Id : Name_Id) is begin Append (Global_Name_Buffer, Id); end Get_Name_String_And_Append; ----------------------------- -- Get_Name_Table_Boolean1 -- ----------------------------- function Get_Name_Table_Boolean1 (Id : Name_Id) return Boolean is begin pragma Assert (Id in Name_Entries.First .. Name_Entries.Last); return Name_Entries.Table (Id).Boolean1_Info; end Get_Name_Table_Boolean1; ----------------------------- -- Get_Name_Table_Boolean2 -- ----------------------------- function Get_Name_Table_Boolean2 (Id : Name_Id) return Boolean is begin pragma Assert (Id in Name_Entries.First .. Name_Entries.Last); return Name_Entries.Table (Id).Boolean2_Info; end Get_Name_Table_Boolean2; ----------------------------- -- Get_Name_Table_Boolean3 -- ----------------------------- function Get_Name_Table_Boolean3 (Id : Name_Id) return Boolean is begin pragma Assert (Id in Name_Entries.First .. Name_Entries.Last); return Name_Entries.Table (Id).Boolean3_Info; end Get_Name_Table_Boolean3; ------------------------- -- Get_Name_Table_Byte -- ------------------------- function Get_Name_Table_Byte (Id : Name_Id) return Byte is begin pragma Assert (Id in Name_Entries.First .. Name_Entries.Last); return Name_Entries.Table (Id).Byte_Info; end Get_Name_Table_Byte; ------------------------- -- Get_Name_Table_Int -- ------------------------- function Get_Name_Table_Int (Id : Name_Id) return Int is begin pragma Assert (Id in Name_Entries.First .. Name_Entries.Last); return Name_Entries.Table (Id).Int_Info; end Get_Name_Table_Int; ----------------------------------------- -- Get_Unqualified_Decoded_Name_String -- ----------------------------------------- procedure Get_Unqualified_Decoded_Name_String (Id : Name_Id) is begin Global_Name_Buffer.Length := 0; Append_Unqualified_Decoded (Global_Name_Buffer, Id); end Get_Unqualified_Decoded_Name_String; --------------------------------- -- Get_Unqualified_Name_String -- --------------------------------- procedure Get_Unqualified_Name_String (Id : Name_Id) is begin Global_Name_Buffer.Length := 0; Append_Unqualified (Global_Name_Buffer, Id); end Get_Unqualified_Name_String; ---------- -- Hash -- ---------- function Hash (Buf : Bounded_String) return Hash_Index_Type is -- This hash function looks at every character, in order to make it -- likely that similar strings get different hash values. The rotate by -- 7 bits has been determined empirically to be good, and it doesn't -- lose bits like a shift would. The final conversion can't overflow, -- because the table is 2**16 in size. This function probably needs to -- be changed if the hash table size is changed. -- Note that we could get some speed improvement by aligning the string -- to 32 or 64 bits, and doing word-wise xor's. We could also implement -- a growable table. It doesn't seem worth the trouble to do those -- things, for now. Result : Unsigned_16 := 0; begin for J in 1 .. Buf.Length loop Result := Rotate_Left (Result, 7) xor Character'Pos (Buf.Chars (J)); end loop; return Hash_Index_Type (Result); end Hash; ---------------- -- Initialize -- ---------------- procedure Initialize is begin null; end Initialize; ---------------- -- Insert_Str -- ---------------- procedure Insert_Str (Buf : in out Bounded_String; S : String; Index : Positive) is SL : constant Natural := S'Length; begin Buf.Chars (Index + SL .. Buf.Length + SL) := Buf.Chars (Index .. Buf.Length); Buf.Chars (Index .. Index + SL - 1) := S; Buf.Length := Buf.Length + SL; end Insert_Str; ------------------------------- -- Insert_Str_In_Name_Buffer -- ------------------------------- procedure Insert_Str_In_Name_Buffer (S : String; Index : Positive) is begin Insert_Str (Global_Name_Buffer, S, Index); end Insert_Str_In_Name_Buffer; ---------------------- -- Is_Internal_Name -- ---------------------- function Is_Internal_Name (Buf : Bounded_String) return Boolean is J : Natural; begin -- Any name starting or ending with underscore is internal if Buf.Chars (1) = '_' or else Buf.Chars (Buf.Length) = '_' then return True; -- Allow quoted character elsif Buf.Chars (1) = ''' then return False; -- All other cases, scan name else -- Test backwards, because we only want to test the last entity -- name if the name we have is qualified with other entities. J := Buf.Length; while J /= 0 loop -- Skip stuff between brackets (A-F OK there) if Buf.Chars (J) = ']' then loop J := J - 1; exit when J = 1 or else Buf.Chars (J) = '['; end loop; -- Test for internal letter elsif Is_OK_Internal_Letter (Buf.Chars (J)) then return True; -- Quit if we come to terminating double underscore (note that -- if the current character is an underscore, we know that -- there is a previous character present, since we already -- filtered out the case of Buf.Chars (1) = '_' above. elsif Buf.Chars (J) = '_' and then Buf.Chars (J - 1) = '_' and then Buf.Chars (J - 2) /= '_' then return False; end if; J := J - 1; end loop; end if; return False; end Is_Internal_Name; function Is_Internal_Name (Id : Name_Id) return Boolean is Buf : Bounded_String; begin if Id in Error_Name_Or_No_Name then return False; else Append (Buf, Id); return Is_Internal_Name (Buf); end if; end Is_Internal_Name; function Is_Internal_Name return Boolean is begin return Is_Internal_Name (Global_Name_Buffer); end Is_Internal_Name; --------------------------- -- Is_OK_Internal_Letter -- --------------------------- function Is_OK_Internal_Letter (C : Character) return Boolean is begin return C in 'A' .. 'Z' and then C /= 'O' and then C /= 'Q' and then C /= 'U' and then C /= 'W' and then C /= 'X'; end Is_OK_Internal_Letter; ---------------------- -- Is_Operator_Name -- ---------------------- function Is_Operator_Name (Id : Name_Id) return Boolean is S : Int; begin pragma Assert (Id in Name_Entries.First .. Name_Entries.Last); S := Name_Entries.Table (Id).Name_Chars_Index; return Name_Chars.Table (S + 1) = 'O'; end Is_Operator_Name; ------------------- -- Is_Valid_Name -- ------------------- function Is_Valid_Name (Id : Name_Id) return Boolean is begin return Id in Name_Entries.First .. Name_Entries.Last; end Is_Valid_Name; -------------------- -- Length_Of_Name -- -------------------- function Length_Of_Name (Id : Name_Id) return Nat is begin return Int (Name_Entries.Table (Id).Name_Len); end Length_Of_Name; ---------- -- Lock -- ---------- procedure Lock is begin Name_Chars.Set_Last (Name_Chars.Last + Name_Chars_Reserve); Name_Entries.Set_Last (Name_Entries.Last + Name_Entries_Reserve); Name_Chars.Locked := True; Name_Entries.Locked := True; Name_Chars.Release; Name_Entries.Release; end Lock; ------------------------ -- Name_Chars_Address -- ------------------------ function Name_Chars_Address return System.Address is begin return Name_Chars.Table (0)'Address; end Name_Chars_Address; ---------------- -- Name_Enter -- ---------------- function Name_Enter (Buf : Bounded_String := Global_Name_Buffer) return Name_Id is begin Name_Entries.Append ((Name_Chars_Index => Name_Chars.Last, Name_Len => Short (Buf.Length), Byte_Info => 0, Int_Info => 0, Boolean1_Info => False, Boolean2_Info => False, Boolean3_Info => False, Name_Has_No_Encodings => False, Hash_Link => No_Name)); -- Set corresponding string entry in the Name_Chars table for J in 1 .. Buf.Length loop Name_Chars.Append (Buf.Chars (J)); end loop; Name_Chars.Append (ASCII.NUL); return Name_Entries.Last; end Name_Enter; -------------------------- -- Name_Entries_Address -- -------------------------- function Name_Entries_Address return System.Address is begin return Name_Entries.Table (First_Name_Id)'Address; end Name_Entries_Address; ------------------------ -- Name_Entries_Count -- ------------------------ function Name_Entries_Count return Nat is begin return Int (Name_Entries.Last - Name_Entries.First + 1); end Name_Entries_Count; --------------- -- Name_Find -- --------------- function Name_Find (Buf : Bounded_String := Global_Name_Buffer) return Name_Id is New_Id : Name_Id; -- Id of entry in hash search, and value to be returned S : Int; -- Pointer into string table Hash_Index : Hash_Index_Type; -- Computed hash index begin -- Quick handling for one character names if Buf.Length = 1 then return Name_Id (First_Name_Id + Character'Pos (Buf.Chars (1))); -- Otherwise search hash table for existing matching entry else Hash_Index := Namet.Hash (Buf); New_Id := Hash_Table (Hash_Index); if New_Id = No_Name then Hash_Table (Hash_Index) := Name_Entries.Last + 1; else Search : loop if Buf.Length /= Integer (Name_Entries.Table (New_Id).Name_Len) then goto No_Match; end if; S := Name_Entries.Table (New_Id).Name_Chars_Index; for J in 1 .. Buf.Length loop if Name_Chars.Table (S + Int (J)) /= Buf.Chars (J) then goto No_Match; end if; end loop; return New_Id; -- Current entry in hash chain does not match <> if Name_Entries.Table (New_Id).Hash_Link /= No_Name then New_Id := Name_Entries.Table (New_Id).Hash_Link; else Name_Entries.Table (New_Id).Hash_Link := Name_Entries.Last + 1; exit Search; end if; end loop Search; end if; -- We fall through here only if a matching entry was not found in the -- hash table. We now create a new entry in the names table. The hash -- link pointing to the new entry (Name_Entries.Last+1) has been set. Name_Entries.Append ((Name_Chars_Index => Name_Chars.Last, Name_Len => Short (Buf.Length), Hash_Link => No_Name, Name_Has_No_Encodings => False, Int_Info => 0, Byte_Info => 0, Boolean1_Info => False, Boolean2_Info => False, Boolean3_Info => False)); -- Set corresponding string entry in the Name_Chars table for J in 1 .. Buf.Length loop Name_Chars.Append (Buf.Chars (J)); end loop; Name_Chars.Append (ASCII.NUL); return Name_Entries.Last; end if; end Name_Find; function Name_Find (S : String) return Name_Id is Buf : Bounded_String; begin Append (Buf, S); return Name_Find (Buf); end Name_Find; ------------- -- Nam_In -- ------------- function Nam_In (T : Name_Id; V1 : Name_Id; V2 : Name_Id) return Boolean is begin return T = V1 or else T = V2; end Nam_In; function Nam_In (T : Name_Id; V1 : Name_Id; V2 : Name_Id; V3 : Name_Id) return Boolean is begin return T = V1 or else T = V2 or else T = V3; end Nam_In; function Nam_In (T : Name_Id; V1 : Name_Id; V2 : Name_Id; V3 : Name_Id; V4 : Name_Id) return Boolean is begin return T = V1 or else T = V2 or else T = V3 or else T = V4; end Nam_In; function Nam_In (T : Name_Id; V1 : Name_Id; V2 : Name_Id; V3 : Name_Id; V4 : Name_Id; V5 : Name_Id) return Boolean is begin return T = V1 or else T = V2 or else T = V3 or else T = V4 or else T = V5; end Nam_In; function Nam_In (T : Name_Id; V1 : Name_Id; V2 : Name_Id; V3 : Name_Id; V4 : Name_Id; V5 : Name_Id; V6 : Name_Id) return Boolean is begin return T = V1 or else T = V2 or else T = V3 or else T = V4 or else T = V5 or else T = V6; end Nam_In; function Nam_In (T : Name_Id; V1 : Name_Id; V2 : Name_Id; V3 : Name_Id; V4 : Name_Id; V5 : Name_Id; V6 : Name_Id; V7 : Name_Id) return Boolean is begin return T = V1 or else T = V2 or else T = V3 or else T = V4 or else T = V5 or else T = V6 or else T = V7; end Nam_In; function Nam_In (T : Name_Id; V1 : Name_Id; V2 : Name_Id; V3 : Name_Id; V4 : Name_Id; V5 : Name_Id; V6 : Name_Id; V7 : Name_Id; V8 : Name_Id) return Boolean is begin return T = V1 or else T = V2 or else T = V3 or else T = V4 or else T = V5 or else T = V6 or else T = V7 or else T = V8; end Nam_In; function Nam_In (T : Name_Id; V1 : Name_Id; V2 : Name_Id; V3 : Name_Id; V4 : Name_Id; V5 : Name_Id; V6 : Name_Id; V7 : Name_Id; V8 : Name_Id; V9 : Name_Id) return Boolean is begin return T = V1 or else T = V2 or else T = V3 or else T = V4 or else T = V5 or else T = V6 or else T = V7 or else T = V8 or else T = V9; end Nam_In; function Nam_In (T : Name_Id; V1 : Name_Id; V2 : Name_Id; V3 : Name_Id; V4 : Name_Id; V5 : Name_Id; V6 : Name_Id; V7 : Name_Id; V8 : Name_Id; V9 : Name_Id; V10 : Name_Id) return Boolean is begin return T = V1 or else T = V2 or else T = V3 or else T = V4 or else T = V5 or else T = V6 or else T = V7 or else T = V8 or else T = V9 or else T = V10; end Nam_In; function Nam_In (T : Name_Id; V1 : Name_Id; V2 : Name_Id; V3 : Name_Id; V4 : Name_Id; V5 : Name_Id; V6 : Name_Id; V7 : Name_Id; V8 : Name_Id; V9 : Name_Id; V10 : Name_Id; V11 : Name_Id) return Boolean is begin return T = V1 or else T = V2 or else T = V3 or else T = V4 or else T = V5 or else T = V6 or else T = V7 or else T = V8 or else T = V9 or else T = V10 or else T = V11; end Nam_In; function Nam_In (T : Name_Id; V1 : Name_Id; V2 : Name_Id; V3 : Name_Id; V4 : Name_Id; V5 : Name_Id; V6 : Name_Id; V7 : Name_Id; V8 : Name_Id; V9 : Name_Id; V10 : Name_Id; V11 : Name_Id; V12 : Name_Id) return Boolean is begin return T = V1 or else T = V2 or else T = V3 or else T = V4 or else T = V5 or else T = V6 or else T = V7 or else T = V8 or else T = V9 or else T = V10 or else T = V11 or else T = V12; end Nam_In; ----------------- -- Name_Equals -- ----------------- function Name_Equals (N1 : Name_Id; N2 : Name_Id) return Boolean is begin return N1 = N2 or else Get_Name_String (N1) = Get_Name_String (N2); end Name_Equals; ------------------ -- Reinitialize -- ------------------ procedure Reinitialize is begin Name_Chars.Init; Name_Entries.Init; -- Initialize entries for one character names for C in Character loop Name_Entries.Append ((Name_Chars_Index => Name_Chars.Last, Name_Len => 1, Byte_Info => 0, Int_Info => 0, Boolean1_Info => False, Boolean2_Info => False, Boolean3_Info => False, Name_Has_No_Encodings => True, Hash_Link => No_Name)); Name_Chars.Append (C); Name_Chars.Append (ASCII.NUL); end loop; -- Clear hash table for J in Hash_Index_Type loop Hash_Table (J) := No_Name; end loop; end Reinitialize; ---------------------- -- Reset_Name_Table -- ---------------------- procedure Reset_Name_Table is begin for J in First_Name_Id .. Name_Entries.Last loop Name_Entries.Table (J).Int_Info := 0; Name_Entries.Table (J).Byte_Info := 0; end loop; end Reset_Name_Table; -------------------------------- -- Set_Character_Literal_Name -- -------------------------------- procedure Set_Character_Literal_Name (Buf : in out Bounded_String; C : Char_Code) is begin Buf.Length := 0; Append (Buf, 'Q'); Append_Encoded (Buf, C); end Set_Character_Literal_Name; procedure Set_Character_Literal_Name (C : Char_Code) is begin Set_Character_Literal_Name (Global_Name_Buffer, C); end Set_Character_Literal_Name; ----------------------------- -- Set_Name_Table_Boolean1 -- ----------------------------- procedure Set_Name_Table_Boolean1 (Id : Name_Id; Val : Boolean) is begin pragma Assert (Id in Name_Entries.First .. Name_Entries.Last); Name_Entries.Table (Id).Boolean1_Info := Val; end Set_Name_Table_Boolean1; ----------------------------- -- Set_Name_Table_Boolean2 -- ----------------------------- procedure Set_Name_Table_Boolean2 (Id : Name_Id; Val : Boolean) is begin pragma Assert (Id in Name_Entries.First .. Name_Entries.Last); Name_Entries.Table (Id).Boolean2_Info := Val; end Set_Name_Table_Boolean2; ----------------------------- -- Set_Name_Table_Boolean3 -- ----------------------------- procedure Set_Name_Table_Boolean3 (Id : Name_Id; Val : Boolean) is begin pragma Assert (Id in Name_Entries.First .. Name_Entries.Last); Name_Entries.Table (Id).Boolean3_Info := Val; end Set_Name_Table_Boolean3; ------------------------- -- Set_Name_Table_Byte -- ------------------------- procedure Set_Name_Table_Byte (Id : Name_Id; Val : Byte) is begin pragma Assert (Id in Name_Entries.First .. Name_Entries.Last); Name_Entries.Table (Id).Byte_Info := Val; end Set_Name_Table_Byte; ------------------------- -- Set_Name_Table_Int -- ------------------------- procedure Set_Name_Table_Int (Id : Name_Id; Val : Int) is begin pragma Assert (Id in Name_Entries.First .. Name_Entries.Last); Name_Entries.Table (Id).Int_Info := Val; end Set_Name_Table_Int; ----------------------------- -- Store_Encoded_Character -- ----------------------------- procedure Store_Encoded_Character (C : Char_Code) is begin Append_Encoded (Global_Name_Buffer, C); end Store_Encoded_Character; -------------------------------------- -- Strip_Qualification_And_Suffixes -- -------------------------------------- procedure Strip_Qualification_And_Suffixes (Buf : in out Bounded_String) is J : Integer; begin -- Strip package body qualification string off end for J in reverse 2 .. Buf.Length loop if Buf.Chars (J) = 'X' then Buf.Length := J - 1; exit; end if; exit when Buf.Chars (J) /= 'b' and then Buf.Chars (J) /= 'n' and then Buf.Chars (J) /= 'p'; end loop; -- Find rightmost __ or $ separator if one exists. First we position -- to start the search. If we have a character constant, position -- just before it, otherwise position to last character but one if Buf.Chars (Buf.Length) = ''' then J := Buf.Length - 2; while J > 0 and then Buf.Chars (J) /= ''' loop J := J - 1; end loop; else J := Buf.Length - 1; end if; -- Loop to search for rightmost __ or $ (homonym) separator while J > 1 loop -- If $ separator, homonym separator, so strip it and keep looking if Buf.Chars (J) = '$' then Buf.Length := J - 1; J := Buf.Length - 1; -- Else check for __ found elsif Buf.Chars (J) = '_' and then Buf.Chars (J + 1) = '_' then -- Found __ so see if digit follows, and if so, this is a -- homonym separator, so strip it and keep looking. if Buf.Chars (J + 2) in '0' .. '9' then Buf.Length := J - 1; J := Buf.Length - 1; -- If not a homonym separator, then we simply strip the -- separator and everything that precedes it, and we are done else Buf.Chars (1 .. Buf.Length - J - 1) := Buf.Chars (J + 2 .. Buf.Length); Buf.Length := Buf.Length - J - 1; exit; end if; else J := J - 1; end if; end loop; end Strip_Qualification_And_Suffixes; --------------- -- To_String -- --------------- function To_String (Buf : Bounded_String) return String is begin return Buf.Chars (1 .. Buf.Length); end To_String; --------------- -- Tree_Read -- --------------- procedure Tree_Read is begin Name_Chars.Tree_Read; Name_Entries.Tree_Read; Tree_Read_Data (Hash_Table'Address, Hash_Table'Length * (Hash_Table'Component_Size / Storage_Unit)); end Tree_Read; ---------------- -- Tree_Write -- ---------------- procedure Tree_Write is begin Name_Chars.Tree_Write; Name_Entries.Tree_Write; Tree_Write_Data (Hash_Table'Address, Hash_Table'Length * (Hash_Table'Component_Size / Storage_Unit)); end Tree_Write; ------------ -- Unlock -- ------------ procedure Unlock is begin Name_Chars.Set_Last (Name_Chars.Last - Name_Chars_Reserve); Name_Entries.Set_Last (Name_Entries.Last - Name_Entries_Reserve); Name_Chars.Locked := False; Name_Entries.Locked := False; Name_Chars.Release; Name_Entries.Release; end Unlock; -------- -- wn -- -------- procedure wn (Id : Name_Id) is begin if Id not in Name_Entries.First .. Name_Entries.Last then Write_Str (""""); elsif Id = No_Name then Write_Str (""""); elsif Id = Error_Name then Write_Str (""""); else declare Buf : Bounded_String; begin Append (Buf, Id); Write_Str (Buf.Chars (1 .. Buf.Length)); end; end if; Write_Eol; end wn; ---------------- -- Write_Name -- ---------------- procedure Write_Name (Id : Name_Id) is Buf : Bounded_String; begin if Id >= First_Name_Id then Append (Buf, Id); Write_Str (Buf.Chars (1 .. Buf.Length)); end if; end Write_Name; ------------------------ -- Write_Name_Decoded -- ------------------------ procedure Write_Name_Decoded (Id : Name_Id) is Buf : Bounded_String; begin if Id >= First_Name_Id then Append_Decoded (Buf, Id); Write_Str (Buf.Chars (1 .. Buf.Length)); end if; end Write_Name_Decoded; -- Package initialization, initialize tables begin Reinitialize; end Namet; ",12529,False,2340.0081532433323,median "[role=""xpack""] [[security-settings]] === Security settings in {es} ++++ Security settings ++++ By default, the {es} {security-features} are disabled when you have a basic or trial license. To enable {security-features}, use the `xpack.security.enabled` setting. You configure `xpack.security` settings to <> and perform message authentication, <>, <>, <>, and <>. All of these settings can be added to the `elasticsearch.yml` configuration file, with the exception of the secure settings, which you add to the {es} keystore. For more information about creating and updating the {es} keystore, see <>. [float] [[general-security-settings]] ==== General security settings `xpack.security.enabled`:: Set to `true` to enable {es} {security-features} on the node. + + -- If set to `false`, which is the default value for basic and trial licenses, {security-features} are disabled. It also affects all {kib} instances that connect to this {es} instance; you do not need to disable {security-features} in those `kibana.yml` files. For more information about disabling {security-features} in specific {kib} instances, see {kibana-ref}/security-settings-kb.html[{kib} security settings]. TIP: If you have gold or higher licenses, the default value is `true`; we recommend that you explicitly add this setting to avoid confusion. -- `xpack.security.hide_settings`:: A comma-separated list of settings that are omitted from the results of the <>. You can use wildcards to include multiple settings in the list. For example, the following value hides all the settings for the ad1 active_directory realm: `xpack.security.authc.realms.active_directory.ad1.*`. The API already omits all `ssl` settings, `bind_dn`, and `bind_password` due to the sensitive nature of the information. `xpack.security.fips_mode.enabled`:: Enables fips mode of operation. Set this to `true` if you run this {es} instance in a FIPS 140-2 enabled JVM. For more information, see <>. Defaults to `false`. [float] [[password-security-settings]] ==== Default password security settings `xpack.security.authc.accept_default_password`:: In `elasticsearch.yml`, set this to `false` to disable support for the default ""changeme"" password. [float] [[password-hashing-settings]] ==== Password hashing settings `xpack.security.authc.password_hashing.algorithm`:: Specifies the hashing algorithm that is used for secure user credential storage. See <>. Defaults to `bcrypt`. [float] [[anonymous-access-settings]] ==== Anonymous access settings You can configure the following anonymous access settings in `elasticsearch.yml`. For more information, see {stack-ov}/anonymous-access.html[ Enabling anonymous access]. `xpack.security.authc.anonymous.username`:: The username (principal) of the anonymous user. Defaults to `_es_anonymous_user`. `xpack.security.authc.anonymous.roles`:: The roles to associate with the anonymous user. Required. `xpack.security.authc.anonymous.authz_exception`:: When `true`, an HTTP 403 response is returned if the anonymous user does not have the appropriate permissions for the requested action. The user is not prompted to provide credentials to access the requested resource. When set to `false`, an HTTP 401 response is returned and the user can provide credentials with the appropriate permissions to gain access. Defaults to `true`. [float] [[security-automata-settings]] ==== Automata Settings In places where the {security-features} accept wildcard patterns (e.g. index patterns in roles, group matches in the role mapping API), each pattern is compiled into an Automaton. The follow settings are available to control this behaviour. `xpack.security.automata.max_determinized_states`:: The upper limit on how many automaton states may be created by a single pattern. This protects against too-difficult (e.g. exponentially hard) patterns. Defaults to `100,000`. `xpack.security.automata.cache.enabled`:: Whether to cache the compiled automata. Compiling automata can be CPU intensive and may slowdown some operations. The cache reduces the frequency with which automata need to be compiled. Defaults to `true`. `xpack.security.automata.cache.size`:: The maximum number of items to retain in the automata cache. Defaults to `10,000`. `xpack.security.automata.cache.ttl`:: The length of time to retain in an item in the automata cache (based on most recent usage). Defaults to `48h` (48 hours). [float] [[field-document-security-settings]] ==== Document and field level security settings You can set the following document and field level security settings in `elasticsearch.yml`. For more information, see {stack-ov}/field-and-document-access-control.html[Setting up document and field level security]. `xpack.security.dls_fls.enabled`:: Set to `false` to prevent document and field level security from being configured. Defaults to `true`. `xpack.security.dls.bitset.cache.ttl`:: The time-to-live for cached `BitSet` entries for document level security. Document level security queries may depend on Lucene BitSet objects, and these are automatically cached to improve performance. Defaults to expire entries that are unused for `168h` (7 days). `xpack.security.dls.bitset.cache.size`:: The maximum memory usage of cached `BitSet` entries for document level security. Document level security queries may depend on Lucene BitSet objects, and these are automatically cached to improve performance. Defaults to `50mb`, after which least-recently-used entries will be evicted. [float] [[token-service-settings]] ==== Token service settings You can set the following token service settings in `elasticsearch.yml`. `xpack.security.authc.token.enabled`:: Set to `false` to disable the built-in token service. Defaults to `true` unless `xpack.security.http.ssl.enabled` is `false`. This prevents sniffing the token from a connection over plain http. `xpack.security.authc.token.timeout`:: The length of time that a token is valid for. By default this value is `20m` or 20 minutes. The maximum value is 1 hour. [float] [[api-key-service-settings]] ==== API key service settings You can set the following API key service settings in `elasticsearch.yml`. `xpack.security.authc.api_key.enabled`:: Set to `false` to disable the built-in API key service. Defaults to `true` unless `xpack.security.http.ssl.enabled` is `false`. This prevents sniffing the API key from a connection over plain http. `xpack.security.authc.api_key.hashing.algorithm`:: Specifies the hashing algorithm that is used for securing API key credentials. See <>. Defaults to `pbkdf2`. `xpack.security.authc.api_key.cache.ttl`:: The time-to-live for cached API key entries. A API key id and a hash of its API key are cached for this period of time. Specify the time period using the standard {es} <>. Defaults to `1d`. `xpack.security.authc.api_key.cache.max_keys`:: The maximum number of API key entries that can live in the cache at any given time. Defaults to 10,000. `xpack.security.authc.api_key.cache.hash_algo`:: (Expert Setting) The hashing algorithm that is used for the in-memory cached API key credentials. For possible values, see <>. Defaults to `ssha256`. [float] [[realm-settings]] ==== Realm settings You configure realm settings in the `xpack.security.authc.realms` namespace in `elasticsearch.yml`. For example: [source,yaml] ---------------------------------------- xpack.security.authc.realms: native.realm1: order: 0 ... ldap.realm2: order: 1 ... active_directory.realm3: order: 2 ... ... ---------------------------------------- The valid settings vary depending on the realm type. For more information, see {stack-ov}/setting-up-authentication.html[Setting up authentication]. [float] [[ref-realm-settings]] ===== Settings valid for all realms `type`:: The type of the realm: `native, `ldap`, `active_directory`, `pki`, or `file`. Required. `order`:: The priority of the realm within the realm chain. Realms with a lower order are consulted first. Although not required, use of this setting is strongly recommended when you configure multiple realms. Defaults to `Integer.MAX_VALUE`. `enabled`:: Indicates whether a realm is enabled. You can use this setting to disable a realm without removing its configuration information. Defaults to `true`. [[ref-native-settings]] [float] ===== Native realm settings For a native realm, the `type` must be set to `native`. In addition to the <>, you can specify the following optional settings: `cache.ttl`:: The time-to-live for cached user entries. A user and a hash of its credentials are cached for this period of time. Specify the time period using the standard {es} <>. Defaults to `20m`. `cache.max_users`:: The maximum number of user entries that can live in the cache at any given time. Defaults to 100,000. `cache.hash_algo`:: (Expert Setting) The hashing algorithm that is used for the in-memory cached user credentials. For possible values, see <>. Defaults to `ssha256`. `authentication.enabled`:: If set to `false`, disables authentication support in this realm, so that it only supports user lookups. (See the {stack-ov}/run-as-privilege.html[run as] and {stack-ov}/realm-chains.html#authorization_realms[authorization realms] features). Defaults to `true`. [[ref-users-settings]] [float] ===== File realm settings The `type` setting must be set to `file`. In addition to the <>, you can specify the following settings: `cache.ttl`:: The time-to-live for cached user entries. A user and a hash of its credentials are cached for this configured period of time. Defaults to `20m`. Specify values using the standard {es} {ref}/common-options.html#time-units[time units]. Defaults to `20m`. `cache.max_users`:: The maximum number of user entries that can live in the cache at a given time. Defaults to 100,000. `cache.hash_algo`:: (Expert Setting) The hashing algorithm that is used for the in-memory cached user credentials. See <>. Defaults to `ssha256`. `authentication.enabled`:: If set to `false`, disables authentication support in this realm, so that it only supports user lookups. (See the {stack-ov}/run-as-privilege.html[run as] and {stack-ov}/realm-chains.html#authorization_realms[authorization realms] features). Defaults to `true`. [[ref-ldap-settings]] [float] ===== LDAP realm settings The `type` setting must be set to `ldap`. In addition to the <>, you can specify the following settings: `url`:: One or more LDAP URLs in the `ldap[s]://:` format. Required. + To provide multiple URLs, use a YAML array (`[""ldap://server1:636"", ""ldap://server2:636""]`) or comma-separated string (`""ldap://server1:636, ldap://server2:636""`). + While both are supported, you can't mix the `ldap` and `ldaps` protocols. `load_balance.type`:: The behavior to use when there are multiple LDAP URLs defined. For supported values see <>. Defaults to `failover`. `load_balance.cache_ttl`:: When using `dns_failover` or `dns_round_robin` as the load balancing type, this setting controls the amount of time to cache DNS lookups. Defaults to `1h`. `bind_dn`:: The DN of the user that is used to bind to the LDAP and perform searches. Only applicable in user search mode. If not specified, an anonymous bind is attempted. Defaults to Empty. Due to its potential security impact, `bind_dn` is not exposed via the <>. `bind_password`:: deprecated[6.3] Use `secure_bind_password` instead. The password for the user that is used to bind to the LDAP directory. Defaults to Empty. Due to its potential security impact, `bind_password` is not exposed via the <>. `secure_bind_password` (<>):: The password for the user that is used to bind to the LDAP directory. Defaults to Empty. `user_dn_templates`:: The DN template that replaces the user name with the string `{0}`. This setting is multivalued; you can specify multiple user contexts. Required to operate in user template mode. If `user_search.base_dn` is specified, this setting is not valid. For more information on the different modes, see {stack-ov}/ldap-realm.html[LDAP realms]. `authorization_realms`:: The names of the realms that should be consulted for delegated authorization. If this setting is used, then the LDAP realm does not perform role mapping and instead loads the user from the listed realms. The referenced realms are consulted in the order that they are defined in this list. See {stack-ov}/realm-chains.html#authorization_realms[Delegating authorization to another realm] + -- NOTE: If any settings starting with `user_search` are specified, the `user_dn_templates` settings are ignored. -- `user_group_attribute`:: Specifies the attribute to examine on the user for group membership. If any `group_search` settings are specified, this setting is ignored. Defaults to `memberOf`. `user_search.base_dn`:: Specifies a container DN to search for users. Required to operated in user search mode. If `user_dn_templates` is specified, this setting is not valid. For more information on the different modes, see {stack-ov}/ldap-realm.html[LDAP realms]. `user_search.scope`:: The scope of the user search. Valid values are `sub_tree`, `one_level` or `base`. `one_level` only searches objects directly contained within the `base_dn`. `sub_tree` searches all objects contained under `base_dn`. `base` specifies that the `base_dn` is the user object, and that it is the only user considered. Defaults to `sub_tree`. `user_search.filter`:: Specifies the filter used to search the directory in attempts to match an entry with the username provided by the user. Defaults to `(uid={0})`. `{0}` is substituted with the username provided when searching. `user_search.attribute`:: deprecated[5.6] Use `user_search.filter` instead. The attribute to match with the username sent with the request. Defaults to `uid`. `user_search.pool.enabled`:: Enables or disables connection pooling for user search. If set to `false`, a new connection is created for every search. The default is `true` when `bind_dn` is set. `user_search.pool.size`:: The maximum number of connections to the LDAP server to allow in the connection pool. Defaults to `20`. `user_search.pool.initial_size`:: The initial number of connections to create to the LDAP server on startup. Defaults to `0`. If the LDAP server is down, values greater than `0` could cause startup failures. `user_search.pool.health_check.enabled`:: Enables or disables a health check on LDAP connections in the connection pool. Connections are checked in the background at the specified interval. Defaults to `true`. `user_search.pool.health_check.dn`:: The distinguished name that is retrieved as part of the health check. Defaults to the value of `bind_dn` if present; if not, falls back to `user_search.base_dn`. `user_search.pool.health_check.interval`:: The interval to perform background checks of connections in the pool. Defaults to `60s`. `group_search.base_dn`:: The container DN to search for groups in which the user has membership. When this element is absent, {es} searches for the attribute specified by `user_group_attribute` set on the user in order to determine group membership. `group_search.scope`:: Specifies whether the group search should be `sub_tree`, `one_level` or `base`. `one_level` only searches objects directly contained within the `base_dn`. `sub_tree` searches all objects contained under `base_dn`. `base` specifies that the `base_dn` is a group object, and that it is the only group considered. Defaults to `sub_tree`. `group_search.filter`:: Specifies a filter to use to look up a group. When not set, the realm searches for `group`, `groupOfNames`, `groupOfUniqueNames`, or `posixGroup` with the attributes `member`, `memberOf`, or `memberUid`. Any instance of `{0}` in the filter is replaced by the user attribute defined in `group_search.user_attribute`. `group_search.user_attribute`:: Specifies the user attribute that is fetched and provided as a parameter to the filter. If not set, the user DN is passed into the filter. Defaults to Empty. `unmapped_groups_as_roles`:: If set to `true`, the names of any unmapped LDAP groups are used as role names and assigned to the user. A group is considered to be _unmapped_ if it is not referenced in a {stack-ov}/mapping-roles.html#mapping-roles-file[role-mapping file]. API-based role mappings are not considered. Defaults to `false`. `files.role_mapping`:: The <> for the {stack-ov}/mapping-roles.html#mapping-roles[ YAML role mapping configuration file]. Defaults to `ES_PATH_CONF/role_mapping.yml`. `follow_referrals`:: Specifies whether {es} should follow referrals returned by the LDAP server. Referrals are URLs returned by the server that are to be used to continue the LDAP operation (for example, search). Defaults to `true`. `metadata`:: A list of additional LDAP attributes that should be loaded from the LDAP server and stored in the authenticated user's metadata field. `timeout.tcp_connect`:: The TCP connect timeout period for establishing an LDAP connection. An `s` at the end indicates seconds, or `ms` indicates milliseconds. Defaults to `5s` (5 seconds ). `timeout.tcp_read`:: The TCP read timeout period after establishing an LDAP connection. An `s` at the end indicates seconds, or `ms` indicates milliseconds. Defaults to `5s` (5 seconds ). `timeout.ldap_search`:: The LDAP Server enforced timeout period for an LDAP search. An `s` at the end indicates seconds, or `ms` indicates milliseconds. Defaults to `5s` (5 seconds ). `ssl.key`:: Path to a PEM encoded file containing the private key, which is used if the LDAP server requires client authentication. `ssl.key` and `ssl.keystore.path` cannot be used at the same time. `ssl.key_passphrase`:: The passphrase that is used to decrypt the private key. This value is optional as the key may not be encrypted. `ssl.secure_key_passphrase` (<>):: The passphrase that is used to decrypt the private key. `ssl.certificate`:: Path to a PEM encoded file containing the certificate (or certificate chain) that will be presented to clients when they connect. `ssl.certificate_authorities`:: List of paths to PEM encoded certificate files that should be trusted. `ssl.certificate_authorities` and `ssl.truststore.path` cannot be used at the same time. `ssl.keystore.path`:: The path to the Java Keystore file that contains a private key and certificate. `ssl.key` and `ssl.keystore.path` may not be used at the same time. `ssl.keystore.type`:: The format of the keystore file. Should be `jks` to use the Java Keystore format, `PKCS12` to use PKCS#12 files, or `PKCS11` to use a PKCS#11 token. The default is `jks`. `ssl.keystore.password`:: The password to the keystore. `ssl.keystore.secure_password` (<>):: The password to the keystore. `ssl.keystore.key_password`:: The password for the key in the keystore. Defaults to the keystore password. `ssl.keystore.secure_key_password`:: The password for the key in the keystore. Defaults to the keystore password. `ssl.truststore.path`:: The path to the Java Keystore file that contains the certificates to trust. `ssl.certificate_authorities` and `ssl.truststore.path` cannot be used at the same time. `ssl.truststore.password`:: The password to the truststore. `ssl.truststore.secure_password` (<>):: The password to the truststore. `ssl.truststore.type`:: The format of the keystore file. Should be `jks` to use the Java Keystore format, `PKCS12` to use PKCS#12 files, or `PKCS11` to use a PKCS#11 token. The default is `jks`. `ssl.verification_mode`:: Indicates the type of verification when using `ldaps` to protect against man in the middle attacks and certificate forgery. Values are `none`, `certificate`, and `full`. Defaults to `full`. + See <> for an explanation of these values. `ssl.supported_protocols`:: Supported protocols for TLS/SSL (with versions). Defaults to `TLSv1.3,TLSv1.2,TLSv1.1`. `ssl.cipher_suites`:: Specifies the cipher suites that should be supported when communicating with the LDAP server. Supported cipher suites can be found in Oracle's http://docs.oracle.com/javase/8/docs/technotes/guides/security/SunProviders.html[ Java Cryptography Architecture documentation]. See <> for the default value. `cache.ttl`:: Specifies the time-to-live for cached user entries. A user and a hash of its credentials are cached for this period of time. Use the standard {es} <>. Defaults to `20m`. `cache.max_users`:: Specifies the maximum number of user entries that the cache can contain. Defaults to `100000`. `cache.hash_algo`:: (Expert Setting) Specifies the hashing algorithm that is used for the in-memory cached user credentials. See <>. Defaults to `ssha256`. `authentication.enabled`:: If set to `false`, disables authentication support in this realm, so that it only supports user lookups. (See the {stack-ov}/run-as-privilege.html[run as] and {stack-ov}/realm-chains.html#authorization_realms[authorization realms] features). Defaults to `true`. [[ref-ad-settings]] [float] ===== Active Directory realm settings The `type` setting must be set to `active_directory`. In addition to the <>, you can specify the following settings: `url`:: One or more LDAP URLs in the `ldap[s]://:` format. Defaults to `ldap://:389`. This setting is required when connecting using SSL/TLS or when using a custom port. + To provide multiple URLs, use a YAML array (`[""ldap://server1:636"", ""ldap://server2:636""]`) or comma-separated string (`""ldap://server1:636, ldap://server2:636""`). + While both are supported, you can't mix the `ldap` and `ldaps` protocols. + If no URL is provided, {es} uses a default of `ldap://:389`. This default uses the `domain_name` setting value and assumes an unencrypted connection to port 389. `load_balance.type`:: The behavior to use when there are multiple LDAP URLs defined. For supported values see <>. Defaults to `failover`. `load_balance.cache_ttl`:: When using `dns_failover` or `dns_round_robin` as the load balancing type, this setting controls the amount of time to cache DNS lookups. Defaults to `1h`. `domain_name`:: The domain name of Active Directory. If the `url` and the `user_search_dn` settings are not specified, the cluster can derive those values from this setting. Required. `bind_dn`:: The DN of the user that is used to bind to Active Directory and perform searches. Defaults to Empty. Due to its potential security impact, `bind_dn` is not exposed via the <>. `bind_password`:: deprecated[6.3] Use `secure_bind_password` instead. The password for the user that is used to bind to Active Directory. Defaults to Empty. Due to its potential security impact, `bind_password` is not exposed via the <>. `secure_bind_password` (<>):: The password for the user that is used to bind to Active Directory. Defaults to Empty. `unmapped_groups_as_roles`:: If set to `true`, the names of any unmapped Active Directory groups are used as role names and assigned to the user. A group is considered _unmapped_ when it is not referenced in any role-mapping files. API-based role mappings are not considered. Defaults to `false`. `files.role_mapping`:: The <> for the YAML role mapping configuration file. Defaults to `ES_PATH_CONF/role_mapping.yml`. `user_search.base_dn`:: The context to search for a user. Defaults to the root of the Active Directory domain. `user_search.scope`:: Specifies whether the user search should be `sub_tree`, `one_level` or `base`. `one_level` only searches users directly contained within the `base_dn`. `sub_tree` searches all objects contained under `base_dn`. `base` specifies that the `base_dn` is a user object, and that it is the only user considered. Defaults to `sub_tree`. `user_search.filter`:: Specifies a filter to use to lookup a user given a username. The default filter looks up `user` objects with either `sAMAccountName` or `userPrincipalName`. If specified, this must be a valid LDAP user search filter. For example `(&(objectClass=user)(sAMAccountName={0}))`. For more information, see https://msdn.microsoft.com/en-us/library/aa746475(v=vs.85).aspx[Search Filter Syntax]. `user_search.upn_filter`:: Specifies a filter to use to lookup a user given a user principal name. The default filter looks up `user` objects with a matching `userPrincipalName`. If specified, this must be a valid LDAP user search filter. For example, `(&(objectClass=user)(userPrincipalName={1}))`. `{1}` is the full user principal name provided by the user. For more information, see https://msdn.microsoft.com/en-us/library/aa746475(v=vs.85).aspx[Search Filter Syntax]. `user_search.down_level_filter`:: Specifies a filter to use to lookup a user given a down level logon name (DOMAIN\\user). The default filter looks up `user` objects with a matching `sAMAccountName` in the domain provided. If specified, this must be a valid LDAP user search filter. For example, `(&(objectClass=user)(sAMAccountName={0}))`. For more information, see https://msdn.microsoft.com/en-us/library/aa746475(v=vs.85).aspx[Search Filter Syntax]. `user_search.pool.enabled`:: Enables or disables connection pooling for user search. When disabled a new connection is created for every search. The default is `true` when `bind_dn` is provided. `user_search.pool.size`:: The maximum number of connections to the Active Directory server to allow in the connection pool. Defaults to `20`. `user_search.pool.initial_size`:: The initial number of connections to create to the Active Directory server on startup. Defaults to `0`. If the LDAP server is down, values greater than 0 could cause startup failures. `user_search.pool.health_check.enabled`:: Enables or disables a health check on Active Directory connections in the connection pool. Connections are checked in the background at the specified interval. Defaults to `true`. `user_search.pool.health_check.dn`:: The distinguished name to be retrieved as part of the health check. Defaults to the value of `bind_dn` if that setting is present. Otherwise, it defaults to the value of the `user_search.base_dn` setting. `user_search.pool.health_check.interval`:: The interval to perform background checks of connections in the pool. Defaults to `60s`. `group_search.base_dn`:: The context to search for groups in which the user has membership. Defaults to the root of the Active Directory domain. `group_search.scope`:: Specifies whether the group search should be `sub_tree`, `one_level` or `base`. `one_level` searches for groups directly contained within the `base_dn`. `sub_tree` searches all objects contained under `base_dn`. `base` specifies that the `base_dn` is a group object, and that it is the only group considered. Defaults to `sub_tree`. `metadata`:: A list of additional LDAP attributes that should be loaded from the LDAP server and stored in the authenticated user's metadata field. `timeout.tcp_connect`:: The TCP connect timeout period for establishing an LDAP connection. An `s` at the end indicates seconds, or `ms` indicates milliseconds. Defaults to `5s` (5 seconds ). `timeout.tcp_read`:: The TCP read timeout period after establishing an LDAP connection. An `s` at the end indicates seconds, or `ms` indicates milliseconds. Defaults to `5s` (5 seconds ). `timeout.ldap_search`:: The LDAP Server enforced timeout period for an LDAP search. An `s` at the end indicates seconds, or `ms` indicates milliseconds. Defaults to `5s` (5 seconds ). `ssl.certificate`:: Path to a PEM encoded file containing the certificate (or certificate chain) that will be presented to clients when they connect. `ssl.certificate_authorities`:: List of paths to PEM encoded certificate files that should be trusted. `ssl.certificate_authorities` and `ssl.truststore.path` cannot be used at the same time. `ssl.key`:: Path to the PEM encoded file containing the private key, which is used when the Active Directory server requires client authentication. `ssl.key` and `ssl.keystore.path` cannot be used at the same time. `ssl.key_passphrase`:: The passphrase that is used to decrypt the private key. This value is optional as the key might not be encrypted. `ssl.secure_key_passphrase` (<>):: The passphrase that is used to decrypt the private key. This value is optional as the key might not be encrypted. `ssl.keystore.key_password`:: The password for the key in the keystore. Defaults to the keystore password. `ssl.keystore.secure_key_password` (<>):: The password for the key in the keystore. Defaults to the keystore password. `ssl.keystore.password`:: The password to the keystore. `ssl.secure_keystore.password` (<>):: The password to the keystore. `ssl.keystore.path`:: The path to the Java Keystore file that contains a private key and certificate. `ssl.key` and `ssl.keystore.path` cannot be used at the same time. `ssl.keystore.type`:: The format of the keystore file. Should be `jks` to use the Java Keystore format, `PKCS12` to use PKCS#12 files, or `PKCS11` to use a PKCS#11 token. The default is `jks`. `ssl.truststore.password`:: The password to the truststore. `ssl.truststore.secure_password` (<>):: The password to the truststore. `ssl.truststore.path`:: The path to the Java Keystore file that contains the certificates to trust. `ssl.certificate_authorities` and `ssl.truststore.path` cannot be used at the same time. `ssl.truststore.type`:: The format of the truststore file. Should be `jks` to use the Java Keystore format, `PKCS12` to use PKCS#12 files, or `PKCS11` to use a PKCS#11 token. The default is `jks`. `ssl.verification_mode`:: Indicates the type of verification when using `ldaps` to protect against man in the middle attacks and certificate forgery. Values are `none`, `certificate`, and `full`. Defaults to `full`. + See <> for an explanation of these values. `ssl.supported_protocols`:: Supported protocols for TLS/SSL (with versions). Defaults to `TLSv1.3,TLSv1.2,TLSv1.1`. `ssl.cipher_suites`:: Specifies the cipher suites that should be supported when communicating with the Active Directory server. Supported cipher suites can be found in Oracle's http://docs.oracle.com/javase/8/docs/technotes/guides/security/SunProviders.html[ Java Cryptography Architecture documentation]. See <> for the default values. `cache.ttl`:: Specifies the time-to-live for cached user entries. A user and a hash of its credentials are cached for this configured period of time. Use the standard Elasticsearch {ref}/common-options.html#time-units[time units]). Defaults to `20m`. `cache.max_users`:: Specifies the maximum number of user entries that the cache can contain. Defaults to `100000`. `cache.hash_algo`:: (Expert Setting) Specifies the hashing algorithm that is used for the in-memory cached user credentials. See <>. Defaults to `ssha256`. `authentication.enabled`:: If set to `false`, disables authentication support in this realm, so that it only supports user lookups. (See the {stack-ov}/run-as-privilege.html[run as] and {stack-ov}/realm-chains.html#authorization_realms[authorization realms] features). Defaults to `true`. `follow_referrals`:: If set to `true`, {es} follows referrals returned by the LDAP server. Referrals are URLs returned by the server that are to be used to continue the LDAP operation (such as `search`). Defaults to `true`. [[ref-pki-settings]] [float] ===== PKI realm settings The `type` setting must be set to `pki`. In addition to the <>, you can specify the following settings: `username_pattern`:: The regular expression pattern used to extract the username from the certificate DN. The first match group is the used as the username. Defaults to `CN=(.*?)(?:,\\|$)`. `certificate_authorities`:: List of paths to the PEM certificate files that should be used to authenticate a user's certificate as trusted. Defaults to the trusted certificates configured for SSL. This setting cannot be used with `truststore.path`. `truststore.algorithm`:: Algorithm for the truststore. Defaults to `SunX509`. `truststore.password`:: The password for the truststore. Must be provided if `truststore.path` is set. `truststore.secure_password` (<>):: The password for the truststore. `truststore.path`:: The path of a truststore to use. Defaults to the trusted certificates configured for SSL. This setting cannot be used with `certificate_authorities`. `files.role_mapping`:: Specifies the <> of the {stack-ov}/mapping-roles.html[YAML role mapping configuration file]. Defaults to `ES_PATH_CONF/role_mapping.yml`. `authorization_realms`:: The names of the realms that should be consulted for delegated authorization. If this setting is used, then the PKI realm does not perform role mapping and instead loads the user from the listed realms. See {stack-ov}/realm-chains.html#authorization_realms[Delegating authorization to another realm] `cache.ttl`:: Specifies the time-to-live for cached user entries. A user and a hash of its credentials are cached for this period of time. Use the standard {es} {ref}/common-options.html#time-units[time units]). Defaults to `20m`. `cache.max_users`:: Specifies the maximum number of user entries that the cache can contain. Defaults to `100000`. [[ref-saml-settings]] [float] ===== SAML realm settings The `type` setting must be set to `saml`. In addition to the <>, you can specify the following settings: `idp.entity_id`:: The Entity ID of the SAML Identity Provider. An Entity ID is a URI with a maximum length of 1024 characters. It can be a URL (https://idp.example.com/) or a URN (`urn:example.com:idp`) and can be found in the configuration or the SAML metadata of the Identity Provider. `idp.metadata.path`:: The path _(recommended)_ or URL to a SAML 2.0 metadata file describing the capabilities and configuration of the Identity Provider. If a path is provided, then it is resolved relative to the {es} config directory. If a URL is provided, then it must be either a `file` URL or a `https` URL. {es} automatically polls this metadata resource and reloads the IdP configuration when changes are detected. File based resources are polled at a frequency determined by the global {es} `resource.reload.interval.high` setting, which defaults to 5 seconds. HTTPS resources are polled at a frequency determined by the realm's `idp.metadata.http.refresh` setting. `idp.metadata.http.refresh`:: Controls the frequency with which `https` metadata is checked for changes. Defaults to `1h` (1 hour). `idp.use_single_logout`:: Indicates whether to utilise the Identity Provider's Single Logout service (if one exists in the IdP metadata file). Defaults to `true`. `sp.entity_id`:: The Entity ID to use for this SAML Service Provider. This should be entered as a URI. We recommend that you use the base URL of your Kibana instance. For example, `https://kibana.example.com/`. `sp.acs`:: The URL of the Assertion Consumer Service within {kib}. Typically this is the ""api/security/v1/saml"" endpoint of your Kibana server. For example, `https://kibana.example.com/api/security/v1/saml`. `sp.logout`:: The URL of the Single Logout service within {kib}. Typically this is the ""logout"" endpoint of your Kibana server. For example, `https://kibana.example.com/logout`. `attributes.principal`:: The Name of the SAML attribute that contains the user's principal (username). `attributes.groups`:: The Name of the SAML attribute that contains the user's groups. `attributes.name`:: The Name of the SAML attribute that contains the user's full name. `attributes.mail`:: The Name of the SAML attribute that contains the user's email address. `attributes.dn`:: The Name of the SAML attribute that contains the user's X.50 _Distinguished Name_. `attribute_patterns.principal`:: A Java regular expression that is matched against the SAML attribute specified by `attributes.pattern` before it is applied to the user's _principal_ property. The attribute value must match the pattern and the value of the first _capturing group_ is used as the principal. For example, `^([^@]+)@example\\\\.com$` matches email addresses from the ""example.com"" domain and uses the local-part as the principal. `attribute_patterns.groups`:: As per `attribute_patterns.principal`, but for the _group_ property. `attribute_patterns.name`:: As per `attribute_patterns.principal`, but for the _name_ property. `attribute_patterns.mail`:: As per `attribute_patterns.principal`, but for the _mail_ property. `attribute_patterns.dn`:: As per `attribute_patterns.principal`, but for the _dn_ property. `nameid_format`:: The NameID format that should be requested when asking the IdP to authenticate the current user. The default is to not include the `nameid_format` attribute. `nameid.allow_create`:: The value of the `AllowCreate` attribute of the `NameIdPolicy` element in an authentication request. The default value is false. `nameid.sp_qualifier`:: The value of the `SPNameQualifier` attribute of the `NameIdPolicy` element in an authentication request. The default is to not include the `SPNameQualifier` attribute. `force_authn`:: Specifies whether to set the `ForceAuthn` attribute when requesting that the IdP authenticate the current user. If set to `true`, the IdP is required to verify the user’s identity, irrespective of any existing sessions they might have. Defaults to `false`. `populate_user_metadata`:: Specifies whether to populate the {es} user's metadata with the values that are provided by the SAML attributes. Defaults to `true`. `authorization_realms`:: The names of the realms that should be consulted for delegated authorization. If this setting is used, then the SAML realm does not perform role mapping and instead loads the user from the listed realms. See {stack-ov}/realm-chains.html#authorization_realms[Delegating authorization to another realm] `allowed_clock_skew`:: The maximum amount of skew that can be tolerated between the IdP's clock and the {es} node's clock. Defaults to `3m` (3 minutes). `req_authn_context_class_ref`:: A comma separated list of Authentication Context Class Reference values to be included in the Requested Authentication Context when requesting the IdP to authenticate the current user. The Authentication Context of the corresponding authentication response should contain at least one of the requested values. + For more information, see {stack-ov}/saml-guide-authentication.html#req-authn-context[Requesting specific authentication methods]. [float] [[ref-saml-signing-settings]] ===== SAML realm signing settings If a signing key is configured (that is, either `signing.key` or `signing.keystore.path` is set), then {es} signs outgoing SAML messages. Signing can be configured using the following settings: `signing.saml_messages`:: A list of SAML message types that should be signed or `*` to sign all messages. Each element in the list should be the local name of a SAML XML Element. Supported element types are `AuthnRequest`, `LogoutRequest` and `LogoutResponse`. Only valid if `signing.key` or `signing.keystore.path` is also specified. Defaults to `*`. `signing.key`:: Specifies the path to the PEM encoded private key to use for SAML message signing. `signing.key` and `signing.keystore.path` cannot be used at the same time. `signing.secure_key_passphrase` (<>):: Specifies the passphrase to decrypt the PEM encoded private key (`signing.key`) if it is encrypted. `signing.certificate`:: Specifies the path to the PEM encoded certificate (or certificate chain) that corresponds to the `signing.key`. This certificate must also be included in the Service Provider metadata or manually configured within the IdP to allow for signature validation. This setting can only be used if `signing.key` is set. `signing.keystore.path`:: The path to the keystore that contains a private key and certificate. Must be either a Java Keystore (jks) or a PKCS#12 file. `signing.key` and `signing.keystore.path` cannot be used at the same time. `signing.keystore.type`:: The type of the keystore in `signing.keystore.path`. Must be either `jks` or `PKCS12`. If the keystore path ends in "".p12"", "".pfx"", or ""pkcs12"", this setting defaults to `PKCS12`. Otherwise, it defaults to `jks`. `signing.keystore.alias`:: Specifies the alias of the key within the keystore that should be used for SAML message signing. If the keystore contains more than one private key, this setting must be specified. `signing.keystore.secure_password` (<>):: The password to the keystore in `signing.keystore.path`. `signing.keystore.secure_key_password` (<>):: The password for the key in the keystore (`signing.keystore.path`). Defaults to the keystore password. [float] [[ref-saml-encryption-settings]] ===== SAML realm encryption settings If an encryption key is configured (that is, either `encryption.key` or `encryption.keystore.path` is set), then {es} publishes an encryption certificate when generating metadata and attempts to decrypt incoming SAML content. Encryption can be configured using the following settings: `encryption.key`:: Specifies the path to the PEM encoded private key to use for SAML message decryption. `encryption.key` and `encryption.keystore.path` cannot be used at the same time. `encryption.secure_key_passphrase` (<>):: Specifies the passphrase to decrypt the PEM encoded private key (`encryption.key`) if it is encrypted. `encryption.certificate`:: Specifies the path to the PEM encoded certificate (or certificate chain) that is associated with the `encryption.key`. This certificate must also be included in the Service Provider metadata or manually configured within the IdP to enable message encryption. This setting can be used only if `encryption.key` is set. `encryption.keystore.path`:: The path to the keystore that contains a private key and certificate. Must be either a Java Keystore (jks) or a PKCS#12 file. `encryption.key` and `encryption.keystore.path` cannot be used at the same time. `encryption.keystore.type`:: The type of the keystore (`encryption.keystore.path`). Must be either `jks` or `PKCS12`. If the keystore path ends in "".p12"", "".pfx"", or ""pkcs12"", this setting defaults to `PKCS12`. Otherwise, it defaults to `jks`. `encryption.keystore.alias`:: Specifies the alias of the key within the keystore (`encryption.keystore.path`) that should be used for SAML message decryption. If not specified, all compatible key pairs from the keystore are considered as candidate keys for decryption. `encryption.keystore.secure_password` (<>):: The password to the keystore (`encryption.keystore.path`). `encryption.keystore.secure_key_password` (<>):: The password for the key in the keystore (`encryption.keystore.path`). Only a single password is supported. If you are using multiple decryption keys, they cannot have individual passwords. [float] [[ref-saml-ssl-settings]] ===== SAML realm SSL settings If you are loading the IdP metadata over SSL/TLS (that is, `idp.metadata.path` is a URL using the `https` protocol), the following settings can be used to configure SSL. NOTE: These settings are not used for any purpose other than loading metadata over https. `ssl.key`:: Specifies the path to the PEM encoded private key to use for http client authentication (if required). `ssl.key` and `ssl.keystore.path` cannot be used at the same time. `ssl.key_passphrase`:: Specifies the passphrase to decrypt the PEM encoded private key (`ssl.key`) if it is encrypted. Cannot be used with `ssl.secure_key_passphrase`. `ssl.secure_key_passphrase` (<>):: Specifies the passphrase to decrypt the PEM encoded private key (`ssl.key`) if it is encrypted. Cannot be used with `ssl.key_passphrase`. `ssl.certificate`:: Specifies the path to the PEM encoded certificate (or certificate chain) that is associated with the key (`ssl.key`). This setting can be used only if `ssl.key` is set. `ssl.certificate_authorities`:: Specifies the paths to the PEM encoded certificate authority certificates that should be trusted. `ssl.certificate_authorities` and `ssl.truststore.path` cannot be used at the same time. `ssl.keystore.path`:: Specifies the path to the keystore that contains a private key and certificate. Must be either a Java Keystore (jks) or a PKCS#12 file. `ssl.key` and `ssl.keystore.path` cannot be used at the same time. `ssl.keystore.type`:: The type of the keystore (`ssl.keystore.path`). Must be either `jks` or `PKCS12`. If the keystore path ends in "".p12"", "".pfx"" or ""pkcs12"", this setting defaults to `PKCS12`. Otherwise, it defaults to `jks`. `ssl.keystore.password`:: The password to the keystore (`ssl.keystore.path`). This setting cannot be used with `ssl.keystore.secure_password`. `ssl.keystore.secure_password` (<>):: The password to the keystore (`ssl.keystore.path`). This setting cannot be used with `ssl.keystore.password`. `ssl.keystore.key_password`:: The password for the key in the keystore (`ssl.keystore.path`). Defaults to the keystore password. This setting cannot be used with `ssl.keystore.secure_key_password`. `ssl.keystore.secure_key_password` (<>):: The password for the key in the keystore (`ssl.keystore.path`). Defaults to the keystore password. This setting cannot be used with `ssl.keystore.key_password`. `ssl.truststore.path`:: The path to the keystore that contains the certificates to trust. Must be either a Java Keystore (jks) or a PKCS#12 file. `ssl.certificate_authorities` and `ssl.truststore.path` cannot be used at the same time. `ssl.truststore.type`:: The type of the truststore (`ssl.truststore.path`). Must be either `jks` or `PKCS12`. If the keystore path ends in "".p12"", "".pfx"" or ""pkcs12"", this setting defaults to `PKCS12`. Otherwise, it defaults to `jks`. `ssl.truststore.password`:: The password to the truststore (`ssl.truststore.path`). This setting cannot be used with `ssl.truststore.secure_password`. `ssl.truststore.secure_password` (<>):: The password to the truststore (`ssl.truststore.path`). This setting cannot be used with `ssl.truststore.password`. `ssl.verification_mode`:: One of `full` (verify the hostname and the certificate path), `certificate` (verify the certificate path, but not the hostname) or `none` (perform no verification). Defaults to `full`. + See <> for a more detailed explanation of these values. `ssl.supported_protocols`:: Specifies the supported protocols for TLS/SSL. Defaults to `TLSv1.3,TLSv1.2,TLSv1.1`. `ssl.cipher_suites`:: Specifies the cipher suites that should be supported. [float] [[ref-kerberos-settings]] ===== Kerberos realm settings For a Kerberos realm, the `type` must be set to `kerberos`. In addition to the <>, you can specify the following settings: `keytab.path`:: Specifies the path to the Kerberos keytab file that contains the service principal used by this {es} node. This must be a location within the {es} configuration directory and the file must have read permissions. Required. `remove_realm_name`:: Set to `true` to remove the realm part of principal names. Principal names in Kerberos have the form `user/instance@REALM`. If this option is `true`, the realm part (`@REALM`) will not be included in the username. Defaults to `false`. `krb.debug`:: Set to `true` to enable debug logs for the Java login module that provides support for Kerberos authentication. Defaults to `false`. `cache.ttl`:: The time-to-live for cached user entries. A user is cached for this period of time. Specify the time period using the standard {es} <>. Defaults to `20m`. `cache.max_users`:: The maximum number of user entries that can live in the cache at any given time. Defaults to 100,000. `authorization_realms`:: The names of the realms that should be consulted for delegated authorization. If this setting is used, then the Kerberos realm does not perform role mapping and instead loads the user from the listed realms. See {stack-ov}/realm-chains.html#authorization_realms[Delegating authorization to another realm] [[ref-oidc-settings]] [float] ===== OpenID Connect realm settings In addition to the <>, you can specify the following settings: `op.issuer`:: A verifiable Identifier for your OpenID Connect Provider. An Issuer Identifier is usually a case sensitive URL using the https scheme that contains scheme, host, and optionally, port number and path components and no query or fragment components. The value for this setting should be provided by your OpenID Connect Provider. `op.authorization_endpoint`:: The URL for the Authorization Endpoint at the OpenID Connect Provider. The value for this setting should be provided by your OpenID Connect Provider. `op.token_endpoint`:: The URL for the Token Endpoint at the OpenID Connect Provider. The value for this setting should be provided by your OpenID Connect Provider. `op.userinfo_endpoint`:: The URL for the User Info Endpoint at the OpenID Connect Provider. The value for this setting should be provided by your OpenID Connect Provider. `op.endsession_endpoint`:: The URL for the End Session Endpoint at the OpenID Connect Provider. The value for this setting should be provided by your OpenID Connect Provider. `op.jwkset_path`:: The path or URL to a JSON Web Key Set with the key material that the OpenID Connect Provider uses for signing tokens and claims responses. If a path is provided, then it is resolved relative to the {es} config directory. If a URL is provided, then it must be either a `file` URL or a `https` URL. {es} automatically caches the retrieved JWK set to avoid unnecessary HTTP requests but will attempt to refresh the JWK upon signature verification failure, as this might indicate that the OpenID Connect Provider has rotated the signing keys. File based resources are polled at a frequency determined by the global {es} `resource.reload.interval.high` setting, which defaults to 5 seconds. `rp.client_id`:: The OAuth 2.0 Client Identifier that was assigned to {es} during registration at the OpenID Connect Provider `rp.client_secret`(<>):: The OAuth 2.0 Client Secret that was assigned to {es} during registration at the OpenID Connect Provider `rp.redirect_uri`:: The Redirect URI within {kib}. Typically this is the ""api/security/v1/oidc"" endpoint of your Kibana server. For example, `https://kibana.example.com/api/security/v1/oidc`. `rp.response_type`:: OAuth 2.0 Response Type value that determines the authorization processing flow to be used. Can be `code` for authorization code grant flow, or one of `id_token`, `id_token token` for the implicit flow. `rp.signature_algorithm`:: The signature algorithm that will be used by {es} in order to verify the signature of the id tokens it will receive from the OpenID Connect Provider. Defaults to `RSA256` `rp.requested_scopes`:: The scope values that will be requested by the OpenID Connect Provider as part of the Authentication Request. Optional, defaults to `openid` `rp.post_logout_redirect_uri`:: The Redirect URI (usually within {kib}) that the OpenID Connect Provider should redirect the browser to after a successful Single Logout. `claims.principal`:: The name of the OpenID Connect claim that contains the user's principal (username). `claims.groups`:: The name of the OpenID Connect claim that contains the user's groups. `claims.name`:: The name of the OpenID Connect claim that contains the user's full name. `claims.mail`:: The name of the OpenID Connect claim that contains the user's email address. `claims.dn`:: The name of the OpenID Connect claim that contains the user's X.509 _Distinguished Name_. `claim_patterns.principal`:: A Java regular expression that is matched against the OpenID Connect claim specified by `claims.principal` before it is applied to the user's _principal_ property. The attribute value must match the pattern and the value of the first _capturing group_ is used as the principal. For example, `^([^@]+)@example\\\\.com$` matches email addresses from the ""example.com"" domain and uses the local-part as the principal. `claim_patterns.groups`:: As per `claim_patterns.principal`, but for the _group_ property. `claim_patterns.name`:: As per `claim_patterns.principal`, but for the _name_ property. `claim_patterns.mail`:: As per `claim_patterns.principal`, but for the _mail_ property. `claim_patterns.dn`:: As per `claim_patterns.principal`, but for the _dn_ property. `allowed_clock_skew`:: The maximum allowed clock skew to be taken into consideration when validating id tokens with regards to their creation and expiration times. `populate_user_metadata`:: Specifies whether to populate the {es} user's metadata with the values that are provided by the OpenID Connect claims. Defaults to `true`. `http.connect_timeout`:: Controls the behavior of the http client used for back-channel communication to the OpenID Connect Provider endpoints. Specifies the timeout until a connection is established. A value of zero means the timeout is not used. Defaults to `5s` `http.connection_read_timeout`:: Controls the behavior of the http client used for back-channel communication to the OpenID Connect Provider endpoints. Specifies the timeout used when requesting a connection from the connection manager. Defaults to `5s` `http.socket_timeout`:: Controls the behavior of the http client used for back-channel communication to the OpenID Connect Provider endpoints. Specifies the socket timeout (SO_TIMEOUT) in milliseconds, which is the timeout for waiting for data or, put differently, a maximum period inactivity between two consecutive data packets). Defaults to `5s` `http.max_connections`:: Controls the behavior of the http client used for back-channel communication to the OpenID Connect Provider endpoints. Specifies the maximum number of connections allowed across all endpoints. `http.max_endpoint_connections`:: Controls the behavior of the http client used for back-channel communication to the OpenID Connect Provider endpoints. Specifies the maximum number of connections allowed per endpoint. [float] [[ref-oidc-ssl-settings]] ===== OpenID Connect realm SSL settings The following settings can be used to configure SSL for all outgoing http connections to the OpenID Connect Provider endpoints. NOTE: These settings are _only_ used for the back-channel communication between {es} and the OpenID Connect Provider `ssl.key`:: Specifies the path to the PEM encoded private key to use for http client authentication (if required). `ssl.key` and `ssl.keystore.path` cannot be used at the same time. `ssl.key_passphrase`:: Specifies the passphrase to decrypt the PEM encoded private key (`ssl.key`) if it is encrypted. Cannot be used with `ssl.secure_key_passphrase`. `ssl.secure_key_passphrase` (<>):: Specifies the passphrase to decrypt the PEM encoded private key (`ssl.key`) if it is encrypted. Cannot be used with `ssl.key_passphrase`. `ssl.certificate`:: Specifies the path to the PEM encoded certificate (or certificate chain) that is associated with the key (`ssl.key`). This setting can be used only if `ssl.key` is set. `ssl.certificate_authorities`:: Specifies the paths to the PEM encoded certificate authority certificates that should be trusted. `ssl.certificate_authorities` and `ssl.truststore.path` cannot be used at the same time. `ssl.keystore.path`:: Specifies the path to the keystore that contains a private key and certificate. Must be either a Java Keystore (jks) or a PKCS#12 file. `ssl.key` and `ssl.keystore.path` cannot be used at the same time. `ssl.keystore.type`:: The type of the keystore (`ssl.keystore.path`). Must be either `jks` or `PKCS12`. If the keystore path ends in "".p12"", "".pfx"" or ""pkcs12"", this setting defaults to `PKCS12`. Otherwise, it defaults to `jks`. `ssl.keystore.password`:: The password to the keystore (`ssl.keystore.path`). This setting cannot be used with `ssl.keystore.secure_password`. `ssl.keystore.secure_password` (<>):: The password to the keystore (`ssl.keystore.path`). This setting cannot be used with `ssl.keystore.password`. `ssl.keystore.key_password`:: The password for the key in the keystore (`ssl.keystore.path`). Defaults to the keystore password. This setting cannot be used with `ssl.keystore.secure_key_password`. `ssl.keystore.secure_key_password` (<>):: The password for the key in the keystore (`ssl.keystore.path`). Defaults to the keystore password. This setting cannot be used with `ssl.keystore.key_password`. `ssl.truststore.path`:: The path to the keystore that contains the certificates to trust. Must be either a Java Keystore (jks) or a PKCS#12 file. `ssl.certificate_authorities` and `ssl.truststore.path` cannot be used at the same time. `ssl.truststore.type`:: The type of the truststore (`ssl.truststore.path`). Must be either `jks` or `PKCS12`. If the keystore path ends in "".p12"", "".pfx"" or ""pkcs12"", this setting defaults to `PKCS12`. Otherwise, it defaults to `jks`. `ssl.truststore.password`:: The password to the truststore (`ssl.truststore.path`). This setting cannot be used with `ssl.truststore.secure_password`. `ssl.truststore.secure_password` (<>):: The password to the truststore (`ssl.truststore.path`). This setting cannot be used with `ssl.truststore.password`. `ssl.verification_mode`:: One of `full` (verify the hostname and the certificate path), `certificate` (verify the certificate path, but not the hostname) or `none` (perform no verification). Defaults to `full`. + See <> for a more detailed explanation of these values. `ssl.supported_protocols`:: Specifies the supported protocols for TLS/SSL. Defaults to `TLSv1.3,TLSv1.2,TLSv1.1` if the JVM supports TLSv1.3, otherwise `TLSv1.2,TLSv1.1`. `ssl.cipher_suites`:: Specifies the cipher suites that should be supported. [float] [[load-balancing]] ===== Load balancing and failover The `load_balance.type` setting can have the following values: * `failover`: The URLs specified are used in the order that they are specified. The first server that can be connected to will be used for all subsequent connections. If a connection to that server fails then the next server that a connection can be established to will be used for subsequent connections. * `dns_failover`: In this mode of operation, only a single URL may be specified. This URL must contain a DNS name. The system will be queried for all IP addresses that correspond to this DNS name. Connections to the Active Directory or LDAP server will always be tried in the order in which they were retrieved. This differs from `failover` in that there is no reordering of the list and if a server has failed at the beginning of the list, it will still be tried for each subsequent connection. * `round_robin`: Connections will continuously iterate through the list of provided URLs. If a server is unavailable, iterating through the list of URLs will continue until a successful connection is made. * `dns_round_robin`: In this mode of operation, only a single URL may be specified. This URL must contain a DNS name. The system will be queried for all IP addresses that correspond to this DNS name. Connections will continuously iterate through the list of addresses. If a server is unavailable, iterating through the list of URLs will continue until a successful connection is made. [float] [[ssl-tls-settings]] ==== Default values for TLS/SSL settings In general, the values below represent the default values for the various TLS settings. The prefixes for these settings are based on the context in which they are used (e.g. `xpack.security.authc.realms.ldap.corp_ldap.ssl.verification_mode` or `xpack.security.transport.ssl.supported_protocols`). For more information, see {stack-ov}/encrypting-communications.html[Encrypting communications]. `*.ssl.supported_protocols`:: Supported protocols with versions. Valid protocols: `SSLv2Hello`, `SSLv3`, `TLSv1`, `TLSv1.1`, `TLSv1.2`, `TLSv1.3`. Defaults to `TLSv1.3,TLSv1.2,TLSv1.1`. + -- NOTE: If `xpack.security.fips_mode.enabled` is `true`, you cannot use `SSLv2Hello` or `SSLv3`. See <>. -- `*.ssl.client_authentication`:: Controls the server's behavior in regard to requesting a certificate from client connections. Valid values are `required`, `optional`, and `none`. `required` forces a client to present a certificate, while `optional` requests a client certificate but the client is not required to present one. Defaults to `required`, except for HTTP, which defaults to `none`. See <>. `*.ssl.verification_mode`:: Controls the verification of certificates. Valid values are: - `full`, which verifies that the provided certificate is signed by a trusted authority (CA) and also verifies that the server's hostname (or IP address) matches the names identified within the certificate. - `certificate`, which verifies that the provided certificate is signed by a trusted authority (CA), but does not perform any hostname verification. - `none`, which performs _no verification_ of the server's certificate. This mode disables many of the security benefits of SSL/TLS and should only be used after very careful consideration. It is primarily intended as a temporary diagnostic mechanism when attempting to resolve TLS errors, and its use on production clusters is strongly discouraged. + The default value is `full`. `*.ssl.cipher_suites`:: Supported cipher suites can be found in Oracle's https://docs.oracle.com/en/java/javase/11/security/oracle-providers.html#GUID-7093246A-31A3-4304-AC5F-5FB6400405E2[Java Cryptography Architecture documentation]. Defaults to `TLS_AES_256_GCM_SHA384`, `TLS_AES_128_GCM_SHA256`, `TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384`, `TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256`, `TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384`, `TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256`, `TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384`, `TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256`, `TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384`, `TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256`, `TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA`, `TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA`, `TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA`, `TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA`, `TLS_RSA_WITH_AES_256_GCM_SHA384`, `TLS_RSA_WITH_AES_128_GCM_SHA256`, `TLS_RSA_WITH_AES_256_CBC_SHA256`, `TLS_RSA_WITH_AES_128_CBC_SHA256`, `TLS_RSA_WITH_AES_256_CBC_SHA`, `TLS_RSA_WITH_AES_128_CBC_SHA`. [float] [[tls-ssl-key-settings]] ===== TLS/SSL key and trusted certificate settings The following settings are used to specify a private key, certificate, and the trusted certificates that should be used when communicating over an SSL/TLS connection. If no trusted certificates are configured, the default certificates that are trusted by the JVM will be trusted along with the certificate(s) associated with a key in the same context. The key and certificate must be in place for connections that require client authentication or when acting as a SSL enabled server. [[pkcs12-truststore-note]] [NOTE] Storing trusted certificates in a PKCS#12 file, although supported, is uncommon in practice. The {ref}/certutil.html[`elasticsearch-certutil`] tool, as well as Java's `keytool`, are designed to generate PKCS#12 files that can be used both as a keystore and as a truststore, but this may not be the case for container files that are created using other tools. Usually, PKCS#12 files only contain secret and private entries. To confirm that a PKCS#12 container includes trusted certificate (""anchor"") entries look for `2.16.840.1.113894.746875.1.1: ` in the `openssl pkcs12 -info` output, or `trustedCertEntry` in the `keytool -list` output. [[http-tls-ssl-settings]] :ssl-prefix: xpack.security.http :component: HTTP :client-auth-default: none :verifies!: :server: :ssl-context: security-http include::ssl-settings.asciidoc[] [[transport-tls-ssl-settings]] :ssl-prefix: xpack.security.transport :component: Transport :client-auth-default!: :verifies: :server: :ssl-context: security-transport include::ssl-settings.asciidoc[] [[ssl-tls-profile-settings]] [float] ===== Transport profile TLS/SSL settings The same settings that are available for the <> are also available for each transport profile. By default, the settings for a transport profile will be the same as the default transport unless they are specified. As an example, lets look at the key setting. For the default transport this is `xpack.security.transport.ssl.key`. In order to use this setting in a transport profile, use the prefix `transport.profiles.$PROFILE.xpack.security.` and append the portion of the setting after `xpack.security.transport.`. For the key setting, this would be `transport.profiles.$PROFILE.xpack.security.ssl.key`. [float] [[ip-filtering-settings]] ==== IP filtering settings You can configure the following settings for {stack-ov}/ip-filtering.html[IP filtering]. `xpack.security.transport.filter.allow`:: List of IP addresses to allow. `xpack.security.transport.filter.deny`:: List of IP addresses to deny. `xpack.security.http.filter.allow`:: List of IP addresses to allow just for HTTP. `xpack.security.http.filter.deny`:: List of IP addresses to deny just for HTTP. `transport.profiles.$PROFILE.xpack.security.filter.allow`:: List of IP addresses to allow for this profile. `transport.profiles.$PROFILE.xpack.security.filter.deny`:: List of IP addresses to deny for this profile. include::security-hash-settings.asciidoc[] ",16282,True,3217.4813999798184,median "-- This spec has been automatically generated from STM32WL5x_CM4.svd pragma Restrictions (No_Elaboration_Code); pragma Ada_2012; pragma Style_Checks (Off); with HAL; with System; package STM32_SVD.GPIO is pragma Preelaborate; --------------- -- Registers -- --------------- -- MODER array element subtype MODER_Element is HAL.UInt2; -- MODER array type MODER_Field_Array is array (0 .. 15) of MODER_Element with Component_Size => 2, Size => 32; -- GPIO port mode register type MODER_Register (As_Array : Boolean := False) is record case As_Array is when False => -- MODER as a value Val : HAL.UInt32; when True => -- MODER as an array Arr : MODER_Field_Array; end case; end record with Unchecked_Union, Size => 32, Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for MODER_Register use record Val at 0 range 0 .. 31; Arr at 0 range 0 .. 31; end record; -- OTYPER_OT array type OTYPER_OT_Field_Array is array (0 .. 15) of Boolean with Component_Size => 1, Size => 16; -- Type definition for OTYPER_OT type OTYPER_OT_Field (As_Array : Boolean := False) is record case As_Array is when False => -- OT as a value Val : HAL.UInt16; when True => -- OT as an array Arr : OTYPER_OT_Field_Array; end case; end record with Unchecked_Union, Size => 16; for OTYPER_OT_Field use record Val at 0 range 0 .. 15; Arr at 0 range 0 .. 15; end record; -- GPIO port output type register type OTYPER_Register is record -- Port x configuration bits (y = 0..15) OT : OTYPER_OT_Field := (As_Array => False, Val => 16#0#); -- unspecified Reserved_16_31 : HAL.UInt16 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for OTYPER_Register use record OT at 0 range 0 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; -- OSPEEDR array element subtype OSPEEDR_Element is HAL.UInt2; -- OSPEEDR array type OSPEEDR_Field_Array is array (0 .. 15) of OSPEEDR_Element with Component_Size => 2, Size => 32; -- GPIO port output speed register type OSPEEDR_Register (As_Array : Boolean := False) is record case As_Array is when False => -- OSPEEDR as a value Val : HAL.UInt32; when True => -- OSPEEDR as an array Arr : OSPEEDR_Field_Array; end case; end record with Unchecked_Union, Size => 32, Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for OSPEEDR_Register use record Val at 0 range 0 .. 31; Arr at 0 range 0 .. 31; end record; -- PUPDR array element subtype PUPDR_Element is HAL.UInt2; -- PUPDR array type PUPDR_Field_Array is array (0 .. 15) of PUPDR_Element with Component_Size => 2, Size => 32; -- GPIO port pull-up/pull-down register type PUPDR_Register (As_Array : Boolean := False) is record case As_Array is when False => -- PUPDR as a value Val : HAL.UInt32; when True => -- PUPDR as an array Arr : PUPDR_Field_Array; end case; end record with Unchecked_Union, Size => 32, Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for PUPDR_Register use record Val at 0 range 0 .. 31; Arr at 0 range 0 .. 31; end record; -- IDR array type IDR_Field_Array is array (0 .. 15) of Boolean with Component_Size => 1, Size => 16; -- Type definition for IDR type IDR_Field (As_Array : Boolean := False) is record case As_Array is when False => -- IDR as a value Val : HAL.UInt16; when True => -- IDR as an array Arr : IDR_Field_Array; end case; end record with Unchecked_Union, Size => 16; for IDR_Field use record Val at 0 range 0 .. 15; Arr at 0 range 0 .. 15; end record; -- GPIO port input data register type IDR_Register is record -- Read-only. Port input data (y = 0..15) IDR : IDR_Field; -- unspecified Reserved_16_31 : HAL.UInt16; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for IDR_Register use record IDR at 0 range 0 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; -- ODR array type ODR_Field_Array is array (0 .. 15) of Boolean with Component_Size => 1, Size => 16; -- Type definition for ODR type ODR_Field (As_Array : Boolean := False) is record case As_Array is when False => -- ODR as a value Val : HAL.UInt16; when True => -- ODR as an array Arr : ODR_Field_Array; end case; end record with Unchecked_Union, Size => 16; for ODR_Field use record Val at 0 range 0 .. 15; Arr at 0 range 0 .. 15; end record; -- GPIO port output data register type ODR_Register is record -- Port output data (y = 0..15) ODR : ODR_Field := (As_Array => False, Val => 16#0#); -- unspecified Reserved_16_31 : HAL.UInt16 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for ODR_Register use record ODR at 0 range 0 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; -- BSRR_BS array type BSRR_BS_Field_Array is array (0 .. 15) of Boolean with Component_Size => 1, Size => 16; -- Type definition for BSRR_BS type BSRR_BS_Field (As_Array : Boolean := False) is record case As_Array is when False => -- BS as a value Val : HAL.UInt16; when True => -- BS as an array Arr : BSRR_BS_Field_Array; end case; end record with Unchecked_Union, Size => 16; for BSRR_BS_Field use record Val at 0 range 0 .. 15; Arr at 0 range 0 .. 15; end record; -- BSRR_BR array type BSRR_BR_Field_Array is array (0 .. 15) of Boolean with Component_Size => 1, Size => 16; -- Type definition for BSRR_BR type BSRR_BR_Field (As_Array : Boolean := False) is record case As_Array is when False => -- BR as a value Val : HAL.UInt16; when True => -- BR as an array Arr : BSRR_BR_Field_Array; end case; end record with Unchecked_Union, Size => 16; for BSRR_BR_Field use record Val at 0 range 0 .. 15; Arr at 0 range 0 .. 15; end record; -- GPIO port bit set/reset register type BSRR_Register is record -- Write-only. Port x set bit y (y= 0..15) BS : BSRR_BS_Field := (As_Array => False, Val => 16#0#); -- Write-only. Port x set bit y (y= 0..15) BR : BSRR_BR_Field := (As_Array => False, Val => 16#0#); end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for BSRR_Register use record BS at 0 range 0 .. 15; BR at 0 range 16 .. 31; end record; -- LCKR_LCK array type LCKR_LCK_Field_Array is array (0 .. 15) of Boolean with Component_Size => 1, Size => 16; -- Type definition for LCKR_LCK type LCKR_LCK_Field (As_Array : Boolean := False) is record case As_Array is when False => -- LCK as a value Val : HAL.UInt16; when True => -- LCK as an array Arr : LCKR_LCK_Field_Array; end case; end record with Unchecked_Union, Size => 16; for LCKR_LCK_Field use record Val at 0 range 0 .. 15; Arr at 0 range 0 .. 15; end record; -- GPIO port configuration lock register type LCKR_Register is record -- Port x lock bit y (y= 0..15) LCK : LCKR_LCK_Field := (As_Array => False, Val => 16#0#); -- Port x lock bit y (y= 0..15) LCKK : Boolean := False; -- unspecified Reserved_17_31 : HAL.UInt15 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for LCKR_Register use record LCK at 0 range 0 .. 15; LCKK at 0 range 16 .. 16; Reserved_17_31 at 0 range 17 .. 31; end record; -- AFRL array element subtype AFRL_Element is HAL.UInt4; -- AFRL array type AFRL_Field_Array is array (0 .. 7) of AFRL_Element with Component_Size => 4, Size => 32; -- GPIO alternate function low register type AFRL_Register (As_Array : Boolean := False) is record case As_Array is when False => -- AFRL as a value Val : HAL.UInt32; when True => -- AFRL as an array Arr : AFRL_Field_Array; end case; end record with Unchecked_Union, Size => 32, Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for AFRL_Register use record Val at 0 range 0 .. 31; Arr at 0 range 0 .. 31; end record; -- AFRH array element subtype AFRH_Element is HAL.UInt4; -- AFRH array type AFRH_Field_Array is array (8 .. 15) of AFRH_Element with Component_Size => 4, Size => 32; -- GPIO alternate function high register type AFRH_Register (As_Array : Boolean := False) is record case As_Array is when False => -- AFRH as a value Val : HAL.UInt32; when True => -- AFRH as an array Arr : AFRH_Field_Array; end case; end record with Unchecked_Union, Size => 32, Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for AFRH_Register use record Val at 0 range 0 .. 31; Arr at 0 range 0 .. 31; end record; -- BRR_BR array type BRR_BR_Field_Array is array (0 .. 15) of Boolean with Component_Size => 1, Size => 16; -- Type definition for BRR_BR type BRR_BR_Field (As_Array : Boolean := False) is record case As_Array is when False => -- BR as a value Val : HAL.UInt16; when True => -- BR as an array Arr : BRR_BR_Field_Array; end case; end record with Unchecked_Union, Size => 16; for BRR_BR_Field use record Val at 0 range 0 .. 15; Arr at 0 range 0 .. 15; end record; -- GPIO port bit reset register type BRR_Register is record -- Port Reset bit BR : BRR_BR_Field := (As_Array => False, Val => 16#0#); -- unspecified Reserved_16_31 : HAL.UInt16 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for BRR_Register use record BR at 0 range 0 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; -- MODER array type MODER_Field_Array_1 is array (0 .. 6) of MODER_Element with Component_Size => 2, Size => 14; -- Type definition for MODER type MODER_Field (As_Array : Boolean := False) is record case As_Array is when False => -- MODER as a value Val : HAL.UInt14; when True => -- MODER as an array Arr : MODER_Field_Array_1; end case; end record with Unchecked_Union, Size => 14; for MODER_Field use record Val at 0 range 0 .. 13; Arr at 0 range 0 .. 13; end record; -- MODER array type MODER_Field_Array_2 is array (13 .. 15) of MODER_Element with Component_Size => 2, Size => 6; -- Type definition for MODER type MODER_Field_1 (As_Array : Boolean := False) is record case As_Array is when False => -- MODER as a value Val : HAL.UInt6; when True => -- MODER as an array Arr : MODER_Field_Array_2; end case; end record with Unchecked_Union, Size => 6; for MODER_Field_1 use record Val at 0 range 0 .. 5; Arr at 0 range 0 .. 5; end record; -- GPIO port mode register type MODER_Register_1 is record -- Port x configuration bits (y = 0..15) MODER : MODER_Field := (As_Array => False, Val => 16#3#); -- unspecified Reserved_14_25 : HAL.UInt12 := 16#0#; -- Port x configuration bits (y = 0..15) MODER_1 : MODER_Field_1 := (As_Array => False, Val => 16#3#); end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for MODER_Register_1 use record MODER at 0 range 0 .. 13; Reserved_14_25 at 0 range 14 .. 25; MODER_1 at 0 range 26 .. 31; end record; -- OTYPER_OT array type OTYPER_OT_Field_Array_1 is array (0 .. 6) of Boolean with Component_Size => 1, Size => 7; -- Type definition for OTYPER_OT type OTYPER_OT_Field_1 (As_Array : Boolean := False) is record case As_Array is when False => -- OT as a value Val : HAL.UInt7; when True => -- OT as an array Arr : OTYPER_OT_Field_Array_1; end case; end record with Unchecked_Union, Size => 7; for OTYPER_OT_Field_1 use record Val at 0 range 0 .. 6; Arr at 0 range 0 .. 6; end record; -- OTYPER_OT array type OTYPER_OT_Field_Array_2 is array (13 .. 15) of Boolean with Component_Size => 1, Size => 3; -- Type definition for OTYPER_OT type OTYPER_OT_Field_2 (As_Array : Boolean := False) is record case As_Array is when False => -- OT as a value Val : HAL.UInt3; when True => -- OT as an array Arr : OTYPER_OT_Field_Array_2; end case; end record with Unchecked_Union, Size => 3; for OTYPER_OT_Field_2 use record Val at 0 range 0 .. 2; Arr at 0 range 0 .. 2; end record; -- GPIO port output type register type OTYPER_Register_1 is record -- Port x configuration bits (y = 0..15) OT : OTYPER_OT_Field_1 := (As_Array => False, Val => 16#0#); -- unspecified Reserved_7_12 : HAL.UInt6 := 16#0#; -- Port x configuration bits (y = 0..15) OT_1 : OTYPER_OT_Field_2 := (As_Array => False, Val => 16#0#); -- unspecified Reserved_16_31 : HAL.UInt16 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for OTYPER_Register_1 use record OT at 0 range 0 .. 6; Reserved_7_12 at 0 range 7 .. 12; OT_1 at 0 range 13 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; -- OSPEEDR array type OSPEEDR_Field_Array_1 is array (0 .. 6) of OSPEEDR_Element with Component_Size => 2, Size => 14; -- Type definition for OSPEEDR type OSPEEDR_Field (As_Array : Boolean := False) is record case As_Array is when False => -- OSPEEDR as a value Val : HAL.UInt14; when True => -- OSPEEDR as an array Arr : OSPEEDR_Field_Array_1; end case; end record with Unchecked_Union, Size => 14; for OSPEEDR_Field use record Val at 0 range 0 .. 13; Arr at 0 range 0 .. 13; end record; -- OSPEEDR array type OSPEEDR_Field_Array_2 is array (13 .. 15) of OSPEEDR_Element with Component_Size => 2, Size => 6; -- Type definition for OSPEEDR type OSPEEDR_Field_1 (As_Array : Boolean := False) is record case As_Array is when False => -- OSPEEDR as a value Val : HAL.UInt6; when True => -- OSPEEDR as an array Arr : OSPEEDR_Field_Array_2; end case; end record with Unchecked_Union, Size => 6; for OSPEEDR_Field_1 use record Val at 0 range 0 .. 5; Arr at 0 range 0 .. 5; end record; -- GPIO port output speed register type OSPEEDR_Register_1 is record -- Port x configuration bits (y = 0..15) OSPEEDR : OSPEEDR_Field := (As_Array => False, Val => 16#0#); -- unspecified Reserved_14_25 : HAL.UInt12 := 16#0#; -- Port x configuration bits (y = 0..15) OSPEEDR_1 : OSPEEDR_Field_1 := (As_Array => False, Val => 16#0#); end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for OSPEEDR_Register_1 use record OSPEEDR at 0 range 0 .. 13; Reserved_14_25 at 0 range 14 .. 25; OSPEEDR_1 at 0 range 26 .. 31; end record; -- PUPDR array type PUPDR_Field_Array_1 is array (0 .. 6) of PUPDR_Element with Component_Size => 2, Size => 14; -- Type definition for PUPDR type PUPDR_Field (As_Array : Boolean := False) is record case As_Array is when False => -- PUPDR as a value Val : HAL.UInt14; when True => -- PUPDR as an array Arr : PUPDR_Field_Array_1; end case; end record with Unchecked_Union, Size => 14; for PUPDR_Field use record Val at 0 range 0 .. 13; Arr at 0 range 0 .. 13; end record; -- PUPDR array type PUPDR_Field_Array_2 is array (13 .. 15) of PUPDR_Element with Component_Size => 2, Size => 6; -- Type definition for PUPDR type PUPDR_Field_1 (As_Array : Boolean := False) is record case As_Array is when False => -- PUPDR as a value Val : HAL.UInt6; when True => -- PUPDR as an array Arr : PUPDR_Field_Array_2; end case; end record with Unchecked_Union, Size => 6; for PUPDR_Field_1 use record Val at 0 range 0 .. 5; Arr at 0 range 0 .. 5; end record; -- GPIO port pull-up/pull-down register type PUPDR_Register_1 is record -- Port x configuration bits (y = 0..15) PUPDR : PUPDR_Field := (As_Array => False, Val => 16#0#); -- unspecified Reserved_14_25 : HAL.UInt12 := 16#0#; -- Port x configuration bits (y = 0..15) PUPDR_1 : PUPDR_Field_1 := (As_Array => False, Val => 16#0#); end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for PUPDR_Register_1 use record PUPDR at 0 range 0 .. 13; Reserved_14_25 at 0 range 14 .. 25; PUPDR_1 at 0 range 26 .. 31; end record; -- IDR array type IDR_Field_Array_1 is array (0 .. 6) of Boolean with Component_Size => 1, Size => 7; -- Type definition for IDR type IDR_Field_1 (As_Array : Boolean := False) is record case As_Array is when False => -- IDR as a value Val : HAL.UInt7; when True => -- IDR as an array Arr : IDR_Field_Array_1; end case; end record with Unchecked_Union, Size => 7; for IDR_Field_1 use record Val at 0 range 0 .. 6; Arr at 0 range 0 .. 6; end record; -- IDR array type IDR_Field_Array_2 is array (13 .. 15) of Boolean with Component_Size => 1, Size => 3; -- Type definition for IDR type IDR_Field_2 (As_Array : Boolean := False) is record case As_Array is when False => -- IDR as a value Val : HAL.UInt3; when True => -- IDR as an array Arr : IDR_Field_Array_2; end case; end record with Unchecked_Union, Size => 3; for IDR_Field_2 use record Val at 0 range 0 .. 2; Arr at 0 range 0 .. 2; end record; -- GPIO port input data register type IDR_Register_1 is record -- Read-only. Port input data (y = 0..15) IDR : IDR_Field_1; -- unspecified Reserved_7_12 : HAL.UInt6; -- Read-only. Port input data (y = 0..15) IDR_1 : IDR_Field_2; -- unspecified Reserved_16_31 : HAL.UInt16; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for IDR_Register_1 use record IDR at 0 range 0 .. 6; Reserved_7_12 at 0 range 7 .. 12; IDR_1 at 0 range 13 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; -- ODR array type ODR_Field_Array_1 is array (0 .. 6) of Boolean with Component_Size => 1, Size => 7; -- Type definition for ODR type ODR_Field_1 (As_Array : Boolean := False) is record case As_Array is when False => -- ODR as a value Val : HAL.UInt7; when True => -- ODR as an array Arr : ODR_Field_Array_1; end case; end record with Unchecked_Union, Size => 7; for ODR_Field_1 use record Val at 0 range 0 .. 6; Arr at 0 range 0 .. 6; end record; -- ODR array type ODR_Field_Array_2 is array (13 .. 15) of Boolean with Component_Size => 1, Size => 3; -- Type definition for ODR type ODR_Field_2 (As_Array : Boolean := False) is record case As_Array is when False => -- ODR as a value Val : HAL.UInt3; when True => -- ODR as an array Arr : ODR_Field_Array_2; end case; end record with Unchecked_Union, Size => 3; for ODR_Field_2 use record Val at 0 range 0 .. 2; Arr at 0 range 0 .. 2; end record; -- GPIO port output data register type ODR_Register_1 is record -- Port output data (y = 0..15) ODR : ODR_Field_1 := (As_Array => False, Val => 16#0#); -- unspecified Reserved_7_12 : HAL.UInt6 := 16#0#; -- Port output data (y = 0..15) ODR_1 : ODR_Field_2 := (As_Array => False, Val => 16#0#); -- unspecified Reserved_16_31 : HAL.UInt16 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for ODR_Register_1 use record ODR at 0 range 0 .. 6; Reserved_7_12 at 0 range 7 .. 12; ODR_1 at 0 range 13 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; -- BSRR_BS array type BSRR_BS_Field_Array_1 is array (0 .. 6) of Boolean with Component_Size => 1, Size => 7; -- Type definition for BSRR_BS type BSRR_BS_Field_1 (As_Array : Boolean := False) is record case As_Array is when False => -- BS as a value Val : HAL.UInt7; when True => -- BS as an array Arr : BSRR_BS_Field_Array_1; end case; end record with Unchecked_Union, Size => 7; for BSRR_BS_Field_1 use record Val at 0 range 0 .. 6; Arr at 0 range 0 .. 6; end record; -- BSRR_BS array type BSRR_BS_Field_Array_2 is array (13 .. 15) of Boolean with Component_Size => 1, Size => 3; -- Type definition for BSRR_BS type BSRR_BS_Field_2 (As_Array : Boolean := False) is record case As_Array is when False => -- BS as a value Val : HAL.UInt3; when True => -- BS as an array Arr : BSRR_BS_Field_Array_2; end case; end record with Unchecked_Union, Size => 3; for BSRR_BS_Field_2 use record Val at 0 range 0 .. 2; Arr at 0 range 0 .. 2; end record; -- BSRR_BR array type BSRR_BR_Field_Array_1 is array (0 .. 6) of Boolean with Component_Size => 1, Size => 7; -- Type definition for BSRR_BR type BSRR_BR_Field_1 (As_Array : Boolean := False) is record case As_Array is when False => -- BR as a value Val : HAL.UInt7; when True => -- BR as an array Arr : BSRR_BR_Field_Array_1; end case; end record with Unchecked_Union, Size => 7; for BSRR_BR_Field_1 use record Val at 0 range 0 .. 6; Arr at 0 range 0 .. 6; end record; -- BSRR_BR array type BSRR_BR_Field_Array_2 is array (13 .. 15) of Boolean with Component_Size => 1, Size => 3; -- Type definition for BSRR_BR type BSRR_BR_Field_2 (As_Array : Boolean := False) is record case As_Array is when False => -- BR as a value Val : HAL.UInt3; when True => -- BR as an array Arr : BSRR_BR_Field_Array_2; end case; end record with Unchecked_Union, Size => 3; for BSRR_BR_Field_2 use record Val at 0 range 0 .. 2; Arr at 0 range 0 .. 2; end record; -- GPIO port bit set/reset register type BSRR_Register_1 is record -- Write-only. Port x set bit y (y= 0..15) BS : BSRR_BS_Field_1 := (As_Array => False, Val => 16#0#); -- unspecified Reserved_7_12 : HAL.UInt6 := 16#0#; -- Write-only. Port x set bit y (y= 0..15) BS_1 : BSRR_BS_Field_2 := (As_Array => False, Val => 16#0#); -- Write-only. Port x set bit y (y= 0..15) BR : BSRR_BR_Field_1 := (As_Array => False, Val => 16#0#); -- unspecified Reserved_23_28 : HAL.UInt6 := 16#0#; -- Write-only. Port x reset bit y (y = 0..15) BR_1 : BSRR_BR_Field_2 := (As_Array => False, Val => 16#0#); end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for BSRR_Register_1 use record BS at 0 range 0 .. 6; Reserved_7_12 at 0 range 7 .. 12; BS_1 at 0 range 13 .. 15; BR at 0 range 16 .. 22; Reserved_23_28 at 0 range 23 .. 28; BR_1 at 0 range 29 .. 31; end record; -- LCKR_LCK array type LCKR_LCK_Field_Array_1 is array (0 .. 6) of Boolean with Component_Size => 1, Size => 7; -- Type definition for LCKR_LCK type LCKR_LCK_Field_1 (As_Array : Boolean := False) is record case As_Array is when False => -- LCK as a value Val : HAL.UInt7; when True => -- LCK as an array Arr : LCKR_LCK_Field_Array_1; end case; end record with Unchecked_Union, Size => 7; for LCKR_LCK_Field_1 use record Val at 0 range 0 .. 6; Arr at 0 range 0 .. 6; end record; -- LCKR_LCK array type LCKR_LCK_Field_Array_2 is array (13 .. 15) of Boolean with Component_Size => 1, Size => 3; -- Type definition for LCKR_LCK type LCKR_LCK_Field_2 (As_Array : Boolean := False) is record case As_Array is when False => -- LCK as a value Val : HAL.UInt3; when True => -- LCK as an array Arr : LCKR_LCK_Field_Array_2; end case; end record with Unchecked_Union, Size => 3; for LCKR_LCK_Field_2 use record Val at 0 range 0 .. 2; Arr at 0 range 0 .. 2; end record; -- GPIO port configuration lock register type LCKR_Register_1 is record -- Port x lock bit y (y= 0..15) LCK : LCKR_LCK_Field_1 := (As_Array => False, Val => 16#0#); -- unspecified Reserved_7_12 : HAL.UInt6 := 16#0#; -- Port x lock bit y (y= 0..15) LCK_1 : LCKR_LCK_Field_2 := (As_Array => False, Val => 16#0#); -- Port x lock bit y (y= 0..15) LCKK : Boolean := False; -- unspecified Reserved_17_31 : HAL.UInt15 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for LCKR_Register_1 use record LCK at 0 range 0 .. 6; Reserved_7_12 at 0 range 7 .. 12; LCK_1 at 0 range 13 .. 15; LCKK at 0 range 16 .. 16; Reserved_17_31 at 0 range 17 .. 31; end record; -- BRR_BR array type BRR_BR_Field_Array_1 is array (0 .. 6) of Boolean with Component_Size => 1, Size => 7; -- Type definition for BRR_BR type BRR_BR_Field_1 (As_Array : Boolean := False) is record case As_Array is when False => -- BR as a value Val : HAL.UInt7; when True => -- BR as an array Arr : BRR_BR_Field_Array_1; end case; end record with Unchecked_Union, Size => 7; for BRR_BR_Field_1 use record Val at 0 range 0 .. 6; Arr at 0 range 0 .. 6; end record; -- BRR_BR array type BRR_BR_Field_Array_2 is array (13 .. 15) of Boolean with Component_Size => 1, Size => 3; -- Type definition for BRR_BR type BRR_BR_Field_2 (As_Array : Boolean := False) is record case As_Array is when False => -- BR as a value Val : HAL.UInt3; when True => -- BR as an array Arr : BRR_BR_Field_Array_2; end case; end record with Unchecked_Union, Size => 3; for BRR_BR_Field_2 use record Val at 0 range 0 .. 2; Arr at 0 range 0 .. 2; end record; -- GPIO port bit reset register type BRR_Register_1 is record -- Port Reset bit BR : BRR_BR_Field_1 := (As_Array => False, Val => 16#0#); -- unspecified Reserved_7_12 : HAL.UInt6 := 16#0#; -- Port Reset bit BR_1 : BRR_BR_Field_2 := (As_Array => False, Val => 16#0#); -- unspecified Reserved_16_31 : HAL.UInt16 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for BRR_Register_1 use record BR at 0 range 0 .. 6; Reserved_7_12 at 0 range 7 .. 12; BR_1 at 0 range 13 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; subtype MODER_MODER3_Field is HAL.UInt2; -- GPIO port mode register type MODER_Register_2 is record -- unspecified Reserved_0_5 : HAL.UInt6 := 16#0#; -- Port x configuration bits (y = 0..15) MODER3 : MODER_MODER3_Field := 16#3#; -- unspecified Reserved_8_31 : HAL.UInt24 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for MODER_Register_2 use record Reserved_0_5 at 0 range 0 .. 5; MODER3 at 0 range 6 .. 7; Reserved_8_31 at 0 range 8 .. 31; end record; -- GPIO port output type register type OTYPER_Register_2 is record -- unspecified Reserved_0_2 : HAL.UInt3 := 16#0#; -- Port x configuration bits (y = 0..15) OT3 : Boolean := False; -- unspecified Reserved_4_31 : HAL.UInt28 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for OTYPER_Register_2 use record Reserved_0_2 at 0 range 0 .. 2; OT3 at 0 range 3 .. 3; Reserved_4_31 at 0 range 4 .. 31; end record; subtype OSPEEDR_OSPEEDR3_Field is HAL.UInt2; -- GPIO port output speed register type OSPEEDR_Register_2 is record -- unspecified Reserved_0_5 : HAL.UInt6 := 16#0#; -- Port x configuration bits (y = 0..15) OSPEEDR3 : OSPEEDR_OSPEEDR3_Field := 16#0#; -- unspecified Reserved_8_31 : HAL.UInt24 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for OSPEEDR_Register_2 use record Reserved_0_5 at 0 range 0 .. 5; OSPEEDR3 at 0 range 6 .. 7; Reserved_8_31 at 0 range 8 .. 31; end record; subtype PUPDR_PUPDR3_Field is HAL.UInt2; -- GPIO port pull-up/pull-down register type PUPDR_Register_2 is record -- unspecified Reserved_0_5 : HAL.UInt6 := 16#0#; -- Port x configuration bits (y = 0..15) PUPDR3 : PUPDR_PUPDR3_Field := 16#0#; -- unspecified Reserved_8_31 : HAL.UInt24 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for PUPDR_Register_2 use record Reserved_0_5 at 0 range 0 .. 5; PUPDR3 at 0 range 6 .. 7; Reserved_8_31 at 0 range 8 .. 31; end record; -- GPIO port input data register type IDR_Register_2 is record -- unspecified Reserved_0_2 : HAL.UInt3; -- Read-only. Port input data (y = 0..15) IDR3 : Boolean; -- unspecified Reserved_4_31 : HAL.UInt28; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for IDR_Register_2 use record Reserved_0_2 at 0 range 0 .. 2; IDR3 at 0 range 3 .. 3; Reserved_4_31 at 0 range 4 .. 31; end record; -- GPIO port output data register type ODR_Register_2 is record -- unspecified Reserved_0_2 : HAL.UInt3 := 16#0#; -- Port output data (y = 0..15) ODR3 : Boolean := False; -- unspecified Reserved_4_31 : HAL.UInt28 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for ODR_Register_2 use record Reserved_0_2 at 0 range 0 .. 2; ODR3 at 0 range 3 .. 3; Reserved_4_31 at 0 range 4 .. 31; end record; -- GPIO port bit set/reset register type BSRR_Register_2 is record -- unspecified Reserved_0_2 : HAL.UInt3 := 16#0#; -- Write-only. Port x set bit y (y= 0..15) BS3 : Boolean := False; -- unspecified Reserved_4_18 : HAL.UInt15 := 16#0#; -- Write-only. Port x reset bit y (y = 0..15) BR3 : Boolean := False; -- unspecified Reserved_20_31 : HAL.UInt12 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for BSRR_Register_2 use record Reserved_0_2 at 0 range 0 .. 2; BS3 at 0 range 3 .. 3; Reserved_4_18 at 0 range 4 .. 18; BR3 at 0 range 19 .. 19; Reserved_20_31 at 0 range 20 .. 31; end record; -- GPIO port configuration lock register type LCKR_Register_2 is record -- unspecified Reserved_0_2 : HAL.UInt3 := 16#0#; -- Port x lock bit y (y= 0..15) LCK3 : Boolean := False; -- unspecified Reserved_4_15 : HAL.UInt12 := 16#0#; -- Port x lock bit y (y= 0..15) LCKK : Boolean := False; -- unspecified Reserved_17_31 : HAL.UInt15 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for LCKR_Register_2 use record Reserved_0_2 at 0 range 0 .. 2; LCK3 at 0 range 3 .. 3; Reserved_4_15 at 0 range 4 .. 15; LCKK at 0 range 16 .. 16; Reserved_17_31 at 0 range 17 .. 31; end record; subtype AFRL_AFRL3_Field is HAL.UInt4; -- GPIO alternate function low register type AFRL_Register_1 is record -- unspecified Reserved_0_11 : HAL.UInt12 := 16#0#; -- Alternate function selection for port x bit y (y = 0..7) AFRL3 : AFRL_AFRL3_Field := 16#0#; -- unspecified Reserved_16_31 : HAL.UInt16 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for AFRL_Register_1 use record Reserved_0_11 at 0 range 0 .. 11; AFRL3 at 0 range 12 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; -- GPIO port bit reset register type BRR_Register_2 is record -- unspecified Reserved_0_2 : HAL.UInt3 := 16#0#; -- Port Reset bit BR3 : Boolean := False; -- unspecified Reserved_4_31 : HAL.UInt28 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for BRR_Register_2 use record Reserved_0_2 at 0 range 0 .. 2; BR3 at 0 range 3 .. 3; Reserved_4_31 at 0 range 4 .. 31; end record; ----------------- -- Peripherals -- ----------------- -- General-purpose I/Os type GPIO_Peripheral is record -- GPIO port mode register MODER : aliased MODER_Register; -- GPIO port output type register OTYPER : aliased OTYPER_Register; -- GPIO port output speed register OSPEEDR : aliased OSPEEDR_Register; -- GPIO port pull-up/pull-down register PUPDR : aliased PUPDR_Register; -- GPIO port input data register IDR : aliased IDR_Register; -- GPIO port output data register ODR : aliased ODR_Register; -- GPIO port bit set/reset register BSRR : aliased BSRR_Register; -- GPIO port configuration lock register LCKR : aliased LCKR_Register; -- GPIO alternate function low register AFRL : aliased AFRL_Register; -- GPIO alternate function high register AFRH : aliased AFRH_Register; -- GPIO port bit reset register BRR : aliased BRR_Register; end record with Volatile; for GPIO_Peripheral use record MODER at 16#0# range 0 .. 31; OTYPER at 16#4# range 0 .. 31; OSPEEDR at 16#8# range 0 .. 31; PUPDR at 16#C# range 0 .. 31; IDR at 16#10# range 0 .. 31; ODR at 16#14# range 0 .. 31; BSRR at 16#18# range 0 .. 31; LCKR at 16#1C# range 0 .. 31; AFRL at 16#20# range 0 .. 31; AFRH at 16#24# range 0 .. 31; BRR at 16#28# range 0 .. 31; end record; -- General-purpose I/Os GPIOA_Periph : aliased GPIO_Peripheral with Import, Address => GPIOA_Base; -- General-purpose I/Os GPIOB_Periph : aliased GPIO_Peripheral with Import, Address => GPIOB_Base; -- General-purpose I/Os GPIOC_Periph : aliased GPIO_Peripheral with Import, Address => GPIOC_Base; -- General-purpose I/Os GPIOH_Periph : aliased GPIO_Peripheral with Import, Address => GPIOH_Base; end STM32_SVD.GPIO; ",12295,True,3934.1180426751143,median