text,length,is_long_context,metric_val,label_metric "--- title: Chapter 7. Multimedia part: Part II. Common Tasks prev: books/handbook/desktop next: books/handbook/kernelconfig description: FreeBSD supports a wide variety of sound cards, allowing users to enjoy high fidelity output from a FreeBSD system tags: [""multimedia"", ""sound card"", ""MP3"", ""MythTV"", ""scanner"", ""SANE""] --- [[multimedia]] = Multimedia :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :sectnumoffset: 7 :partnums: :source-highlighter: rouge :experimental: :images-path: books/handbook/multimedia/ ifdef::env-beastie[] ifdef::backend-html5[] :imagesdir: ../../../../images/{images-path} endif::[] ifndef::book[] include::shared/authors.adoc[] include::shared/mirrors.adoc[] include::shared/releases.adoc[] include::shared/attributes/attributes-{{% lang %}}.adoc[] include::shared/{{% lang %}}/teams.adoc[] include::shared/{{% lang %}}/mailing-lists.adoc[] include::shared/{{% lang %}}/urls.adoc[] toc::[] endif::[] ifdef::backend-pdf,backend-epub3[] include::../../../../../shared/asciidoctor.adoc[] endif::[] endif::[] ifndef::env-beastie[] toc::[] include::../../../../../shared/asciidoctor.adoc[] endif::[] [[multimedia-synopsis]] == Synopsis FreeBSD supports a wide variety of sound cards, allowing users to enjoy high fidelity output from a FreeBSD system. This includes the ability to record and play back audio in the MPEG Audio Layer 3 (`MP3`), Waveform Audio File (`WAV`), Ogg Vorbis, and other formats. The FreeBSD Ports Collection contains many applications for editing recorded audio, adding sound effects, and controlling attached MIDI devices. FreeBSD also supports the playback of video files and ``DVD``s. The FreeBSD Ports Collection contains applications to encode, convert, and playback various video media. This chapter describes how to configure sound cards, video playback, TV tuner cards, and scanners on FreeBSD. It also describes some of the applications which are available for using these devices. After reading this chapter, you will know how to: * Configure a sound card on FreeBSD. * Troubleshoot the sound setup. * Playback and encode MP3s and other audio. * Prepare a FreeBSD system for video playback. * Play ``DVD``s, [.filename]#.mpg#, and [.filename]#.avi# files. * Rip `CD` and `DVD` content into files. * Configure a TV card. * Install and setup MythTV on FreeBSD * Configure an image scanner. * Configure a Bluetooth headset. Before reading this chapter, you should: * Know how to install applications as described in crossref:ports[ports,Installing Applications: Packages and Ports]. [[sound-setup]] == Setting Up the Sound Card Before beginning the configuration, determine the model of the sound card and the chip it uses. FreeBSD supports a wide variety of sound cards. Check the supported audio devices list of the link:{u-rel120-hardware}[Hardware Notes] to see if the card is supported and which FreeBSD driver it uses. In order to use the sound device, its device driver must be loaded. The easiest way is to load a kernel module for the sound card with man:kldload[8]. This example loads the driver for a built-in audio chipset based on the Intel specification: [source,shell] .... # kldload snd_hda .... To automate the loading of this driver at boot time, add the driver to [.filename]#/boot/loader.conf#. The line for this driver is: [.programlisting] .... snd_hda_load=""YES"" .... Other available sound modules are listed in [.filename]#/boot/defaults/loader.conf#. When unsure which driver to use, load the [.filename]#snd_driver# module: [source,shell] .... # kldload snd_driver .... This is a metadriver which loads all of the most common sound drivers and can be used to speed up the search for the correct driver. It is also possible to load all sound drivers by adding the metadriver to [.filename]#/boot/loader.conf#. To determine which driver was selected for the sound card after loading the [.filename]#snd_driver# metadriver, type `cat /dev/sndstat`. === Configuring a Custom Kernel with Sound Support This section is for users who prefer to statically compile in support for the sound card in a custom kernel. For more information about recompiling a kernel, refer to crossref:kernelconfig[kernelconfig,Configuring the FreeBSD Kernel]. When using a custom kernel to provide sound support, make sure that the audio framework driver exists in the custom kernel configuration file: [.programlisting] .... device sound .... Next, add support for the sound card. To continue the example of the built-in audio chipset based on the Intel specification from the previous section, use the following line in the custom kernel configuration file: [.programlisting] .... device snd_hda .... Be sure to read the manual page of the driver for the device name to use for the driver. Non-PnP ISA sound cards may require the IRQ and I/O port settings of the card to be added to [.filename]#/boot/device.hints#. During the boot process, man:loader[8] reads this file and passes the settings to the kernel. For example, an old Creative SoundBlaster(R) 16 ISA non-PnP card will use the man:snd_sbc[4] driver in conjunction with `snd_sb16`. For this card, the following lines must be added to the kernel configuration file: [.programlisting] .... device snd_sbc device snd_sb16 .... If the card uses the `0x220` I/O port and IRQ `5`, these lines must also be added to [.filename]#/boot/device.hints#: [.programlisting] .... hint.sbc.0.at=""isa"" hint.sbc.0.port=""0x220"" hint.sbc.0.irq=""5"" hint.sbc.0.drq=""1"" hint.sbc.0.flags=""0x15"" .... The syntax used in [.filename]#/boot/device.hints# is described in man:sound[4] and the manual page for the driver of the sound card. The settings shown above are the defaults. In some cases, the IRQ or other settings may need to be changed to match the card. Refer to man:snd_sbc[4] for more information about this card. [[sound-testing]] === Testing Sound After loading the required module or rebooting into the custom kernel, the sound card should be detected. To confirm, run `dmesg | grep pcm`. This example is from a system with a built-in Conexant CX20590 chipset: [source,shell] .... pcm0: at nid 5 on hdaa0 pcm1: at nid 6 on hdaa0 pcm2: at nid 31,25 and 35,27 on hdaa1 .... The status of the sound card may also be checked using this command: [source,shell] .... # cat /dev/sndstat FreeBSD Audio Driver (newpcm: 64bit 2009061500/amd64) Installed devices: pcm0: (play) pcm1: (play) pcm2: (play/rec) default .... The output will vary depending upon the sound card. If no [.filename]#pcm# devices are listed, double-check that the correct device driver was loaded or compiled into the kernel. The next section lists some common problems and their solutions. If all goes well, the sound card should now work in FreeBSD. If the `CD` or `DVD` drive is properly connected to the sound card, one can insert an audio `CD` in the drive and play it with man:cdcontrol[1]: [source,shell] .... % cdcontrol -f /dev/acd0 play 1 .... [WARNING] ==== Audio ``CD``s have specialized encodings which means that they should not be mounted using man:mount[8]. ==== Various applications, such as package:audio/workman[], provide a friendlier interface. The package:audio/mpg123[] port can be installed to listen to MP3 audio files. Another quick way to test the card is to send data to [.filename]#/dev/dsp#: [source,shell] .... % cat filename > /dev/dsp .... where [.filename]#filename# can be any type of file. This command should produce some noise, confirming that the sound card is working. [NOTE] ==== The [.filename]#/dev/dsp*# device nodes will be created automatically as needed. When not in use, they do not exist and will not appear in the output of man:ls[1]. ==== [[bluetooth-headset]] === Setting up Bluetooth Sound Devices Connecting to a Bluetooth device is out of scope for this chapter. Refer to crossref:advanced-networking[network-bluetooth,“Bluetooth”] for more information. To get Bluetooth sound sink working with FreeBSD's sound system, users have to install package:audio/virtual_oss[] first: [source,shell] .... # pkg install virtual_oss .... package:audio/virtual_oss[] requires `cuse` to be loaded into the kernel: [source,shell] .... # kldload cuse .... To load `cuse` during system startup, run this command: [source,shell] .... # echo 'cuse_load=yes' >> /boot/loader.conf .... To use headphones as a sound sink with package:audio/virtual_oss[], users need to create a virtual device after connecting to a Bluetooth audio device: [source,shell] .... # virtual_oss -C 2 -c 2 -r 48000 -b 16 -s 768 -R /dev/null -P /dev/bluetooth/headphones -d dsp .... [NOTE] ==== _headphones_ in this example is a hostname from [.filename]#/etc/bluetooth/hosts#. `BT_ADDR` could be used instead. ==== Refer to man:virtual_oss[8] for more information. [[troubleshooting]] === Troubleshooting Sound <> lists some common error messages and their solutions: [[multimedia-sound-common-error-messages]] .Common Error Messages [cols=""1,1"", frame=""none"", options=""header""] |=== | Error | Solution |`sb_dspwr(XX) timed out` | The I/O port is not set correctly. |`bad irq XX` | The IRQ is set incorrectly. Make sure that the set IRQ and the sound IRQ are the same. |`xxx: gus pcm not attached, out of memory` | There is not enough available memory to use the device. |`xxx: can't open /dev/dsp!` | Type `fstat \\| grep` dsp to check if another application is holding the device open. Noteworthy troublemakers are esound and KDE's sound support. |=== Modern graphics cards often come with their own sound driver for use with `HDMI`. This sound device is sometimes enumerated before the sound card meaning that the sound card will not be used as the default playback device. To check if this is the case, run dmesg and look for `pcm`. The output looks something like this: [.programlisting] .... ... hdac0: HDA Driver Revision: 20100226_0142 hdac1: HDA Driver Revision: 20100226_0142 hdac0: HDA Codec #0: NVidia (Unknown) hdac0: HDA Codec #1: NVidia (Unknown) hdac0: HDA Codec #2: NVidia (Unknown) hdac0: HDA Codec #3: NVidia (Unknown) pcm0: at cad 0 nid 1 on hdac0 pcm1: at cad 1 nid 1 on hdac0 pcm2: at cad 2 nid 1 on hdac0 pcm3: at cad 3 nid 1 on hdac0 hdac1: HDA Codec #2: Realtek ALC889 pcm4: at cad 2 nid 1 on hdac1 pcm5: at cad 2 nid 1 on hdac1 pcm6: at cad 2 nid 1 on hdac1 pcm7: at cad 2 nid 1 on hdac1 ... .... In this example, the graphics card (`NVidia`) has been enumerated before the sound card (`Realtek ALC889`). To use the sound card as the default playback device, change `hw.snd.default_unit` to the unit that should be used for playback: [source,shell] .... # sysctl hw.snd.default_unit=n .... where `n` is the number of the sound device to use. In this example, it should be `4`. Make this change permanent by adding the following line to [.filename]#/etc/sysctl.conf#: [.programlisting] .... hw.snd.default_unit=4 .... Programs using package:audio/pulseaudio[] might need to restart the package:audio/pulseaudio[] daemon for the changes in `hw.snd.default_unit` to take effect. Alternatively, package:audio/pulseaudio[] settings can be changed on the fly. man:pacmd[1] opens a command line connection to the package:audio/pulseaudio[] daemon: [source,shell] .... # pacmd Welcome to PulseAudio 14.2! Use ""help"" for usage information. >>> .... The following command changes the default sink to card number 4 as in the previous example: [.programlisting] .... set-default-sink 4 .... [WARNING] ==== Do not use the `exit` command to exit the command line interface. That will kill the package:audio/pulseaudio[] daemon. Use kbd:[Ctrl+D] instead. ==== [[sound-multiple-sources]] === Utilizing Multiple Sound Sources It is often desirable to have multiple sources of sound that are able to play simultaneously. FreeBSD uses ""Virtual Sound Channels"" to multiplex the sound card's playback by mixing sound in the kernel. Three man:sysctl[8] knobs are available for configuring virtual channels: [source,shell] .... # sysctl dev.pcm.0.play.vchans=4 # sysctl dev.pcm.0.rec.vchans=4 # sysctl hw.snd.maxautovchans=4 .... This example allocates four virtual channels, which is a practical number for everyday use. Both `dev.pcm.0.play.vchans=4` and `dev.pcm.0.rec.vchans=4` are configurable after a device has been attached and represent the number of virtual channels [.filename]#pcm0# has for playback and recording. Since the [.filename]#pcm# module can be loaded independently of the hardware drivers, `hw.snd.maxautovchans` indicates how many virtual channels will be given to an audio device when it is attached. Refer to man:pcm[4] for more information. [NOTE] ==== The number of virtual channels for a device cannot be changed while it is in use. First, close any programs using the device, such as music players or sound daemons. ==== The correct [.filename]#pcm# device will automatically be allocated transparently to a program that requests [.filename]#/dev/dsp0#. === Setting Default Values for Mixer Channels The default values for the different mixer channels are hardcoded in the source code of the man:pcm[4] driver. While sound card mixer levels can be changed using man:mixer[8] or third-party applications and daemons, this is not a permanent solution. To instead set default mixer values at the driver level, define the appropriate values in [.filename]#/boot/device.hints#, as seen in this example: [.programlisting] .... hint.pcm.0.vol=""50"" .... This will set the volume channel to a default value of `50` when the man:pcm[4] module is loaded. [[sound-mp3]] == MP3 Audio This section describes some `MP3` players available for FreeBSD, how to rip audio `CD` tracks, and how to encode and decode ``MP3``s. [[mp3-players]] === MP3 Players A popular graphical `MP3` player is Audacious. It supports Winamp skins and additional plugins. The interface is intuitive, with a playlist, graphic equalizer, and more. Those familiar with Winamp will find Audacious simple to use. On FreeBSD, Audacious can be installed from the package:multimedia/audacious[] port or package. Audacious is a descendant of XMMS. The package:audio/mpg123[] package or port provides an alternative, command-line `MP3` player. Once installed, specify the `MP3` file to play on the command line. If the system has multiple audio devices, the sound device can also be specified: [source,shell] .... # mpg123 -a /dev/dsp1.0 Foobar-GreatestHits.mp3 High Performance MPEG 1.0/2.0/2.5 Audio Player for Layers 1, 2 and 3 version 1.18.1; written and copyright by Michael Hipp and others free software (LGPL) without any warranty but with best wishes Playing MPEG stream from Foobar-GreatestHits.mp3 ... MPEG 1.0 layer III, 128 kbit/s, 44100 Hz joint-stereo .... Additional `MP3` players are available in the FreeBSD Ports Collection. [[rip-cd]] === Ripping `CD` Audio Tracks Before encoding a `CD` or `CD` track to `MP3`, the audio data on the `CD` must be ripped to the hard drive. This is done by copying the raw `CD` Digital Audio (`CDDA`) data to `WAV` files. The `cdda2wav` tool, which is installed with the package:sysutils/cdrtools[] suite, can be used to rip audio information from ``CD``s. With the audio `CD` in the drive, the following command can be issued as `root` to rip an entire `CD` into individual, per track, `WAV` files: [source,shell] .... # cdda2wav -D 0,1,0 -B .... In this example, the `-D _0,1,0_` indicates the `SCSI` device [.filename]#0,1,0# containing the `CD` to rip. Use `cdrecord -scanbus` to determine the correct device parameters for the system. To rip individual tracks, use `-t` to specify the track: [source,shell] .... # cdda2wav -D 0,1,0 -t 7 .... To rip a range of tracks, such as track one to seven, specify a range: [source,shell] .... # cdda2wav -D 0,1,0 -t 1+7 .... To rip from an `ATAPI` (`IDE`) `CDROM` drive, specify the device name in place of the `SCSI` unit numbers. For example, to rip track 7 from an IDE drive: [source,shell] .... # cdda2wav -D /dev/acd0 -t 7 .... Alternately, `dd` can be used to extract audio tracks on `ATAPI` drives, as described in crossref:disks[duplicating-audiocds,“Duplicating Audio CDs”]. [[mp3-encoding]] === Encoding and Decoding MP3s Lame is a popular `MP3` encoder which can be installed from the package:audio/lame[] port. Due to patent issues, a package is not available. The following command will convert the ripped `WAV` file [.filename]#audio01.wav# to [.filename]#audio01.mp3#: [source,shell] .... # lame -h -b 128 --tt ""Foo Song Title"" --ta ""FooBar Artist"" --tl ""FooBar Album"" \\ --ty ""2014"" --tc ""Ripped and encoded by Foo"" --tg ""Genre"" audio01.wav audio01.mp3 .... The specified 128 kbits is a standard `MP3` bitrate while the 160 and 192 bitrates provide higher quality. The higher the bitrate, the larger the size of the resulting `MP3`. The `-h` turns on the ""higher quality but a little slower"" mode. The options beginning with `--t` indicate `ID3` tags, which usually contain song information, to be embedded within the `MP3` file. Additional encoding options can be found in the lame manual page. In order to burn an audio `CD` from ``MP3``s, they must first be converted to a non-compressed file format. XMMS can be used to convert to the `WAV` format, while mpg123 can be used to convert to the raw Pulse-Code Modulation (`PCM`) audio data format. To convert [.filename]#audio01.mp3# using mpg123, specify the name of the `PCM` file: [source,shell] .... # mpg123 -s audio01.mp3 > audio01.pcm .... To use XMMS to convert a `MP3` to `WAV` format, use these steps: [.procedure] .Procedure: Converting to `WAV` Format in XMMS . Launch XMMS. . Right-click the window to bring up the XMMS menu. . Select `Preferences` under `Options`. . Change the Output Plugin to ""Disk Writer Plugin"". . Press `Configure`. . Enter or browse to a directory to write the uncompressed files to. . Load the `MP3` file into XMMS as usual, with volume at 100% and EQ settings turned off. . Press `Play`. The XMMS will appear as if it is playing the `MP3`, but no music will be heard. It is actually playing the `MP3` to a file. . When finished, be sure to set the default Output Plugin back to what it was before in order to listen to ``MP3``s again. Both the `WAV` and `PCM` formats can be used with cdrecord. When using `WAV` files, there will be a small tick sound at the beginning of each track. This sound is the header of the `WAV` file. The package:audio/sox[] port or package can be used to remove the header: [source,shell] .... % sox -t wav -r 44100 -s -w -c 2 track.wav track.raw .... Refer to crossref:disks[creating-cds,“Creating and Using CD Media”] for more information on using a `CD` burner in FreeBSD. [[video-playback]] == Video Playback Before configuring video playback, determine the model and chipset of the video card. While Xorg supports a wide variety of video cards, not all provide good playback performance. To obtain a list of extensions supported by the Xorg server using the card, run `xdpyinfo` while Xorg is running. It is a good idea to have a short MPEG test file for evaluating various players and options. Since some `DVD` applications look for `DVD` media in [.filename]#/dev/dvd# by default, or have this device name hardcoded in them, it might be useful to make a symbolic link to the proper device: [source,shell] .... # ln -sf /dev/cd0 /dev/dvd .... Due to the nature of man:devfs[5], manually created links will not persist after a system reboot. In order to recreate the symbolic link automatically when the system boots, add the following line to [.filename]#/etc/devfs.conf#: [.programlisting] .... link cd0 dvd .... `DVD` decryption invokes certain functions that require write permission to the `DVD` device. To enhance the shared memory Xorg interface, it is recommended to increase the values of these man:sysctl[8] variables: [.programlisting] .... kern.ipc.shmmax=67108864 kern.ipc.shmall=32768 .... [[video-interface]] === Determining Video Capabilities There are several possible ways to display video under Xorg and what works is largely hardware dependent. Each method described below will have varying quality across different hardware. Common video interfaces include: . Xorg: normal output using shared memory. . XVideo: an extension to the Xorg interface which allows video to be directly displayed in drawable objects through a special acceleration. This extension provides good quality playback even on low-end machines. The next section describes how to determine if this extension is running. . `SDL`: the Simple Directmedia Layer is a porting layer for many operating systems, allowing cross-platform applications to be developed which make efficient use of sound and graphics. `SDL` provides a low-level abstraction to the hardware which can sometimes be more efficient than the Xorg interface. On FreeBSD, `SDL` can be installed using the package:devel/sdl20[] package or port. . `DGA`: the Direct Graphics Access is an Xorg extension which allows a program to bypass the Xorg server and directly alter the framebuffer. As it relies on a low-level memory mapping, programs using it must be run as `root`. The `DGA` extension can be tested and benchmarked using man:dga[1]. When `dga` is running, it changes the colors of the display whenever a key is pressed. To quit, press kbd:[q]. . SVGAlib: a low level console graphics layer. [[video-interface-xvideo]] ==== XVideo To check whether this extension is running, use `xvinfo`: [source,shell] .... % xvinfo .... XVideo is supported for the card if the result is similar to: [source,shell] .... X-Video Extension version 2.2 screen #0 Adaptor #0: ""Savage Streams Engine"" number of ports: 1 port base: 43 operations supported: PutImage supported visuals: depth 16, visualID 0x22 depth 16, visualID 0x23 number of attributes: 5 ""XV_COLORKEY"" (range 0 to 16777215) client settable attribute client gettable attribute (current value is 2110) ""XV_BRIGHTNESS"" (range -128 to 127) client settable attribute client gettable attribute (current value is 0) ""XV_CONTRAST"" (range 0 to 255) client settable attribute client gettable attribute (current value is 128) ""XV_SATURATION"" (range 0 to 255) client settable attribute client gettable attribute (current value is 128) ""XV_HUE"" (range -180 to 180) client settable attribute client gettable attribute (current value is 0) maximum XvImage size: 1024 x 1024 Number of image formats: 7 id: 0x32595559 (YUY2) guid: 59555932-0000-0010-8000-00aa00389b71 bits per pixel: 16 number of planes: 1 type: YUV (packed) id: 0x32315659 (YV12) guid: 59563132-0000-0010-8000-00aa00389b71 bits per pixel: 12 number of planes: 3 type: YUV (planar) id: 0x30323449 (I420) guid: 49343230-0000-0010-8000-00aa00389b71 bits per pixel: 12 number of planes: 3 type: YUV (planar) id: 0x36315652 (RV16) guid: 52563135-0000-0000-0000-000000000000 bits per pixel: 16 number of planes: 1 type: RGB (packed) depth: 0 red, green, blue masks: 0x1f, 0x3e0, 0x7c00 id: 0x35315652 (RV15) guid: 52563136-0000-0000-0000-000000000000 bits per pixel: 16 number of planes: 1 type: RGB (packed) depth: 0 red, green, blue masks: 0x1f, 0x7e0, 0xf800 id: 0x31313259 (Y211) guid: 59323131-0000-0010-8000-00aa00389b71 bits per pixel: 6 number of planes: 3 type: YUV (packed) id: 0x0 guid: 00000000-0000-0000-0000-000000000000 bits per pixel: 0 number of planes: 0 type: RGB (packed) depth: 1 red, green, blue masks: 0x0, 0x0, 0x0 .... The formats listed, such as YUV2 and YUV12, are not present with every implementation of XVideo and their absence may hinder some players. If the result instead looks like: [source,shell] .... X-Video Extension version 2.2 screen #0 no adaptors present .... XVideo is probably not supported for the card. This means that it will be more difficult for the display to meet the computational demands of rendering video, depending on the video card and processor. [[video-ports]] === Ports and Packages Dealing with Video This section introduces some of the software available from the FreeBSD Ports Collection which can be used for video playback. [[video-mplayer]] ==== MPlayer and MEncoder MPlayer is a command-line video player with an optional graphical interface which aims to provide speed and flexibility. Other graphical front-ends to MPlayer are available from the FreeBSD Ports Collection. MPlayer can be installed using the package:multimedia/mplayer[] package or port. Several compile options are available and a variety of hardware checks occur during the build process. For these reasons, some users prefer to build the port rather than install the package. When compiling the port, the menu options should be reviewed to determine the type of support to compile into the port. If an option is not selected, MPlayer will not be able to display that type of video format. Use the arrow keys and spacebar to select the required formats. When finished, press kbd:[Enter] to continue the port compile and installation. By default, the package or port will build the `mplayer` command line utility and the `gmplayer` graphical utility. To encode videos, compile the package:multimedia/mencoder[] port. Due to licensing restrictions, a package is not available for MEncoder. The first time MPlayer is run, it will create [.filename]#~/.mplayer# in the user's home directory. This subdirectory contains default versions of the user-specific configuration files. This section describes only a few common uses. Refer to mplayer(1) for a complete description of its numerous options. To play the file [.filename]#testfile.avi#, specify the video interfaces with `-vo`, as seen in the following examples: [source,shell] .... % mplayer -vo xv testfile.avi .... [source,shell] .... % mplayer -vo sdl testfile.avi .... [source,shell] .... % mplayer -vo x11 testfile.avi .... [source,shell] .... # mplayer -vo dga testfile.avi .... [source,shell] .... # mplayer -vo 'sdl:dga' testfile.avi .... It is worth trying all of these options, as their relative performance depends on many factors and will vary significantly with hardware. To play a `DVD`, replace [.filename]#testfile.avi# with `dvd://_N_ -dvd-device _DEVICE_`, where _N_ is the title number to play and _DEVICE_ is the device node for the `DVD`. For example, to play title 3 from [.filename]#/dev/dvd#: [source,shell] .... # mplayer -vo xv dvd://3 -dvd-device /dev/dvd .... [NOTE] ==== The default `DVD` device can be defined during the build of the MPlayer port by including the `WITH_DVD_DEVICE=/path/to/desired/device` option. By default, the device is [.filename]#/dev/cd0#. More details can be found in the port's [.filename]#Makefile.options#. ==== To stop, pause, advance, and so on, use a keybinding. To see the list of keybindings, run `mplayer -h` or read mplayer(1). Additional playback options include `-fs -zoom`, which engages fullscreen mode, and `-framedrop`, which helps performance. Each user can add commonly used options to their [.filename]#~/.mplayer/config# like so: [.programlisting] .... vo=xv fs=yes zoom=yes .... `mplayer` can be used to rip a `DVD` title to a [.filename]#.vob#. To dump the second title from a `DVD`: [source,shell] .... # mplayer -dumpstream -dumpfile out.vob dvd://2 -dvd-device /dev/dvd .... The output file, [.filename]#out.vob#, will be in `MPEG` format. Anyone wishing to obtain a high level of expertise with UNIX(R) video should consult http://www.mplayerhq.hu/DOCS/[mplayerhq.hu/DOCS] as it is technically informative. This documentation should be considered as required reading before submitting any bug reports. Before using `mencoder`, it is a good idea to become familiar with the options described at http://www.mplayerhq.hu/DOCS/HTML/en/mencoder.html[mplayerhq.hu/DOCS/HTML/en/mencoder.html]. There are innumerable ways to improve quality, lower bitrate, and change formats, and some of these options may make the difference between good or bad performance. Improper combinations of command line options can yield output files that are unplayable even by `mplayer`. Here is an example of a simple copy: [source,shell] .... % mencoder input.avi -oac copy -ovc copy -o output.avi .... To rip to a file, use `-dumpfile` with `mplayer`. To convert [.filename]#input.avi# to the MPEG4 codec with MPEG3 audio encoding, first install the package:audio/lame[] port. Due to licensing restrictions, a package is not available. Once installed, type: [source,shell] .... % mencoder input.avi -oac mp3lame -lameopts br=192 \\ -ovc lavc -lavcopts vcodec=mpeg4:vhq -o output.avi .... This will produce output playable by applications such as `mplayer` and `xine`. [.filename]#input.avi# can be replaced with `dvd://1 -dvd-device /dev/dvd` and run as `root` to re-encode a `DVD` title directly. Since it may take a few tries to get the desired result, it is recommended to instead dump the title to a file and to work on the file. [[video-xine]] ==== The xine Video Player xine is a video player with a reusable base library and a modular executable which can be extended with plugins. It can be installed using the package:multimedia/xine[] package or port. In practice, xine requires either a fast CPU with a fast video card, or support for the XVideo extension. The xine video player performs best on XVideo interfaces. By default, the xine player starts a graphical user interface. The menus can then be used to open a specific file. Alternatively, xine may be invoked from the command line by specifying the name of the file to play: [source,shell] .... % xine -g -p mymovie.avi .... Refer to http://www.xine-project.org/faq[xine-project.org/faq] for more information and troubleshooting tips. [[video-ports-transcode]] ==== The Transcode Utilities Transcode provides a suite of tools for re-encoding video and audio files. Transcode can be used to merge video files or repair broken files using command line tools with stdin/stdout stream interfaces. In FreeBSD, Transcode can be installed using the package:multimedia/transcode[] package or port. Many users prefer to compile the port as it provides a menu of compile options for specifying the support and codecs to compile in. If an option is not selected, Transcode will not be able to encode that format. Use the arrow keys and spacebar to select the required formats. When finished, press kbd:[Enter] to continue the port compile and installation. This example demonstrates how to convert a DivX file into a PAL MPEG-1 file (PAL VCD): [source,shell] .... % transcode -i input.avi -V --export_prof vcd-pal -o output_vcd % mplex -f 1 -o output_vcd.mpg output_vcd.m1v output_vcd.mpa .... The resulting `MPEG` file, [.filename]#output_vcd.mpg#, is ready to be played with MPlayer. The file can be burned on a `CD` media to create a video `CD` using a utility such as package:multimedia/vcdimager[] or package:sysutils/cdrdao[]. In addition to the manual page for `transcode`, refer to http://www.transcoding.org/cgi-bin/transcode[transcoding.org/cgi-bin/transcode] for further information and examples. [[tvcard]] == TV Cards TV cards can be used to watch broadcast or cable TV on a computer. Most cards accept composite video via an `RCA` or S-video input and some cards include a `FM` radio tuner. FreeBSD provides support for PCI-based TV cards using a Brooktree Bt848/849/878/879 video capture chip with the man:bktr[4] driver. This driver supports most Pinnacle PCTV video cards. Before purchasing a TV card, consult man:bktr[4] for a list of supported tuners. === Loading the Driver In order to use the card, the man:bktr[4] driver must be loaded. To automate this at boot time, add the following line to [.filename]#/boot/loader.conf#: [.programlisting] .... bktr_load=""YES"" .... Alternatively, one can statically compile support for the TV card into a custom kernel. In that case, add the following lines to the custom kernel configuration file: [.programlisting] .... device bktr device iicbus device iicbb device smbus .... These additional devices are necessary as the card components are interconnected via an I2C bus. Then, build and install a new kernel. To test that the tuner is correctly detected, reboot the system. The TV card should appear in the boot messages, as seen in this example: [.programlisting] .... bktr0: mem 0xd7000000-0xd7000fff irq 10 at device 10.0 on pci0 iicbb0: on bti2c0 iicbus0: on iicbb0 master-only iicbus1: on iicbb0 master-only smbus0: on bti2c0 bktr0: Pinnacle/Miro TV, Philips SECAM tuner. .... The messages will differ according to the hardware. If necessary, it is possible to override some of the detected parameters using man:sysctl[8] or custom kernel configuration options. For example, to force the tuner to a Philips SECAM tuner, add the following line to a custom kernel configuration file: [.programlisting] .... options OVERRIDE_TUNER=6 .... or, use man:sysctl[8]: [source,shell] .... # sysctl hw.bt848.tuner=6 .... Refer to man:bktr[4] for a description of the available man:sysctl[8] parameters and kernel options. === Useful Applications To use the TV card, install one of the following applications: * package:multimedia/fxtv[] provides TV-in-a-window and image/audio/video capture capabilities. * package:multimedia/xawtv[] is another TV application with similar features. * package:audio/xmradio[] provides an application for using the FM radio tuner of a TV card. More applications are available in the FreeBSD Ports Collection. === Troubleshooting If any problems are encountered with the TV card, check that the video capture chip and the tuner are supported by man:bktr[4] and that the right configuration options were used. For more support or to ask questions about supported TV cards, refer to the {freebsd-multimedia} mailing list. [[mythtv]] == MythTV MythTV is a popular, open source Personal Video Recorder (`PVR`) application. This section demonstrates how to install and setup MythTV on FreeBSD. Refer to http://www.mythtv.org/wiki/[mythtv.org/wiki] for more information on how to use MythTV. MythTV requires a frontend and a backend. These components can either be installed on the same system or on different machines. The frontend can be installed on FreeBSD using the package:multimedia/mythtv-frontend[] package or port. Xorg must also be installed and configured as described in crossref:x11[x11,The X Window System]. Ideally, this system has a video card that supports X-Video Motion Compensation (`XvMC`) and, optionally, a Linux Infrared Remote Control (`LIRC`)-compatible remote. To install both the backend and the frontend on FreeBSD, use the package:multimedia/mythtv[] package or port. A MySQL(TM) database server is also required and should automatically be installed as a dependency. Optionally, this system should have a tuner card and sufficient storage to hold recorded data. === Hardware MythTV uses Video for Linux (`V4L`) to access video input devices such as encoders and tuners. In FreeBSD, MythTV works best with `USB` DVB-S/C/T cards as they are well supported by the package:multimedia/webcamd[] package or port which provides a `V4L` userland application. Any Digital Video Broadcasting (`DVB`) card supported by webcamd should work with MythTV. A list of known working cards can be found at https://wiki.freebsd.org/WebcamCompat[wiki.freebsd.org/WebcamCompat]. Drivers are also available for Hauppauge cards in the package:multimedia/pvr250[] and package:multimedia/pvrxxx[] ports, but they provide a non-standard driver interface that does not work with versions of MythTV greater than 0.23. Due to licensing restrictions, no packages are available and these two ports must be compiled. The https://wiki.freebsd.org/HTPC[wiki.freebsd.org/HTPC] page contains a list of all available `DVB` drivers. === Setting up the MythTV Backend To install MythTV using binary packages: [source,shell] .... # pkg install mythtv .... Alternatively, to install from the Ports Collection: [source,shell] .... # cd /usr/ports/multimedia/mythtv # make install .... Once installed, set up the MythTV database: [source,shell] .... # mysql -uroot -p < /usr/local/share/mythtv/database/mc.sql .... Then, configure the backend: [source,shell] .... # mythtv-setup .... Finally, start the backend: [source,shell] .... # sysrc mythbackend_enable=yes # service mythbackend start .... [[scanners]] == Image Scanners In FreeBSD, access to image scanners is provided by SANE (Scanner Access Now Easy), which is available in the FreeBSD Ports Collection. SANE will also use some FreeBSD device drivers to provide access to the scanner hardware. FreeBSD supports both `SCSI` and `USB` scanners. Depending upon the scanner interface, different device drivers are required. Be sure the scanner is supported by SANE prior to performing any configuration. Refer to http://www.sane-project.org/sane-supported-devices.html[http://www.sane-project.org/sane-supported-devices.html] for more information about supported scanners. This chapter describes how to determine if the scanner has been detected by FreeBSD. It then provides an overview of how to configure and use SANE on a FreeBSD system. [[scanners-kernel-usb]] === Checking the Scanner The [.filename]#GENERIC# kernel includes the device drivers needed to support `USB` scanners. Users with a custom kernel should ensure that the following lines are present in the custom kernel configuration file: [.programlisting] .... device usb device uhci device ohci device ehci device xhci .... To determine if the `USB` scanner is detected, plug it in and use `dmesg` to determine whether the scanner appears in the system message buffer. If it does, it should display a message similar to this: [source,shell] .... ugen0.2: at usbus0 .... In this example, an EPSON Perfection(R) 1650 `USB` scanner was detected on [.filename]#/dev/ugen0.2#. If the scanner uses a `SCSI` interface, it is important to know which `SCSI` controller board it will use. Depending upon the `SCSI` chipset, a custom kernel configuration file may be needed. The [.filename]#GENERIC# kernel supports the most common `SCSI` controllers. Refer to [.filename]#/usr/src/sys/conf/NOTES# to determine the correct line to add to a custom kernel configuration file. In addition to the `SCSI` adapter driver, the following lines are needed in a custom kernel configuration file: [.programlisting] .... device scbus device pass .... Verify that the device is displayed in the system message buffer: [source,shell] .... pass2 at aic0 bus 0 target 2 lun 0 pass2: Fixed Scanner SCSI-2 device pass2: 3.300MB/s transfers .... If the scanner was not powered-on at system boot, it is still possible to manually force detection by performing a `SCSI` bus scan with `camcontrol`: [source,shell] .... # camcontrol rescan all Re-scan of bus 0 was successful Re-scan of bus 1 was successful Re-scan of bus 2 was successful Re-scan of bus 3 was successful .... The scanner should now appear in the `SCSI` devices list: [source,shell] .... # camcontrol devlist at scbus0 target 5 lun 0 (pass0,da0) at scbus0 target 6 lun 0 (pass1,da1) at scbus1 target 2 lun 0 (pass3) at scbus2 target 0 lun 0 (pass2,cd0) .... Refer to man:scsi[4] and man:camcontrol[8] for more details about `SCSI` devices on FreeBSD. === SANE Configuration The SANE system provides the access to the scanner via backends (package:graphics/sane-backends[]). Refer to http://www.sane-project.org/sane-supported-devices.html[http://www.sane-project.org/sane-supported-devices.html] to determine which backend supports the scanner. A graphical scanning interface is provided by third party applications like Kooka (package:graphics/kooka[]) or XSane (package:graphics/xsane[]). SANE's backends are enough to test the scanner. To install the backends from binary package: [source,shell] .... # pkg install sane-backends .... Alternatively, to install from the Ports Collection [source,shell] .... # cd /usr/ports/graphics/sane-backends # make install clean .... After installing the package:graphics/sane-backends[] port or package, use `sane-find-scanner` to check the scanner detection by the SANE system: [source,shell] .... # sane-find-scanner -q found SCSI scanner ""AGFA SNAPSCAN 600 1.10"" at /dev/pass3 .... The output should show the interface type of the scanner and the device node used to attach the scanner to the system. The vendor and the product model may or may not appear. [NOTE] ==== Some `USB` scanners require firmware to be loaded. Refer to sane-find-scanner(1) and sane(7) for details. ==== Next, check if the scanner will be identified by a scanning frontend. The SANE backends include `scanimage` which can be used to list the devices and perform an image acquisition. Use `-L` to list the scanner devices. The first example is for a `SCSI` scanner and the second is for a `USB` scanner: [source,shell] .... # scanimage -L device `snapscan:/dev/pass3' is a AGFA SNAPSCAN 600 flatbed scanner # scanimage -L device 'epson2:libusb:000:002' is a Epson GT-8200 flatbed scanner .... In this second example, `epson2` is the backend name and `libusb:000:002` means [.filename]#/dev/ugen0.2# is the device node used by the scanner. If `scanimage` is unable to identify the scanner, this message will appear: [source,shell] .... # scanimage -L No scanners were identified. If you were expecting something different, check that the scanner is plugged in, turned on and detected by the sane-find-scanner tool (if appropriate). Please read the documentation which came with this software (README, FAQ, manpages). .... If this happens, edit the backend configuration file in [.filename]#/usr/local/etc/sane.d/# and define the scanner device used. For example, if the undetected scanner model is an EPSON Perfection(R) 1650 and it uses the `epson2` backend, edit [.filename]#/usr/local/etc/sane.d/epson2.conf#. When editing, add a line specifying the interface and the device node used. In this case, add the following line: [.programlisting] .... usb /dev/ugen0.2 .... Save the edits and verify that the scanner is identified with the right backend name and the device node: [source,shell] .... # scanimage -L device 'epson2:libusb:000:002' is a Epson GT-8200 flatbed scanner .... Once `scanimage -L` sees the scanner, the configuration is complete and the scanner is now ready to use. While `scanimage` can be used to perform an image acquisition from the command line, it is often preferable to use a graphical interface to perform image scanning. Applications like Kooka or XSane are popular scanning frontends. They offer advanced features such as various scanning modes, color correction, and batch scans. XSane is also usable as a GIMP plugin. === Scanner Permissions In order to have access to the scanner, a user needs read and write permissions to the device node used by the scanner. In the previous example, the `USB` scanner uses the device node [.filename]#/dev/ugen0.2# which is really a symlink to the real device node [.filename]#/dev/usb/0.2.0#. The symlink and the device node are owned, respectively, by the `wheel` and `operator` groups. While adding the user to these groups will allow access to the scanner, it is considered insecure to add a user to `wheel`. A better solution is to create a group and make the scanner device accessible to members of this group. This example creates a group called `_usb_`: [source,shell] .... # pw groupadd usb .... Then, make the [.filename]#/dev/ugen0.2# symlink and the [.filename]#/dev/usb/0.2.0# device node accessible to the `usb` group with write permissions of `0660` or `0664` by adding the following lines to [.filename]#/etc/devfs.rules#: [.programlisting] .... [system=5] add path ugen0.2 mode 0660 group usb add path usb/0.2.0 mode 0666 group usb .... [NOTE] ==== It happens the device node changes with the addition or removal of devices, so one may want to give access to all USB devices using this ruleset instead: [.programlisting] .... [system=5] add path 'ugen*' mode 0660 group usb add path 'usb/*' mode 0666 group usb .... ==== Refer to man:devfs.rules[5] for more information about this file. Next, enable the ruleset in /etc/rc.conf: [.programlisting] .... devfs_system_ruleset=""system"" .... And, restart the man:devfs[8] system: [source,shell] .... # service devfs restart .... Finally, add the users to `_usb_` in order to allow access to the scanner: [source,shell] .... # pw groupmod usb -m joe .... For more details refer to man:pw[8]. ",12222,False,2137.338826379226,median "//===-- ClangASTSource.cpp ---------------------------------------*- C++-*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include ""ClangASTSource.h"" #include ""ClangDeclVendor.h"" #include ""ClangModulesDeclVendor.h"" #include ""lldb/Core/Module.h"" #include ""lldb/Core/ModuleList.h"" #include ""lldb/Symbol/ClangASTContext.h"" #include ""lldb/Symbol/ClangUtil.h"" #include ""lldb/Symbol/CompilerDeclContext.h"" #include ""lldb/Symbol/Function.h"" #include ""lldb/Symbol/SymbolFile.h"" #include ""lldb/Symbol/TaggedASTType.h"" #include ""lldb/Target/Target.h"" #include ""lldb/Utility/Log.h"" #include ""clang/AST/ASTContext.h"" #include ""clang/AST/RecordLayout.h"" #include ""Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h"" #include #include using namespace clang; using namespace lldb_private; // Scoped class that will remove an active lexical decl from the set when it // goes out of scope. namespace { class ScopedLexicalDeclEraser { public: ScopedLexicalDeclEraser(std::set &decls, const clang::Decl *decl) : m_active_lexical_decls(decls), m_decl(decl) {} ~ScopedLexicalDeclEraser() { m_active_lexical_decls.erase(m_decl); } private: std::set &m_active_lexical_decls; const clang::Decl *m_decl; }; } ClangASTSource::ClangASTSource(const lldb::TargetSP &target, const lldb::ClangASTImporterSP &importer) : m_import_in_progress(false), m_lookups_enabled(false), m_target(target), m_ast_context(nullptr), m_active_lexical_decls(), m_active_lookups() { m_ast_importer_sp = importer; } void ClangASTSource::InstallASTContext(ClangASTContext &clang_ast_context) { m_ast_context = &clang_ast_context.getASTContext(); m_clang_ast_context = &clang_ast_context; m_file_manager = &m_ast_context->getSourceManager().getFileManager(); m_ast_importer_sp->InstallMapCompleter(m_ast_context, *this); } ClangASTSource::~ClangASTSource() { if (!m_ast_importer_sp) return; m_ast_importer_sp->ForgetDestination(m_ast_context); if (!m_target) return; // We are in the process of destruction, don't create clang ast context on // demand by passing false to // Target::GetScratchClangASTContext(create_on_demand). ClangASTContext *scratch_clang_ast_context = ClangASTContext::GetScratch(*m_target, false); if (!scratch_clang_ast_context) return; clang::ASTContext &scratch_ast_context = scratch_clang_ast_context->getASTContext(); if (m_ast_context != &scratch_ast_context && m_ast_importer_sp) m_ast_importer_sp->ForgetSource(&scratch_ast_context, m_ast_context); } void ClangASTSource::StartTranslationUnit(ASTConsumer *Consumer) { if (!m_ast_context) return; m_ast_context->getTranslationUnitDecl()->setHasExternalVisibleStorage(); m_ast_context->getTranslationUnitDecl()->setHasExternalLexicalStorage(); } // The core lookup interface. bool ClangASTSource::FindExternalVisibleDeclsByName( const DeclContext *decl_ctx, DeclarationName clang_decl_name) { if (!m_ast_context) { SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name); return false; } if (GetImportInProgress()) { SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name); return false; } std::string decl_name(clang_decl_name.getAsString()); // if (m_decl_map.DoingASTImport ()) // return DeclContext::lookup_result(); // switch (clang_decl_name.getNameKind()) { // Normal identifiers. case DeclarationName::Identifier: { clang::IdentifierInfo *identifier_info = clang_decl_name.getAsIdentifierInfo(); if (!identifier_info || identifier_info->getBuiltinID() != 0) { SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name); return false; } } break; // Operator names. case DeclarationName::CXXOperatorName: case DeclarationName::CXXLiteralOperatorName: break; // Using directives found in this context. // Tell Sema we didn't find any or we'll end up getting asked a *lot*. case DeclarationName::CXXUsingDirective: SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name); return false; case DeclarationName::ObjCZeroArgSelector: case DeclarationName::ObjCOneArgSelector: case DeclarationName::ObjCMultiArgSelector: { llvm::SmallVector method_decls; NameSearchContext method_search_context(*this, method_decls, clang_decl_name, decl_ctx); FindObjCMethodDecls(method_search_context); SetExternalVisibleDeclsForName(decl_ctx, clang_decl_name, method_decls); return (method_decls.size() > 0); } // These aren't possible in the global context. case DeclarationName::CXXConstructorName: case DeclarationName::CXXDestructorName: case DeclarationName::CXXConversionFunctionName: case DeclarationName::CXXDeductionGuideName: SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name); return false; } if (!GetLookupsEnabled()) { // Wait until we see a '$' at the start of a name before we start doing any // lookups so we can avoid lookup up all of the builtin types. if (!decl_name.empty() && decl_name[0] == '$') { SetLookupsEnabled(true); } else { SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name); return false; } } ConstString const_decl_name(decl_name.c_str()); const char *uniqued_const_decl_name = const_decl_name.GetCString(); if (m_active_lookups.find(uniqued_const_decl_name) != m_active_lookups.end()) { // We are currently looking up this name... SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name); return false; } m_active_lookups.insert(uniqued_const_decl_name); // static uint32_t g_depth = 0; // ++g_depth; // printf(""[%5u] FindExternalVisibleDeclsByName() \\""%s\\""\\n"", g_depth, // uniqued_const_decl_name); llvm::SmallVector name_decls; NameSearchContext name_search_context(*this, name_decls, clang_decl_name, decl_ctx); FindExternalVisibleDecls(name_search_context); SetExternalVisibleDeclsForName(decl_ctx, clang_decl_name, name_decls); // --g_depth; m_active_lookups.erase(uniqued_const_decl_name); return (name_decls.size() != 0); } void ClangASTSource::CompleteType(TagDecl *tag_decl) { Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); static unsigned int invocation_id = 0; unsigned int current_id = invocation_id++; if (log) { LLDB_LOGF(log, "" CompleteTagDecl[%u] on (ASTContext*)%p Completing "" ""(TagDecl*)%p named %s"", current_id, static_cast(m_ast_context), static_cast(tag_decl), tag_decl->getName().str().c_str()); LLDB_LOG(log, "" CTD[%u] Before:\\n{0}"", current_id, ClangUtil::DumpDecl(tag_decl)); } auto iter = m_active_lexical_decls.find(tag_decl); if (iter != m_active_lexical_decls.end()) return; m_active_lexical_decls.insert(tag_decl); ScopedLexicalDeclEraser eraser(m_active_lexical_decls, tag_decl); if (!m_ast_importer_sp) { return; } if (!m_ast_importer_sp->CompleteTagDecl(tag_decl)) { // We couldn't complete the type. Maybe there's a definition somewhere // else that can be completed. LLDB_LOGF(log, "" CTD[%u] Type could not be completed in the module in "" ""which it was first found."", current_id); bool found = false; DeclContext *decl_ctx = tag_decl->getDeclContext(); if (const NamespaceDecl *namespace_context = dyn_cast(decl_ctx)) { ClangASTImporter::NamespaceMapSP namespace_map = m_ast_importer_sp->GetNamespaceMap(namespace_context); if (log && log->GetVerbose()) LLDB_LOGF(log, "" CTD[%u] Inspecting namespace map %p (%d entries)"", current_id, static_cast(namespace_map.get()), static_cast(namespace_map->size())); if (!namespace_map) return; for (ClangASTImporter::NamespaceMap::iterator i = namespace_map->begin(), e = namespace_map->end(); i != e && !found; ++i) { LLDB_LOGF(log, "" CTD[%u] Searching namespace %s in module %s"", current_id, i->second.GetName().AsCString(), i->first->GetFileSpec().GetFilename().GetCString()); TypeList types; ConstString name(tag_decl->getName().str().c_str()); i->first->FindTypesInNamespace(name, &i->second, UINT32_MAX, types); for (uint32_t ti = 0, te = types.GetSize(); ti != te && !found; ++ti) { lldb::TypeSP type = types.GetTypeAtIndex(ti); if (!type) continue; CompilerType clang_type(type->GetFullCompilerType()); if (!ClangUtil::IsClangType(clang_type)) continue; const TagType *tag_type = ClangUtil::GetQualType(clang_type)->getAs(); if (!tag_type) continue; TagDecl *candidate_tag_decl = const_cast(tag_type->getDecl()); if (m_ast_importer_sp->CompleteTagDeclWithOrigin(tag_decl, candidate_tag_decl)) found = true; } } } else { TypeList types; ConstString name(tag_decl->getName().str().c_str()); const ModuleList &module_list = m_target->GetImages(); bool exact_match = false; llvm::DenseSet searched_symbol_files; module_list.FindTypes(nullptr, name, exact_match, UINT32_MAX, searched_symbol_files, types); for (uint32_t ti = 0, te = types.GetSize(); ti != te && !found; ++ti) { lldb::TypeSP type = types.GetTypeAtIndex(ti); if (!type) continue; CompilerType clang_type(type->GetFullCompilerType()); if (!ClangUtil::IsClangType(clang_type)) continue; const TagType *tag_type = ClangUtil::GetQualType(clang_type)->getAs(); if (!tag_type) continue; TagDecl *candidate_tag_decl = const_cast(tag_type->getDecl()); // We have found a type by basename and we need to make sure the decl // contexts are the same before we can try to complete this type with // another if (!ClangASTContext::DeclsAreEquivalent(tag_decl, candidate_tag_decl)) continue; if (m_ast_importer_sp->CompleteTagDeclWithOrigin(tag_decl, candidate_tag_decl)) found = true; } } } LLDB_LOG(log, "" [CTD] After:\\n{0}"", ClangUtil::DumpDecl(tag_decl)); } void ClangASTSource::CompleteType(clang::ObjCInterfaceDecl *interface_decl) { Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); LLDB_LOGF(log, "" [CompleteObjCInterfaceDecl] on (ASTContext*)%p Completing "" ""an ObjCInterfaceDecl named %s"", static_cast(m_ast_context), interface_decl->getName().str().c_str()); LLDB_LOG(log, "" [COID] Before:\\n{0}"", ClangUtil::DumpDecl(interface_decl)); if (!m_ast_importer_sp) { lldbassert(0 && ""No mechanism for completing a type!""); return; } ClangASTImporter::DeclOrigin original = m_ast_importer_sp->GetDeclOrigin(interface_decl); if (original.Valid()) { if (ObjCInterfaceDecl *original_iface_decl = dyn_cast(original.decl)) { ObjCInterfaceDecl *complete_iface_decl = GetCompleteObjCInterface(original_iface_decl); if (complete_iface_decl && (complete_iface_decl != original_iface_decl)) { m_ast_importer_sp->SetDeclOrigin(interface_decl, complete_iface_decl); } } } m_ast_importer_sp->CompleteObjCInterfaceDecl(interface_decl); if (interface_decl->getSuperClass() && interface_decl->getSuperClass() != interface_decl) CompleteType(interface_decl->getSuperClass()); if (log) { LLDB_LOGF(log, "" [COID] After:""); LLDB_LOG(log, "" [COID] {0}"", ClangUtil::DumpDecl(interface_decl)); } } clang::ObjCInterfaceDecl *ClangASTSource::GetCompleteObjCInterface( const clang::ObjCInterfaceDecl *interface_decl) { lldb::ProcessSP process(m_target->GetProcessSP()); if (!process) return nullptr; ObjCLanguageRuntime *language_runtime(ObjCLanguageRuntime::Get(*process)); if (!language_runtime) return nullptr; ConstString class_name(interface_decl->getNameAsString().c_str()); lldb::TypeSP complete_type_sp( language_runtime->LookupInCompleteClassCache(class_name)); if (!complete_type_sp) return nullptr; TypeFromUser complete_type = TypeFromUser(complete_type_sp->GetFullCompilerType()); lldb::opaque_compiler_type_t complete_opaque_type = complete_type.GetOpaqueQualType(); if (!complete_opaque_type) return nullptr; const clang::Type *complete_clang_type = QualType::getFromOpaquePtr(complete_opaque_type).getTypePtr(); const ObjCInterfaceType *complete_interface_type = dyn_cast(complete_clang_type); if (!complete_interface_type) return nullptr; ObjCInterfaceDecl *complete_iface_decl(complete_interface_type->getDecl()); return complete_iface_decl; } void ClangASTSource::FindExternalLexicalDecls( const DeclContext *decl_context, llvm::function_ref predicate, llvm::SmallVectorImpl &decls) { if (!m_ast_importer_sp) return; Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); const Decl *context_decl = dyn_cast(decl_context); if (!context_decl) return; auto iter = m_active_lexical_decls.find(context_decl); if (iter != m_active_lexical_decls.end()) return; m_active_lexical_decls.insert(context_decl); ScopedLexicalDeclEraser eraser(m_active_lexical_decls, context_decl); static unsigned int invocation_id = 0; unsigned int current_id = invocation_id++; if (log) { if (const NamedDecl *context_named_decl = dyn_cast(context_decl)) LLDB_LOGF( log, ""FindExternalLexicalDecls[%u] on (ASTContext*)%p in '%s' (%sDecl*)%p"", current_id, static_cast(m_ast_context), context_named_decl->getNameAsString().c_str(), context_decl->getDeclKindName(), static_cast(context_decl)); else if (context_decl) LLDB_LOGF( log, ""FindExternalLexicalDecls[%u] on (ASTContext*)%p in (%sDecl*)%p"", current_id, static_cast(m_ast_context), context_decl->getDeclKindName(), static_cast(context_decl)); else LLDB_LOGF( log, ""FindExternalLexicalDecls[%u] on (ASTContext*)%p in a NULL context"", current_id, static_cast(m_ast_context)); } ClangASTImporter::DeclOrigin original = m_ast_importer_sp->GetDeclOrigin(context_decl); if (!original.Valid()) return; LLDB_LOG( log, "" FELD[{0}] Original decl (ASTContext*){1:x} (Decl*){2:x}:\\n{3}"", current_id, static_cast(original.ctx), static_cast(original.decl), ClangUtil::DumpDecl(original.decl)); if (ObjCInterfaceDecl *original_iface_decl = dyn_cast(original.decl)) { ObjCInterfaceDecl *complete_iface_decl = GetCompleteObjCInterface(original_iface_decl); if (complete_iface_decl && (complete_iface_decl != original_iface_decl)) { original.decl = complete_iface_decl; original.ctx = &complete_iface_decl->getASTContext(); m_ast_importer_sp->SetDeclOrigin(context_decl, complete_iface_decl); } } if (TagDecl *original_tag_decl = dyn_cast(original.decl)) { ExternalASTSource *external_source = original.ctx->getExternalSource(); if (external_source) external_source->CompleteType(original_tag_decl); } const DeclContext *original_decl_context = dyn_cast(original.decl); if (!original_decl_context) return; // Indicates whether we skipped any Decls of the original DeclContext. bool SkippedDecls = false; for (TagDecl::decl_iterator iter = original_decl_context->decls_begin(); iter != original_decl_context->decls_end(); ++iter) { Decl *decl = *iter; // The predicate function returns true if the passed declaration kind is // the one we are looking for. // See clang::ExternalASTSource::FindExternalLexicalDecls() if (predicate(decl->getKind())) { if (log) { std::string ast_dump = ClangUtil::DumpDecl(decl); if (const NamedDecl *context_named_decl = dyn_cast(context_decl)) LLDB_LOGF(log, "" FELD[%d] Adding [to %sDecl %s] lexical %sDecl %s"", current_id, context_named_decl->getDeclKindName(), context_named_decl->getNameAsString().c_str(), decl->getDeclKindName(), ast_dump.c_str()); else LLDB_LOGF(log, "" FELD[%d] Adding lexical %sDecl %s"", current_id, decl->getDeclKindName(), ast_dump.c_str()); } Decl *copied_decl = CopyDecl(decl); if (!copied_decl) continue; if (FieldDecl *copied_field = dyn_cast(copied_decl)) { QualType copied_field_type = copied_field->getType(); m_ast_importer_sp->RequireCompleteType(copied_field_type); } auto decl_context_non_const = const_cast(decl_context); // The decl ended up in the wrong DeclContext. Let's fix that so // the decl we copied will actually be found. // FIXME: This is a horrible hack that shouldn't be necessary. However // it seems our current setup sometimes fails to copy decls to the right // place. See rdar://55129537. if (copied_decl->getDeclContext() != decl_context) { assert(copied_decl->getDeclContext()->containsDecl(copied_decl)); copied_decl->getDeclContext()->removeDecl(copied_decl); copied_decl->setDeclContext(decl_context_non_const); assert(!decl_context_non_const->containsDecl(copied_decl)); decl_context_non_const->addDeclInternal(copied_decl); } } else { SkippedDecls = true; } } // CopyDecl may build a lookup table which may set up ExternalLexicalStorage // to false. However, since we skipped some of the external Decls we must // set it back! if (SkippedDecls) { decl_context->setHasExternalLexicalStorage(true); // This sets HasLazyExternalLexicalLookups to true. By setting this bit we // ensure that the lookup table is rebuilt, which means the external source // is consulted again when a clang::DeclContext::lookup is called. const_cast(decl_context)->setMustBuildLookupTable(); } return; } void ClangASTSource::FindExternalVisibleDecls(NameSearchContext &context) { assert(m_ast_context); const ConstString name(context.m_decl_name.getAsString().c_str()); Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); static unsigned int invocation_id = 0; unsigned int current_id = invocation_id++; if (log) { if (!context.m_decl_context) LLDB_LOGF(log, ""ClangASTSource::FindExternalVisibleDecls[%u] on "" ""(ASTContext*)%p for '%s' in a NULL DeclContext"", current_id, static_cast(m_ast_context), name.GetCString()); else if (const NamedDecl *context_named_decl = dyn_cast(context.m_decl_context)) LLDB_LOGF(log, ""ClangASTSource::FindExternalVisibleDecls[%u] on "" ""(ASTContext*)%p for '%s' in '%s'"", current_id, static_cast(m_ast_context), name.GetCString(), context_named_decl->getNameAsString().c_str()); else LLDB_LOGF(log, ""ClangASTSource::FindExternalVisibleDecls[%u] on "" ""(ASTContext*)%p for '%s' in a '%s'"", current_id, static_cast(m_ast_context), name.GetCString(), context.m_decl_context->getDeclKindName()); } context.m_namespace_map = std::make_shared(); if (const NamespaceDecl *namespace_context = dyn_cast(context.m_decl_context)) { ClangASTImporter::NamespaceMapSP namespace_map = m_ast_importer_sp ? m_ast_importer_sp->GetNamespaceMap(namespace_context) : nullptr; if (log && log->GetVerbose()) LLDB_LOGF(log, "" CAS::FEVD[%u] Inspecting namespace map %p (%d entries)"", current_id, static_cast(namespace_map.get()), static_cast(namespace_map->size())); if (!namespace_map) return; for (ClangASTImporter::NamespaceMap::iterator i = namespace_map->begin(), e = namespace_map->end(); i != e; ++i) { LLDB_LOGF(log, "" CAS::FEVD[%u] Searching namespace %s in module %s"", current_id, i->second.GetName().AsCString(), i->first->GetFileSpec().GetFilename().GetCString()); FindExternalVisibleDecls(context, i->first, i->second, current_id); } } else if (isa(context.m_decl_context)) { FindObjCPropertyAndIvarDecls(context); } else if (!isa(context.m_decl_context)) { // we shouldn't be getting FindExternalVisibleDecls calls for these return; } else { CompilerDeclContext namespace_decl; LLDB_LOGF(log, "" CAS::FEVD[%u] Searching the root namespace"", current_id); FindExternalVisibleDecls(context, lldb::ModuleSP(), namespace_decl, current_id); } if (!context.m_namespace_map->empty()) { if (log && log->GetVerbose()) LLDB_LOGF(log, "" CAS::FEVD[%u] Registering namespace map %p (%d entries)"", current_id, static_cast(context.m_namespace_map.get()), static_cast(context.m_namespace_map->size())); NamespaceDecl *clang_namespace_decl = AddNamespace(context, context.m_namespace_map); if (clang_namespace_decl) clang_namespace_decl->setHasExternalVisibleStorage(); } } clang::Sema *ClangASTSource::getSema() { return m_clang_ast_context->getSema(); } bool ClangASTSource::IgnoreName(const ConstString name, bool ignore_all_dollar_names) { static const ConstString id_name(""id""); static const ConstString Class_name(""Class""); if (m_ast_context->getLangOpts().ObjC) if (name == id_name || name == Class_name) return true; StringRef name_string_ref = name.GetStringRef(); // The ClangASTSource is not responsible for finding $-names. return name_string_ref.empty() || (ignore_all_dollar_names && name_string_ref.startswith(""$"")) || name_string_ref.startswith(""_$""); } void ClangASTSource::FindExternalVisibleDecls( NameSearchContext &context, lldb::ModuleSP module_sp, CompilerDeclContext &namespace_decl, unsigned int current_id) { assert(m_ast_context); Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); SymbolContextList sc_list; const ConstString name(context.m_decl_name.getAsString().c_str()); if (IgnoreName(name, true)) return; if (!m_target) return; if (module_sp && namespace_decl) { CompilerDeclContext found_namespace_decl; if (SymbolFile *symbol_file = module_sp->GetSymbolFile()) { found_namespace_decl = symbol_file->FindNamespace(name, &namespace_decl); if (found_namespace_decl) { context.m_namespace_map->push_back( std::pair( module_sp, found_namespace_decl)); LLDB_LOGF(log, "" CAS::FEVD[%u] Found namespace %s in module %s"", current_id, name.GetCString(), module_sp->GetFileSpec().GetFilename().GetCString()); } } } else { const ModuleList &target_images = m_target->GetImages(); std::lock_guard guard(target_images.GetMutex()); for (size_t i = 0, e = target_images.GetSize(); i < e; ++i) { lldb::ModuleSP image = target_images.GetModuleAtIndexUnlocked(i); if (!image) continue; CompilerDeclContext found_namespace_decl; SymbolFile *symbol_file = image->GetSymbolFile(); if (!symbol_file) continue; found_namespace_decl = symbol_file->FindNamespace(name, &namespace_decl); if (found_namespace_decl) { context.m_namespace_map->push_back( std::pair( image, found_namespace_decl)); LLDB_LOGF(log, "" CAS::FEVD[%u] Found namespace %s in module %s"", current_id, name.GetCString(), image->GetFileSpec().GetFilename().GetCString()); } } } do { if (context.m_found.type) break; TypeList types; const bool exact_match = true; llvm::DenseSet searched_symbol_files; if (module_sp && namespace_decl) module_sp->FindTypesInNamespace(name, &namespace_decl, 1, types); else { m_target->GetImages().FindTypes(module_sp.get(), name, exact_match, 1, searched_symbol_files, types); } if (size_t num_types = types.GetSize()) { for (size_t ti = 0; ti < num_types; ++ti) { lldb::TypeSP type_sp = types.GetTypeAtIndex(ti); if (log) { const char *name_string = type_sp->GetName().GetCString(); LLDB_LOGF(log, "" CAS::FEVD[%u] Matching type found for \\""%s\\"": %s"", current_id, name.GetCString(), (name_string ? name_string : """")); } CompilerType full_type = type_sp->GetFullCompilerType(); CompilerType copied_clang_type(GuardedCopyType(full_type)); if (!copied_clang_type) { LLDB_LOGF(log, "" CAS::FEVD[%u] - Couldn't export a type"", current_id); continue; } context.AddTypeDecl(copied_clang_type); context.m_found.type = true; break; } } if (!context.m_found.type) { // Try the modules next. do { if (ClangModulesDeclVendor *modules_decl_vendor = m_target->GetClangModulesDeclVendor()) { bool append = false; uint32_t max_matches = 1; std::vector decls; if (!modules_decl_vendor->FindDecls(name, append, max_matches, decls)) break; if (log) { LLDB_LOGF(log, "" CAS::FEVD[%u] Matching entity found for \\""%s\\"" in "" ""the modules"", current_id, name.GetCString()); } clang::NamedDecl *const decl_from_modules = decls[0]; if (llvm::isa(decl_from_modules) || llvm::isa(decl_from_modules) || llvm::isa(decl_from_modules)) { clang::Decl *copied_decl = CopyDecl(decl_from_modules); clang::NamedDecl *copied_named_decl = copied_decl ? dyn_cast(copied_decl) : nullptr; if (!copied_named_decl) { LLDB_LOGF( log, "" CAS::FEVD[%u] - Couldn't export a type from the modules"", current_id); break; } context.AddNamedDecl(copied_named_decl); context.m_found.type = true; } } } while (false); } if (!context.m_found.type) { do { // Couldn't find any types elsewhere. Try the Objective-C runtime if // one exists. lldb::ProcessSP process(m_target->GetProcessSP()); if (!process) break; ObjCLanguageRuntime *language_runtime( ObjCLanguageRuntime::Get(*process)); if (!language_runtime) break; DeclVendor *decl_vendor = language_runtime->GetDeclVendor(); if (!decl_vendor) break; bool append = false; uint32_t max_matches = 1; std::vector decls; auto *clang_decl_vendor = llvm::cast(decl_vendor); if (!clang_decl_vendor->FindDecls(name, append, max_matches, decls)) break; if (log) { LLDB_LOGF( log, "" CAS::FEVD[%u] Matching type found for \\""%s\\"" in the runtime"", current_id, name.GetCString()); } clang::Decl *copied_decl = CopyDecl(decls[0]); clang::NamedDecl *copied_named_decl = copied_decl ? dyn_cast(copied_decl) : nullptr; if (!copied_named_decl) { LLDB_LOGF(log, "" CAS::FEVD[%u] - Couldn't export a type from the runtime"", current_id); break; } context.AddNamedDecl(copied_named_decl); } while (false); } } while (false); } template class TaggedASTDecl { public: TaggedASTDecl() : decl(nullptr) {} TaggedASTDecl(D *_decl) : decl(_decl) {} bool IsValid() const { return (decl != nullptr); } bool IsInvalid() const { return !IsValid(); } D *operator->() const { return decl; } D *decl; }; template class TD, class D1> TD DynCast(TD source) { return TD(dyn_cast(source.decl)); } template class DeclFromParser; template class DeclFromUser; template class DeclFromParser : public TaggedASTDecl { public: DeclFromParser() : TaggedASTDecl() {} DeclFromParser(D *_decl) : TaggedASTDecl(_decl) {} DeclFromUser GetOrigin(ClangASTSource &source); }; template class DeclFromUser : public TaggedASTDecl { public: DeclFromUser() : TaggedASTDecl() {} DeclFromUser(D *_decl) : TaggedASTDecl(_decl) {} DeclFromParser Import(ClangASTSource &source); }; template DeclFromUser DeclFromParser::GetOrigin(ClangASTSource &source) { ClangASTImporter::DeclOrigin origin = source.GetDeclOrigin(this->decl); if (!origin.Valid()) return DeclFromUser(); return DeclFromUser(dyn_cast(origin.decl)); } template DeclFromParser DeclFromUser::Import(ClangASTSource &source) { DeclFromParser<> parser_generic_decl(source.CopyDecl(this->decl)); if (parser_generic_decl.IsInvalid()) return DeclFromParser(); return DeclFromParser(dyn_cast(parser_generic_decl.decl)); } bool ClangASTSource::FindObjCMethodDeclsWithOrigin( unsigned int current_id, NameSearchContext &context, ObjCInterfaceDecl *original_interface_decl, const char *log_info) { const DeclarationName &decl_name(context.m_decl_name); clang::ASTContext *original_ctx = &original_interface_decl->getASTContext(); Selector original_selector; if (decl_name.isObjCZeroArgSelector()) { IdentifierInfo *ident = &original_ctx->Idents.get(decl_name.getAsString()); original_selector = original_ctx->Selectors.getSelector(0, &ident); } else if (decl_name.isObjCOneArgSelector()) { const std::string &decl_name_string = decl_name.getAsString(); std::string decl_name_string_without_colon(decl_name_string.c_str(), decl_name_string.length() - 1); IdentifierInfo *ident = &original_ctx->Idents.get(decl_name_string_without_colon); original_selector = original_ctx->Selectors.getSelector(1, &ident); } else { SmallVector idents; clang::Selector sel = decl_name.getObjCSelector(); unsigned num_args = sel.getNumArgs(); for (unsigned i = 0; i != num_args; ++i) { idents.push_back(&original_ctx->Idents.get(sel.getNameForSlot(i))); } original_selector = original_ctx->Selectors.getSelector(num_args, idents.data()); } DeclarationName original_decl_name(original_selector); llvm::SmallVector methods; ClangASTContext::GetCompleteDecl(original_ctx, original_interface_decl); if (ObjCMethodDecl *instance_method_decl = original_interface_decl->lookupInstanceMethod(original_selector)) { methods.push_back(instance_method_decl); } else if (ObjCMethodDecl *class_method_decl = original_interface_decl->lookupClassMethod( original_selector)) { methods.push_back(class_method_decl); } if (methods.empty()) { return false; } for (NamedDecl *named_decl : methods) { if (!named_decl) continue; ObjCMethodDecl *result_method = dyn_cast(named_decl); if (!result_method) continue; Decl *copied_decl = CopyDecl(result_method); if (!copied_decl) continue; ObjCMethodDecl *copied_method_decl = dyn_cast(copied_decl); if (!copied_method_decl) continue; Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); LLDB_LOG(log, "" CAS::FOMD[{0}] found ({1}) {2}"", current_id, log_info, ClangUtil::DumpDecl(copied_method_decl)); context.AddNamedDecl(copied_method_decl); } return true; } void ClangASTSource::FindObjCMethodDecls(NameSearchContext &context) { Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); static unsigned int invocation_id = 0; unsigned int current_id = invocation_id++; const DeclarationName &decl_name(context.m_decl_name); const DeclContext *decl_ctx(context.m_decl_context); const ObjCInterfaceDecl *interface_decl = dyn_cast(decl_ctx); if (!interface_decl) return; do { ClangASTImporter::DeclOrigin original = m_ast_importer_sp->GetDeclOrigin(interface_decl); if (!original.Valid()) break; ObjCInterfaceDecl *original_interface_decl = dyn_cast(original.decl); if (FindObjCMethodDeclsWithOrigin(current_id, context, original_interface_decl, ""at origin"")) return; // found it, no need to look any further } while (false); StreamString ss; if (decl_name.isObjCZeroArgSelector()) { ss.Printf(""%s"", decl_name.getAsString().c_str()); } else if (decl_name.isObjCOneArgSelector()) { ss.Printf(""%s"", decl_name.getAsString().c_str()); } else { clang::Selector sel = decl_name.getObjCSelector(); for (unsigned i = 0, e = sel.getNumArgs(); i != e; ++i) { llvm::StringRef r = sel.getNameForSlot(i); ss.Printf(""%s:"", r.str().c_str()); } } ss.Flush(); if (ss.GetString().contains(""$__lldb"")) return; // we don't need any results ConstString selector_name(ss.GetString()); LLDB_LOGF(log, ""ClangASTSource::FindObjCMethodDecls[%d] on (ASTContext*)%p "" ""for selector [%s %s]"", current_id, static_cast(m_ast_context), interface_decl->getNameAsString().c_str(), selector_name.AsCString()); SymbolContextList sc_list; const bool include_symbols = false; const bool include_inlines = false; std::string interface_name = interface_decl->getNameAsString(); do { StreamString ms; ms.Printf(""-[%s %s]"", interface_name.c_str(), selector_name.AsCString()); ms.Flush(); ConstString instance_method_name(ms.GetString()); sc_list.Clear(); m_target->GetImages().FindFunctions( instance_method_name, lldb::eFunctionNameTypeFull, include_symbols, include_inlines, sc_list); if (sc_list.GetSize()) break; ms.Clear(); ms.Printf(""+[%s %s]"", interface_name.c_str(), selector_name.AsCString()); ms.Flush(); ConstString class_method_name(ms.GetString()); sc_list.Clear(); m_target->GetImages().FindFunctions( class_method_name, lldb::eFunctionNameTypeFull, include_symbols, include_inlines, sc_list); if (sc_list.GetSize()) break; // Fall back and check for methods in categories. If we find methods this // way, we need to check that they're actually in categories on the desired // class. SymbolContextList candidate_sc_list; m_target->GetImages().FindFunctions( selector_name, lldb::eFunctionNameTypeSelector, include_symbols, include_inlines, candidate_sc_list); for (uint32_t ci = 0, ce = candidate_sc_list.GetSize(); ci != ce; ++ci) { SymbolContext candidate_sc; if (!candidate_sc_list.GetContextAtIndex(ci, candidate_sc)) continue; if (!candidate_sc.function) continue; const char *candidate_name = candidate_sc.function->GetName().AsCString(); const char *cursor = candidate_name; if (*cursor != '+' && *cursor != '-') continue; ++cursor; if (*cursor != '[') continue; ++cursor; size_t interface_len = interface_name.length(); if (strncmp(cursor, interface_name.c_str(), interface_len)) continue; cursor += interface_len; if (*cursor == ' ' || *cursor == '(') sc_list.Append(candidate_sc); } } while (false); if (sc_list.GetSize()) { // We found a good function symbol. Use that. for (uint32_t i = 0, e = sc_list.GetSize(); i != e; ++i) { SymbolContext sc; if (!sc_list.GetContextAtIndex(i, sc)) continue; if (!sc.function) continue; CompilerDeclContext function_decl_ctx = sc.function->GetDeclContext(); if (!function_decl_ctx) continue; ObjCMethodDecl *method_decl = ClangASTContext::DeclContextGetAsObjCMethodDecl(function_decl_ctx); if (!method_decl) continue; ObjCInterfaceDecl *found_interface_decl = method_decl->getClassInterface(); if (!found_interface_decl) continue; if (found_interface_decl->getName() == interface_decl->getName()) { Decl *copied_decl = CopyDecl(method_decl); if (!copied_decl) continue; ObjCMethodDecl *copied_method_decl = dyn_cast(copied_decl); if (!copied_method_decl) continue; LLDB_LOG(log, "" CAS::FOMD[{0}] found (in symbols)\\n{1}"", current_id, ClangUtil::DumpDecl(copied_method_decl)); context.AddNamedDecl(copied_method_decl); } } return; } // Try the debug information. do { ObjCInterfaceDecl *complete_interface_decl = GetCompleteObjCInterface( const_cast(interface_decl)); if (!complete_interface_decl) break; // We found the complete interface. The runtime never needs to be queried // in this scenario. DeclFromUser complete_iface_decl( complete_interface_decl); if (complete_interface_decl == interface_decl) break; // already checked this one LLDB_LOGF(log, ""CAS::FOPD[%d] trying origin "" ""(ObjCInterfaceDecl*)%p/(ASTContext*)%p..."", current_id, static_cast(complete_interface_decl), static_cast(&complete_iface_decl->getASTContext())); FindObjCMethodDeclsWithOrigin(current_id, context, complete_interface_decl, ""in debug info""); return; } while (false); do { // Check the modules only if the debug information didn't have a complete // interface. if (ClangModulesDeclVendor *modules_decl_vendor = m_target->GetClangModulesDeclVendor()) { ConstString interface_name(interface_decl->getNameAsString().c_str()); bool append = false; uint32_t max_matches = 1; std::vector decls; if (!modules_decl_vendor->FindDecls(interface_name, append, max_matches, decls)) break; ObjCInterfaceDecl *interface_decl_from_modules = dyn_cast(decls[0]); if (!interface_decl_from_modules) break; if (FindObjCMethodDeclsWithOrigin( current_id, context, interface_decl_from_modules, ""in modules"")) return; } } while (false); do { // Check the runtime only if the debug information didn't have a complete // interface and the modules don't get us anywhere. lldb::ProcessSP process(m_target->GetProcessSP()); if (!process) break; ObjCLanguageRuntime *language_runtime(ObjCLanguageRuntime::Get(*process)); if (!language_runtime) break; DeclVendor *decl_vendor = language_runtime->GetDeclVendor(); if (!decl_vendor) break; ConstString interface_name(interface_decl->getNameAsString().c_str()); bool append = false; uint32_t max_matches = 1; std::vector decls; auto *clang_decl_vendor = llvm::cast(decl_vendor); if (!clang_decl_vendor->FindDecls(interface_name, append, max_matches, decls)) break; ObjCInterfaceDecl *runtime_interface_decl = dyn_cast(decls[0]); if (!runtime_interface_decl) break; FindObjCMethodDeclsWithOrigin(current_id, context, runtime_interface_decl, ""in runtime""); } while (false); } static bool FindObjCPropertyAndIvarDeclsWithOrigin( unsigned int current_id, NameSearchContext &context, ClangASTSource &source, DeclFromUser &origin_iface_decl) { Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); if (origin_iface_decl.IsInvalid()) return false; std::string name_str = context.m_decl_name.getAsString(); StringRef name(name_str); IdentifierInfo &name_identifier( origin_iface_decl->getASTContext().Idents.get(name)); DeclFromUser origin_property_decl( origin_iface_decl->FindPropertyDeclaration( &name_identifier, ObjCPropertyQueryKind::OBJC_PR_query_instance)); bool found = false; if (origin_property_decl.IsValid()) { DeclFromParser parser_property_decl( origin_property_decl.Import(source)); if (parser_property_decl.IsValid()) { LLDB_LOG(log, "" CAS::FOPD[{0}] found\\n{1}"", current_id, ClangUtil::DumpDecl(parser_property_decl.decl)); context.AddNamedDecl(parser_property_decl.decl); found = true; } } DeclFromUser origin_ivar_decl( origin_iface_decl->getIvarDecl(&name_identifier)); if (origin_ivar_decl.IsValid()) { DeclFromParser parser_ivar_decl( origin_ivar_decl.Import(source)); if (parser_ivar_decl.IsValid()) { if (log) { LLDB_LOG(log, "" CAS::FOPD[{0}] found\\n{1}"", current_id, ClangUtil::DumpDecl(parser_ivar_decl.decl)); } context.AddNamedDecl(parser_ivar_decl.decl); found = true; } } return found; } void ClangASTSource::FindObjCPropertyAndIvarDecls(NameSearchContext &context) { Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); static unsigned int invocation_id = 0; unsigned int current_id = invocation_id++; DeclFromParser parser_iface_decl( cast(context.m_decl_context)); DeclFromUser origin_iface_decl( parser_iface_decl.GetOrigin(*this)); ConstString class_name(parser_iface_decl->getNameAsString().c_str()); LLDB_LOGF(log, ""ClangASTSource::FindObjCPropertyAndIvarDecls[%d] on "" ""(ASTContext*)%p for '%s.%s'"", current_id, static_cast(m_ast_context), parser_iface_decl->getNameAsString().c_str(), context.m_decl_name.getAsString().c_str()); if (FindObjCPropertyAndIvarDeclsWithOrigin( current_id, context, *this, origin_iface_decl)) return; LLDB_LOGF(log, ""CAS::FOPD[%d] couldn't find the property on origin "" ""(ObjCInterfaceDecl*)%p/(ASTContext*)%p, searching "" ""elsewhere..."", current_id, static_cast(origin_iface_decl.decl), static_cast(&origin_iface_decl->getASTContext())); SymbolContext null_sc; TypeList type_list; do { ObjCInterfaceDecl *complete_interface_decl = GetCompleteObjCInterface( const_cast(parser_iface_decl.decl)); if (!complete_interface_decl) break; // We found the complete interface. The runtime never needs to be queried // in this scenario. DeclFromUser complete_iface_decl( complete_interface_decl); if (complete_iface_decl.decl == origin_iface_decl.decl) break; // already checked this one LLDB_LOGF(log, ""CAS::FOPD[%d] trying origin "" ""(ObjCInterfaceDecl*)%p/(ASTContext*)%p..."", current_id, static_cast(complete_iface_decl.decl), static_cast(&complete_iface_decl->getASTContext())); FindObjCPropertyAndIvarDeclsWithOrigin(current_id, context, *this, complete_iface_decl); return; } while (false); do { // Check the modules only if the debug information didn't have a complete // interface. ClangModulesDeclVendor *modules_decl_vendor = m_target->GetClangModulesDeclVendor(); if (!modules_decl_vendor) break; bool append = false; uint32_t max_matches = 1; std::vector decls; if (!modules_decl_vendor->FindDecls(class_name, append, max_matches, decls)) break; DeclFromUser interface_decl_from_modules( dyn_cast(decls[0])); if (!interface_decl_from_modules.IsValid()) break; LLDB_LOGF( log, ""CAS::FOPD[%d] trying module "" ""(ObjCInterfaceDecl*)%p/(ASTContext*)%p..."", current_id, static_cast(interface_decl_from_modules.decl), static_cast(&interface_decl_from_modules->getASTContext())); if (FindObjCPropertyAndIvarDeclsWithOrigin(current_id, context, *this, interface_decl_from_modules)) return; } while (false); do { // Check the runtime only if the debug information didn't have a complete // interface and nothing was in the modules. lldb::ProcessSP process(m_target->GetProcessSP()); if (!process) return; ObjCLanguageRuntime *language_runtime(ObjCLanguageRuntime::Get(*process)); if (!language_runtime) return; DeclVendor *decl_vendor = language_runtime->GetDeclVendor(); if (!decl_vendor) break; bool append = false; uint32_t max_matches = 1; std::vector decls; auto *clang_decl_vendor = llvm::cast(decl_vendor); if (!clang_decl_vendor->FindDecls(class_name, append, max_matches, decls)) break; DeclFromUser interface_decl_from_runtime( dyn_cast(decls[0])); if (!interface_decl_from_runtime.IsValid()) break; LLDB_LOGF( log, ""CAS::FOPD[%d] trying runtime "" ""(ObjCInterfaceDecl*)%p/(ASTContext*)%p..."", current_id, static_cast(interface_decl_from_runtime.decl), static_cast(&interface_decl_from_runtime->getASTContext())); if (FindObjCPropertyAndIvarDeclsWithOrigin( current_id, context, *this, interface_decl_from_runtime)) return; } while (false); } typedef llvm::DenseMap FieldOffsetMap; typedef llvm::DenseMap BaseOffsetMap; template static bool ImportOffsetMap(llvm::DenseMap &destination_map, llvm::DenseMap &source_map, ClangASTSource &source) { // When importing fields into a new record, clang has a hard requirement that // fields be imported in field offset order. Since they are stored in a // DenseMap with a pointer as the key type, this means we cannot simply // iterate over the map, as the order will be non-deterministic. Instead we // have to sort by the offset and then insert in sorted order. typedef llvm::DenseMap MapType; typedef typename MapType::value_type PairType; std::vector sorted_items; sorted_items.reserve(source_map.size()); sorted_items.assign(source_map.begin(), source_map.end()); llvm::sort(sorted_items.begin(), sorted_items.end(), [](const PairType &lhs, const PairType &rhs) { return lhs.second < rhs.second; }); for (const auto &item : sorted_items) { DeclFromUser user_decl(const_cast(item.first)); DeclFromParser parser_decl(user_decl.Import(source)); if (parser_decl.IsInvalid()) return false; destination_map.insert( std::pair(parser_decl.decl, item.second)); } return true; } template bool ExtractBaseOffsets(const ASTRecordLayout &record_layout, DeclFromUser &record, BaseOffsetMap &base_offsets) { for (CXXRecordDecl::base_class_const_iterator bi = (IsVirtual ? record->vbases_begin() : record->bases_begin()), be = (IsVirtual ? record->vbases_end() : record->bases_end()); bi != be; ++bi) { if (!IsVirtual && bi->isVirtual()) continue; const clang::Type *origin_base_type = bi->getType().getTypePtr(); const clang::RecordType *origin_base_record_type = origin_base_type->getAs(); if (!origin_base_record_type) return false; DeclFromUser origin_base_record( origin_base_record_type->getDecl()); if (origin_base_record.IsInvalid()) return false; DeclFromUser origin_base_cxx_record( DynCast(origin_base_record)); if (origin_base_cxx_record.IsInvalid()) return false; CharUnits base_offset; if (IsVirtual) base_offset = record_layout.getVBaseClassOffset(origin_base_cxx_record.decl); else base_offset = record_layout.getBaseClassOffset(origin_base_cxx_record.decl); base_offsets.insert(std::pair( origin_base_cxx_record.decl, base_offset)); } return true; } bool ClangASTSource::layoutRecordType(const RecordDecl *record, uint64_t &size, uint64_t &alignment, FieldOffsetMap &field_offsets, BaseOffsetMap &base_offsets, BaseOffsetMap &virtual_base_offsets) { static unsigned int invocation_id = 0; unsigned int current_id = invocation_id++; Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); LLDB_LOGF(log, ""LayoutRecordType[%u] on (ASTContext*)%p for (RecordDecl*)%p "" ""[name = '%s']"", current_id, static_cast(m_ast_context), static_cast(record), record->getNameAsString().c_str()); DeclFromParser parser_record(record); DeclFromUser origin_record( parser_record.GetOrigin(*this)); if (origin_record.IsInvalid()) return false; FieldOffsetMap origin_field_offsets; BaseOffsetMap origin_base_offsets; BaseOffsetMap origin_virtual_base_offsets; ClangASTContext::GetCompleteDecl( &origin_record->getASTContext(), const_cast(origin_record.decl)); clang::RecordDecl *definition = origin_record.decl->getDefinition(); if (!definition || !definition->isCompleteDefinition()) return false; const ASTRecordLayout &record_layout( origin_record->getASTContext().getASTRecordLayout(origin_record.decl)); int field_idx = 0, field_count = record_layout.getFieldCount(); for (RecordDecl::field_iterator fi = origin_record->field_begin(), fe = origin_record->field_end(); fi != fe; ++fi) { if (field_idx >= field_count) return false; // Layout didn't go well. Bail out. uint64_t field_offset = record_layout.getFieldOffset(field_idx); origin_field_offsets.insert( std::pair(*fi, field_offset)); field_idx++; } lldbassert(&record->getASTContext() == m_ast_context); DeclFromUser origin_cxx_record( DynCast(origin_record)); if (origin_cxx_record.IsValid()) { if (!ExtractBaseOffsets(record_layout, origin_cxx_record, origin_base_offsets) || !ExtractBaseOffsets(record_layout, origin_cxx_record, origin_virtual_base_offsets)) return false; } if (!ImportOffsetMap(field_offsets, origin_field_offsets, *this) || !ImportOffsetMap(base_offsets, origin_base_offsets, *this) || !ImportOffsetMap(virtual_base_offsets, origin_virtual_base_offsets, *this)) return false; size = record_layout.getSize().getQuantity() * m_ast_context->getCharWidth(); alignment = record_layout.getAlignment().getQuantity() * m_ast_context->getCharWidth(); if (log) { LLDB_LOGF(log, ""LRT[%u] returned:"", current_id); LLDB_LOGF(log, ""LRT[%u] Original = (RecordDecl*)%p"", current_id, static_cast(origin_record.decl)); LLDB_LOGF(log, ""LRT[%u] Size = %"" PRId64, current_id, size); LLDB_LOGF(log, ""LRT[%u] Alignment = %"" PRId64, current_id, alignment); LLDB_LOGF(log, ""LRT[%u] Fields:"", current_id); for (RecordDecl::field_iterator fi = record->field_begin(), fe = record->field_end(); fi != fe; ++fi) { LLDB_LOGF(log, ""LRT[%u] (FieldDecl*)%p, Name = '%s', Offset = %"" PRId64 "" bits"", current_id, static_cast(*fi), fi->getNameAsString().c_str(), field_offsets[*fi]); } DeclFromParser parser_cxx_record = DynCast(parser_record); if (parser_cxx_record.IsValid()) { LLDB_LOGF(log, ""LRT[%u] Bases:"", current_id); for (CXXRecordDecl::base_class_const_iterator bi = parser_cxx_record->bases_begin(), be = parser_cxx_record->bases_end(); bi != be; ++bi) { bool is_virtual = bi->isVirtual(); QualType base_type = bi->getType(); const RecordType *base_record_type = base_type->getAs(); DeclFromParser base_record(base_record_type->getDecl()); DeclFromParser base_cxx_record = DynCast(base_record); LLDB_LOGF( log, ""LRT[%u] %s(CXXRecordDecl*)%p, Name = '%s', Offset = %"" PRId64 "" chars"", current_id, (is_virtual ? ""Virtual "" : """"), static_cast(base_cxx_record.decl), base_cxx_record.decl->getNameAsString().c_str(), (is_virtual ? virtual_base_offsets[base_cxx_record.decl].getQuantity() : base_offsets[base_cxx_record.decl].getQuantity())); } } else { LLDB_LOGF(log, ""LRD[%u] Not a CXXRecord, so no bases"", current_id); } } return true; } void ClangASTSource::CompleteNamespaceMap( ClangASTImporter::NamespaceMapSP &namespace_map, ConstString name, ClangASTImporter::NamespaceMapSP &parent_map) const { static unsigned int invocation_id = 0; unsigned int current_id = invocation_id++; Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); if (log) { if (parent_map && parent_map->size()) LLDB_LOGF(log, ""CompleteNamespaceMap[%u] on (ASTContext*)%p Searching for "" ""namespace %s in namespace %s"", current_id, static_cast(m_ast_context), name.GetCString(), parent_map->begin()->second.GetName().AsCString()); else LLDB_LOGF(log, ""CompleteNamespaceMap[%u] on (ASTContext*)%p Searching for "" ""namespace %s"", current_id, static_cast(m_ast_context), name.GetCString()); } if (parent_map) { for (ClangASTImporter::NamespaceMap::iterator i = parent_map->begin(), e = parent_map->end(); i != e; ++i) { CompilerDeclContext found_namespace_decl; lldb::ModuleSP module_sp = i->first; CompilerDeclContext module_parent_namespace_decl = i->second; SymbolFile *symbol_file = module_sp->GetSymbolFile(); if (!symbol_file) continue; found_namespace_decl = symbol_file->FindNamespace(name, &module_parent_namespace_decl); if (!found_namespace_decl) continue; namespace_map->push_back(std::pair( module_sp, found_namespace_decl)); LLDB_LOGF(log, "" CMN[%u] Found namespace %s in module %s"", current_id, name.GetCString(), module_sp->GetFileSpec().GetFilename().GetCString()); } } else { const ModuleList &target_images = m_target->GetImages(); std::lock_guard guard(target_images.GetMutex()); CompilerDeclContext null_namespace_decl; for (size_t i = 0, e = target_images.GetSize(); i < e; ++i) { lldb::ModuleSP image = target_images.GetModuleAtIndexUnlocked(i); if (!image) continue; CompilerDeclContext found_namespace_decl; SymbolFile *symbol_file = image->GetSymbolFile(); if (!symbol_file) continue; found_namespace_decl = symbol_file->FindNamespace(name, &null_namespace_decl); if (!found_namespace_decl) continue; namespace_map->push_back(std::pair( image, found_namespace_decl)); LLDB_LOGF(log, "" CMN[%u] Found namespace %s in module %s"", current_id, name.GetCString(), image->GetFileSpec().GetFilename().GetCString()); } } } NamespaceDecl *ClangASTSource::AddNamespace( NameSearchContext &context, ClangASTImporter::NamespaceMapSP &namespace_decls) { if (!namespace_decls) return nullptr; const CompilerDeclContext &namespace_decl = namespace_decls->begin()->second; clang::ASTContext *src_ast = ClangASTContext::DeclContextGetClangASTContext(namespace_decl); if (!src_ast) return nullptr; clang::NamespaceDecl *src_namespace_decl = ClangASTContext::DeclContextGetAsNamespaceDecl(namespace_decl); if (!src_namespace_decl) return nullptr; Decl *copied_decl = CopyDecl(src_namespace_decl); if (!copied_decl) return nullptr; NamespaceDecl *copied_namespace_decl = dyn_cast(copied_decl); if (!copied_namespace_decl) return nullptr; context.m_decls.push_back(copied_namespace_decl); m_ast_importer_sp->RegisterNamespaceMap(copied_namespace_decl, namespace_decls); return dyn_cast(copied_decl); } clang::Decl *ClangASTSource::CopyDecl(Decl *src_decl) { if (m_ast_importer_sp) { return m_ast_importer_sp->CopyDecl(m_ast_context, src_decl); } else { lldbassert(0 && ""No mechanism for copying a decl!""); return nullptr; } } ClangASTImporter::DeclOrigin ClangASTSource::GetDeclOrigin(const clang::Decl *decl) { if (m_ast_importer_sp) { return m_ast_importer_sp->GetDeclOrigin(decl); } else { // this can happen early enough that no ExternalASTSource is installed. return ClangASTImporter::DeclOrigin(); } } CompilerType ClangASTSource::GuardedCopyType(const CompilerType &src_type) { ClangASTContext *src_ast = llvm::dyn_cast_or_null(src_type.GetTypeSystem()); if (src_ast == nullptr) return CompilerType(); SetImportInProgress(true); QualType copied_qual_type; if (m_ast_importer_sp) { copied_qual_type = ClangUtil::GetQualType( m_ast_importer_sp->CopyType(*m_clang_ast_context, src_type)); } else { lldbassert(0 && ""No mechanism for copying a type!""); return CompilerType(); } SetImportInProgress(false); if (copied_qual_type.getAsOpaquePtr() && copied_qual_type->getCanonicalTypeInternal().isNull()) // this shouldn't happen, but we're hardening because the AST importer // seems to be generating bad types on occasion. return CompilerType(); return CompilerType(m_clang_ast_context, copied_qual_type.getAsOpaquePtr()); } clang::NamedDecl *NameSearchContext::AddVarDecl(const CompilerType &type) { assert(type && ""Type for variable must be valid!""); if (!type.IsValid()) return nullptr; ClangASTContext *lldb_ast = llvm::dyn_cast(type.GetTypeSystem()); if (!lldb_ast) return nullptr; IdentifierInfo *ii = m_decl_name.getAsIdentifierInfo(); clang::ASTContext &ast = lldb_ast->getASTContext(); clang::NamedDecl *Decl = VarDecl::Create( ast, const_cast(m_decl_context), SourceLocation(), SourceLocation(), ii, ClangUtil::GetQualType(type), nullptr, SC_Static); m_decls.push_back(Decl); return Decl; } clang::NamedDecl *NameSearchContext::AddFunDecl(const CompilerType &type, bool extern_c) { assert(type && ""Type for variable must be valid!""); if (!type.IsValid()) return nullptr; if (m_function_types.count(type)) return nullptr; ClangASTContext *lldb_ast = llvm::dyn_cast(type.GetTypeSystem()); if (!lldb_ast) return nullptr; m_function_types.insert(type); QualType qual_type(ClangUtil::GetQualType(type)); clang::ASTContext &ast = lldb_ast->getASTContext(); const bool isInlineSpecified = false; const bool hasWrittenPrototype = true; const bool isConstexprSpecified = false; clang::DeclContext *context = const_cast(m_decl_context); if (extern_c) { context = LinkageSpecDecl::Create( ast, context, SourceLocation(), SourceLocation(), clang::LinkageSpecDecl::LanguageIDs::lang_c, false); } // Pass the identifier info for functions the decl_name is needed for // operators clang::DeclarationName decl_name = m_decl_name.getNameKind() == DeclarationName::Identifier ? m_decl_name.getAsIdentifierInfo() : m_decl_name; clang::FunctionDecl *func_decl = FunctionDecl::Create( ast, context, SourceLocation(), SourceLocation(), decl_name, qual_type, nullptr, SC_Extern, isInlineSpecified, hasWrittenPrototype, isConstexprSpecified ? CSK_constexpr : CSK_unspecified); // We have to do more than just synthesize the FunctionDecl. We have to // synthesize ParmVarDecls for all of the FunctionDecl's arguments. To do // this, we raid the function's FunctionProtoType for types. const FunctionProtoType *func_proto_type = qual_type.getTypePtr()->getAs(); if (func_proto_type) { unsigned NumArgs = func_proto_type->getNumParams(); unsigned ArgIndex; SmallVector parm_var_decls; for (ArgIndex = 0; ArgIndex < NumArgs; ++ArgIndex) { QualType arg_qual_type(func_proto_type->getParamType(ArgIndex)); parm_var_decls.push_back( ParmVarDecl::Create(ast, const_cast(context), SourceLocation(), SourceLocation(), nullptr, arg_qual_type, nullptr, SC_Static, nullptr)); } func_decl->setParams(ArrayRef(parm_var_decls)); } else { Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); LLDB_LOGF(log, ""Function type wasn't a FunctionProtoType""); } // If this is an operator (e.g. operator new or operator==), only insert the // declaration we inferred from the symbol if we can provide the correct // number of arguments. We shouldn't really inject random decl(s) for // functions that are analyzed semantically in a special way, otherwise we // will crash in clang. clang::OverloadedOperatorKind op_kind = clang::NUM_OVERLOADED_OPERATORS; if (func_proto_type && ClangASTContext::IsOperator(decl_name.getAsString().c_str(), op_kind)) { if (!ClangASTContext::CheckOverloadedOperatorKindParameterCount( false, op_kind, func_proto_type->getNumParams())) return nullptr; } m_decls.push_back(func_decl); return func_decl; } clang::NamedDecl *NameSearchContext::AddGenericFunDecl() { FunctionProtoType::ExtProtoInfo proto_info; proto_info.Variadic = true; QualType generic_function_type(m_ast_source.m_ast_context->getFunctionType( m_ast_source.m_ast_context->UnknownAnyTy, // result ArrayRef(), // argument types proto_info)); return AddFunDecl(CompilerType(m_ast_source.m_clang_ast_context, generic_function_type.getAsOpaquePtr()), true); } clang::NamedDecl * NameSearchContext::AddTypeDecl(const CompilerType &clang_type) { if (ClangUtil::IsClangType(clang_type)) { QualType qual_type = ClangUtil::GetQualType(clang_type); if (const TypedefType *typedef_type = llvm::dyn_cast(qual_type)) { TypedefNameDecl *typedef_name_decl = typedef_type->getDecl(); m_decls.push_back(typedef_name_decl); return (NamedDecl *)typedef_name_decl; } else if (const TagType *tag_type = qual_type->getAs()) { TagDecl *tag_decl = tag_type->getDecl(); m_decls.push_back(tag_decl); return tag_decl; } else if (const ObjCObjectType *objc_object_type = qual_type->getAs()) { ObjCInterfaceDecl *interface_decl = objc_object_type->getInterface(); m_decls.push_back((NamedDecl *)interface_decl); return (NamedDecl *)interface_decl; } } return nullptr; } void NameSearchContext::AddLookupResult(clang::DeclContextLookupResult result) { for (clang::NamedDecl *decl : result) m_decls.push_back(decl); } void NameSearchContext::AddNamedDecl(clang::NamedDecl *decl) { m_decls.push_back(decl); } ",16136,True,3129.248365705891,median "[[smpp-component]] = SMPP Component *Since Camel 2.2* // HEADER START *Both producer and consumer is supported* // HEADER END This component provides access to an SMSC (Short Message Service Center) over the http://smsforum.net/SMPP_v3_4_Issue1_2.zip[SMPP] protocol to send and receive SMS. The http://jsmpp.org[JSMPP] library is used for the protocol implementation. The Camel component currently operates as an http://en.wikipedia.org/wiki/ESME[ESME] (External Short Messaging Entity) and not as an SMSC itself. You are also able to execute ReplaceSm, QuerySm, SubmitMulti, CancelSm and DataSm. Maven users will need to add the following dependency to their `pom.xml` for this component: [source,xml] ------------------------------------------------------------ org.apache.camel camel-smpp x.x.x ------------------------------------------------------------ == SMS limitations SMS is neither reliable or secure. Users who require reliable and secure delivery may want to consider using the XMPP or SIP components instead, combined with a smartphone app supporting the chosen protocol. * Reliability: although the SMPP standard offers a range of feedback mechanisms to indicate errors, non-delivery and confirmation of delivery it is not uncommon for mobile networks to hide or simulate these responses. For example, some networks automatically send a delivery confirmation for every message even if the destination number is invalid or not switched on. Some networks silently drop messages if they think they are spam. Spam detection rules in the network may be very crude, sometimes more than 100 messages per day from a single sender may be considered spam. * Security: there is basic encryption for the last hop from the radio tower down to the recipient handset. SMS messages are not encrypted or authenticated in any other part of the network. Some operators allow staff in retail outlets or call centres to browse through the SMS message histories of their customers. Message sender identity can be easily forged. Regulators and even the mobile telephone industry itself has cautioned against the use of SMS in two-factor authentication schemes and other purposes where security is important. While the Camel component makes it as easy as possible to send messages to the SMS network, it can not offer an easy solution to these problems. == Data coding, alphabet and international character sets Data coding and alphabet can be specified on a per-message basis. Default values can be specified for the endpoint. It is important to understand the relationship between these options and the way the component acts when more than one value is set. Data coding is an 8 bit field in the SMPP wire format. Alphabet corresponds to bits 0-3 of the data coding field. For some types of message, where a message class is used (by setting bit 5 of the data coding field), the lower two bits of the data coding field are not interpreted as alphabet and only bits 2 and 3 impact the alphabet. Furthermore, current version of the JSMPP library only seems to support bits 2 and 3, assuming that bits 0 and 1 are used for message class. This is why the Alphabet class in JSMPP doesn't support the value 3 (binary 0011) which indicates ISO-8859-1. Although JSMPP provides a representation of the message class parameter, the Camel component doesn't currently provide a way to set it other than manually setting the corresponding bits in the data coding field. When setting the data coding field in the outgoing message, the Camel component considers the following values and uses the first one it can find: * the data coding specified in a header * the alphabet specified in a header * the data coding specified in the endpoint configuration (URI parameter) Older versions of Camel had bugs in support for international character sets. This feature only worked when a single encoding was used for all messages and was troublesome when users wanted to change it on a per-message basis. Users who require this to work should ensure their version of Camel includes the fix for JIRA Issues Macro: com.atlassian.sal.api.net.ResponseStatusException: Unexpected response received. Status code: 404 . In addition to trying to send the data coding value to the SMSC, the Camel component also tries to analyze the message body, convert it to a Java String (Unicode) and convert that to a byte array in the corresponding alphabet When deciding which alphabet to use in the byte array, the Camel SMPP component does not consider the data coding value (header or configuration), it only considers the specified alphabet (from either the header or endpoint parameter). If some characters in the String can't be represented in the chosen alphabet, they may be replaced by the question mark ( ? ) symbol. Users of the API may want to consider checking if their message body can be converted to ISO-8859-1 before passing it to the component and if not, setting the alphabet header to request UCS-2 encoding. If the alphabet and data coding options are not specified at all then the component may try to detect the required encoding and set the data coding for you. The list of alphabet codes are specified in the SMPP specification v3.4, section 5.2.19. One notable limitation of the SMPP specification is that there is no alphabet code for explicitly requesting use of the GSM 3.38 (7 bit) character set. Choosing the value 0 for the alphabet selects the SMSC _default_ alphabet, this usually means GSM 3.38 but it is not guaranteed. The SMPP gateway Nexmo https://help.nexmo.com/hc/en-us/articles/204015813-How-to-change-the-character-encoding-in-SMPP-[actually allows the default to be mapped to any other character set with a control panel option]. It is suggested that users check with their SMSC operator to confirm exactly which character set is being used as the default. == Message splitting and throttling After transforming a message body from a String to a byte array, the Camel component is also responsible for splitting the message into parts (within the 140 byte SMS size limit) before passing it to JSMPP. This is completed automatically. If the GSM 3.38 alphabet is used, the component will pack up to 160 characters into the 140 byte message body. If an 8 bit character set is used (e.g. ISO-8859-1 for western Europe) then 140 characters will be allowed within the 140 byte message body. If 16 bit UCS-2 encoding is used then just 70 characters fit into each 140 byte message. Some SMSC providers implement throttling rules. Each part of a message that has been split may be counted separately by the provider's throttling mechanism. The Camel Throttler component can be useful for throttling messages in the SMPP route before handing them to the SMSC. == URI format [source,java] -------------------------------------------- smpp://[username@]hostname[:port][?options] smpps://[username@]hostname[:port][?options] -------------------------------------------- If no *username* is provided, then Camel will provide the default value `smppclient`. + If no *port* number is provided, then Camel will provide the default value `2775`. + If the protocol name is ""smpps"", camel-smpp with try to use SSLSocket to init a connection to the server. You can append query options to the URI in the following format, `?option=value&option=value&...` == URI Options // component options: START The SMPP component supports 4 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *configuration* (advanced) | To use the shared SmppConfiguration as configuration. | | SmppConfiguration | *basicPropertyBinding* (advanced) | Whether the component should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities | false | boolean | *lazyStartProducer* (producer) | Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel's routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | *bridgeErrorHandler* (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean |=== // component options: END // endpoint options: START The SMPP endpoint is configured using URI syntax: ---- smpp:host:port ---- with the following path and query parameters: === Path Parameters (2 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *host* | Hostname for the SMSC server to use. | localhost | String | *port* | Port number for the SMSC server to use. | 2775 | Integer |=== === Query Parameters (40 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *initialReconnectDelay* (common) | Defines the initial delay in milliseconds after the consumer/producer tries to reconnect to the SMSC, after the connection was lost. | 5000 | long | *maxReconnect* (common) | Defines the maximum number of attempts to reconnect to the SMSC, if SMSC returns a negative bind response | 2147483647 | int | *reconnectDelay* (common) | Defines the interval in milliseconds between the reconnect attempts, if the connection to the SMSC was lost and the previous was not succeed. | 5000 | long | *splittingPolicy* (common) | You can specify a policy for handling long messages: ALLOW - the default, long messages are split to 140 bytes per message TRUNCATE - long messages are split and only the first fragment will be sent to the SMSC. Some carriers drop subsequent fragments so this reduces load on the SMPP connection sending parts of a message that will never be delivered. REJECT - if a message would need to be split, it is rejected with an SMPP NegativeResponseException and the reason code signifying the message is too long. | ALLOW | SmppSplittingPolicy | *systemType* (common) | This parameter is used to categorize the type of ESME (External Short Message Entity) that is binding to the SMSC (max. 13 characters). | | String | *addressRange* (consumer) | You can specify the address range for the SmppConsumer as defined in section 5.2.7 of the SMPP 3.4 specification. The SmppConsumer will receive messages only from SMSC's which target an address (MSISDN or IP address) within this range. | | String | *bridgeErrorHandler* (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | *exceptionHandler* (consumer) | To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored. | | ExceptionHandler | *exchangePattern* (consumer) | Sets the exchange pattern when the consumer creates an exchange. | | ExchangePattern | *destAddr* (producer) | Defines the destination SME address. For mobile terminated messages, this is the directory number of the recipient MS. Only for SubmitSm, SubmitMulti, CancelSm and DataSm. | 1717 | String | *destAddrNpi* (producer) | Defines the type of number (TON) to be used in the SME destination address parameters. Only for SubmitSm, SubmitMulti, CancelSm and DataSm. The following NPI values are defined: 0: Unknown 1: ISDN (E163/E164) 2: Data (X.121) 3: Telex (F.69) 6: Land Mobile (E.212) 8: National 9: Private 10: ERMES 13: Internet (IP) 18: WAP Client Id (to be defined by WAP Forum) | | byte | *destAddrTon* (producer) | Defines the type of number (TON) to be used in the SME destination address parameters. Only for SubmitSm, SubmitMulti, CancelSm and DataSm. The following TON values are defined: 0: Unknown 1: International 2: National 3: Network Specific 4: Subscriber Number 5: Alphanumeric 6: Abbreviated | | byte | *lazySessionCreation* (producer) | Sessions can be lazily created to avoid exceptions, if the SMSC is not available when the Camel producer is started. Camel will check the in message headers 'CamelSmppSystemId' and 'CamelSmppPassword' of the first exchange. If they are present, Camel will use these data to connect to the SMSC. | false | boolean | *lazyStartProducer* (producer) | Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel's routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | *numberingPlanIndicator* (producer) | Defines the numeric plan indicator (NPI) to be used in the SME. The following NPI values are defined: 0: Unknown 1: ISDN (E163/E164) 2: Data (X.121) 3: Telex (F.69) 6: Land Mobile (E.212) 8: National 9: Private 10: ERMES 13: Internet (IP) 18: WAP Client Id (to be defined by WAP Forum) | | byte | *priorityFlag* (producer) | Allows the originating SME to assign a priority level to the short message. Only for SubmitSm and SubmitMulti. Four Priority Levels are supported: 0: Level 0 (lowest) priority 1: Level 1 priority 2: Level 2 priority 3: Level 3 (highest) priority | | byte | *protocolId* (producer) | The protocol id | | byte | *registeredDelivery* (producer) | Is used to request an SMSC delivery receipt and/or SME originated acknowledgements. The following values are defined: 0: No SMSC delivery receipt requested. 1: SMSC delivery receipt requested where final delivery outcome is success or failure. 2: SMSC delivery receipt requested where the final delivery outcome is delivery failure. | | byte | *replaceIfPresentFlag* (producer) | Used to request the SMSC to replace a previously submitted message, that is still pending delivery. The SMSC will replace an existing message provided that the source address, destination address and service type match the same fields in the new message. The following replace if present flag values are defined: 0: Don't replace 1: Replace | | byte | *serviceType* (producer) | The service type parameter can be used to indicate the SMS Application service associated with the message. The following generic service_types are defined: CMT: Cellular Messaging CPT: Cellular Paging VMN: Voice Mail Notification VMA: Voice Mail Alerting WAP: Wireless Application Protocol USSD: Unstructured Supplementary Services Data | | String | *sourceAddr* (producer) | Defines the address of SME (Short Message Entity) which originated this message. | 1616 | String | *sourceAddrNpi* (producer) | Defines the numeric plan indicator (NPI) to be used in the SME originator address parameters. The following NPI values are defined: 0: Unknown 1: ISDN (E163/E164) 2: Data (X.121) 3: Telex (F.69) 6: Land Mobile (E.212) 8: National 9: Private 10: ERMES 13: Internet (IP) 18: WAP Client Id (to be defined by WAP Forum) | | byte | *sourceAddrTon* (producer) | Defines the type of number (TON) to be used in the SME originator address parameters. The following TON values are defined: 0: Unknown 1: International 2: National 3: Network Specific 4: Subscriber Number 5: Alphanumeric 6: Abbreviated | | byte | *typeOfNumber* (producer) | Defines the type of number (TON) to be used in the SME. The following TON values are defined: 0: Unknown 1: International 2: National 3: Network Specific 4: Subscriber Number 5: Alphanumeric 6: Abbreviated | | byte | *basicPropertyBinding* (advanced) | Whether the endpoint should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities | false | boolean | *enquireLinkTimer* (advanced) | Defines the interval in milliseconds between the confidence checks. The confidence check is used to test the communication path between an ESME and an SMSC. | 5000 | Integer | *sessionStateListener* (advanced) | You can refer to a org.jsmpp.session.SessionStateListener in the Registry to receive callbacks when the session state changed. | | SessionStateListener | *synchronous* (advanced) | Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported). | false | boolean | *transactionTimer* (advanced) | Defines the maximum period of inactivity allowed after a transaction, after which an SMPP entity may assume that the session is no longer active. This timer may be active on either communicating SMPP entity (i.e. SMSC or ESME). | 10000 | Integer | *alphabet* (codec) | Defines encoding of data according the SMPP 3.4 specification, section 5.2.19. 0: SMSC Default Alphabet 4: 8 bit Alphabet 8: UCS2 Alphabet | | byte | *dataCoding* (codec) | Defines the data coding according the SMPP 3.4 specification, section 5.2.19. Example data encodings are: 0: SMSC Default Alphabet 3: Latin 1 (ISO-8859-1) 4: Octet unspecified (8-bit binary) 8: UCS2 (ISO/IEC-10646) 13: Extended Kanji JIS(X 0212-1990) | | byte | *encoding* (codec) | Defines the encoding scheme of the short message user data. Only for SubmitSm, ReplaceSm and SubmitMulti. | ISO-8859-1 | String | *httpProxyHost* (proxy) | If you need to tunnel SMPP through a HTTP proxy, set this attribute to the hostname or ip address of your HTTP proxy. | | String | *httpProxyPassword* (proxy) | If your HTTP proxy requires basic authentication, set this attribute to the password required for your HTTP proxy. | | String | *httpProxyPort* (proxy) | If you need to tunnel SMPP through a HTTP proxy, set this attribute to the port of your HTTP proxy. | 3128 | Integer | *httpProxyUsername* (proxy) | If your HTTP proxy requires basic authentication, set this attribute to the username required for your HTTP proxy. | | String | *proxyHeaders* (proxy) | These headers will be passed to the proxy server while establishing the connection. | | Map | *password* (security) | The password for connecting to SMSC server. | | String | *systemId* (security) | The system id (username) for connecting to SMSC server. | smppclient | String | *usingSSL* (security) | Whether using SSL with the smpps protocol | false | boolean |=== // endpoint options: END // spring-boot-auto-configure options: START == Spring Boot Auto-Configuration When using Spring Boot make sure to use the following Maven dependency to have support for auto configuration: [source,xml] ---- org.apache.camel.springboot camel-smpp-starter x.x.x ---- The component supports 40 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *camel.component.smpp.basic-property-binding* | Whether the component should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities | false | Boolean | *camel.component.smpp.bridge-error-handler* | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | Boolean | *camel.component.smpp.configuration.address-range* | You can specify the address range for the SmppConsumer as defined in section 5.2.7 of the SMPP 3.4 specification. The SmppConsumer will receive messages only from SMSC's which target an address (MSISDN or IP address) within this range. | | String | *camel.component.smpp.configuration.alphabet* | Defines encoding of data according the SMPP 3.4 specification, section 5.2.19.
  • 0: SMSC Default Alphabet
  • 4: 8 bit Alphabet
  • 8: UCS2 Alphabet
| | Byte | *camel.component.smpp.configuration.data-coding* | Defines the data coding according the SMPP 3.4 specification, section 5.2.19. Example data encodings are:
  • 0: SMSC Default Alphabet
  • 3: Latin 1 (ISO-8859-1)
  • 4: Octet unspecified (8-bit binary)
  • 8: UCS2 (ISO/IEC-10646)
  • 13: Extended Kanji JIS(X 0212-1990)
| | Byte | *camel.component.smpp.configuration.dest-addr* | Defines the destination SME address. For mobile terminated messages, this is the directory number of the recipient MS. Only for SubmitSm, SubmitMulti, CancelSm and DataSm. | 1717 | String | *camel.component.smpp.configuration.dest-addr-npi* | Defines the type of number (TON) to be used in the SME destination address parameters. Only for SubmitSm, SubmitMulti, CancelSm and DataSm. The following NPI values are defined:
  • 0: Unknown
  • 1: ISDN (E163/E164)
  • 2: Data (X.121)
  • 3: Telex (F.69)
  • 6: Land Mobile (E.212)
  • 8: National
  • 9: Private
  • 10: ERMES
  • 13: Internet (IP)
  • 18: WAP Client Id (to be defined by WAP Forum)
| | Byte | *camel.component.smpp.configuration.dest-addr-ton* | Defines the type of number (TON) to be used in the SME destination address parameters. Only for SubmitSm, SubmitMulti, CancelSm and DataSm. The following TON values are defined:
  • 0: Unknown
  • 1: International
  • 2: National
  • 3: Network Specific
  • 4: Subscriber Number
  • 5: Alphanumeric
  • 6: Abbreviated
| | Byte | *camel.component.smpp.configuration.encoding* | Defines the encoding scheme of the short message user data. Only for SubmitSm, ReplaceSm and SubmitMulti. | ISO-8859-1 | String | *camel.component.smpp.configuration.enquire-link-timer* | Defines the interval in milliseconds between the confidence checks. The confidence check is used to test the communication path between an ESME and an SMSC. | 5000 | Integer | *camel.component.smpp.configuration.host* | Hostname for the SMSC server to use. | localhost | String | *camel.component.smpp.configuration.http-proxy-host* | If you need to tunnel SMPP through a HTTP proxy, set this attribute to the hostname or ip address of your HTTP proxy. | | String | *camel.component.smpp.configuration.http-proxy-password* | If your HTTP proxy requires basic authentication, set this attribute to the password required for your HTTP proxy. | | String | *camel.component.smpp.configuration.http-proxy-port* | If you need to tunnel SMPP through a HTTP proxy, set this attribute to the port of your HTTP proxy. | 3128 | Integer | *camel.component.smpp.configuration.http-proxy-username* | If your HTTP proxy requires basic authentication, set this attribute to the username required for your HTTP proxy. | | String | *camel.component.smpp.configuration.initial-reconnect-delay* | Defines the initial delay in milliseconds after the consumer/producer tries to reconnect to the SMSC, after the connection was lost. | 5000 | Long | *camel.component.smpp.configuration.lazy-session-creation* | Sessions can be lazily created to avoid exceptions, if the SMSC is not available when the Camel producer is started. Camel will check the in message headers 'CamelSmppSystemId' and 'CamelSmppPassword' of the first exchange. If they are present, Camel will use these data to connect to the SMSC. | false | Boolean | *camel.component.smpp.configuration.max-reconnect* | Defines the maximum number of attempts to reconnect to the SMSC, if SMSC returns a negative bind response | 2147483647 | Integer | *camel.component.smpp.configuration.numbering-plan-indicator* | Defines the numeric plan indicator (NPI) to be used in the SME. The following NPI values are defined:
  • 0: Unknown
  • 1: ISDN (E163/E164)
  • 2: Data (X.121)
  • 3: Telex (F.69)
  • 6: Land Mobile (E.212)
  • 8: National
  • 9: Private
  • 10: ERMES
  • 13: Internet (IP)
  • 18: WAP Client Id (to be defined by WAP Forum)
| | Byte | *camel.component.smpp.configuration.password* | Defines the encoding scheme of the short message user data. Only for SubmitSm, ReplaceSm and SubmitMulti. | | String | *camel.component.smpp.configuration.port* | Port number for the SMSC server to use. | 2775 | Integer | *camel.component.smpp.configuration.priority-flag* | Allows the originating SME to assign a priority level to the short message. Only for SubmitSm and SubmitMulti. Four Priority Levels are supported:
  • 0: Level 0 (lowest) priority
  • 1: Level 1 priority
  • 2: Level 2 priority
  • 3: Level 3 (highest) priority
| | Byte | *camel.component.smpp.configuration.protocol-id* | The protocol id | | Byte | *camel.component.smpp.configuration.proxy-headers* | These headers will be passed to the proxy server while establishing the connection. | | Map | *camel.component.smpp.configuration.reconnect-delay* | Defines the interval in milliseconds between the reconnect attempts, if the connection to the SMSC was lost and the previous was not succeed. | 5000 | Long | *camel.component.smpp.configuration.registered-delivery* | Is used to request an SMSC delivery receipt and/or SME originated acknowledgements. The following values are defined:
  • 0: No SMSC delivery receipt requested.
  • 1: SMSC delivery receipt requested where final delivery outcome is success or failure.
  • 2: SMSC delivery receipt requested where the final delivery outcome is delivery failure.
| | Byte | *camel.component.smpp.configuration.replace-if-present-flag* | Used to request the SMSC to replace a previously submitted message, that is still pending delivery. The SMSC will replace an existing message provided that the source address, destination address and service type match the same fields in the new message. The following replace if present flag values are defined:
  • 0: Don't replace
  • 1: Replace
| | Byte | *camel.component.smpp.configuration.service-type* | The service type parameter can be used to indicate the SMS Application service associated with the message. The following generic service_types are defined:
  • CMT: Cellular Messaging
  • CPT: Cellular Paging
  • VMN: Voice Mail Notification
  • VMA: Voice Mail Alerting
  • WAP: Wireless Application Protocol
  • USSD: Unstructured Supplementary Services Data
| | String | *camel.component.smpp.configuration.session-state-listener* | You can refer to a org.jsmpp.session.SessionStateListener in the Registry to receive callbacks when the session state changed. | | SessionStateListener | *camel.component.smpp.configuration.source-addr* | Defines the address of SME (Short Message Entity) which originated this message. | 1616 | String | *camel.component.smpp.configuration.source-addr-npi* | Defines the numeric plan indicator (NPI) to be used in the SME originator address parameters. The following NPI values are defined:
  • 0: Unknown
  • 1: ISDN (E163/E164)
  • 2: Data (X.121)
  • 3: Telex (F.69)
  • 6: Land Mobile (E.212)
  • 8: National
  • 9: Private
  • 10: ERMES
  • 13: Internet (IP)
  • 18: WAP Client Id (to be defined by WAP Forum)
| | Byte | *camel.component.smpp.configuration.source-addr-ton* | Defines the type of number (TON) to be used in the SME originator address parameters. The following TON values are defined:
  • 0: Unknown
  • 1: International
  • 2: National
  • 3: Network Specific
  • 4: Subscriber Number
  • 5: Alphanumeric
  • 6: Abbreviated
| | Byte | *camel.component.smpp.configuration.splitting-policy* | You can specify a policy for handling long messages:
  • ALLOW - the default, long messages are split to 140 bytes per message
  • TRUNCATE - long messages are split and only the first fragment will be sent to the SMSC. Some carriers drop subsequent fragments so this reduces load on the SMPP connection sending parts of a message that will never be delivered.
  • REJECT - if a message would need to be split, it is rejected with an SMPP NegativeResponseException and the reason code signifying the message is too long.
| | SmppSplittingPolicy | *camel.component.smpp.configuration.system-id* | The system id (username) for connecting to SMSC server. | smppclient | String | *camel.component.smpp.configuration.system-type* | This parameter is used to categorize the type of ESME (External Short Message Entity) that is binding to the SMSC (max. 13 characters). | | String | *camel.component.smpp.configuration.transaction-timer* | Defines the maximum period of inactivity allowed after a transaction, after which an SMPP entity may assume that the session is no longer active. This timer may be active on either communicating SMPP entity (i.e. SMSC or ESME). | 10000 | Integer | *camel.component.smpp.configuration.type-of-number* | Defines the type of number (TON) to be used in the SME. The following TON values are defined:
  • 0: Unknown
  • 1: International
  • 2: National
  • 3: Network Specific
  • 4: Subscriber Number
  • 5: Alphanumeric
  • 6: Abbreviated
| | Byte | *camel.component.smpp.configuration.using-s-s-l* | Whether using SSL with the smpps protocol | false | Boolean | *camel.component.smpp.enabled* | Whether to enable auto configuration of the smpp component. This is enabled by default. | | Boolean | *camel.component.smpp.lazy-start-producer* | Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel's routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | Boolean |=== // spring-boot-auto-configure options: END You can have as many of these options as you like. [source,java] ------------------------------------------------------------------------------------------------------------------ smpp://smppclient@localhost:2775?password=password&enquireLinkTimer=3000&transactionTimer=5000&systemType=consumer ------------------------------------------------------------------------------------------------------------------ == Producer Message Headers The following message headers can be used to affect the behavior of the SMPP producer [width=""100%"",cols=""10%,10%,80%"",options=""header"",] |======================================================================= |Header |Type |Description |`CamelSmppDestAddr` |`List`/`String` |*only for SubmitSm, SubmitMulti, CancelSm and DataSm* Defines the destination SME address(es). For mobile terminated messages, this is the directory number of the recipient MS. Is must be a `List` for SubmitMulti and a `String` otherwise. |`CamelSmppDestAddrTon` |`Byte` |*only for SubmitSm, SubmitMulti, CancelSm and DataSm* Defines the type of number (TON) to be used in the SME destination address parameters. Use the `sourceAddrTon` URI option values defined above. |`CamelSmppDestAddrNpi` |`Byte` |*only for SubmitSm, SubmitMulti, CancelSm and DataSm* Defines the numeric plan indicator (NPI) to be used in the SME destination address parameters. Use the URI option `sourceAddrNpi` values defined above. |`CamelSmppSourceAddr` |`String` |Defines the address of SME (Short Message Entity) which originated this message. |`CamelSmppSourceAddrTon` |`Byte` |Defines the type of number (TON) to be used in the SME originator address parameters. Use the `sourceAddrTon` URI option values defined above. |`CamelSmppSourceAddrNpi` |`Byte` |Defines the numeric plan indicator (NPI) to be used in the SME originator address parameters. Use the URI option `sourceAddrNpi` values defined above. |`CamelSmppServiceType` |`String` |The service type parameter can be used to indicate the SMS Application service associated with the message. Use the URI option `serviceType` settings above. |`CamelSmppRegisteredDelivery` |`Byte` |*only for SubmitSm, ReplaceSm, SubmitMulti and DataSm* Is used to request an SMSC delivery receipt and/or SME originated acknowledgements. Use the URI option `registeredDelivery` settings above. |`CamelSmppPriorityFlag` |`Byte` |*only for SubmitSm and SubmitMulti* Allows the originating SME to assign a priority level to the short message. Use the URI option `priorityFlag` settings above. |`CamelSmppScheduleDeliveryTime` |`Date` |*only for SubmitSm, SubmitMulti and ReplaceSm* This parameter specifies the scheduled time at which the message delivery should be first attempted. It defines either the absolute date and time or relative time from the current SMSC time at which delivery of this message will be attempted by the SMSC. It can be specified in either absolute time format or relative time format. The encoding of a time format is specified in chapter 7.1.1. in the smpp specification v3.4. |`CamelSmppValidityPeriod` |`String`/`Date` |*only for SubmitSm, SubmitMulti and ReplaceSm* The validity period parameter indicates the SMSC expiration time, after which the message should be discarded if not delivered to the destination. If it's provided as `Date`, it's interpreted as absolute time or relative time format if you provide it as `String` as specified in chapter 7.1.1 in the smpp specification v3.4. |`CamelSmppReplaceIfPresentFlag` |`Byte` |*only for SubmitSm and SubmitMulti* The replace if present flag parameter is used to request the SMSC to replace a previously submitted message, that is still pending delivery. The SMSC will replace an existing message provided that the source address, destination address and service type match the same fields in the new message. The following values are defined: `0`, Don't replace and `1`, Replace |`CamelSmppAlphabet` / `CamelSmppDataCoding` |`Byte` |*For SubmitSm, SubmitMulti and ReplaceSm* The data coding according to the SMPP 3.4 specification, section 5.2.19. Use the URI option `alphabet` settings above. |`CamelSmppOptionalParameter` |`Map` |*only for SubmitSm, SubmitMulti and DataSm* The optional parameter which are send to the SMSC. The value is converted in the following way: `String` -> `org.jsmpp.bean.OptionalParameter.COctetString`, `byte[]` -> `org.jsmpp.bean.OptionalParameter.OctetString`, `Byte` -> `org.jsmpp.bean.OptionalParameter.Byte`, `Integer` -> `org.jsmpp.bean.OptionalParameter.Int`, `Short` -> `org.jsmpp.bean.OptionalParameter.Short`, `null` -> `org.jsmpp.bean.OptionalParameter.Null` |CamelSmppEncoding |String |*only for SubmitSm, SubmitMulti and DataSm*. Specifies the encoding (character set name) of the bytes in the message body. If the message body is a string then this is not relevant because Java Strings are always Unicode. If the body is a byte array then this header can be used to indicate that it is ISO-8859-1 or some other value. Default value is specified by the endpoint configuration parameter _encoding_ |CamelSmppSplittingPolicy |String |*only for SubmitSm, SubmitMulti and DataSm*. Specifies the policy for message splitting for this exchange. Possible values are described in the endpoint configuration parameter _splittingPolicy_ |======================================================================= The following message headers are used by the SMPP producer to set the response from the SMSC in the message header [width=""100%"",cols=""10%,10%,80%"",options=""header"",] |======================================================================= |Header |Type |Description |`CamelSmppId` |`List`/`String` |The id to identify the submitted short message(s) for later use. In case of a ReplaceSm, QuerySm, CancelSm and DataSm this header vaule is a `String`. In case of a SubmitSm or SubmitMultiSm this header vaule is a `List`. |`CamelSmppSentMessageCount` |`Integer` |*only for SubmitSm and SubmitMultiSm* The total number of messages which has been sent. |`CamelSmppError` |`Map>>` |*only for SubmitMultiSm* The errors which occurred by sending the short message(s) the form `Map>>` (messageID : (destAddr : address, error : errorCode)). |`CamelSmppOptionalParameter` |`Map` |*only for DataSm* The optional parameter which are returned from the SMSC by sending the message. The key is the `Short` code for the optional parameter. The value is converted in the following way: `org.jsmpp.bean.OptionalParameter.COctetString` -> `String`, `org.jsmpp.bean.OptionalParameter.OctetString` -> `byte[]`, `org.jsmpp.bean.OptionalParameter.Byte` -> `Byte`, `org.jsmpp.bean.OptionalParameter.Int` -> `Integer`, `org.jsmpp.bean.OptionalParameter.Short` -> `Short`, `org.jsmpp.bean.OptionalParameter.Null` -> `null` |======================================================================= == Consumer Message Headers The following message headers are used by the SMPP consumer to set the request data from the SMSC in the message header [width=""100%"",cols=""10%,10%,80%"",options=""header"",] |======================================================================= |Header |Type |Description |`CamelSmppSequenceNumber` |`Integer` |*only for AlertNotification, DeliverSm and DataSm* A sequence number allows a response PDU to be correlated with a request PDU. The associated SMPP response PDU must preserve this field. |`CamelSmppCommandId` |`Integer` |*only for AlertNotification, DeliverSm and DataSm* The command id field identifies the particular SMPP PDU. For the complete list of defined values see chapter 5.1.2.1 in the smpp specification v3.4. |`CamelSmppSourceAddr` |`String` |*only for AlertNotification, DeliverSm and DataSm* Defines the address of SME (Short Message Entity) which originated this message. |`CamelSmppSourceAddrNpi` |`Byte` |*only for AlertNotification and DataSm* Defines the numeric plan indicator (NPI) to be used in the SME originator address parameters. Use the URI option `sourceAddrNpi` values defined above. |`CamelSmppSourceAddrTon` |`Byte` |*only for AlertNotification and DataSm* Defines the type of number (TON) to be used in the SME originator address parameters. Use the `sourceAddrTon` URI option values defined above. |`CamelSmppEsmeAddr` |`String` |*only for AlertNotification* Defines the destination ESME address. For mobile terminated messages, this is the directory number of the recipient MS. |`CamelSmppEsmeAddrNpi` |`Byte` |*only for AlertNotification* Defines the numeric plan indicator (NPI) to be used in the ESME originator address parameters. Use the URI option `sourceAddrNpi` values defined above. |`CamelSmppEsmeAddrTon` |`Byte` |*only for AlertNotification* Defines the type of number (TON) to be used in the ESME originator address parameters. Use the `sourceAddrTon` URI option values defined above. |`CamelSmppId` |`String` |*only for smsc DeliveryReceipt and DataSm* The message ID allocated to the message by the SMSC when originally submitted. |`CamelSmppDelivered` |`Integer` |*only for smsc DeliveryReceipt* Number of short messages delivered. This is only relevant where the original message was submitted to a distribution list.The value is padded with leading zeros if necessary. |`CamelSmppDoneDate` |`Date` |*only for smsc DeliveryReceipt* The time and date at which the short message reached it's final state. The format is as follows: YYMMDDhhmm. |`CamelSmppStatus` |`DeliveryReceiptState` |*only for smsc DeliveryReceipt:* The final status of the message. The following values are defined: `DELIVRD`: Message is delivered to destination, `EXPIRED`: Message validity period has expired, `DELETED`: Message has been deleted, `UNDELIV`: Message is undeliverable, `ACCEPTD`: Message is in accepted state (i.e. has been manually read on behalf of the subscriber by customer service), `UNKNOWN`: Message is in invalid state, `REJECTD`: Message is in a rejected state |`CamelSmppCommandStatus` |`Integer` |*only for DataSm* The Command status of the message. |`CamelSmppError` |`String` |*only for smsc DeliveryReceipt* Where appropriate this may hold a Network specific error code or an SMSC error code for the attempted delivery of the message. These errors are Network or SMSC specific and are not included here. |`CamelSmppSubmitDate` |`Date` |*only for smsc DeliveryReceipt* The time and date at which the short message was submitted. In the case of a message which has been replaced, this is the date that the original message was replaced. The format is as follows: YYMMDDhhmm. |`CamelSmppSubmitted` |`Integer` |*only for smsc DeliveryReceipt* Number of short messages originally submitted. This is only relevant when the original message was submitted to a distribution list.The value is padded with leading zeros if necessary. |`CamelSmppDestAddr` |`String` |*only for DeliverSm and DataSm:* Defines the destination SME address. For mobile terminated messages, this is the directory number of the recipient MS. |`CamelSmppScheduleDeliveryTime` |`String` |*only for DeliverSm:* This parameter specifies the scheduled time at which the message delivery should be first attempted. It defines either the absolute date and time or relative time from the current SMSC time at which delivery of this message will be attempted by the SMSC. It can be specified in either absolute time format or relative time format. The encoding of a time format is specified in Section 7.1.1. in the smpp specification v3.4. |`CamelSmppValidityPeriod` |`String` |*only for DeliverSm* The validity period parameter indicates the SMSC expiration time, after which the message should be discarded if not delivered to the destination. It can be defined in absolute time format or relative time format. The encoding of absolute and relative time format is specified in Section 7.1.1 in the smpp specification v3.4. |`CamelSmppServiceType` |`String` |*only for DeliverSm and DataSm* The service type parameter indicates the SMS Application service associated with the message. |`CamelSmppRegisteredDelivery` |`Byte` |*only for DataSm* Is used to request an delivery receipt and/or SME originated acknowledgements. Same values as in Producer header list above. |`CamelSmppDestAddrNpi` |`Byte` |*only for DataSm* Defines the numeric plan indicator (NPI) in the destination address parameters. Use the URI option `sourceAddrNpi` values defined above. |`CamelSmppDestAddrTon` |`Byte` |*only for DataSm* Defines the type of number (TON) in the destination address parameters. Use the `sourceAddrTon` URI option values defined above. |`CamelSmppMessageType` |`String` |Identifies the type of an incoming message: `AlertNotification`: an SMSC alert notification, `DataSm`: an SMSC data short message, `DeliveryReceipt`: an SMSC delivery receipt, `DeliverSm`: an SMSC deliver short message |`CamelSmppOptionalParameter` |`Map` |*only for DeliverSm* The optional parameters send back by the SMSC. The key is the `Short` code for the optional parameter. The value is converted in the following way: `org.jsmpp.bean.OptionalParameter.COctetString` -> `String`, `org.jsmpp.bean.OptionalParameter.OctetString` -> `byte[]`, `org.jsmpp.bean.OptionalParameter.Byte` -> `Byte`, `org.jsmpp.bean.OptionalParameter.Int` -> `Integer`, `org.jsmpp.bean.OptionalParameter.Short` -> `Short`, `org.jsmpp.bean.OptionalParameter.Null` -> `null` |======================================================================= TIP: *JSMPP library* See the documentation of the http://jsmpp.org[JSMPP Library] for more details about the underlying library. == Exception handling This component supports the general Camel exception handling capabilities When an error occurs sending a message with SubmitSm (the default action), the org.apache.camel.component.smpp.SmppException is thrown with a nested exception, org.jsmpp.extra.NegativeResponseException. Call NegativeResponseException.getCommandStatus() to obtain the exact SMPP negative response code, the values are explained in the SMPP specification 3.4, section 5.1.3. + When the SMPP consumer receives a `DeliverSm` or `DataSm` short message and the processing of these messages fails, you can also throw a `ProcessRequestException` instead of handle the failure. In this case, this exception is forwarded to the underlying http://jsmpp.org[JSMPP library] which will return the included error code to the SMSC. This feature is useful to e.g. instruct the SMSC to resend the short message at a later time. This could be done with the following lines of code: [source,java] -------------------------------------------------------------------------------------------------------------------------- from(""smpp://smppclient@localhost:2775?password=password&enquireLinkTimer=3000&transactionTimer=5000&systemType=consumer"") .doTry() .to(""bean:dao?method=updateSmsState"") .doCatch(Exception.class) .throwException(new ProcessRequestException(""update of sms state failed"", 100)) .end(); -------------------------------------------------------------------------------------------------------------------------- Please refer to the http://smsforum.net/SMPP_v3_4_Issue1_2.zip[SMPP specification] for the complete list of error codes and their meanings. == Samples A route which sends an SMS using the Java DSL: [source,java] ------------------------------------------------------------------------------------------ from(""direct:start"") .to(""smpp://smppclient@localhost:2775? password=password&enquireLinkTimer=3000&transactionTimer=5000&systemType=producer""); ------------------------------------------------------------------------------------------ A route which sends an SMS using the Spring XML DSL: [source,xml] ----------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------- A route which receives an SMS using the Java DSL: [source,java] -------------------------------------------------------------------------------------------------------------------------- from(""smpp://smppclient@localhost:2775?password=password&enquireLinkTimer=3000&transactionTimer=5000&systemType=consumer"") .to(""bean:foo""); -------------------------------------------------------------------------------------------------------------------------- A route which receives an SMS using the Spring XML DSL: [source,xml] ---------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------- TIP: *SMSC simulator* If you need an SMSC simulator for your test, you can use the simulator provided by http://opensmpp.logica.com/CommonPart/Download/download2.html#simulator[Logica]. == Debug logging This component has log level *DEBUG*, which can be helpful in debugging problems. If you use log4j, you can add the following line to your configuration: [source,java] -------------------------------------------------- log4j.logger.org.apache.camel.component.smpp=DEBUG -------------------------------------------------- ",12122,False,2391.515324324971,median "// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #define RAPIDJSON_HAS_STDSTRING 1 #include ""flutter/shell/common/shell.h"" #include #include #include #include ""flutter/assets/directory_asset_bundle.h"" #include ""flutter/common/graphics/persistent_cache.h"" #include ""flutter/fml/base32.h"" #include ""flutter/fml/file.h"" #include ""flutter/fml/icu_util.h"" #include ""flutter/fml/log_settings.h"" #include ""flutter/fml/logging.h"" #include ""flutter/fml/make_copyable.h"" #include ""flutter/fml/message_loop.h"" #include ""flutter/fml/paths.h"" #include ""flutter/fml/trace_event.h"" #include ""flutter/runtime/dart_vm.h"" #include ""flutter/shell/common/engine.h"" #include ""flutter/shell/common/skia_event_tracer_impl.h"" #include ""flutter/shell/common/switches.h"" #include ""flutter/shell/common/vsync_waiter.h"" #include ""rapidjson/stringbuffer.h"" #include ""rapidjson/writer.h"" #include ""third_party/dart/runtime/include/dart_tools_api.h"" #include ""third_party/skia/include/core/SkGraphics.h"" #include ""third_party/skia/include/utils/SkBase64.h"" #include ""third_party/tonic/common/log.h"" namespace flutter { constexpr char kSkiaChannel[] = ""flutter/skia""; constexpr char kSystemChannel[] = ""flutter/system""; constexpr char kTypeKey[] = ""type""; constexpr char kFontChange[] = ""fontsChange""; namespace { std::unique_ptr CreateEngine( Engine::Delegate& delegate, const PointerDataDispatcherMaker& dispatcher_maker, DartVM& vm, fml::RefPtr isolate_snapshot, TaskRunners task_runners, const PlatformData& platform_data, Settings settings, std::unique_ptr animator, fml::WeakPtr io_manager, fml::RefPtr unref_queue, fml::WeakPtr snapshot_delegate, std::shared_ptr volatile_path_tracker) { return std::make_unique(delegate, // dispatcher_maker, // vm, // isolate_snapshot, // task_runners, // platform_data, // settings, // std::move(animator), // io_manager, // unref_queue, // snapshot_delegate, // volatile_path_tracker); } // Though there can be multiple shells, some settings apply to all components in // the process. These have to be set up before the shell or any of its // sub-components can be initialized. In a perfect world, this would be empty. // TODO(chinmaygarde): The unfortunate side effect of this call is that settings // that cause shell initialization failures will still lead to some of their // settings being applied. void PerformInitializationTasks(Settings& settings) { { fml::LogSettings log_settings; log_settings.min_log_level = settings.verbose_logging ? fml::LOG_INFO : fml::LOG_ERROR; fml::SetLogSettings(log_settings); } static std::once_flag gShellSettingsInitialization = {}; std::call_once(gShellSettingsInitialization, [&settings] { if (settings.engine_start_timestamp.count() == 0) { settings.engine_start_timestamp = std::chrono::microseconds(Dart_TimelineGetMicros()); } tonic::SetLogHandler( [](const char* message) { FML_LOG(ERROR) << message; }); if (settings.trace_skia) { InitSkiaEventTracer(settings.trace_skia, settings.trace_skia_allowlist); } if (!settings.trace_allowlist.empty()) { fml::tracing::TraceSetAllowlist(settings.trace_allowlist); } if (!settings.skia_deterministic_rendering_on_cpu) { SkGraphics::Init(); } else { FML_DLOG(INFO) << ""Skia deterministic rendering is enabled.""; } if (settings.icu_initialization_required) { if (settings.icu_data_path.size() != 0) { fml::icu::InitializeICU(settings.icu_data_path); } else if (settings.icu_mapper) { fml::icu::InitializeICUFromMapping(settings.icu_mapper()); } else { FML_DLOG(WARNING) << ""Skipping ICU initialization in the shell.""; } } }); PersistentCache::SetCacheSkSL(settings.cache_sksl); } } // namespace std::unique_ptr Shell::Create( const PlatformData& platform_data, TaskRunners task_runners, Settings settings, const Shell::CreateCallback& on_create_platform_view, const Shell::CreateCallback& on_create_rasterizer, bool is_gpu_disabled) { // This must come first as it initializes tracing. PerformInitializationTasks(settings); TRACE_EVENT0(""flutter"", ""Shell::Create""); // Always use the `vm_snapshot` and `isolate_snapshot` provided by the // settings to launch the VM. If the VM is already running, the snapshot // arguments are ignored. auto vm_snapshot = DartSnapshot::VMSnapshotFromSettings(settings); auto isolate_snapshot = DartSnapshot::IsolateSnapshotFromSettings(settings); auto vm = DartVMRef::Create(settings, vm_snapshot, isolate_snapshot); FML_CHECK(vm) << ""Must be able to initialize the VM.""; // If the settings did not specify an `isolate_snapshot`, fall back to the // one the VM was launched with. if (!isolate_snapshot) { isolate_snapshot = vm->GetVMData()->GetIsolateSnapshot(); } return CreateWithSnapshot(std::move(platform_data), // std::move(task_runners), // /*parent_merger=*/nullptr, // /*parent_io_manager=*/nullptr, // std::move(settings), // std::move(vm), // std::move(isolate_snapshot), // std::move(on_create_platform_view), // std::move(on_create_rasterizer), // CreateEngine, is_gpu_disabled); } std::unique_ptr Shell::CreateShellOnPlatformThread( DartVMRef vm, fml::RefPtr parent_merger, std::shared_ptr parent_io_manager, TaskRunners task_runners, const PlatformData& platform_data, Settings settings, fml::RefPtr isolate_snapshot, const Shell::CreateCallback& on_create_platform_view, const Shell::CreateCallback& on_create_rasterizer, const Shell::EngineCreateCallback& on_create_engine, bool is_gpu_disabled) { if (!task_runners.IsValid()) { FML_LOG(ERROR) << ""Task runners to run the shell were invalid.""; return nullptr; } auto shell = std::unique_ptr( new Shell(std::move(vm), task_runners, parent_merger, settings, std::make_shared( task_runners.GetUITaskRunner(), !settings.skia_deterministic_rendering_on_cpu), is_gpu_disabled)); // Create the rasterizer on the raster thread. std::promise> rasterizer_promise; auto rasterizer_future = rasterizer_promise.get_future(); std::promise> snapshot_delegate_promise; auto snapshot_delegate_future = snapshot_delegate_promise.get_future(); fml::TaskRunner::RunNowOrPostTask( task_runners.GetRasterTaskRunner(), [&rasterizer_promise, // &snapshot_delegate_promise, on_create_rasterizer, // shell = shell.get() // ]() { TRACE_EVENT0(""flutter"", ""ShellSetupGPUSubsystem""); std::unique_ptr rasterizer(on_create_rasterizer(*shell)); snapshot_delegate_promise.set_value(rasterizer->GetSnapshotDelegate()); rasterizer_promise.set_value(std::move(rasterizer)); }); // Create the platform view on the platform thread (this thread). auto platform_view = on_create_platform_view(*shell.get()); if (!platform_view || !platform_view->GetWeakPtr()) { return nullptr; } // Ask the platform view for the vsync waiter. This will be used by the engine // to create the animator. auto vsync_waiter = platform_view->CreateVSyncWaiter(); if (!vsync_waiter) { return nullptr; } // Create the IO manager on the IO thread. The IO manager must be initialized // first because it has state that the other subsystems depend on. It must // first be booted and the necessary references obtained to initialize the // other subsystems. std::promise> io_manager_promise; auto io_manager_future = io_manager_promise.get_future(); std::promise> weak_io_manager_promise; auto weak_io_manager_future = weak_io_manager_promise.get_future(); std::promise> unref_queue_promise; auto unref_queue_future = unref_queue_promise.get_future(); auto io_task_runner = shell->GetTaskRunners().GetIOTaskRunner(); // The platform_view will be stored into shell's platform_view_ in // shell->Setup(std::move(platform_view), ...) at the end. PlatformView* platform_view_ptr = platform_view.get(); fml::TaskRunner::RunNowOrPostTask( io_task_runner, [&io_manager_promise, // &weak_io_manager_promise, // &parent_io_manager, // &unref_queue_promise, // platform_view_ptr, // io_task_runner, // is_backgrounded_sync_switch = shell->GetIsGpuDisabledSyncSwitch() // ]() { TRACE_EVENT0(""flutter"", ""ShellSetupIOSubsystem""); std::shared_ptr io_manager; if (parent_io_manager) { io_manager = parent_io_manager; } else { io_manager = std::make_shared( platform_view_ptr->CreateResourceContext(), is_backgrounded_sync_switch, io_task_runner); } weak_io_manager_promise.set_value(io_manager->GetWeakPtr()); unref_queue_promise.set_value(io_manager->GetSkiaUnrefQueue()); io_manager_promise.set_value(io_manager); }); // Send dispatcher_maker to the engine constructor because shell won't have // platform_view set until Shell::Setup is called later. auto dispatcher_maker = platform_view->GetDispatcherMaker(); // Create the engine on the UI thread. std::promise> engine_promise; auto engine_future = engine_promise.get_future(); fml::TaskRunner::RunNowOrPostTask( shell->GetTaskRunners().GetUITaskRunner(), fml::MakeCopyable([&engine_promise, // shell = shell.get(), // &dispatcher_maker, // &platform_data, // isolate_snapshot = std::move(isolate_snapshot), // vsync_waiter = std::move(vsync_waiter), // &weak_io_manager_future, // &snapshot_delegate_future, // &unref_queue_future, // &on_create_engine]() mutable { TRACE_EVENT0(""flutter"", ""ShellSetupUISubsystem""); const auto& task_runners = shell->GetTaskRunners(); // The animator is owned by the UI thread but it gets its vsync pulses // from the platform. auto animator = std::make_unique(*shell, task_runners, std::move(vsync_waiter)); engine_promise.set_value( on_create_engine(*shell, // dispatcher_maker, // *shell->GetDartVM(), // std::move(isolate_snapshot), // task_runners, // platform_data, // shell->GetSettings(), // std::move(animator), // weak_io_manager_future.get(), // unref_queue_future.get(), // snapshot_delegate_future.get(), // shell->volatile_path_tracker_)); })); if (!shell->Setup(std::move(platform_view), // engine_future.get(), // rasterizer_future.get(), // io_manager_future.get()) // ) { return nullptr; } return shell; } std::unique_ptr Shell::CreateWithSnapshot( const PlatformData& platform_data, TaskRunners task_runners, fml::RefPtr parent_thread_merger, std::shared_ptr parent_io_manager, Settings settings, DartVMRef vm, fml::RefPtr isolate_snapshot, const Shell::CreateCallback& on_create_platform_view, const Shell::CreateCallback& on_create_rasterizer, const Shell::EngineCreateCallback& on_create_engine, bool is_gpu_disabled) { // This must come first as it initializes tracing. PerformInitializationTasks(settings); TRACE_EVENT0(""flutter"", ""Shell::CreateWithSnapshot""); const bool callbacks_valid = on_create_platform_view && on_create_rasterizer && on_create_engine; if (!task_runners.IsValid() || !callbacks_valid) { return nullptr; } fml::AutoResetWaitableEvent latch; std::unique_ptr shell; fml::TaskRunner::RunNowOrPostTask( task_runners.GetPlatformTaskRunner(), fml::MakeCopyable( [&latch, // &shell, // parent_thread_merger, // parent_io_manager, // task_runners = std::move(task_runners), // platform_data = std::move(platform_data), // settings = std::move(settings), // vm = std::move(vm), // isolate_snapshot = std::move(isolate_snapshot), // on_create_platform_view = std::move(on_create_platform_view), // on_create_rasterizer = std::move(on_create_rasterizer), // on_create_engine = std::move(on_create_engine), is_gpu_disabled]() mutable { shell = CreateShellOnPlatformThread( std::move(vm), // parent_thread_merger, // parent_io_manager, // std::move(task_runners), // std::move(platform_data), // std::move(settings), // std::move(isolate_snapshot), // std::move(on_create_platform_view), // std::move(on_create_rasterizer), // std::move(on_create_engine), is_gpu_disabled); latch.Signal(); })); latch.Wait(); return shell; } Shell::Shell(DartVMRef vm, TaskRunners task_runners, fml::RefPtr parent_merger, Settings settings, std::shared_ptr volatile_path_tracker, bool is_gpu_disabled) : task_runners_(std::move(task_runners)), parent_raster_thread_merger_(parent_merger), settings_(std::move(settings)), vm_(std::move(vm)), is_gpu_disabled_sync_switch_(new fml::SyncSwitch(is_gpu_disabled)), volatile_path_tracker_(std::move(volatile_path_tracker)), weak_factory_gpu_(nullptr), weak_factory_(this) { FML_CHECK(vm_) << ""Must have access to VM to create a shell.""; FML_DCHECK(task_runners_.IsValid()); FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()); display_manager_ = std::make_unique(); // Generate a WeakPtrFactory for use with the raster thread. This does not // need to wait on a latch because it can only ever be used from the raster // thread from this class, so we have ordering guarantees. fml::TaskRunner::RunNowOrPostTask( task_runners_.GetRasterTaskRunner(), fml::MakeCopyable([this]() mutable { this->weak_factory_gpu_ = std::make_unique>(this); })); // Install service protocol handlers. service_protocol_handlers_[ServiceProtocol::kScreenshotExtensionName] = { task_runners_.GetRasterTaskRunner(), std::bind(&Shell::OnServiceProtocolScreenshot, this, std::placeholders::_1, std::placeholders::_2)}; service_protocol_handlers_[ServiceProtocol::kScreenshotSkpExtensionName] = { task_runners_.GetRasterTaskRunner(), std::bind(&Shell::OnServiceProtocolScreenshotSKP, this, std::placeholders::_1, std::placeholders::_2)}; service_protocol_handlers_[ServiceProtocol::kRunInViewExtensionName] = { task_runners_.GetUITaskRunner(), std::bind(&Shell::OnServiceProtocolRunInView, this, std::placeholders::_1, std::placeholders::_2)}; service_protocol_handlers_ [ServiceProtocol::kFlushUIThreadTasksExtensionName] = { task_runners_.GetUITaskRunner(), std::bind(&Shell::OnServiceProtocolFlushUIThreadTasks, this, std::placeholders::_1, std::placeholders::_2)}; service_protocol_handlers_ [ServiceProtocol::kSetAssetBundlePathExtensionName] = { task_runners_.GetUITaskRunner(), std::bind(&Shell::OnServiceProtocolSetAssetBundlePath, this, std::placeholders::_1, std::placeholders::_2)}; service_protocol_handlers_ [ServiceProtocol::kGetDisplayRefreshRateExtensionName] = { task_runners_.GetUITaskRunner(), std::bind(&Shell::OnServiceProtocolGetDisplayRefreshRate, this, std::placeholders::_1, std::placeholders::_2)}; service_protocol_handlers_[ServiceProtocol::kGetSkSLsExtensionName] = { task_runners_.GetIOTaskRunner(), std::bind(&Shell::OnServiceProtocolGetSkSLs, this, std::placeholders::_1, std::placeholders::_2)}; service_protocol_handlers_ [ServiceProtocol::kEstimateRasterCacheMemoryExtensionName] = { task_runners_.GetRasterTaskRunner(), std::bind(&Shell::OnServiceProtocolEstimateRasterCacheMemory, this, std::placeholders::_1, std::placeholders::_2)}; } Shell::~Shell() { PersistentCache::GetCacheForProcess()->RemoveWorkerTaskRunner( task_runners_.GetIOTaskRunner()); vm_->GetServiceProtocol()->RemoveHandler(this); fml::AutoResetWaitableEvent ui_latch, gpu_latch, platform_latch, io_latch; fml::TaskRunner::RunNowOrPostTask( task_runners_.GetUITaskRunner(), fml::MakeCopyable([this, &ui_latch]() mutable { engine_.reset(); ui_latch.Signal(); })); ui_latch.Wait(); fml::TaskRunner::RunNowOrPostTask( task_runners_.GetRasterTaskRunner(), fml::MakeCopyable( [this, rasterizer = std::move(rasterizer_), &gpu_latch]() mutable { rasterizer.reset(); this->weak_factory_gpu_.reset(); gpu_latch.Signal(); })); gpu_latch.Wait(); fml::TaskRunner::RunNowOrPostTask( task_runners_.GetIOTaskRunner(), fml::MakeCopyable([io_manager = std::move(io_manager_), platform_view = platform_view_.get(), &io_latch]() mutable { io_manager.reset(); if (platform_view) { platform_view->ReleaseResourceContext(); } io_latch.Signal(); })); io_latch.Wait(); // The platform view must go last because it may be holding onto platform side // counterparts to resources owned by subsystems running on other threads. For // example, the NSOpenGLContext on the Mac. fml::TaskRunner::RunNowOrPostTask( task_runners_.GetPlatformTaskRunner(), fml::MakeCopyable([platform_view = std::move(platform_view_), &platform_latch]() mutable { platform_view.reset(); platform_latch.Signal(); })); platform_latch.Wait(); } std::unique_ptr Shell::Spawn( RunConfiguration run_configuration, const std::string& initial_route, const CreateCallback& on_create_platform_view, const CreateCallback& on_create_rasterizer) const { FML_DCHECK(task_runners_.IsValid()); // It's safe to store this value since it is set on the platform thread. bool is_gpu_disabled = false; GetIsGpuDisabledSyncSwitch()->Execute( fml::SyncSwitch::Handlers() .SetIfFalse([&is_gpu_disabled] { is_gpu_disabled = false; }) .SetIfTrue([&is_gpu_disabled] { is_gpu_disabled = true; })); std::unique_ptr result = CreateWithSnapshot( PlatformData{}, task_runners_, rasterizer_->GetRasterThreadMerger(), io_manager_, GetSettings(), vm_, vm_->GetVMData()->GetIsolateSnapshot(), on_create_platform_view, on_create_rasterizer, [engine = this->engine_.get(), initial_route]( Engine::Delegate& delegate, const PointerDataDispatcherMaker& dispatcher_maker, DartVM& vm, fml::RefPtr isolate_snapshot, TaskRunners task_runners, const PlatformData& platform_data, Settings settings, std::unique_ptr animator, fml::WeakPtr io_manager, fml::RefPtr unref_queue, fml::WeakPtr snapshot_delegate, std::shared_ptr volatile_path_tracker) { return engine->Spawn(/*delegate=*/delegate, /*dispatcher_maker=*/dispatcher_maker, /*settings=*/settings, /*animator=*/std::move(animator), /*initial_route=*/initial_route, /*io_manager=*/std::move(io_manager)); }, is_gpu_disabled); result->shared_resource_context_ = io_manager_->GetSharedResourceContext(); result->RunEngine(std::move(run_configuration)); return result; } void Shell::NotifyLowMemoryWarning() const { auto trace_id = fml::tracing::TraceNonce(); TRACE_EVENT_ASYNC_BEGIN0(""flutter"", ""Shell::NotifyLowMemoryWarning"", trace_id); // This does not require a current isolate but does require a running VM. // Since a valid shell will not be returned to the embedder without a valid // DartVMRef, we can be certain that this is a safe spot to assume a VM is // running. ::Dart_NotifyLowMemory(); task_runners_.GetRasterTaskRunner()->PostTask( [rasterizer = rasterizer_->GetWeakPtr(), trace_id = trace_id]() { if (rasterizer) { rasterizer->NotifyLowMemoryWarning(); } TRACE_EVENT_ASYNC_END0(""flutter"", ""Shell::NotifyLowMemoryWarning"", trace_id); }); // The IO Manager uses resource cache limits of 0, so it is not necessary // to purge them. } void Shell::RunEngine(RunConfiguration run_configuration) { RunEngine(std::move(run_configuration), nullptr); } void Shell::RunEngine( RunConfiguration run_configuration, const std::function& result_callback) { auto result = [platform_runner = task_runners_.GetPlatformTaskRunner(), result_callback](Engine::RunStatus run_result) { if (!result_callback) { return; } platform_runner->PostTask( [result_callback, run_result]() { result_callback(run_result); }); }; FML_DCHECK(is_setup_); FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()); fml::TaskRunner::RunNowOrPostTask( task_runners_.GetUITaskRunner(), fml::MakeCopyable( [run_configuration = std::move(run_configuration), weak_engine = weak_engine_, result]() mutable { if (!weak_engine) { FML_LOG(ERROR) << ""Could not launch engine with configuration - no engine.""; result(Engine::RunStatus::Failure); return; } auto run_result = weak_engine->Run(std::move(run_configuration)); if (run_result == flutter::Engine::RunStatus::Failure) { FML_LOG(ERROR) << ""Could not launch engine with configuration.""; } result(run_result); })); } std::optional Shell::GetUIIsolateLastError() const { FML_DCHECK(is_setup_); FML_DCHECK(task_runners_.GetUITaskRunner()->RunsTasksOnCurrentThread()); if (!weak_engine_) { return std::nullopt; } switch (weak_engine_->GetUIIsolateLastError()) { case tonic::kCompilationErrorType: return DartErrorCode::CompilationError; case tonic::kApiErrorType: return DartErrorCode::ApiError; case tonic::kUnknownErrorType: return DartErrorCode::UnknownError; case tonic::kNoError: return DartErrorCode::NoError; } return DartErrorCode::UnknownError; } bool Shell::EngineHasLivePorts() const { FML_DCHECK(is_setup_); FML_DCHECK(task_runners_.GetUITaskRunner()->RunsTasksOnCurrentThread()); if (!weak_engine_) { return false; } return weak_engine_->UIIsolateHasLivePorts(); } bool Shell::IsSetup() const { return is_setup_; } bool Shell::Setup(std::unique_ptr platform_view, std::unique_ptr engine, std::unique_ptr rasterizer, std::shared_ptr io_manager) { if (is_setup_) { return false; } if (!platform_view || !engine || !rasterizer || !io_manager) { return false; } platform_view_ = std::move(platform_view); platform_message_handler_ = platform_view_->GetPlatformMessageHandler(); engine_ = std::move(engine); rasterizer_ = std::move(rasterizer); io_manager_ = io_manager; // Set the external view embedder for the rasterizer. auto view_embedder = platform_view_->CreateExternalViewEmbedder(); rasterizer_->SetExternalViewEmbedder(view_embedder); rasterizer_->SetSnapshotSurfaceProducer( platform_view_->CreateSnapshotSurfaceProducer()); // The weak ptr must be generated in the platform thread which owns the unique // ptr. weak_engine_ = engine_->GetWeakPtr(); weak_rasterizer_ = rasterizer_->GetWeakPtr(); weak_platform_view_ = platform_view_->GetWeakPtr(); // Setup the time-consuming default font manager right after engine created. if (!settings_.prefetched_default_font_manager) { fml::TaskRunner::RunNowOrPostTask(task_runners_.GetUITaskRunner(), [engine = weak_engine_] { if (engine) { engine->SetupDefaultFontManager(); } }); } is_setup_ = true; PersistentCache::GetCacheForProcess()->AddWorkerTaskRunner( task_runners_.GetIOTaskRunner()); PersistentCache::GetCacheForProcess()->SetIsDumpingSkp( settings_.dump_skp_on_shader_compilation); if (settings_.purge_persistent_cache) { PersistentCache::GetCacheForProcess()->Purge(); } return true; } const Settings& Shell::GetSettings() const { return settings_; } const TaskRunners& Shell::GetTaskRunners() const { return task_runners_; } const fml::RefPtr Shell::GetParentRasterThreadMerger() const { return parent_raster_thread_merger_; } fml::TaskRunnerAffineWeakPtr Shell::GetRasterizer() const { FML_DCHECK(is_setup_); return weak_rasterizer_; } fml::WeakPtr Shell::GetEngine() { FML_DCHECK(is_setup_); return weak_engine_; } fml::WeakPtr Shell::GetPlatformView() { FML_DCHECK(is_setup_); return weak_platform_view_; } fml::WeakPtr Shell::GetIOManager() { FML_DCHECK(is_setup_); return io_manager_->GetWeakPtr(); } DartVM* Shell::GetDartVM() { return &vm_; } // |PlatformView::Delegate| void Shell::OnPlatformViewCreated(std::unique_ptr surface) { TRACE_EVENT0(""flutter"", ""Shell::OnPlatformViewCreated""); FML_DCHECK(is_setup_); FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()); // Prevent any request to change the thread configuration for raster and // platform queues while the platform view is being created. // // This prevents false positives such as this method starts assuming that the // raster and platform queues have a given thread configuration, but then the // configuration is changed by a task, and the assumption is no longer true. // // This incorrect assumption can lead to deadlock. // See `should_post_raster_task` for more. rasterizer_->DisableThreadMergerIfNeeded(); // The normal flow executed by this method is that the platform thread is // starting the sequence and waiting on the latch. Later the UI thread posts // raster_task to the raster thread which signals the latch. If the raster and // the platform threads are the same this results in a deadlock as the // raster_task will never be posted to the platform/raster thread that is // blocked on a latch. To avoid the described deadlock, if the raster and the // platform threads are the same, should_post_raster_task will be false, and // then instead of posting a task to the raster thread, the ui thread just // signals the latch and the platform/raster thread follows with executing // raster_task. const bool should_post_raster_task = !task_runners_.GetRasterTaskRunner()->RunsTasksOnCurrentThread(); fml::AutoResetWaitableEvent latch; auto raster_task = fml::MakeCopyable([&waiting_for_first_frame = waiting_for_first_frame_, rasterizer = rasterizer_->GetWeakPtr(), // surface = std::move(surface)]() mutable { if (rasterizer) { // Enables the thread merger which may be used by the external view // embedder. rasterizer->EnableThreadMergerIfNeeded(); rasterizer->Setup(std::move(surface)); } waiting_for_first_frame.store(true); }); // TODO(91717): This probably isn't necessary. The engine should be able to // handle things here via normal lifecycle messages. // https://github.com/flutter/flutter/issues/91717 auto ui_task = [engine = engine_->GetWeakPtr()] { if (engine) { engine->OnOutputSurfaceCreated(); } }; // Threading: Capture platform view by raw pointer and not the weak pointer. // We are going to use the pointer on the IO thread which is not safe with a // weak pointer. However, we are preventing the platform view from being // collected by using a latch. auto* platform_view = platform_view_.get(); FML_DCHECK(platform_view); auto io_task = [io_manager = io_manager_->GetWeakPtr(), platform_view, ui_task_runner = task_runners_.GetUITaskRunner(), ui_task, shared_resource_context = shared_resource_context_, raster_task_runner = task_runners_.GetRasterTaskRunner(), raster_task, should_post_raster_task, &latch] { if (io_manager && !io_manager->GetResourceContext()) { sk_sp resource_context; if (shared_resource_context) { resource_context = shared_resource_context; } else { resource_context = platform_view->CreateResourceContext(); } io_manager->NotifyResourceContextAvailable(resource_context); } // Step 1: Post a task on the UI thread to tell the engine that it has // an output surface. fml::TaskRunner::RunNowOrPostTask(ui_task_runner, ui_task); // Step 2: Tell the raster thread that it should create a surface for // its rasterizer. if (should_post_raster_task) { fml::TaskRunner::RunNowOrPostTask(raster_task_runner, raster_task); } latch.Signal(); }; fml::TaskRunner::RunNowOrPostTask(task_runners_.GetIOTaskRunner(), io_task); latch.Wait(); if (!should_post_raster_task) { // See comment on should_post_raster_task, in this case the raster_task // wasn't executed, and we just run it here as the platform thread // is the raster thread. raster_task(); } } // |PlatformView::Delegate| void Shell::OnPlatformViewDestroyed() { TRACE_EVENT0(""flutter"", ""Shell::OnPlatformViewDestroyed""); FML_DCHECK(is_setup_); FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()); // Prevent any request to change the thread configuration for raster and // platform queues while the platform view is being destroyed. // // This prevents false positives such as this method starts assuming that the // raster and platform queues have a given thread configuration, but then the // configuration is changed by a task, and the assumption is no longer true. // // This incorrect assumption can lead to deadlock. rasterizer_->DisableThreadMergerIfNeeded(); // Note: // This is a synchronous operation because certain platforms depend on // setup/suspension of all activities that may be interacting with the GPU in // a synchronous fashion. // The UI thread does not need to be serialized here - there is sufficient // guardrailing in the rasterizer to allow the UI thread to post work to it // even after the surface has been torn down. fml::AutoResetWaitableEvent latch; auto io_task = [io_manager = io_manager_.get(), &latch]() { // Execute any pending Skia object deletions while GPU access is still // allowed. io_manager->GetIsGpuDisabledSyncSwitch()->Execute( fml::SyncSwitch::Handlers().SetIfFalse( [&] { io_manager->GetSkiaUnrefQueue()->Drain(); })); // Step 4: All done. Signal the latch that the platform thread is waiting // on. latch.Signal(); }; auto raster_task = [rasterizer = rasterizer_->GetWeakPtr(), io_task_runner = task_runners_.GetIOTaskRunner(), io_task]() { if (rasterizer) { // Enables the thread merger which is required prior tearing down the // rasterizer. If the raster and platform threads are merged, tearing down // the rasterizer unmerges the threads. rasterizer->EnableThreadMergerIfNeeded(); rasterizer->Teardown(); } // Step 3: Tell the IO thread to complete its remaining work. fml::TaskRunner::RunNowOrPostTask(io_task_runner, io_task); }; // TODO(91717): This probably isn't necessary. The engine should be able to // handle things here via normal lifecycle messages. // https://github.com/flutter/flutter/issues/91717 auto ui_task = [engine = engine_->GetWeakPtr()]() { if (engine) { engine->OnOutputSurfaceDestroyed(); } }; // Step 1: Post a task onto the UI thread to tell the engine that its output // surface is about to go away. fml::TaskRunner::RunNowOrPostTask(task_runners_.GetUITaskRunner(), ui_task); // Step 2: Post a task to the Raster thread (possibly this thread) to tell the // rasterizer the output surface is going away. fml::TaskRunner::RunNowOrPostTask(task_runners_.GetRasterTaskRunner(), raster_task); latch.Wait(); } // |PlatformView::Delegate| void Shell::OnPlatformViewSetViewportMetrics(const ViewportMetrics& metrics) { FML_DCHECK(is_setup_); FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()); if (metrics.device_pixel_ratio <= 0 || metrics.physical_width <= 0 || metrics.physical_height <= 0) { FML_DLOG(ERROR) << ""Embedding reported invalid ViewportMetrics, ignoring update."" << ""\\nphysical_width: "" << metrics.physical_width << ""\\nphysical_height: "" << metrics.physical_height << ""\\ndevice_pixel_ratio: "" << metrics.device_pixel_ratio; return; } // This is the formula Android uses. // https://android.googlesource.com/platform/frameworks/base/+/master/libs/hwui/renderthread/CacheManager.cpp#41 size_t max_bytes = metrics.physical_width * metrics.physical_height * 12 * 4; task_runners_.GetRasterTaskRunner()->PostTask( [rasterizer = rasterizer_->GetWeakPtr(), max_bytes] { if (rasterizer) { rasterizer->SetResourceCacheMaxBytes(max_bytes, false); } }); task_runners_.GetUITaskRunner()->PostTask( [engine = engine_->GetWeakPtr(), metrics]() { if (engine) { engine->SetViewportMetrics(metrics); } }); { std::scoped_lock lock(resize_mutex_); expected_frame_size_ = SkISize::Make(metrics.physical_width, metrics.physical_height); } } // |PlatformView::Delegate| void Shell::OnPlatformViewDispatchPlatformMessage( std::unique_ptr message) { FML_DCHECK(is_setup_); FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()); task_runners_.GetUITaskRunner()->PostTask(fml::MakeCopyable( [engine = engine_->GetWeakPtr(), message = std::move(message)]() mutable { if (engine) { engine->DispatchPlatformMessage(std::move(message)); } })); } // |PlatformView::Delegate| void Shell::OnPlatformViewDispatchPointerDataPacket( std::unique_ptr packet) { TRACE_EVENT0(""flutter"", ""Shell::OnPlatformViewDispatchPointerDataPacket""); TRACE_FLOW_BEGIN(""flutter"", ""PointerEvent"", next_pointer_flow_id_); FML_DCHECK(is_setup_); FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()); task_runners_.GetUITaskRunner()->PostTask( fml::MakeCopyable([engine = weak_engine_, packet = std::move(packet), flow_id = next_pointer_flow_id_]() mutable { if (engine) { engine->DispatchPointerDataPacket(std::move(packet), flow_id); } })); next_pointer_flow_id_++; } // |PlatformView::Delegate| void Shell::OnPlatformViewDispatchSemanticsAction(int32_t id, SemanticsAction action, fml::MallocMapping args) { FML_DCHECK(is_setup_); FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()); task_runners_.GetUITaskRunner()->PostTask( fml::MakeCopyable([engine = engine_->GetWeakPtr(), id, action, args = std::move(args)]() mutable { if (engine) { engine->DispatchSemanticsAction(id, action, std::move(args)); } })); } // |PlatformView::Delegate| void Shell::OnPlatformViewSetSemanticsEnabled(bool enabled) { FML_DCHECK(is_setup_); FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()); task_runners_.GetUITaskRunner()->PostTask( [engine = engine_->GetWeakPtr(), enabled] { if (engine) { engine->SetSemanticsEnabled(enabled); } }); } // |PlatformView::Delegate| void Shell::OnPlatformViewSetAccessibilityFeatures(int32_t flags) { FML_DCHECK(is_setup_); FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()); task_runners_.GetUITaskRunner()->PostTask( [engine = engine_->GetWeakPtr(), flags] { if (engine) { engine->SetAccessibilityFeatures(flags); } }); } // |PlatformView::Delegate| void Shell::OnPlatformViewRegisterTexture( std::shared_ptr texture) { FML_DCHECK(is_setup_); FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()); task_runners_.GetRasterTaskRunner()->PostTask( [rasterizer = rasterizer_->GetWeakPtr(), texture] { if (rasterizer) { if (auto* registry = rasterizer->GetTextureRegistry()) { registry->RegisterTexture(texture); } } }); } // |PlatformView::Delegate| void Shell::OnPlatformViewUnregisterTexture(int64_t texture_id) { FML_DCHECK(is_setup_); FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()); task_runners_.GetRasterTaskRunner()->PostTask( [rasterizer = rasterizer_->GetWeakPtr(), texture_id]() { if (rasterizer) { if (auto* registry = rasterizer->GetTextureRegistry()) { registry->UnregisterTexture(texture_id); } } }); } // |PlatformView::Delegate| void Shell::OnPlatformViewMarkTextureFrameAvailable(int64_t texture_id) { FML_DCHECK(is_setup_); FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()); // Tell the rasterizer that one of its textures has a new frame available. task_runners_.GetRasterTaskRunner()->PostTask( [rasterizer = rasterizer_->GetWeakPtr(), texture_id]() { auto* registry = rasterizer->GetTextureRegistry(); if (!registry) { return; } auto texture = registry->GetTexture(texture_id); if (!texture) { return; } texture->MarkNewFrameAvailable(); }); // Schedule a new frame without having to rebuild the layer tree. task_runners_.GetUITaskRunner()->PostTask([engine = engine_->GetWeakPtr()]() { if (engine) { engine->ScheduleFrame(false); } }); } // |PlatformView::Delegate| void Shell::OnPlatformViewSetNextFrameCallback(const fml::closure& closure) { FML_DCHECK(is_setup_); FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()); task_runners_.GetRasterTaskRunner()->PostTask( [rasterizer = rasterizer_->GetWeakPtr(), closure = closure]() { if (rasterizer) { rasterizer->SetNextFrameCallback(std::move(closure)); } }); } // |Animator::Delegate| void Shell::OnAnimatorBeginFrame(fml::TimePoint frame_target_time, uint64_t frame_number) { FML_DCHECK(is_setup_); FML_DCHECK(task_runners_.GetUITaskRunner()->RunsTasksOnCurrentThread()); // record the target time for use by rasterizer. { std::scoped_lock time_recorder_lock(time_recorder_mutex_); latest_frame_target_time_.emplace(frame_target_time); } if (engine_) { engine_->BeginFrame(frame_target_time, frame_number); } } // |Animator::Delegate| void Shell::OnAnimatorNotifyIdle(int64_t deadline) { FML_DCHECK(is_setup_); FML_DCHECK(task_runners_.GetUITaskRunner()->RunsTasksOnCurrentThread()); if (engine_) { engine_->NotifyIdle(deadline); volatile_path_tracker_->OnFrame(); } } // |Animator::Delegate| void Shell::OnAnimatorDraw( std::shared_ptr> pipeline, std::unique_ptr frame_timings_recorder) { FML_DCHECK(is_setup_); // record the target time for use by rasterizer. { std::scoped_lock time_recorder_lock(time_recorder_mutex_); const fml::TimePoint frame_target_time = frame_timings_recorder->GetVsyncTargetTime(); if (!latest_frame_target_time_) { latest_frame_target_time_ = frame_target_time; } else if (latest_frame_target_time_ < frame_target_time) { latest_frame_target_time_ = frame_target_time; } } auto discard_callback = [this](flutter::LayerTree& tree) { std::scoped_lock lock(resize_mutex_); return !expected_frame_size_.isEmpty() && tree.frame_size() != expected_frame_size_; }; task_runners_.GetRasterTaskRunner()->PostTask(fml::MakeCopyable( [&waiting_for_first_frame = waiting_for_first_frame_, &waiting_for_first_frame_condition = waiting_for_first_frame_condition_, rasterizer = rasterizer_->GetWeakPtr(), weak_pipeline = std::weak_ptr>(pipeline), discard_callback = std::move(discard_callback), frame_timings_recorder = std::move(frame_timings_recorder)]() mutable { if (rasterizer) { std::shared_ptr> pipeline = weak_pipeline.lock(); if (pipeline) { rasterizer->Draw(std::move(frame_timings_recorder), std::move(pipeline), std::move(discard_callback)); } if (waiting_for_first_frame.load()) { waiting_for_first_frame.store(false); waiting_for_first_frame_condition.notify_all(); } } })); } // |Animator::Delegate| void Shell::OnAnimatorDrawLastLayerTree( std::unique_ptr frame_timings_recorder) { FML_DCHECK(is_setup_); auto task = fml::MakeCopyable( [rasterizer = rasterizer_->GetWeakPtr(), frame_timings_recorder = std::move(frame_timings_recorder)]() mutable { if (rasterizer) { rasterizer->DrawLastLayerTree(std::move(frame_timings_recorder)); } }); task_runners_.GetRasterTaskRunner()->PostTask(task); } // |Engine::Delegate| void Shell::OnEngineUpdateSemantics(SemanticsNodeUpdates update, CustomAccessibilityActionUpdates actions) { FML_DCHECK(is_setup_); FML_DCHECK(task_runners_.GetUITaskRunner()->RunsTasksOnCurrentThread()); task_runners_.GetPlatformTaskRunner()->PostTask( [view = platform_view_->GetWeakPtr(), update = std::move(update), actions = std::move(actions)] { if (view) { view->UpdateSemantics(std::move(update), std::move(actions)); } }); } // |Engine::Delegate| void Shell::OnEngineHandlePlatformMessage( std::unique_ptr message) { FML_DCHECK(is_setup_); FML_DCHECK(task_runners_.GetUITaskRunner()->RunsTasksOnCurrentThread()); if (message->channel() == kSkiaChannel) { HandleEngineSkiaMessage(std::move(message)); return; } if (platform_message_handler_) { platform_message_handler_->HandlePlatformMessage(std::move(message)); } else { task_runners_.GetPlatformTaskRunner()->PostTask( fml::MakeCopyable([view = platform_view_->GetWeakPtr(), message = std::move(message)]() mutable { if (view) { view->HandlePlatformMessage(std::move(message)); } })); } } void Shell::HandleEngineSkiaMessage(std::unique_ptr message) { const auto& data = message->data(); rapidjson::Document document; document.Parse(reinterpret_cast(data.GetMapping()), data.GetSize()); if (document.HasParseError() || !document.IsObject()) { return; } auto root = document.GetObject(); auto method = root.FindMember(""method""); if (method->value != ""Skia.setResourceCacheMaxBytes"") { return; } auto args = root.FindMember(""args""); if (args == root.MemberEnd() || !args->value.IsInt()) { return; } task_runners_.GetRasterTaskRunner()->PostTask( [rasterizer = rasterizer_->GetWeakPtr(), max_bytes = args->value.GetInt(), response = std::move(message->response())] { if (rasterizer) { rasterizer->SetResourceCacheMaxBytes(static_cast(max_bytes), true); } if (response) { // The framework side expects this to be valid json encoded as a list. // Return `[true]` to signal success. std::vector data = {'[', 't', 'r', 'u', 'e', ']'}; response->Complete( std::make_unique(std::move(data))); } }); } // |Engine::Delegate| void Shell::OnPreEngineRestart() { FML_DCHECK(is_setup_); FML_DCHECK(task_runners_.GetUITaskRunner()->RunsTasksOnCurrentThread()); fml::AutoResetWaitableEvent latch; fml::TaskRunner::RunNowOrPostTask( task_runners_.GetPlatformTaskRunner(), [view = platform_view_->GetWeakPtr(), &latch]() { if (view) { view->OnPreEngineRestart(); } latch.Signal(); }); // This is blocking as any embedded platform views has to be flushed before // we re-run the Dart code. latch.Wait(); } // |Engine::Delegate| void Shell::OnRootIsolateCreated() { if (is_added_to_service_protocol_) { return; } auto description = GetServiceProtocolDescription(); fml::TaskRunner::RunNowOrPostTask( task_runners_.GetPlatformTaskRunner(), [self = weak_factory_.GetWeakPtr(), description = std::move(description)]() { if (self) { self->vm_->GetServiceProtocol()->AddHandler(self.get(), description); } }); is_added_to_service_protocol_ = true; } // |Engine::Delegate| void Shell::UpdateIsolateDescription(const std::string isolate_name, int64_t isolate_port) { Handler::Description description(isolate_port, isolate_name); vm_->GetServiceProtocol()->SetHandlerDescription(this, description); } void Shell::SetNeedsReportTimings(bool value) { needs_report_timings_ = value; } // |Engine::Delegate| std::unique_ptr> Shell::ComputePlatformResolvedLocale( const std::vector& supported_locale_data) { return platform_view_->ComputePlatformResolvedLocales(supported_locale_data); } void Shell::LoadDartDeferredLibrary( intptr_t loading_unit_id, std::unique_ptr snapshot_data, std::unique_ptr snapshot_instructions) { task_runners_.GetUITaskRunner()->PostTask(fml::MakeCopyable( [engine = engine_->GetWeakPtr(), loading_unit_id, data = std::move(snapshot_data), instructions = std::move(snapshot_instructions)]() mutable { if (engine) { engine->LoadDartDeferredLibrary(loading_unit_id, std::move(data), std::move(instructions)); } })); } void Shell::LoadDartDeferredLibraryError(intptr_t loading_unit_id, const std::string error_message, bool transient) { engine_->LoadDartDeferredLibraryError(loading_unit_id, error_message, transient); } void Shell::UpdateAssetResolverByType( std::unique_ptr updated_asset_resolver, AssetResolver::AssetResolverType type) { engine_->GetAssetManager()->UpdateResolverByType( std::move(updated_asset_resolver), type); } // |Engine::Delegate| void Shell::RequestDartDeferredLibrary(intptr_t loading_unit_id) { task_runners_.GetPlatformTaskRunner()->PostTask( [view = platform_view_->GetWeakPtr(), loading_unit_id] { if (view) { view->RequestDartDeferredLibrary(loading_unit_id); } }); } void Shell::ReportTimings() { FML_DCHECK(is_setup_); FML_DCHECK(task_runners_.GetRasterTaskRunner()->RunsTasksOnCurrentThread()); auto timings = std::move(unreported_timings_); unreported_timings_ = {}; task_runners_.GetUITaskRunner()->PostTask([timings, engine = weak_engine_] { if (engine) { engine->ReportTimings(std::move(timings)); } }); } size_t Shell::UnreportedFramesCount() const { // Check that this is running on the raster thread to avoid race conditions. FML_DCHECK(task_runners_.GetRasterTaskRunner()->RunsTasksOnCurrentThread()); FML_DCHECK(unreported_timings_.size() % (FrameTiming::kStatisticsCount) == 0); return unreported_timings_.size() / (FrameTiming::kStatisticsCount); } void Shell::OnFrameRasterized(const FrameTiming& timing) { FML_DCHECK(is_setup_); FML_DCHECK(task_runners_.GetRasterTaskRunner()->RunsTasksOnCurrentThread()); // The C++ callback defined in settings.h and set by Flutter runner. This is // independent of the timings report to the Dart side. if (settings_.frame_rasterized_callback) { settings_.frame_rasterized_callback(timing); } if (!needs_report_timings_) { return; } size_t old_count = unreported_timings_.size(); (void)old_count; for (auto phase : FrameTiming::kPhases) { unreported_timings_.push_back( timing.Get(phase).ToEpochDelta().ToMicroseconds()); } unreported_timings_.push_back(timing.GetLayerCacheCount()); unreported_timings_.push_back(timing.GetLayerCacheBytes()); unreported_timings_.push_back(timing.GetPictureCacheCount()); unreported_timings_.push_back(timing.GetPictureCacheBytes()); unreported_timings_.push_back(timing.GetFrameNumber()); FML_DCHECK(unreported_timings_.size() == old_count + FrameTiming::kStatisticsCount); // In tests using iPhone 6S with profile mode, sending a batch of 1 frame or a // batch of 100 frames have roughly the same cost of less than 0.1ms. Sending // a batch of 500 frames costs about 0.2ms. The 1 second threshold usually // kicks in before we reaching the following 100 frames threshold. The 100 // threshold here is mainly for unit tests (so we don't have to write a // 1-second unit test), and make sure that our vector won't grow too big with // future 120fps, 240fps, or 1000fps displays. // // In the profile/debug mode, the timings are used by development tools which // require a latency of no more than 100ms. Hence we lower that 1-second // threshold to 100ms because performance overhead isn't that critical in // those cases. if (!first_frame_rasterized_ || UnreportedFramesCount() >= 100) { first_frame_rasterized_ = true; ReportTimings(); } else if (!frame_timings_report_scheduled_) { #if FLUTTER_RELEASE constexpr int kBatchTimeInMilliseconds = 1000; #else constexpr int kBatchTimeInMilliseconds = 100; #endif // Also make sure that frame times get reported with a max latency of 1 // second. Otherwise, the timings of last few frames of an animation may // never be reported until the next animation starts. frame_timings_report_scheduled_ = true; task_runners_.GetRasterTaskRunner()->PostDelayedTask( [self = weak_factory_gpu_->GetWeakPtr()]() { if (!self) { return; } self->frame_timings_report_scheduled_ = false; if (self->UnreportedFramesCount() > 0) { self->ReportTimings(); } }, fml::TimeDelta::FromMilliseconds(kBatchTimeInMilliseconds)); } } fml::Milliseconds Shell::GetFrameBudget() { double display_refresh_rate = display_manager_->GetMainDisplayRefreshRate(); if (display_refresh_rate > 0) { return fml::RefreshRateToFrameBudget(display_refresh_rate); } else { return fml::kDefaultFrameBudget; } } fml::TimePoint Shell::GetLatestFrameTargetTime() const { std::scoped_lock time_recorder_lock(time_recorder_mutex_); FML_CHECK(latest_frame_target_time_.has_value()) << ""GetLatestFrameTargetTime called before OnAnimatorBeginFrame""; return latest_frame_target_time_.value(); } // |ServiceProtocol::Handler| fml::RefPtr Shell::GetServiceProtocolHandlerTaskRunner( std::string_view method) const { FML_DCHECK(is_setup_); auto found = service_protocol_handlers_.find(method); if (found != service_protocol_handlers_.end()) { return found->second.first; } return task_runners_.GetUITaskRunner(); } // |ServiceProtocol::Handler| bool Shell::HandleServiceProtocolMessage( std::string_view method, // one if the extension names specified above. const ServiceProtocolMap& params, rapidjson::Document* response) { auto found = service_protocol_handlers_.find(method); if (found != service_protocol_handlers_.end()) { return found->second.second(params, response); } return false; } // |ServiceProtocol::Handler| ServiceProtocol::Handler::Description Shell::GetServiceProtocolDescription() const { FML_DCHECK(task_runners_.GetUITaskRunner()->RunsTasksOnCurrentThread()); if (!weak_engine_) { return ServiceProtocol::Handler::Description(); } return { weak_engine_->GetUIIsolateMainPort(), weak_engine_->GetUIIsolateName(), }; } static void ServiceProtocolParameterError(rapidjson::Document* response, std::string error_details) { auto& allocator = response->GetAllocator(); response->SetObject(); const int64_t kInvalidParams = -32602; response->AddMember(""code"", kInvalidParams, allocator); response->AddMember(""message"", ""Invalid params"", allocator); { rapidjson::Value details(rapidjson::kObjectType); details.AddMember(""details"", error_details, allocator); response->AddMember(""data"", details, allocator); } } static void ServiceProtocolFailureError(rapidjson::Document* response, std::string message) { auto& allocator = response->GetAllocator(); response->SetObject(); const int64_t kJsonServerError = -32000; response->AddMember(""code"", kJsonServerError, allocator); response->AddMember(""message"", message, allocator); } // Service protocol handler bool Shell::OnServiceProtocolScreenshot( const ServiceProtocol::Handler::ServiceProtocolMap& params, rapidjson::Document* response) { FML_DCHECK(task_runners_.GetRasterTaskRunner()->RunsTasksOnCurrentThread()); auto screenshot = rasterizer_->ScreenshotLastLayerTree( Rasterizer::ScreenshotType::CompressedImage, true); if (screenshot.data) { response->SetObject(); auto& allocator = response->GetAllocator(); response->AddMember(""type"", ""Screenshot"", allocator); rapidjson::Value image; image.SetString(static_cast(screenshot.data->data()), screenshot.data->size(), allocator); response->AddMember(""screenshot"", image, allocator); return true; } ServiceProtocolFailureError(response, ""Could not capture image screenshot.""); return false; } // Service protocol handler bool Shell::OnServiceProtocolScreenshotSKP( const ServiceProtocol::Handler::ServiceProtocolMap& params, rapidjson::Document* response) { FML_DCHECK(task_runners_.GetRasterTaskRunner()->RunsTasksOnCurrentThread()); auto screenshot = rasterizer_->ScreenshotLastLayerTree( Rasterizer::ScreenshotType::SkiaPicture, true); if (screenshot.data) { response->SetObject(); auto& allocator = response->GetAllocator(); response->AddMember(""type"", ""ScreenshotSkp"", allocator); rapidjson::Value skp; skp.SetString(static_cast(screenshot.data->data()), screenshot.data->size(), allocator); response->AddMember(""skp"", skp, allocator); return true; } ServiceProtocolFailureError(response, ""Could not capture SKP screenshot.""); return false; } // Service protocol handler bool Shell::OnServiceProtocolRunInView( const ServiceProtocol::Handler::ServiceProtocolMap& params, rapidjson::Document* response) { FML_DCHECK(task_runners_.GetUITaskRunner()->RunsTasksOnCurrentThread()); if (params.count(""mainScript"") == 0) { ServiceProtocolParameterError(response, ""'mainScript' parameter is missing.""); return false; } if (params.count(""assetDirectory"") == 0) { ServiceProtocolParameterError(response, ""'assetDirectory' parameter is missing.""); return false; } std::string main_script_path = fml::paths::FromURI(params.at(""mainScript"").data()); std::string asset_directory_path = fml::paths::FromURI(params.at(""assetDirectory"").data()); auto main_script_file_mapping = std::make_unique(fml::OpenFile( main_script_path.c_str(), false, fml::FilePermission::kRead)); auto isolate_configuration = IsolateConfiguration::CreateForKernel( std::move(main_script_file_mapping)); RunConfiguration configuration(std::move(isolate_configuration)); configuration.SetEntrypointAndLibrary(engine_->GetLastEntrypoint(), engine_->GetLastEntrypointLibrary()); configuration.SetEntrypointArgs(engine_->GetLastEntrypointArgs()); configuration.AddAssetResolver(std::make_unique( fml::OpenDirectory(asset_directory_path.c_str(), false, fml::FilePermission::kRead), false)); // Preserve any original asset resolvers to avoid syncing unchanged assets // over the DevFS connection. auto old_asset_manager = engine_->GetAssetManager(); if (old_asset_manager != nullptr) { for (auto& old_resolver : old_asset_manager->TakeResolvers()) { if (old_resolver->IsValidAfterAssetManagerChange()) { configuration.AddAssetResolver(std::move(old_resolver)); } } } auto& allocator = response->GetAllocator(); response->SetObject(); if (engine_->Restart(std::move(configuration))) { response->AddMember(""type"", ""Success"", allocator); auto new_description = GetServiceProtocolDescription(); rapidjson::Value view(rapidjson::kObjectType); new_description.Write(this, view, allocator); response->AddMember(""view"", view, allocator); return true; } else { FML_DLOG(ERROR) << ""Could not run configuration in engine.""; ServiceProtocolFailureError(response, ""Could not run configuration in engine.""); return false; } FML_DCHECK(false); return false; } // Service protocol handler bool Shell::OnServiceProtocolFlushUIThreadTasks( const ServiceProtocol::Handler::ServiceProtocolMap& params, rapidjson::Document* response) { FML_DCHECK(task_runners_.GetUITaskRunner()->RunsTasksOnCurrentThread()); // This API should not be invoked by production code. // It can potentially starve the service isolate if the main isolate pauses // at a breakpoint or is in an infinite loop. // // It should be invoked from the VM Service and and blocks it until UI thread // tasks are processed. response->SetObject(); response->AddMember(""type"", ""Success"", response->GetAllocator()); return true; } bool Shell::OnServiceProtocolGetDisplayRefreshRate( const ServiceProtocol::Handler::ServiceProtocolMap& params, rapidjson::Document* response) { FML_DCHECK(task_runners_.GetUITaskRunner()->RunsTasksOnCurrentThread()); response->SetObject(); response->AddMember(""type"", ""DisplayRefreshRate"", response->GetAllocator()); response->AddMember(""fps"", display_manager_->GetMainDisplayRefreshRate(), response->GetAllocator()); return true; } double Shell::GetMainDisplayRefreshRate() { return display_manager_->GetMainDisplayRefreshRate(); } void Shell::RegisterImageDecoder(ImageGeneratorFactory factory, int32_t priority) { FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()); FML_DCHECK(is_setup_); fml::TaskRunner::RunNowOrPostTask( task_runners_.GetUITaskRunner(), [engine = engine_->GetWeakPtr(), factory = std::move(factory), priority]() { if (engine) { engine->GetImageGeneratorRegistry()->AddFactory(factory, priority); } }); } bool Shell::OnServiceProtocolGetSkSLs( const ServiceProtocol::Handler::ServiceProtocolMap& params, rapidjson::Document* response) { FML_DCHECK(task_runners_.GetIOTaskRunner()->RunsTasksOnCurrentThread()); response->SetObject(); response->AddMember(""type"", ""GetSkSLs"", response->GetAllocator()); rapidjson::Value shaders_json(rapidjson::kObjectType); PersistentCache* persistent_cache = PersistentCache::GetCacheForProcess(); std::vector sksls = persistent_cache->LoadSkSLs(); for (const auto& sksl : sksls) { size_t b64_size = SkBase64::Encode(sksl.value->data(), sksl.value->size(), nullptr); sk_sp b64_data = SkData::MakeUninitialized(b64_size + 1); char* b64_char = static_cast(b64_data->writable_data()); SkBase64::Encode(sksl.value->data(), sksl.value->size(), b64_char); b64_char[b64_size] = 0; // make it null terminated for printing rapidjson::Value shader_value(b64_char, response->GetAllocator()); std::string_view key_view(reinterpret_cast(sksl.key->data()), sksl.key->size()); auto encode_result = fml::Base32Encode(key_view); if (!encode_result.first) { continue; } rapidjson::Value shader_key(encode_result.second, response->GetAllocator()); shaders_json.AddMember(shader_key, shader_value, response->GetAllocator()); } response->AddMember(""SkSLs"", shaders_json, response->GetAllocator()); return true; } bool Shell::OnServiceProtocolEstimateRasterCacheMemory( const ServiceProtocol::Handler::ServiceProtocolMap& params, rapidjson::Document* response) { FML_DCHECK(task_runners_.GetRasterTaskRunner()->RunsTasksOnCurrentThread()); const auto& raster_cache = rasterizer_->compositor_context()->raster_cache(); response->SetObject(); response->AddMember(""type"", ""EstimateRasterCacheMemory"", response->GetAllocator()); response->AddMember(""layerBytes"", raster_cache.EstimateLayerCacheByteSize(), response->GetAllocator()); response->AddMember(""pictureBytes"", raster_cache.EstimatePictureCacheByteSize(), response->GetAllocator()); return true; } // Service protocol handler bool Shell::OnServiceProtocolSetAssetBundlePath( const ServiceProtocol::Handler::ServiceProtocolMap& params, rapidjson::Document* response) { FML_DCHECK(task_runners_.GetUITaskRunner()->RunsTasksOnCurrentThread()); if (params.count(""assetDirectory"") == 0) { ServiceProtocolParameterError(response, ""'assetDirectory' parameter is missing.""); return false; } auto& allocator = response->GetAllocator(); response->SetObject(); auto asset_manager = std::make_shared(); asset_manager->PushFront(std::make_unique( fml::OpenDirectory(params.at(""assetDirectory"").data(), false, fml::FilePermission::kRead), false)); // Preserve any original asset resolvers to avoid syncing unchanged assets // over the DevFS connection. auto old_asset_manager = engine_->GetAssetManager(); if (old_asset_manager != nullptr) { for (auto& old_resolver : old_asset_manager->TakeResolvers()) { if (old_resolver->IsValidAfterAssetManagerChange()) { asset_manager->PushBack(std::move(old_resolver)); } } } if (engine_->UpdateAssetManager(std::move(asset_manager))) { response->AddMember(""type"", ""Success"", allocator); auto new_description = GetServiceProtocolDescription(); rapidjson::Value view(rapidjson::kObjectType); new_description.Write(this, view, allocator); response->AddMember(""view"", view, allocator); return true; } else { FML_DLOG(ERROR) << ""Could not update asset directory.""; ServiceProtocolFailureError(response, ""Could not update asset directory.""); return false; } FML_DCHECK(false); return false; } Rasterizer::Screenshot Shell::Screenshot( Rasterizer::ScreenshotType screenshot_type, bool base64_encode) { TRACE_EVENT0(""flutter"", ""Shell::Screenshot""); fml::AutoResetWaitableEvent latch; Rasterizer::Screenshot screenshot; fml::TaskRunner::RunNowOrPostTask( task_runners_.GetRasterTaskRunner(), [&latch, // rasterizer = GetRasterizer(), // &screenshot, // screenshot_type, // base64_encode // ]() { if (rasterizer) { screenshot = rasterizer->ScreenshotLastLayerTree(screenshot_type, base64_encode); } latch.Signal(); }); latch.Wait(); return screenshot; } fml::Status Shell::WaitForFirstFrame(fml::TimeDelta timeout) { FML_DCHECK(is_setup_); if (task_runners_.GetUITaskRunner()->RunsTasksOnCurrentThread() || task_runners_.GetRasterTaskRunner()->RunsTasksOnCurrentThread()) { return fml::Status(fml::StatusCode::kFailedPrecondition, ""WaitForFirstFrame called from thread that can't wait "" ""because it is responsible for generating the frame.""); } // Check for overflow. auto now = std::chrono::steady_clock::now(); auto max_duration = std::chrono::steady_clock::time_point::max() - now; auto desired_duration = std::chrono::milliseconds(timeout.ToMilliseconds()); auto duration = now + (desired_duration > max_duration ? max_duration : desired_duration); std::unique_lock lock(waiting_for_first_frame_mutex_); bool success = waiting_for_first_frame_condition_.wait_until( lock, duration, [&waiting_for_first_frame = waiting_for_first_frame_] { return !waiting_for_first_frame.load(); }); if (success) { return fml::Status(); } else { return fml::Status(fml::StatusCode::kDeadlineExceeded, ""timeout""); } } bool Shell::ReloadSystemFonts() { FML_DCHECK(is_setup_); FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()); if (!engine_) { return false; } engine_->SetupDefaultFontManager(); engine_->GetFontCollection().GetFontCollection()->ClearFontFamilyCache(); // After system fonts are reloaded, we send a system channel message // to notify flutter framework. rapidjson::Document document; document.SetObject(); auto& allocator = document.GetAllocator(); rapidjson::Value message_value; message_value.SetString(kFontChange, allocator); document.AddMember(kTypeKey, message_value, allocator); rapidjson::StringBuffer buffer; rapidjson::Writer writer(buffer); document.Accept(writer); std::string message = buffer.GetString(); std::unique_ptr fontsChangeMessage = std::make_unique( kSystemChannel, fml::MallocMapping::Copy(message.c_str(), message.length()), nullptr); OnPlatformViewDispatchPlatformMessage(std::move(fontsChangeMessage)); return true; } std::shared_ptr Shell::GetIsGpuDisabledSyncSwitch() const { return is_gpu_disabled_sync_switch_; } void Shell::SetGpuAvailability(GpuAvailability availability) { FML_DCHECK(task_runners_.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()); switch (availability) { case GpuAvailability::kAvailable: is_gpu_disabled_sync_switch_->SetSwitch(false); return; case GpuAvailability::kFlushAndMakeUnavailable: { fml::AutoResetWaitableEvent latch; fml::TaskRunner::RunNowOrPostTask( task_runners_.GetIOTaskRunner(), [io_manager = io_manager_.get(), &latch]() { io_manager->GetSkiaUnrefQueue()->Drain(); latch.Signal(); }); latch.Wait(); } // FALLTHROUGH case GpuAvailability::kUnavailable: is_gpu_disabled_sync_switch_->SetSwitch(true); return; default: FML_DCHECK(false); } } void Shell::OnDisplayUpdates(DisplayUpdateType update_type, std::vector> displays) { display_manager_->HandleDisplayUpdates(update_type, std::move(displays)); } fml::TimePoint Shell::GetCurrentTimePoint() { return fml::TimePoint::Now(); } const std::shared_ptr& Shell::GetPlatformMessageHandler() const { return platform_message_handler_; } } // namespace flutter ",16361,True,2943.0578995790474,median "//// This guide is maintained in the main Quarkus repository and pull requests should be submitted there: https://github.com/quarkusio/quarkus/tree/main/docs/src/main/asciidoc //// = Building applications with Maven include::./attributes.adoc[] :devtools-no-gradle: [[project-creation]] == Creating a new project You can scaffold a new Maven project with: :create-app-group-id: my-groupId :create-app-artifact-id: my-artifactId :create-app-code: :create-app-post-command: include::includes/devtools/create-app.adoc[] If you are using the CLI, you can get the list of available options with: [source,bash] ---- quarkus create app --help ---- If you are using the Maven command, the following table lists the attributes you can pass to the `create` command: [cols=3*,options=""header""] |=== | Attribute | Default Value | Description | `projectGroupId` | `org.acme.sample` | The group id of the created project | `projectArtifactId` | _mandatory_ | The artifact id of the created project. Not passing it triggers the interactive mode. | `projectVersion` | `1.0.0-SNAPSHOT` | The version of the created project | `platformGroupId` | `io.quarkus.platform` | The group id of the target platform. | `platformArtifactId` | `quarkus-bom` | The artifact id of the target platform BOM. | `platformVersion` | The version currently recommended by the https://quarkus.io/guides/extension-registry-user[Quarkus Extension Registry] | The version of the platform you want the project to use. It can also accept a version range, in which case the latest from the specified range will be used. | `className` | _Not created if omitted_ | The fully qualified name of the generated resource | `path` | `/hello` | The resource path, only relevant if `className` is set. | `extensions` | _[]_ | The list of extensions to add to the project (comma-separated) | `quarkusRegistryClient` | `true` | Whether or not Quarkus should use the online registry to resolve extension catalogs. If this is set to false, the extension catalog will be narrowed to the defined (or default) platform BOM. |=== By default, the command will target the `io.quarkus.platform:quarkus-bom:{quarkus-version}` platform release (unless the coordinates of the desired platform release have been specified). The project is generated in a directory named after the passed artifactId. If the directory already exists, the generation fails. A pair of Dockerfiles for native and jvm mode are also generated in `src/main/docker`. Instructions to build the image and run the container are written in those Dockerfiles. == Dealing with extensions From inside a Quarkus project, you can obtain a list of the available extensions with: include::includes/devtools/extension-list.adoc[] You can add an extension using: :add-extension-extensions: hibernate-validator include::includes/devtools/extension-add.adoc[] Extensions are passed using a comma-separated list. The extension name is the GAV name of the extension: e.g. `io.quarkus:quarkus-agroal`. But you can pass a partial name and Quarkus will do its best to find the right extension. For example, `agroal`, `Agroal` or `agro` will expand to `io.quarkus:quarkus-agroal`. If no extension is found or if more than one extensions match, you will see a red check mark ❌ in the command result. [source,shell] ---- $ ./mvnw quarkus:add-extensions -Dextensions=jdbc,agroal,non-exist-ent [...] ❌ Multiple extensions matching 'jdbc' * io.quarkus:quarkus-jdbc-h2 * io.quarkus:quarkus-jdbc-mariadb * io.quarkus:quarkus-jdbc-postgresql Be more specific e.g using the exact name or the full gav. ✅ Adding extension io.quarkus:quarkus-agroal ❌ Cannot find a dependency matching 'non-exist-ent', maybe a typo? [...] ---- You can install all extensions which match a globbing pattern : :add-extension-extensions: smallrye-* include::includes/devtools/extension-add.adoc[] [[dev-mode]] == Development mode Quarkus comes with a built-in development mode. Run your application with: include::includes/devtools/dev.adoc[] You can then update the application sources, resources and configurations. The changes are automatically reflected in your running application. This is great to do development spanning UI and database as you see changes reflected immediately. Dev mode enables hot deployment with background compilation, which means that when you modify your Java files or your resource files and refresh your browser these changes will automatically take effect. This works too for resource files like the configuration property file. The act of refreshing the browser triggers a scan of the workspace, and if any changes are detected the Java files are compiled, and the application is redeployed, then your request is serviced by the redeployed application. If there are any issues with compilation or deployment an error page will let you know. Hit `CTRL+C` to stop the application. [NOTE] ==== By default, `quarkus:dev` sets the debug host to `localhost` (for security reasons). If you need to change this, for example to enable debugging on all hosts, you can use the `-DdebugHost` option like so: :dev-additional-parameters: -DdebugHost=0.0.0.0 include::includes/devtools/dev-parameters.adoc[] :!dev-additional-parameters: ==== === Remote Development Mode It is possible to use development mode remotely, so that you can run Quarkus in a container environment (such as OpenShift) and have changes made to your local files become immediately visible. This allows you to develop in the same environment you will actually run your app in, and with access to the same services. WARNING: Do not use this in production. This should only be used in a development environment. You should not run production application in dev mode. To do this you must build a mutable application, using the `mutable-jar` format. Set the following properties in `application.properties`: [source,properties] ---- quarkus.package.type=mutable-jar <1> quarkus.live-reload.password=changeit <2> quarkus.live-reload.url=http://my.cluster.host.com:8080 <3> ---- <1> This tells Quarkus to use the mutable-jar format. Mutable applications also include the deployment time parts of Quarkus, so they take up a bit more disk space. If run normally they start just as fast and use the same memory as an immutable application, however they can also be started in dev mode. <2> The password that is used to secure communication between the remote side and the local side. <3> The URL that your app is going to be running in dev mode at. This is only needed on the local side, so you may want to leave it out of the properties file and specify it as a system property on the command line. The `mutable-jar` is then built in the same way that a regular Quarkus jar is built, i.e. by issuing: include::includes/devtools/build.adoc[] Before you start Quarkus on the remote host set the environment variable `QUARKUS_LAUNCH_DEVMODE=true`. If you are on bare metal you can set it via the `export QUARKUS_LAUNCH_DEVMODE=true` command and then run the application with the proper `java -jar ...` command to run the application. If you plan on running the application via Docker, then you'll need to add `-e QUARKUS_LAUNCH_DEVMODE=true` to the `docker run` command. When the application starts you should now see the following line in the logs: `Profile dev activated. Live Coding activated`. NOTE: The remote side does not need to include Maven or any other development tools. The normal `fast-jar` Dockerfile that is generated with a new Quarkus application is all you need. If you are using bare metal launch the Quarkus runner jar, do not attempt to run normal devmode. Now you need to connect your local agent to the remote host, using the `remote-dev` command: [source,bash] ---- ./mvnw quarkus:remote-dev -Dquarkus.live-reload.url=http://my-remote-host:8080 ---- Now every time you refresh the browser you should see any changes you have made locally immediately visible in the remote app. This is done via a HTTP based long polling transport, that will synchronize your local workspace and the remote application via HTTP calls. If you do not want to use the HTTP feature then you can simply run the `remote-dev` command without specifying the URL. In this mode the command will continuously rebuild the local application, so you can use an external tool such as odo or rsync to sync to the remote application. All the config options are shown below: include::{generated-dir}/config/quarkus-live-reload-live-reload-config.adoc[opts=optional, leveloffset=+1] NOTE: It is recommended you use SSL when using remote dev mode, however even if you are using an unencrypted connection your password is never sent directly over the wire. For the initial connection request the password is hashed with the initial state data, and subsequent requests hash it with a random session id generated by the server and any body contents for POST requests, and the path for DELETE requests, as well as an incrementing counter to prevent replay attacks. === Configuring Development Mode By default, the Maven plugin picks up compiler flags to pass to `javac` from `maven-compiler-plugin`. If you need to customize the compiler flags used in development mode, add a `configuration` section to the `plugin` block and set the `compilerArgs` property just as you would when configuring `maven-compiler-plugin`. You can also set `source`, `target`, and `jvmArgs`. For example, to pass `--enable-preview` to both the JVM and `javac`: [source,xml] ---- ${quarkus.platform.group-id} quarkus-maven-plugin ${quarkus.platform.version} ${maven.compiler.source} ${maven.compiler.target} --enable-preview --enable-preview ... ---- == Debugging In development mode, Quarkus starts by default with debug mode enabled, listening to port `5005` without suspending the JVM. This behavior can be changed by giving the `debug` system property one of the following values: * `false` - the JVM will start with debug mode disabled * `true` - The JVM is started in debug mode and will be listening on port `5005` * `client` - the JVM will start in client mode and attempt to connect to `localhost:5005` * `{port}` - The JVM is started in debug mode and will be listening on `{port}` An additional system property `suspend` can be used to suspend the JVM, when launched in debug mode. `suspend` supports the following values: * `y` or `true` - The debug mode JVM launch is suspended * `n` or `false` - The debug mode JVM is started without suspending [TIP] ==== You can also run a Quarkus application in debug mode with a suspended JVM using: :dev-additional-parameters: -Dsuspend -Ddebug include::includes/devtools/dev-parameters.adoc[] :!dev-additional-parameters: Then, attach your debugger to `localhost:5005`. ==== == Import in your IDE Once you have a <>, you can import it in your favorite IDE. The only requirement is the ability to import a Maven project. **Eclipse** In Eclipse, click on: `File -> Import`. In the wizard, select: `Maven -> Existing Maven Project`. On the next screen, select the root location of the project. The next screen list the found modules; select the generated project and click on `Finish`. Done! In a separated terminal, run: include::includes/devtools/dev.adoc[] and enjoy a highly productive environment. **IntelliJ** In IntelliJ: 1. From inside IntelliJ select `File -> New -> Project From Existing Sources...` or, if you are on the welcome dialog, select `Import project`. 2. Select the project root 3. Select `Import project from external model` and `Maven` 4. Next a few times (review the different options if needed) 5. On the last screen click on Finish In a separated terminal or in the embedded terminal, run: include::includes/devtools/dev.adoc[] Enjoy! **Apache NetBeans** In NetBeans: 1. Select `File -> Open Project` 2. Select the project root 3. Click on `Open Project` In a separated terminal or the embedded terminal, go to the project root and run: include::includes/devtools/dev.adoc[] Enjoy! **Visual Studio Code** Open the project directory in VS Code. If you have installed the Java Extension Pack (grouping a set of Java extensions), the project is loaded as a Maven project. == Logging Quarkus application build classpath tree Usually, dependencies of an application (which is a Maven project) could be displayed using `mvn dependency:tree` command. In case of a Quarkus application, however, this command will list only the runtime dependencies of the application. Given that the Quarkus build process adds deployment dependencies of the extensions used in the application to the original application classpath, it could be useful to know which dependencies and which versions end up on the build classpath. Luckily, the `quarkus` Maven plugin includes the `dependency-tree` goal which displays the build dependency tree for the application. Executing `./mvnw quarkus:dependency-tree` on your project should result in an output similar to: [source,text,subs=attributes+] ---- [INFO] --- quarkus-maven-plugin:{quarkus-version}:dependency-tree (default-cli) @ getting-started --- [INFO] org.acme:getting-started:jar:1.0.0-SNAPSHOT [INFO] └─ io.quarkus:quarkus-resteasy-deployment:jar:{quarkus-version} (compile) [INFO] ├─ io.quarkus:quarkus-resteasy-server-common-deployment:jar:{quarkus-version} (compile) [INFO] │ ├─ io.quarkus:quarkus-core-deployment:jar:{quarkus-version} (compile) [INFO] │ │ ├─ commons-beanutils:commons-beanutils:jar:1.9.3 (compile) [INFO] │ │ │ ├─ commons-logging:commons-logging:jar:1.2 (compile) [INFO] │ │ │ └─ commons-collections:commons-collections:jar:3.2.2 (compile) ... ---- The goal accepts the following optional parameters: * `mode` - the default value is `prod`, i.e. the production build dependency tree. Alternatively, it accepts values `test` to display the test dependency tree and `dev` to display the dev mode dependency tree; * `outputFile` - specifies the file to persist the dependency tree to; * `appendOutput` - the default value is `false`, indicates whether the output to the command should be appended to the file specified with the `outputFile` parameter or it should be overriden. == Downloading Maven artifact dependencies for offline development and testing Quarkus extension dependencies are divided into the runtime extension dependencies that end up on the application runtime classpath and the deployment (or build time) extension dependencies that are resolved by Quarkus only at application build time to create the build classpath. Application developers are expected to express dependencies only on the runtime artifacts of Quarkus extensions. As a consequence, the deployment extension dependencies aren't visible to Maven plugins that aren't aware of the Quarkus extension dependency model, such as the `maven-dependency-plugin`, `go-offline-maven-plugin`, etc. That means those plugins can not be used to pre-download all the application dependencies to be able to build and test the application later in offline mode. To enable the use-case of building and testing a Quarkus application offline, the `quarkus-maven-plugin` includes the `go-offline` goal that could be called from the command line like this: [source,bash] ---- ./mvnw quarkus:go-offline ---- This goal will resolve all the runtime, build time, test and dev mode dependencies of the application downloading them to the configured local Maven repository. == Building a native executable Native executables make Quarkus applications ideal for containers and serverless workloads. Make sure to have `GRAALVM_HOME` configured and pointing to GraalVM version {graalvm-version} (Make sure to use a Java 11 version of GraalVM). Verify that your `pom.xml` has the proper `native` profile (see <>). Create a native executable using: include::includes/devtools/build-native.adoc[] A native executable will be present in `target/`. To run Integration Tests on the native executable, make sure to have the proper Maven plugin configured (see <>) and launch the `verify` goal. [source,shell] ---- $ ./mvnw verify -Pnative ... [quarkus-quickstart-runner:50955] universe: 391.96 ms [quarkus-quickstart-runner:50955] (parse): 904.37 ms [quarkus-quickstart-runner:50955] (inline): 1,143.32 ms [quarkus-quickstart-runner:50955] (compile): 6,228.44 ms [quarkus-quickstart-runner:50955] compile: 9,130.58 ms [quarkus-quickstart-runner:50955] image: 2,101.42 ms [quarkus-quickstart-runner:50955] write: 803.18 ms [quarkus-quickstart-runner:50955] [total]: 33,520.15 ms [INFO] [INFO] --- maven-failsafe-plugin:2.22.0:integration-test (default) @ quarkus-quickstart-native --- [INFO] [INFO] ------------------------------------------------------- [INFO] T E S T S [INFO] ------------------------------------------------------- [INFO] Running org.acme.quickstart.GreetingResourceIT Executing [/Users/starksm/Dev/JBoss/Quarkus/starksm64-quarkus-quickstarts/getting-started-native/target/quarkus-quickstart-runner, -Dquarkus.http.port=8081, -Dtest.url=http://localhost:8081, -Dquarkus.log.file.path=target/quarkus.log] 2019-02-28 16:52:42,020 INFO [io.quarkus] (main) Quarkus started in 0.007s. Listening on: http://localhost:8080 2019-02-28 16:52:42,021 INFO [io.quarkus] (main) Installed features: [cdi, resteasy] [INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.081 s - in org.acme.quickstart.GreetingResourceIT [INFO] [INFO] Results: [INFO] [INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0 ... ---- === Build a container friendly executable The native executable will be specific to your operating system. To create an executable that will run in a container, use the following: :build-additional-parameters: -Dquarkus.native.container-build=true include::includes/devtools/build-native.adoc[] :!build-additional-parameters: The produced executable will be a 64 bit Linux executable, so depending on your operating system it may no longer be runnable. However, it's not an issue as we are going to copy it to a Docker container. Note that in this case the build itself runs in a Docker container too, so you don't need to have GraalVM installed locally. [TIP] ==== By default, the native executable will be generated using the `quay.io/quarkus/ubi-quarkus-native-image:{graalvm-flavor}` Docker image. If you want to build a native executable with a different Docker image (for instance to use a different GraalVM version), use the `-Dquarkus.native.builder-image=` build argument. The list of the available Docker images can be found on https://quay.io/repository/quarkus/ubi-quarkus-native-image?tab=tags[quay.io]. Be aware that a given Quarkus version might not be compatible with all the images available. ==== You can follow the xref:building-native-image.adoc[Build a native executable guide] as well as xref:deploying-to-kubernetes.adoc[Deploying Application to Kubernetes and OpenShift] for more information. [[build-tool-maven]] == Maven configuration If you have not used <>, add the following elements in your `pom.xml` [source,xml,subs=attributes+] ---- <1> ${quarkus.platform.group-id} quarkus-bom ${quarkus.platform.version} pom import <2> ${quarkus.platform.group-id} quarkus-maven-plugin ${quarkus.platform.version} true <3> build generate-code generate-code-tests <4> org.apache.maven.plugins maven-surefire-plugin ${surefire-plugin.version} org.jboss.logmanager.LogManager ${maven.home} <5> native <6> native <7> org.apache.maven.plugins maven-failsafe-plugin ${surefire-plugin.version} integration-test verify ${project.build.directory}/${project.build.finalName}-runner org.jboss.logmanager.LogManager ${maven.home} ---- <1> Optionally use a BOM file to omit the version of the different Quarkus dependencies. <2> Use the Quarkus Maven plugin that will hook into the build process. <3> Enabling Maven plugin extensions will register a Quarkus `MavenLifecycleParticipant` which will make sure the Quarkus classloaders used during the build are properly closed. During the `generate-code` and `generate-code-tests` goals the Quarkus application bootstrap is initialized and re-used in the `build` goal (which actually builds and packages a production application). The Quarkus classloaders will be properly closed in the `build` goal of the `quarkus-maven-plugin`. However, if the build fails in between the `generate-code` or `generate-code-tests` and `build` then the Quarkus augmentation classloader won't be properly closed, which may lead to locking of JAR files that happened to be on the classpath on Windows OS. <4> Add system properties to `maven-surefire-plugin`. + `maven.home` is only required if you have custom configuration in `${maven.home}/conf/settings.xml`. <5> Use a specific `native` profile for native executable building. <6> Enable the `native` package type. The build will therefore produce a native executable. <7> If you want to test your native executable with Integration Tests, add the following plugin configuration. Test names `*IT` and annotated `@NativeImageTest` will be run against the native executable. See the xref:building-native-image.adoc[Native executable guide] for more info. [[fast-jar]] === Using fast-jar `fast-jar` is the default quarkus package type. The result of the build is a directory under `target` named `quarkus-app`. You can run the application using: `java -jar target/quarkus-app/quarkus-run.jar`. WARNING: In order to successfully run the produced jar, you need to have the entire contents of the `quarkus-app` directory. If any of the files are missing, the application will not start or might not function correctly. TIP: The `fast-jar` packaging results in creating an artifact that starts a little faster and consumes slightly less memory than a legacy Quarkus jar because it has indexed information about which dependency jar contains classes and resources. It can thus avoid the lookup into potentially every jar on the classpath that the legacy jar necessitates, when loading a class or resource. [[uber-jar-maven]] === Uber-Jar Creation Quarkus Maven plugin supports the generation of Uber-Jars by specifying a `quarkus.package.type=uber-jar` configuration option in your `application.properties` (or `uber-jar` in your `pom.xml`). The original jar will still be present in the `target` directory but it will be renamed to contain the `.original` suffix. When building an Uber-Jar you can specify entries that you want to exclude from the generated jar by using the `quarkus.package.ignored-entries` configuration option, this takes a comma separated list of entries to ignore. Uber-Jar creation by default excludes link:https://docs.oracle.com/javase/tutorial/deployment/jar/intro.html[signature files] that might be present in the dependencies of the application. Uber-Jar's final name is configurable via a Maven's build settings `finalName` option. [[multi-module-maven]] === Working with multi-module projects By default, Quarkus will not discover CDI beans inside another module. The best way to enable CDI bean discovery for a module in a multi-module project would be to include the `jandex-maven-plugin`, unless it is the main application module already configured with the quarkus-maven-plugin, in which case it will indexed automatically. [source,xml,subs=""attributes+""] ---- org.jboss.jandex jandex-maven-plugin {jandex-maven-plugin-version} make-index jandex ---- More information on this topic can be found on the xref:cdi-reference.adoc#bean_discovery[Bean Discovery] section of the CDI guide. [[maven-configuration-profile]] === Building with a specific configuration profile Quarkus supports xref:config-reference.adoc#profiles[configuration profiles] in order to provide a specific configuration according to the target environment. The profile can be provided directly in the Maven build's command thanks to the system property `quarkus.profile` with a command of type: // TODO switch to once escaping issue is fixed in Asciidoctor :build-additional-parameters: -Dquarkus.profile=profile-name-here include::includes/devtools/build.adoc[] :!build-additional-parameters: However it is also possible to specify the profile directly in the POM file of the project using project properties, the Quarkus Maven plugin configuration properties or system properties set in the Quarkus Maven plugin configuration. In order of precedence (greater precedence first): .1. System properties set in the Quarkus Maven plugin configuration [source,xml] ---- ... ... ${quarkus.platform.group-id} quarkus-maven-plugin ${quarkus.platform.version} true prod-aws <1> ... ... ---- <1> The default configuration profile of this project is `prod-aws`. .2. Quarkus Maven plugin configuration properties [source,xml] ---- ... ... ${quarkus.platform.group-id} quarkus-maven-plugin ${quarkus.platform.version} true prod-aws <1> ... ... ---- <1> The default configuration profile of this project is `prod-aws`. .3. Project properties [source,xml] ---- ... prod-aws <1> ... ... ---- <1> The default configuration profile of this project is `prod-aws`. NOTE: Whatever the approach is chosen, the profile can still be overridden with the `quarkus.profile` system property or the `QUARKUS_PROFILE` environment variable. [[maven-multi-build]] === Building several artifacts from a single module In some particular use cases, it can be interesting to build several artifacts of your application from the same module. A typical example is when you want to build your application with different configuration profiles. In that case, it is possible to add as many executions as needed to the Quarkus Maven plugin configuration. Below is an example of a Quarkus Maven plugin configuration that will produce two builds of the same application: one using the `prod-oracle` profile and the other one using the `prod-postgresql` profile. [source,xml] ---- ... ... ${quarkus.platform.group-id} quarkus-maven-plugin ${quarkus.platform.version} true oracle build prod-oracle <1> oracle-quarkus-app <2> postgresql build prod-postgresql <3> postgresql-quarkus-app <4> ... ... ---- <1> The default configuration profile of the first execution of the plugin is `prod-oracle`. <2> The output directory of the first execution of the plugin is set to `oracle-quarkus-app` instead of `quarkus-app` to have a dedicated directory. <3> The default configuration profile of the second execution of the plugin is `prod-postgresql`. <4> The output directory of the second execution of the plugin is set to `postgresql-quarkus-app` instead of `quarkus-app` to have a dedicated directory. NOTE: With the configuration above, both profile builds will be using the same dependencies, so if we added dependencies on the Oracle and PostgreSQL drivers to the application, both of the drivers will appear in both builds. To isolate profile-specific dependencies from other profiles, the JDBC drivers could be added as optional dependencies to the application but configured to be included in each profile that requires them, e.g.: [source,xml] ---- ... ... org.postgresql postgresql ${postgresql.driver.version} true <1> ... ${quarkus.platform.group-id} quarkus-maven-plugin ${quarkus.platform.version} true ... postgresql build prod-postgresql postgresql-quarkus-app true <2> org.postgresql:postgresql::jar <3> ... ... ---- <1> The JDBC driver of PostgreSQL is defined as an optional dependency <2> For backward compatibility reasons, it is necessary to explicitly indicate that the optional dependencies need to be filtered. <3> Only the optional dependency corresponding to the JDBC driver of PostgreSQL is expected in the final artifact. [[configuration-reference]] == Configuring the Project Output There are a several configuration options that will define what the output of your project build will be. These are provided in `application.properties` the same as any other config property. The properties are shown below: include::{generated-dir}/config/quarkus-package-pkg-package-config.adoc[opts=optional] [[custom-test-configuration-profile]] === Custom test configuration profile in JVM mode By default, Quarkus tests in JVM mode are run using the `test` configuration profile. If you are not familiar with Quarkus configuration profiles, everything you need to know is explained in the xref:config.adoc#configuration-profiles[Configuration Profiles Documentation]. It is however possible to use a custom configuration profile for your tests with the Maven Surefire and Maven Failsafe configurations shown below. This can be useful if you need for example to run some tests using a specific database which is not your default testing database. [source,xml,subs=attributes+] ---- [...] org.apache.maven.plugins maven-surefire-plugin ${surefire-plugin.version} foo <1> ${project.build.directory} [...] org.apache.maven.plugins maven-failsafe-plugin ${failsafe-plugin.version} foo <1> ${project.build.directory} [...] [...] ---- <1> The `foo` configuration profile will be used to run the tests. [WARNING] ==== It is not possible to use a custom test configuration profile in native mode for now. Native tests are always run using the `prod` profile. ==== [[bootstrap-maven-properties]] === Bootstrap Maven properties Quarkus bootstrap includes a Maven resolver implementation that is used to resolve application runtime and build time dependencies. The Quarkus Maven resolver is initialized from the same Maven command line that launched the build, test or dev mode. Typically, there is no need to add any extra configuration for it. However, there could be cases where an extra configuration option may be necessary to properly resolve application dependencies in test or dev modes, or IDEs. Maven test plugins (such as `surefire` and `failsafe`), for example, are not propagating build system properties to the running tests by default. Which means some of the system properties set by the Maven CLI aren't available for the Quarkus Maven resolver initialized for the tests, which may result in test dependencies being resolved using different settings than the main Maven build. Here is a list of system properties the Quarkus bootstrap Maven resolver checks during its initialization. [cols=3*,options=""header""] |=== | Property name | Default Value | Description | `maven.home` | `MAVEN_HOME` envvar | The Maven home dir is used to resolve the global settings file unless it was explicitly provided on the command line with the `-gs` argument | `maven.settings` | `~/m2/settings.xml` | Unless the custom settings file has been provided with the `-s` argument, this property can be used to point the resolver to a custom Maven settings file | `maven.repo.local` | `~/m2/repository` | This property could be used to configure a custom local Maven repository directory, if it is different from the default one and the one specified in the `settings.xml` | `maven.top-level-basedir` | none | This property may be useful to help the Maven resolver identify the top-level Maven project in the workspace. By default, the Maven resolver will be discovering a project's workspace by navigating the parent-module POM relationship. However there could be project layouts that are using an aggregator module which isn't appearing as the parent for its modules. In this case, this property will help the Quarkus Maven resolver to properly discover the workspace. | `quarkus.bootstrap.effective-model-builder` | `false` | By default, the Quarkus Maven resolver is reading project's POMs directly when discovering the project's layout. While in most cases it works well enough and relatively fast, reading raw POMs has its limitation. E.g. if a POM includes modules in a profile, these modules will not be discovered. This system property enables project's layout discovery based on the effective POM models, that are properly interpolated, instead of the raw ones. The reason this option is not enabled by default is it may appear to be significantly more time consuming that could increase, e.g. CI testing times. Until there is a better approach found that could be used by default, projects that require it should enable this option. |=== These system properties above could be added to, e.g., a `surefire` and/or `failsafe` plugin configuration as [source,xml,subs=attributes+] ---- [...] org.apache.maven.plugins maven-surefire-plugin ${surefire-plugin.version} ${maven.hom} <1> ${settings.localRepository} <2> ${session.request.userSettingsFile.path} <3> ${session.topLevelProject.basedir.absolutePath} <4> true <5> [...] ---- <1> Propagate `maven.home` system property set by the Maven CLI to the tests <2> Set the Maven local repository directory for the tests <3> Set the Maven settings file the tests <4> Point to the top-level project directory for the tests <5> Enable effective POM-based project layout discovery ==== Top-level vs Multi-module project directory In Maven there appears to be a notion of the top-level project (that is exposed as a project property `${session.topLevelProject.basedir.absolutePath}`) and the multi-module project directory (that is available as property `${maven.multiModuleProjectDirectory}`). These directories might not always match! IMPORTANT: `maven.multiModuleProjectDirectory` is meant to be consulted by the Maven code itself and not something to be relied upon by user code. So, if you find it useful, use it at your own risk! The `${maven.multiModuleProjectDirectory}` will be resolved to the first directory that contains `.mvn` directory as its child going up the workspace file system tree starting from the current directory (or the one specified with the `-f` argument) from which the `mvn` command was launched. If the `.mvn` directory was not found, however, the `${maven.multiModuleProjectDirectory}` will be pointing to the directory from which the `mvn` command was launched (or the one targeted with the `-f` argument). The `${session.topLevelProject.basedir.absolutePath}` will be pointing either to the directory from which the `mvn` command was launched or to the directory targeted with the `-f` argument, if it was specified. [[project-info]] == Quarkus project info The Quarkus Maven plugin includes a goal called `info` (currently marked as 'experimental') that logs Quarkus-specific information about the project, such as: the imported Quarkus platform BOMs and the Quarkus extensions found among the project dependencies. In a multi-module project `quarkus:info` will assume that the current module, in which it is executed, is the main module of the application. NOTE: The report generated by `quarkus:info` is not currently including the Quarkus Maven plugin information, however it's planned to be added in the future releases. Here is an example `info` output for a simple project: [source,text,subs=attributes+] ---- [aloubyansky@localhost code-with-quarkus]$ mvn quarkus:info [INFO] Scanning for projects... [INFO] [INFO] ---------------------< org.acme:code-with-quarkus >--------------------- [INFO] Building code-with-quarkus 1.0.0-SNAPSHOT [INFO] --------------------------------[ jar ]--------------------------------- [INFO] [INFO] --- quarkus-maven-plugin:{quarkus-version}:info (default-cli) @ code-with-quarkus --- [WARNING] quarkus:info goal is experimental, its options and output may change in future versions [INFO] Quarkus platform BOMs: <1> [INFO] io.quarkus.platform:quarkus-bom:pom:{quarkus-version} [INFO] io.quarkus.platform:quarkus-kogito-bom:pom:{quarkus-version} [INFO] io.quarkus.platform:quarkus-camel-bom:pom:{quarkus-version} [INFO] [INFO] Extensions from io.quarkus.platform:quarkus-bom: <2> [INFO] io.quarkus:quarkus-resteasy-reactive [INFO] [INFO] Extensions from io.quarkus.platform:quarkus-kogito-bom: <3> [INFO] org.kie.kogito:kogito-quarkus-decisions [INFO] [INFO] Extensions from io.quarkus.platform:quarkus-camel-bom: <4> [INFO] org.apache.camel.quarkus:camel-quarkus-rabbitmq [INFO] [INFO] Extensions from registry.quarkus.io: <5> [INFO] io.quarkiverse.prettytime:quarkus-prettytime:0.2.1 ---- <1> Quarkus platform BOMs imported in the project (BOMs imported by parent POMs will also be reported) <2> Direct Quarkus extension dependencies managed by the `quarkus-bom` <3> Direct Quarkus extension dependencies managed by the `quarkus-kogito-bom` <4> Direct Quarkus extension dependencies managed by the `quarkus-camel-bom` <5> Direct Quarkus extensions dependencies that aren't managed by Quarkus BOMs but found in the Quarkus extension registry NOTE: `quarkus:info` will also report Quarkus extensions that aren't found in the Quarkus extension registries if those are present among the project dependencies, indicating they have an 'unknown origin'. [[project-info-misaligned]] === Highlighing misaligned versions `quarkus:info` will also highlight basic Quarkus dependency version misalignments, in case they are detected. For example, if we modify the project mentioned above by removing the `kogito-quarkus-decisions` extension from the dependencies and adding a `2.6.3.Final` `` element to the `quarkus-resteasy-reactive` dependency that is managed by the `quarkus-bom` and then run `quarkus:info` again, we'll see something like: [source,text,subs=attributes+] ---- [INFO] --- quarkus-maven-plugin:{quarkus-version}:info (default-cli) @ code-with-quarkus --- [WARNING] quarkus:info goal is experimental, its options and output may change in future versions [INFO] Quarkus platform BOMs: [INFO] io.quarkus.platform:quarkus-bom:pom:{quarkus-version} [INFO] io.quarkus.platform:quarkus-kogito-bom:pom:{quarkus-version} | unnecessary <1> [INFO] io.quarkus.platform:quarkus-camel-bom:pom:{quarkus-version} [INFO] [INFO] Extensions from io.quarkus.platform:quarkus-bom: [INFO] io.quarkus:quarkus-resteasy-reactive:2.6.3.Final | misaligned <2> [INFO] [INFO] Extensions from io.quarkus.platform:quarkus-camel-bom: [INFO] org.apache.camel.quarkus:camel-quarkus-rabbitmq [INFO] [INFO] Extensions from registry.quarkus.io: [INFO] io.quarkiverse.prettytime:quarkus-prettytime:0.2.1 [INFO] [WARNING] Non-recommended Quarkus platform BOM and/or extension versions were found. For more details, please, execute 'mvn quarkus:update -Drectify' ---- <1> The `quarkus-kogito-bom` import is now reported as 'unnecessary' since none of the Quarkus extensions it includes are found among the project dependencies <2> The version `2.6.3.Final` of the `quarkus-resteasy-reactive` is now reported as being misaligned with the version managed by the Quarkus platform BOM imported in the project, which is {quarkus-version} [[project-update]] == Quarkus project update The `quarkus:update` goal (currently marked as 'experimental') provided by the Quarkus Maven plugin can be used to check whether there are Quarkus-related updates available for a project, such as: new releases of the relevant Quarkus platform BOMs and non-platform Quarkus extensions present in the project. In a multi-module project the `update` goal is meant to be executed from the main Quarkus application module. IMPORTANT: At this point, the `quarkus:update` goal does not actually apply the recommended updates but simply reports what they are and how to apply them manually. NOTE: The Quarkus Maven plugin version isn't currently included in the update report, however it's planned to be added in the future releases. The way `quarkus:update` works, first, all the direct Quarkus extension dependencies of the project are collected (those that are managed by the Quarkus platform BOMs and those that aren't but found in the Quarkus extension registries). Then the configured Quarkus extension registries (typically the `registry.quarkus.io`) will be queried for the latest recommended/supported Quarkus platform versions and non-platform Quarkus extensions compatible with them. The algorithm will then select the latest compatible combination of all the extensions found in the project, assuming such a combination actually exists. Otherwise, no updates will be suggested. Assuming we have a project including Kogito, Camel and core Quarkus extensions available in the Quarkus platform based on Quarkus `2.7.1.Final`, the output of the `quarkus:update` would look like: [source,text,subs=attributes+] ---- [aloubyansky@localhost code-with-quarkus]$ mvn quarkus:update [INFO] Scanning for projects... [INFO] [INFO] ---------------------< org.acme:code-with-quarkus >--------------------- [INFO] Building code-with-quarkus 1.0.0-SNAPSHOT [INFO] --------------------------------[ jar ]--------------------------------- [INFO] [INFO] --- quarkus-maven-plugin:{quarkus-version}:update (default-cli) @ code-with-quarkus --- [WARNING] quarkus:update goal is experimental, its options and output might change in future versions [INFO] [INFO] Recommended Quarkus platform BOM updates: <1> [INFO] Update: io.quarkus.platform:quarkus-bom:pom:2.7.1.Final -> {quarkus-version} [INFO] Update: io.quarkus.platform:quarkus-kogito-bom:pom:2.7.1.Final -> {quarkus-version} [INFO] Update: io.quarkus.platform:quarkus-camel-bom:pom:2.7.1.Final -> {quarkus-version} ---- <1> A list of currently recommended Quarkus platform BOM updates NOTE: Typically, a single project property will be used to manage all the Quarkus platform BOMs but the implementation isn't currently smart enough to point that out and will report updates for each BOM individually. If we modify the project to remove all the Kogito extensions from the project, change the version of the `quarkus-resteasy-reactive` extension to `2.6.3.Final` and downgrade `quarkus-prettytime` which is not included in the Quarkus platform BOMs to `0.2.0`, `quarkus:update` will report something like: [source,text,subs=attributes+] ---- [INFO] Recommended Quarkus platform BOM updates: <1> [INFO] Update: io.quarkus.platform:quarkus-bom:pom:2.7.1.Final -> {quarkus-version} [INFO] Update: io.quarkus.platform:quarkus-camel-bom:pom:2.7.1.Final -> {quarkus-version} [INFO] Remove: io.quarkus.platform:quarkus-kogito-bom:pom:2.7.1.Final <2> [INFO] [INFO] Extensions from io.quarkus.platform:quarkus-bom: [INFO] Update: io.quarkus:quarkus-resteasy-reactive:2.6.3.Final -> remove version (managed) <3> [INFO] [INFO] Extensions from registry.quarkus.io: [INFO] Update: io.quarkiverse.prettytime:quarkus-prettytime:0.2.0 -> 0.2.1 <4> ---- <1> A list of the currently recommended Quarkus platform BOM updates for the project <2> Given that the project does not include any Kogito extensions, the BOM import is recommended to be removed <3> An outdated version of the `quarkus-resteasy-reactive` is recommended to be removed in favor of the one managed by the `quarkus-bom` <4> The latest compatible version of the `quarkus-prettytime` extension === Quarkus project rectify As was mentioned above, `quarkus:info`, besides reporting Quarkus platform and extension versions, performs a quick version alignment check, to make sure the extension versions used in the project are compatible with the imported Quarkus platform BOMs. If misalignments are detected, the following warning message will be logged: [source,text,subs=attributes+] ---- [WARNING] Non-recommended Quarkus platform BOM and/or extension versions were found. For more details, please, execute 'mvn quarkus:update -Drectify' ---- When the `rectify` option is enabled, `quarkus:update`, instead of suggesting the latest recommended Quarkus version updates, will log update instructions to simply align the extension dependency versions found in the project with the currently imported Quarkus platform BOMs. ",12477,False,2224.5024769560755,median "= `just` :toc: macro :toc-title: image:https://img.shields.io/crates/v/just.svg[crates.io version,link=https://crates.io/crates/just] image:https://github.com/casey/just/workflows/Build/badge.svg[build status,link=https://github.com/casey/just/actions] image:https://img.shields.io/github/downloads/casey/just/total.svg[downloads,link=https://github.com/casey/just/releases] image:https://img.shields.io/discord/695580069837406228?logo=discord[chat on discord,link=https://discord.gg/ezYScXR] image:https://img.shields.io/badge/Say%20Thanks-!-1EAEDB.svg[say thanks,link=mailto:casey@rodarmor.com?subject=Thanks for Just!] `just` is a handy way to save and run project-specific commands. (非官方中文文档,link:https://github.com/chinanf-boy/just-zh[这里],快看过来!) Commands, called recipes, are stored in a file called `justfile` with syntax inspired by `make`: image:screenshot.png[screenshot] You can then run them with `just RECIPE`: ```sh $ just test-all cc *.c -o main ./test --all Yay, all your tests passed! ``` `just` has a ton of useful features, and many improvements over `make`: - `just` is a command runner, not a build system, so it avoids much of link:https://github.com/casey/just#what-are-the-idiosyncrasies-of-make-that-just-avoids[`make`'s complexity and idiosyncrasies]. No need for `.PHONY` recipes! - Linux, MacOS, and Windows are supported with no additional dependencies. (Although if your system doesn't have an `sh`, you'll need to link:https://github.com/casey/just#shell[choose a different shell].) - Errors are specific and informative, and syntax errors are reported along with their source context. - Recipes can accept link:https://github.com/casey/just#recipe-parameters[command line arguments]. - Wherever possible, errors are resolved statically. Unknown recipes and circular dependencies are reported before anything runs. - `just` link:https://github.com/casey/just#dotenv-integration[loads `.env` files], making it easy to populate environment variables. - Recipes can be link:https://github.com/casey/just#listing-available-recipes[listed from the command line]. - Command line completion scripts are link:https://github.com/casey/just#shell-completion-scripts[available for most popular shells]. - Recipes can be written in link:https://github.com/casey/just#writing-recipes-in-other-languages[arbitrary languages], like Python or NodeJS. - `just` can be invoked from any subdirectory, not just the directory that contains the `justfile`. - And link:https://github.com/casey/just#manual[much more]! If you need help with `just` please feel free to open an issue or ping me on link:https://discord.gg/ezYScXR[Discord]. Feature requests and bug reports are always welcome! [discrete] == Manual toc::[] == Installation === Prerequisites `just` should run on any system with a reasonable `sh`, including Linux, MacOS, and the BSDs. On Windows, `just` works with the `sh` provided by https://git-scm.com[Git for Windows], https://desktop.github.com[GitHub Desktop], or http://www.cygwin.com[Cygwin]. If you'd rather not install `sh`, you can use the `shell` setting to use the shell of your choice. Like PowerShell: ```make # use PowerShell instead of sh: set shell := [""powershell.exe"", ""-c""] hello: Write-Host ""Hello, world!"" ``` …or `cmd.exe`: ```make # use cmd.exe instead of sh: set shell := [""cmd.exe"", ""/c""] list: dir ``` (PowerShell is installed by default on Windows 7 SP1 and Windows Server 2008 R2 S1 and later, and `cmd.exe` is quite fiddly, so PowerShell is recommended for most Windows users.) === Packages [options=""header""] |================================================================================================================================================================================================================================================================================================================================================================================================================================ | Operating System | Package Manager | Package | Command | https://forge.rust-lang.org/release/platform-support.html[Various] | https://www.rust-lang.org[Cargo] | https://crates.io/crates/just[just] | `cargo install just` | https://en.wikipedia.org/wiki/Microsoft_Windows[Microsoft Windows] | https://scoop.sh[Scoop] | https://github.com/ScoopInstaller/Main/blob/master/bucket/just.json[just] | `scoop install just` | https://en.wikipedia.org/wiki/MacOS[macOS] | https://brew.sh[Homebrew] | https://formulae.brew.sh/formula/just[just] | `brew install just` | https://en.wikipedia.org/wiki/MacOS[macOS] | https://www.macports.org[MacPorts] | https://ports.macports.org/port/just/summary[just] | `port install just` | https://www.archlinux.org[Arch Linux] | https://wiki.archlinux.org/title/Pacman[pacman] | https://archlinux.org/packages/community/x86_64/just/[just] | `pacman -S just` | https://nixos.org/nixos/[NixOS], https://nixos.org/nix/manual/#ch-supported-platforms[Linux], https://nixos.org/nix/manual/#ch-supported-platforms[macOS] | https://nixos.org/nix/[Nix] | https://github.com/NixOS/nixpkgs/blob/master/pkgs/development/tools/just/default.nix[just] | `nix-env -iA nixos.just` | https://getsol.us/[Solus] | https://getsol.us/articles/package-management/basics/en[eopkg] | https://dev.getsol.us/source/just/[just] | `eopkg install just` | https://voidlinux.org[Void Linux] | https://wiki.voidlinux.org/XBPS[XBPS] | https://github.com/void-linux/void-packages/blob/master/srcpkgs/just/template[just] | `xbps-install -S just` | https://www.freebsd.org/[FreeBSD] | https://www.freebsd.org/doc/handbook/pkgng-intro.html[pkg] | https://www.freshports.org/deskutils/just/[just] | `pkg install just` | https://alpinelinux.org/[Alpine Linux] | https://wiki.alpinelinux.org/wiki/Alpine_Linux_package_management[apk-tools] | https://pkgs.alpinelinux.org/package/edge/community/x86_64/just[just] | `apk add just` | https://getfedora.org/[Fedora Linux] | https://dnf.readthedocs.io/en/latest/[DNF] | https://src.fedoraproject.org/rpms/rust-just[just] | `dnf install just` | https://www.gentoo.org/[Gentoo Linux] | https://wiki.gentoo.org/wiki/Portage[Portage] | https://github.com/gentoo-mirror/dm9pZCAq/tree/master/sys-devel/just[dm9pZCAq overlay: sys-devel/just] | `eselect repository enable dm9pZCAq && emerge --sync dm9pZCAq && emerge sys-devel/just` |================================================================================================================================================================================================================================================================================================================================================================================================================================ === Pre-Built Binaries Pre-built binaries for Linux, MacOS, and Windows can be found on https://github.com/casey/just/releases[the releases page]. You can use the following command on Linux, MacOS, or Windows to download the latest release, just replace `DEST` with the directory where you'd like to put `just`: ```sh curl --proto '=https' --tlsv1.2 -sSf https://just.systems/install.sh | bash -s -- --to DEST ``` === GitHub Actions link:https://github.com/extractions/setup-just[extractions/setup-just] can be used to install `just` in a GitHub Actions workflow. Example usage: ```yaml - uses: extractions/setup-just@v1 with: just-version: 0.8 # optional semver specification, otherwise latest ``` === Release RSS Feed An https://en.wikipedia.org/wiki/RSS[RSS feed] of `just` releases is available https://github.com/casey/just/releases.atom[here]. == Editor Support `justfile` syntax is close enough to `make` that you may want to tell your editor to use `make` syntax highlighting for `just`. === Vim and Neovim ==== `vim-just` The https://github.com/NoahTheDuke/vim-just[vim-just] plugin provides syntax highlighting for justfiles. Install it with your favorite package manager, like https://github.com/junegunn/vim-plug[Plug]: ```vim call plug#begin() Plug 'NoahTheDuke/vim-just' call plug#end() ``` Or with Vim's built-in package support: ``` mkdir -p ~/.vim/pack/vendor/start cd ~/.vim/pack/vendor/start git clone https://github.com/NoahTheDuke/vim-just.git ``` `vim-just` is also available from https://github.com/sheerun/vim-polyglot[vim-polyglot], a multi-language Vim plugin. ==== `tree-sitter-just` https://github.com/IndianBoy42/tree-sitter-just[tree-sitter-just] is an https://github.com/nvim-treesitter/nvim-treesitter[Nvim Treesitter] plugin for Neovim. ==== Makefile Syntax Highlighting Vim's built-in makefile syntax highlighting isn't perfect for justfiles, but it's better than nothing. You can put the following in `~/.vim/filetype.vim`: ```vimscript if exists(""did_load_filetypes"") finish endif augroup filetypedetect au BufNewFile,BufRead justfile setf make augroup END ``` Or add the following to an individual justfile to enable `make` mode on a per-file basis: ``` # vim: set ft=make : ``` === Emacs https://github.com/leon-barrett/just-mode.el[just-mode] provides syntax highlighting and automatic indentation of justfiles. It is available on https://melpa.org/[MELPA] as https://melpa.org/#/just-mode[just-mode] https://github.com/psibi/justl.el[justl] provides commands for executing and listing recipes. You can add the following to an individual justfile to enable `make` mode on a per-file basis: ``` # Local Variables: # mode: makefile # End: ``` === Visual Studio Code An extension for VS Code by https://github.com/skellock[skellock] is https://marketplace.visualstudio.com/items?itemName=skellock.just[available here]. (https://github.com/skellock/vscode-just[repository]) You can install it from the command line by running: ``` code --install-extension skellock.just ``` === Kakoune Kakoune supports `justfile` syntax highlighting out of the box, thanks to TeddyDD. === Sublime Text A syntax file for Sublime Text written by TonioGela is available in link:extras/just.sublime-syntax[extras/just.sublime-syntax]. === Other Editors Feel free to send me the commands necessary to get syntax highlighting working in your editor of choice so that I may include them here. == Quick Start See xref:Installation[] for how to install `just` on your computer. Try running `just --version` to make sure that it's installed correctly. Once `just` is installed and working, create a file named `justfile` in the root of your project with the following contents: ```make recipe-name: echo 'This is a recipe!' # this is a comment another-recipe: @echo 'This is another recipe.' ``` When you invoke `just` it looks for file `justfile` in the current directory and upwards, so you can invoke it from any subdirectory of your project. The search for a `justfile` is case insensitive, so any case, like `Justfile`, `JUSTFILE`, or `JuStFiLe`, will work. `just` will also look for files with the name `.justfile`, in case you'd like to hide a `justfile`. Running `just` with no arguments runs the first recipe in the `justfile`: ```sh $ just echo 'This is a recipe!' This is a recipe! ``` One or more arguments specify the recipe(s) to run: ```sh $ just another-recipe This is another recipe. ``` `just` prints each command to standard error before running it, which is why `echo 'This is a recipe!'` was printed. This is suppressed for lines starting with `@`, which is why `echo 'Another recipe.'` was not printed. Recipes stop running if a command fails. Here `cargo publish` will only run if `cargo test` succeeds: ```make publish: cargo test # tests passed, time to publish! cargo publish ``` Recipes can depend on other recipes. Here the `test` recipe depends on the `build` recipe, so `build` will run before `test`: ```make build: cc main.c foo.c bar.c -o main test: build ./test sloc: @echo ""`wc -l *.c` lines of code"" ``` ```sh $ just test cc main.c foo.c bar.c -o main ./test testing... all tests passed! ``` Recipes without dependencies will run in the order they're given on the command line: ```sh $ just build sloc cc main.c foo.c bar.c -o main 1337 lines of code ``` Dependencies will always run first, even if they are passed after a recipe that depends on them: ```sh $ just test build cc main.c foo.c bar.c -o main ./test testing... all tests passed! ``` == Examples A variety of example justfiles can be found in the link:examples[examples directory]. This https://toniogela.dev/just/[blog post] discusses using `just` to improve management of shared machines, and includes a number of example justfiles. == Features === Listing Available Recipes Recipes can be listed in alphabetical order with `just --list`: ```sh $ just --list Available recipes: build test deploy lint ``` `just --summary` is more concise: ```sh $ just --summary build test deploy lint ``` Pass `--unsorted` to print recipes in the order they appear in the justfile: ```make test: echo 'Testing!' build: echo 'Building!' ``` ```sh $ just --list --unsorted Available recipes: test build ``` ```sh $ just --summary --unsorted test build ``` If you'd like `just` to default to listing the recipes in the justfile, you can use this as your default recipe: ```make default: @just --list ``` The heading text can be customized with `--list-heading`: ``` $ just --list --list-heading $'Cool stuff…\\n' Cool stuff… test build ``` And the indentation can be customized with `--list-prefix`: ``` $ just --list --list-prefix ···· Available recipes: ····test ····build ``` The argument to `--list-heading` replaces both the heading and the newline following it, so it should contain a newline if non-empty. It works this way so you can suppress the heading line entirely by passing the empty string: ``` $ just --list --list-heading '' test build ``` === Aliases Aliases allow recipes to be invoked with alternative names: ```make alias b := build build: echo 'Building!' ``` ```sh $ just b build echo 'Building!' Building! ``` === Settings Settings control interpretation and execution. Each setting may be specified at most once, anywhere in the justfile. For example: ```make set shell := [""zsh"", ""-cu""] foo: # this line will be run as `zsh -cu 'ls **/*.txt'` ls **/*.txt ``` ==== Table of Settings [options=""header""] |================= | Name | Value | Description | `dotenv-load` | boolean | Load a `.env` file, if present. | `export` | boolean | Export all variables as environment variables. | `positional-arguments` | boolean | Pass positional arguments. | `shell` | `[COMMAND, ARGS...]` | Set the command used to invoke recipes and evaluate backticks. |================= Boolean settings can be written as: ``` set NAME ``` Which is equivalent to: ``` set NAME := true ``` ==== Dotenv Load If `dotenv-load` is `true`, a `.env` file will be loaded if present. Defaults to `true`. ==== Export The `export` setting causes all `just` variables to be exported as environment variables. Defaults to `false`. ```make set export a := ""hello"" @foo b: echo $a echo $b ``` ``` $ just foo goodbye hello goodbye ``` ==== Positional Arguments If `positional-arguments` is `true`, recipe arguments will be passed as positional arguments to commands. For linewise recipes, argument `$0` will be the name of the recipe. For example, running this recipe: ```make set positional-arguments @foo bar: echo $0 echo $1 ``` Will produce the following output: ``` $ just foo hello foo hello ``` ==== Shell The `shell` setting controls the command used to invoke recipe lines and backticks. Shebang recipes are unaffected. ```make # use python3 to execute recipe lines and backticks set shell := [""python3"", ""-c""] # use print to capture result of evaluation foos := `print(""foo"" * 4)` foo: print(""Snake snake snake snake."") print(""{{foos}}"") ``` `just` passes the command to be executed as an argument. Many shells will need an additional flag, often `-c`, to make them evaluate the first argument. ===== Python 3 ```make set shell := [""python3"", ""-c""] ``` ===== Bash ```make set shell := [""bash"", ""-uc""] ``` ===== Z Shell ```make set shell := [""zsh"", ""-uc""] ``` ===== Fish ```make set shell := [""fish"", ""-c""] ``` === Documentation Comments Comments immediately preceding a recipe will appear in `just --list`: ```make # build stuff build: ./bin/build # test stuff test: ./bin/test ``` ```sh $ just --list Available recipes: build # build stuff test # test stuff ``` === Variables and Substitution Variables, strings, concatenation, and substitution using `{{...}}` are supported: ```make version := ""0.2.7"" tardir := ""awesomesauce-"" + version tarball := tardir + "".tar.gz"" publish: rm -f {{tarball}} mkdir {{tardir}} cp README.md *.c {{tardir}} tar zcvf {{tarball}} {{tardir}} scp {{tarball}} me@server.com:release/ rm -rf {{tarball}} {{tardir}} ``` ==== Escaping `{{` To write a recipe containing `{{`, use `{{{{`: ```make braces: echo 'I {{{{LOVE}} curly braces!' ``` (An unmatched `}}` is ignored, so it doesn't need to be escaped.) Another option is to put all the text you'd like to escape inside of an interpolation: ```make braces: echo '{{'I {{LOVE}} curly braces!'}}' ``` Yet another option is to use `{{ ""{{"" }}`: ```make braces: echo 'I {{ ""{{"" }}LOVE}} curly braces!' ``` === Strings Double-quoted strings support escape sequences: ```make string-with-tab := ""\\t"" string-with-newline := ""\\n"" string-with-carriage-return := ""\\r"" string-with-double-quote := ""\\"""" string-with-slash := ""\\\\"" string-with-no-newline := ""\\ "" ``` ```sh $ just --evaluate ""tring-with-carriage-return := "" string-with-double-quote := """""" string-with-newline := "" "" string-with-no-newline := """" string-with-slash := ""\\"" string-with-tab := "" "" ``` Strings may contain line breaks: ```make single := ' hello ' double := "" goodbye "" ``` Single-quoted strings do not recognize escape sequences: ```make escapes := '\\t\\n\\r\\""\\\\' ``` ```sh $ just --evaluate escapes := ""\\t\\n\\r\\""\\\\"" ``` Indented versions of both single- and double-quoted strings, delimited by triple single- or triple double-quotes, are supported. Indented string lines are stripped of leading whitespace common to all non-blank lines: ```make # this string will evaluate to `foo\\nbar\\n` x := ''' foo bar ''' # this string will evaluate to `abc\\n wuv\\nbar\\n` y := """""" abc wuv xyz """""" ``` Similar to unindented strings, indented double-quoted strings process escape sequences, and indented single-quoted strings ignore escape sequences. Escape sequence processing takes place after unindentation. The unindention algorithm does not take escape-sequence produced whitespace or newlines into account. === Ignoring Errors Normally, if a command returns a non-zero exit status, execution will stop. To continue execution after a command, even if it fails, prefix the command with `-`: ```make foo: -cat foo echo 'Done!' ``` ```sh $ just foo cat foo cat: foo: No such file or directory echo 'Done!' Done! ``` === Functions `just` provides a few built-in functions that might be useful when writing recipes. ==== System Information - `arch()` – Instruction set architecture. Possible values are: `""aarch64""`, `""arm""`, `""asmjs""`, `""hexagon""`, `""mips""`, `""msp430""`, `""powerpc""`, `""powerpc64""`, `""s390x""`, `""sparc""`, `""wasm32""`, `""x86""`, `""x86_64""`, and `""xcore""`. - `os()` – Operating system. Possible values are: `""android""`, `""bitrig""`, `""dragonfly""`, `""emscripten""`, `""freebsd""`, `""haiku""`, `""ios""`, `""linux""`, `""macos""`, `""netbsd""`, `""openbsd""`, `""solaris""`, and `""windows""`. - `os_family()` – Operating system family; possible values are: `""unix""` and `""windows""`. For example: ```make system-info: @echo ""This is an {{arch()}} machine"". ``` ``` $ just system-info This is an x86_64 machine ``` ==== Environment Variables - `env_var(key)` – Retrieves the environment variable with name `key`, aborting if it is not present. - `env_var_or_default(key, default)` – Retrieves the environment variable with name `key`, returning `default` if it is not present. ==== Invocation Directory - `invocation_directory()` - Retrieves the path of the current working directory, before `just` changed it (chdir'd) prior to executing commands. For example, to call `rustfmt` on files just under the ""current directory"" (from the user/invoker's perspective), use the following rule: ``` rustfmt: find {{invocation_directory()}} -name \\*.rs -exec rustfmt {} \\; ``` Alternatively, if your command needs to be run from the current directory, you could use (e.g.): ``` build: cd {{invocation_directory()}}; ./some_script_that_needs_to_be_run_from_here ``` ==== Justfile and Justfile Directory - `justfile()` - Retrieves the path of the current justfile. - `justfile_directory()` - Retrieves the path of the parent directory of the current justfile. For example, to run a command relative to the location of the current justfile: ``` script: ./{{justfile_directory()}}/scripts/some_script ``` ==== Just Executable - `just_executable()` - Absolute path to the `just` executable. For example: ```make executable: @echo The executable is at: {{just_executable()}} ``` ``` $ just The executable is at: /bin/just ``` ==== String Manipulation - `uppercase(s)` - Convert `s` to uppercase. - `lowercase(s)` - Convert `s` to lowercase. - `trim(s)` - Remove leading and trailing whitespace from `s`. - `replace(s, from, to)` - Replace all occurrences of `from` in `s` to `to`. ==== Dotenv Integration `just` will load environment variables from a file named `.env`. This file can be located in the same directory as your justfile or in a parent directory. These variables are environment variables, not `just` variables, and so must be accessed using `$VARIABLE_NAME` in recipes and backticks. For example, if your `.env` file contains: ``` # a comment, will be ignored DATABASE_ADDRESS=localhost:6379 SERVER_PORT=1337 ``` And your justfile contains: ```make serve: @echo ""Starting server with database $DATABASE_ADDRESS on port $SERVER_PORT..."" ./server --database $DATABASE_ADDRESS --port $SERVER_PORT ``` `just serve` will output: ```sh $ just serve Starting server with database localhost:6379 on port 1337... ./server --database $DATABASE_ADDRESS --port $SERVER_PORT ``` ==== Path Manipulation ===== Fallible - `extension(path)` - Extension of `path`. `extension(""/foo/bar.txt"")` is `txt`. - `file_name(path)` - File name of `path` with any leading directory components removed. `file_name(""/foo/bar.txt"")` is `bar.txt`. - `file_stem(path)` - File name of `path` without extension. `file_stem(""/foo/bar.txt"")` is `bar`. - `parent_directory(path)` - Parent directory of `path`. `parent_directory(""/foo/bar.txt"")` is `/foo`. - `without_extension(path)` - `path` without extension. `without_extension(""/foo/bar.txt"")` is `/foo/bar`. These functions can fail, for example if a path does not have an extension, which will halt execution. ===== Infallible - `join(a, b)` - Join path `a` with path `b`. `join(""foo/bar"", ""baz"")` is `foo/bar/baz`. - `clean(path)` - Simplify `path` by removing extra path separators, intermediate `.` components, and `..` where possible. `clean(""foo//bar"")` is `foo/bar`, `clean(""foo/.."")` is `.`, `clean(""foo/./bar"")` is `foo/bar`. === Command Evaluation Using Backticks Backticks can be used to store the result of commands: ```make localhost := `dumpinterfaces | cut -d: -f2 | sed 's/\\/.*//' | sed 's/ //g'` serve: ./serve {{localhost}} 8080 ``` Indented backticks, delimited by three backticks, are de-indented in the same manner as indented strings: ```make # This backtick evaluates the command `echo foo\\necho bar\\n`, which produces the value `foo\\nbar\\n`. stuff := ``` echo foo echo bar ``` ``` See the <> section for details on unindenting. Backticks may not start with `#!`. This syntax is reserved for a future upgrade. === Conditional Expressions `if`/`else` expressions evaluate different branches depending on if two expressions evaluate to the same value: ```make foo := if ""2"" == ""2"" { ""Good!"" } else { ""1984"" } bar: @echo ""{{foo}}"" ``` ```sh $ just bar Good! ``` It is also possible to test for inequality: ```make foo := if ""hello"" != ""goodbye"" { ""xyz"" } else { ""abc"" } bar: @echo {{foo}} ``` ```sh $ just bar xyz ``` And match against regular expressions: ```make foo := if ""hello"" =~ 'hel+o' { ""match"" } else { ""mismatch"" } bar: @echo {{foo}} ``` ```sh $ just bar match ``` Regular expressions are provided by the https://github.com/rust-lang/regex[regex crate], whose syntax is documented on https://docs.rs/regex/1.5.4/regex/#syntax[docs.rs]. Since regular expressions commonly use backslash escape sequences, consider using single-quoted string literals, which will pass slashes to the regex parser unmolested. Conditional expressions short-circuit, which means they only evaluate one of their branches. This can be used to make sure that backtick expressions don't run when they shouldn't. ```make foo := if env_var(""RELEASE"") == ""true"" { `get-something-from-release-database` } else { ""dummy-value"" } ``` Conditionals can be used inside of recipes: ```make bar foo: echo {{ if foo == ""bar"" { ""hello"" } else { ""goodbye"" } }} ``` Note the space after the final `}`! Without the space, the interpolation will be prematurely closed. Multiple conditionals can be chained: ```make foo := if ""hello"" == ""goodbye"" { ""xyz"" } else if ""a"" == ""a"" { ""abc"" } else { ""123"" } bar: @echo {{foo}} ``` ```sh $ just bar abc ``` === Setting Variables from the Command Line Variables can be overridden from the command line. ```make os := ""linux"" test: build ./test --test {{os}} build: ./build {{os}} ``` ```sh $ just ./build linux ./test --test linux ``` Any number of arguments of the form `NAME=VALUE` can be passed before recipes: ```sh $ just os=plan9 ./build plan9 ./test --test plan9 ``` Or you can use the `--set` flag: ```sh $ just --set os bsd ./build bsd ./test --test bsd ``` === Environment Variables Assignments prefixed with the `export` keyword will be exported to recipes as environment variables: ```make export RUST_BACKTRACE := ""1"" test: # will print a stack trace if it crashes cargo test ``` Parameters prefixed with a `$` will be exported as environment variables: ```make test $RUST_BACKTRACE=""1"": # will print a stack trace if it crashes cargo test ``` Exported variables and parameters are not exported to backticks in the same scope. ```make export WORLD := ""world"" # This backtick will fail with ""WORLD: unbound variable"" BAR := `echo hello $WORLD` ``` ```make # Running `just a foo` will fail with ""A: unbound variable"" a $A $B=`echo $A`: echo $A $B ``` === Recipe Parameters Recipes may have parameters. Here recipe `build` has a parameter called `target`: ```make build target: @echo 'Building {{target}}...' cd {{target}} && make ``` To pass arguments on the command line, put them after the recipe name: ```sh $ just build my-awesome-project Building my-awesome-project... cd my-awesome-project && make ``` To pass arguments to a dependency, put the dependency in parentheses along with the arguments: ```make default: (build ""main"") build target: @echo 'Building {{target}}...' cd {{target}} && make ``` Parameters may have default values: ```make default := 'all' test target tests=default: @echo 'Testing {{target}}:{{tests}}...' ./test --tests {{tests}} {{target}} ``` Parameters with default values may be omitted: ```sh $ just test server Testing server:all... ./test --tests all server ``` Or supplied: ```sh $ just test server unit Testing server:unit... ./test --tests unit server ``` Default values may be arbitrary expressions, but concatenations must be parenthesized: ```make arch := ""wasm"" test triple=(arch + ""-unknown-unknown""): ./test {{triple}} ``` The last parameter of a recipe may be variadic, indicated with either a `+` or a `*` before the argument name: ```make backup +FILES: scp {{FILES}} me@server.com: ``` Variadic parameters prefixed with `+` accept _one or more_ arguments and expand to a string containing those arguments separated by spaces: ```sh $ just backup FAQ.md GRAMMAR.md scp FAQ.md GRAMMAR.md me@server.com: FAQ.md 100% 1831 1.8KB/s 00:00 GRAMMAR.md 100% 1666 1.6KB/s 00:00 ``` Variadic parameters prefixed with `*` accept _zero or more_ arguments and expand to a string containing those arguments separated by spaces, or an empty string if no arguments are present: ```make commit MESSAGE *FLAGS: git commit {{FLAGS}} -m ""{{MESSAGE}}"" ``` Variadic parameters can be assigned default values. These are overridden by arguments passed on the command line: ```make test +FLAGS='-q': cargo test {{FLAGS}} ``` `{{...}}` substitutions may need to be quoted if they contain spaces. For example, if you have the following recipe: ```make search QUERY: lynx https://www.google.com/?q={{QUERY}} ``` And you type: ```sh $ just search ""cat toupee"" ``` `just` will run the command `lynx https://www.google.com/?q=cat toupee`, which will get parsed by `sh` as `lynx`, `https://www.google.com/?q=cat`, and `toupee`, and not the intended `lynx` and `https://www.google.com/?q=cat toupee`. You can fix this by adding quotes: ```make search QUERY: lynx 'https://www.google.com/?q={{QUERY}}' ``` Parameters prefixed with a `$` will be exported as environment variables: ```make foo $bar: echo $bar ``` === Running Recipes at the End of a Recipe Normal dependencies of a recipes always run before a recipe starts. That is to say, the dependee always runs before the depender. These dependencies are called ""prior dependencies"". A recipe can also have subsequent dependencies, which run after the recipe and are introduced with an `&&`: ```make a: echo 'A!' b: a && c d echo 'B!' c: echo 'C!' d: echo 'D!' ``` …running 'b' prints: ```sh $ just b echo 'A!' A! echo 'B!' B! echo 'C!' C! echo 'D!' D! ``` === Running Recipes in the Middle of a Recipe `just` doesn't support running recipes in the middle of another recipe, but you can call `just` recursively in the middle of a recipe. Given the following justfile: ```make a: echo 'A!' b: a echo 'B start!' just c echo 'B end!' c: echo 'C!' ``` …running 'b' prints: ```sh $ just b echo 'A!' A! echo 'B start!' B start! echo 'C!' C! echo 'B end!' B end! ``` This has limitations, since recipe `c` is run with an entirely new invocation of `just`: Assignments will be recalculated, dependencies might run twice, and command line arguments will not be propagated to the child `just` process. === Writing Recipes in Other Languages Recipes that start with a `#!` are executed as scripts, so you can write recipes in other languages: ```make polyglot: python js perl sh ruby python: #!/usr/bin/env python3 print('Hello from python!') js: #!/usr/bin/env node console.log('Greetings from JavaScript!') perl: #!/usr/bin/env perl print ""Larry Wall says Hi!\\n""; sh: #!/usr/bin/env sh hello='Yo' echo ""$hello from a shell script!"" ruby: #!/usr/bin/env ruby puts ""Hello from ruby!"" ``` ```sh $ just polyglot Hello from python! Greetings from JavaScript! Larry Wall says Hi! Yo from a shell script! Hello from ruby! ``` === Safer Bash Shebang Recipes If you're writing a `bash` shebang recipe, consider adding `set -euxo pipefail`: ```make foo: #!/usr/bin/env bash set -euxo pipefail hello='Yo' echo ""$hello from Bash!"" ``` It isn't strictly necessary, but `set -euxo pipefail` turns on a few useful features that make `bash` shebang recipes behave more like normal, linewise `just` recipe: - `set -e` makes `bash` exit if a command fails. - `set -u` makes `bash` exit if a variable is undefined. - `set -x` makes `bash` print each script line before it's run. - `set -o pipefail` makes `bash` exit if a command in a pipeline fails. Together, these avoid a lot of shell scripting gotchas. ==== Shebang Recipe Execution on Windows On Windows, shebang interpreter paths containing a `/` are translated from Unix-style paths to Windows-style paths using `cygpath`, a utility that ships with http://www.cygwin.com[Cygwin]. For example, to execute this recipe on Windows: ```make echo: #!/bin/sh echo ""Hello!"" ``` The interpreter path `/bin/sh` will be translated to a Windows-style path using `cygpath` before being executed. If the interpreter path does not contain a `/` it will be executed without being translated. This is useful if `cygpath` is not available, or you wish to pass a Windows-style path to the interpreter. === Setting Variables in a Recipe Recipe lines are interpreted by the shell, not `just`, so it's not possible to set `just` variables in the middle of a recipe: ``` foo: x := ""hello"" # This doesn't work! echo {{x}} ``` It is possible to use shell variables, but there's another problem. Every recipe line is run by a new shell instance, so variables set in one line won't be set in the next: ```make foo: x=hello && echo $x # This works! y=bye echo $y # This doesn't, `y` is undefined here! ``` The best way to work around this is to use a shebang recipe. Shebang recipe bodies are extracted and run as scripts, so a single shell instance will run the whole thing: ```make foo: #!/usr/bin/env bash set -euxo pipefail x=hello echo $x ``` === Changing the Working Directory in a Recipe Each recipe line is executed by a new shell, so if you change the working directory on one line, it won't have an effect on later lines: ```make foo: pwd # This `pwd` will print the same directory… cd bar pwd # …as this `pwd`! ``` There are a couple ways around this. One is to call `cd` on the same line as the command you want to run: ```make foo: cd bar && pwd ``` The other is to use a shebang recipe. Shebang recipe bodies are extracted and run as scripts, so a single shell instance will run the whole thing, and thus a `pwd` on one line will affect later lines, just like a shell script: ```make foo: #!/usr/bin/env bash set -euxo pipefail cd bar pwd ``` === Multi-Line Constructs Recipes without an initial shebang are evaluated and run line-by-line, which means that multi-line constructs probably won't do what you want. For example, with the following justfile: ``` conditional: if true; then echo 'True!' fi ``` The extra leading whitespace before the second line of the `conditional` recipe will produce a parse error: ``` $ just conditional error: Recipe line has extra leading whitespace | 3 | echo 'True!' | ^^^^^^^^^^^^^^^^ ``` To work around this, you can write conditionals on one line, escape newlines with slashes, or add a shebang to your recipe. Some examples of multi-line constructs are provided for reference. ==== `if` statements ```make conditional: if true; then echo 'True!'; fi ``` ```make conditional: if true; then \\ echo 'True!'; \\ fi ``` ```make conditional: #!/usr/bin/env sh if true; then echo 'True!' fi ``` ==== `for` loops ```make for: for file in `ls .`; do echo $file; done ``` ```make for: for file in `ls .`; do \\ echo $file; \\ done ``` ```make for: #!/usr/bin/env sh for file in `ls .`; do echo $file done ``` ==== `while` loops ```make while: while `server-is-dead`; do ping -c 1 server; done ``` ```make while: while `server-is-dead`; do \\ ping -c 1 server; \\ done ``` ```make while: #!/usr/bin/env sh while `server-is-dead`; do do ping -c 1 server done ``` === Command Line Options `just` supports a number of useful command line options for listing, dumping, and debugging recipes and variable: ```sh $ just --list Available recipes: js perl polyglot python ruby $ just --show perl perl: #!/usr/bin/env perl print ""Larry Wall says Hi!\\n""; $ just --show polyglot polyglot: python js perl sh ruby ``` Run `just --help` to see all the options. === Private Recipes Recipes and aliases whose name starts with a `_` are omitted from `just --list`: ```make test: _test-helper ./bin/test _test-helper: ./bin/super-secret-test-helper-stuff ``` ```sh $ just --list Available recipes: test ``` And from `just --summary`: ```sh $ just --summary test ``` This is useful for helper recipes which are only meant to be used as dependencies of other recipes. === Quiet Recipes A recipe name may be prefixed with '@' to invert the meaning of '@' before each line: ```make @quiet: echo hello echo goodbye @# all done! ``` Now only the lines starting with '@' will be echoed: ```sh $ j quiet hello goodbye # all done! ``` Shebang recipes are quiet by default: ```make foo: #!/usr/bin/env bash echo 'Foo!' ``` ```sh $ just foo Foo! ``` Adding `@` to a shebang recipe name makes `just` print the recipe before executing it: ```make @bar: #!/usr/bin/env bash echo 'Bar!' ``` ```sh $ just bar ~/src/just #!/usr/bin/env bash echo 'Bar!' Bar! ``` === Selecting Recipes to Run With an Interactive Chooser The `--choose` subcommand makes `just` invoke a chooser to select which recipes to run. Choosers should read lines containing recipe names from standard input and print one or more of those names separated by spaces to standard output. Because there is currently no way to run a recipe that requires arguments with `--choose`, such recipes will not be given to the chooser. Private recipes and aliases are also skipped. The chooser can be overridden with the `--chooser` flag. If `--chooser` is not given, then `just` first checks if `$JUST_CHOOSER` is set. If it isn't, then the chooser defaults to `fzf`, a popular fuzzy finder. Arguments can be included in the chooser, i.e. `fzf --exact`. The chooser is invoked in the same way as recipe lines. For example, if the chooser is `fzf`, it will be invoked with `sh -cu 'fzf'`, and if the shell, or the shell arguments are overridden, the chooser invocation will respect those overrides. If you'd like `just` to default to selecting recipes with a chooser, you can use this as your default recipe: ```make default: @just --choose ``` === Invoking Justfiles in Other Directories If the first argument passed to `just` contains a `/`, then the following occurs: 1. The argument is split at the last `/`. 2. The part before the last `/` is treated as a directory. `just` will start its search for the justfile there, instead of in the current directory. 3. The part after the last slash is treated as a normal argument, or ignored if it is empty. This may seem a little strange, but it's useful if you wish to run a command in a justfile that is in a subdirectory. For example, if you are in a directory which contains a subdirectory named `foo`, which contains a justfile with the recipe `build`, which is also the default recipe, the following are all equivalent: ```sh $ (cd foo && just build) $ just foo/build $ just foo/ ``` === Hiding Justfiles `just` looks for justfiles named `justfile` and `.justfile`, which can be used to keep a `justfile` hidden. === Just Scripts By adding a shebang line to the top of a justfile and making it executable, `just` can be used as an interpreter for scripts: ```sh $ cat > script < just.zsh ``` === Grammar A non-normative grammar of justfiles can be found in link:GRAMMAR.md[]. === just.sh Before `just` was a fancy Rust program it was a tiny shell script that called `make`. You can find the old version in link:extras/just.sh[]. === Non-Project Specific Justfile If you want some commands to be available everywhere, put them in `~/.global.justfile` and add the following to your shell's initialization file: ```sh alias .j='just --justfile ~/.global.justfile --working-directory ~' ``` Or, if you'd rather they run in the current directory: ```sh alias .j='just --justfile ~/.global.justfile --working-directory .' ``` I'm pretty sure that nobody actually uses this feature, but it's there. ¯\\\\_(ツ)_/¯ == Contributing `just` welcomes your contributions! `just` is released under the maximally permissive https://creativecommons.org/publicdomain/zero/1.0/legalcode.txt[CC0] public domain dedication and fallback license, so your changes must also be released under this license. === Janus https://github.com/casey/janus[Janus] is a tool that collects and analyzes justfiles, and can determine if a new version of `just` breaks or changes the interpretation of existing justfiles. Before merging a particularly large or gruesome change, Janus should be run to make sure that nothing breaks. Don't worry about running Janus yourself, Casey will happily run it for you on changes that need it. === Minimum Supported Rust Version The minimum supported Rust version, or MSRV, can be found in link:rust-toolchain[]. == Frequently Asked Questions === What are the idiosyncrasies of Make that Just avoids? `make` has some behaviors which are confusing, complicated, or make it unsuitable for use as a general command runner. One example is that under some circumstances, `make` won't actually run the commands in a recipe. For example, if you have a file called `test` and the following makefile: ```make test: ./test ``` `make` will refuse to run your tests: ```sh $ make test make: `test' is up to date. ``` `make` assumes that the `test` recipe produces a file called `test`. Since this file exists and the recipe has no other dependencies, `make` thinks that it doesn't have anything to do and exits. To be fair, this behavior is desirable when using `make` as a build system, but not when using it as a command runner. You can disable this behavior for specific targets using `make`'s built-in link:https://www.gnu.org/software/make/manual/html_node/Phony-Targets.html[`.PHONY` target name], but the syntax is verbose and can be hard to remember. The explicit list of phony targets, written separately from the recipe definitions, also introduces the risk of accidentally defining a new non-phony target. In `just`, all recipes are treated as if they were phony. Other examples of `make`'s idiosyncrasies include the difference between `=` and `:=` in assignments, the confusing error messages that are produced if you mess up your makefile, needing `$$` to use environment variables in recipes, and incompatibilities between different flavors of `make`. === What's the relationship between Just and Cargo build scripts? http://doc.crates.io/build-script.html[`cargo` build scripts] have a pretty specific use, which is to control how `cargo` builds your Rust project. This might include adding flags to `rustc` invocations, building an external dependency, or running some kind of codegen step. `just`, on the other hand, is for all the other miscellaneous commands you might run as part of development. Things like running tests in different configurations, linting your code, pushing build artifacts to a server, removing temporary files, and the like. Also, although `just` is written in Rust, it can be used regardless of the language or build system your project uses. == Further Ramblings I personally find it very useful to write a `justfile` for almost every project, big or small. On a big project with multiple contributors, it's very useful to have a file with all the commands needed to work on the project close at hand. There are probably different commands to test, build, lint, deploy, and the like, and having them all in one place is useful and cuts down on the time you have to spend telling people which commands to run and how to type them. And, with an easy place to put commands, it's likely that you'll come up with other useful things which are part of the project's collective wisdom, but which aren't written down anywhere, like the arcane commands needed for some part of your revision control workflow, install all your project's dependencies, or all the random flags you might need to pass to the build system. Some ideas for recipes: * Deploying/publishing the project * Building in release mode vs debug mode * Running in debug mode or with logging enabled * Complex git workflows * Updating dependencies * Running different sets of tests, for example fast tests vs slow tests, or running them with verbose output * Any complex set of commands that you really should write down somewhere, if only to be able to remember them Even for small, personal projects it's nice to be able to remember commands by name instead of ^Reverse searching your shell history, and it's a huge boon to be able to go into an old project written in a random language with a mysterious build system and know that all the commands you need to do whatever you need to do are in the `justfile`, and that if you type `just` something useful (or at least interesting!) will probably happen. For ideas for recipes, check out link:justfile[this project's `justfile`], or some of the `justfile`{zwsp}s https://github.com/search?o=desc&q=filename%3Ajustfile&s=indexed&type=Code[out in the wild]. Anyways, I think that's about it for this incredibly long-winded README. I hope you enjoy using `just` and find great success and satisfaction in all your computational endeavors! 😸 ",12284,False,1925.6689713030287,median ":gradle-issues: https://github.com/gradle/gradle/issues/ [[config_cache]] = Configuration cache // Run tests for snippets included in this chapter with: // ./gradlew :docs:docsTest --tests=""ExemplarExternalSamplesFunctionalTest.snippet-configuration-cache-*"" // ./gradlew :docs:docsTest --tests=""ExemplarExternalSamplesFunctionalTest.snippet-value-providers-*"" [NOTE] ==== The configuration cache is an <> feature, and the details described here may change. ==== [[config_cache:intro]] == Introduction The configuration cache is a feature that significantly improves build performance by caching the result of the <> and reusing this for subsequent builds. Using the configuration cache, Gradle can skip the configuration phase entirely when nothing that affects the build configuration, such as build scripts, has changed. Gradle also applies some performance improvements to task execution as well. The configuration cache is conceptually similar to the <>, but caches different information. The build cache takes care of caching the outputs and intermediate files of the build, such as task outputs or artifact transform outputs. The configuration cache takes care of caching the build configuration for a particular set of tasks. In other words, the configuration cache saves the output of the configuration phase, and the build cache saves the outputs of the execution phase. [IMPORTANT] ==== This feature is currently *_incubating_* and not enabled by default. Not all <> are supported. Your build and the plugins you depend on might require changes to fulfil the <>. Some Gradle features are <>. Importing and syncing Gradle builds in IDEs is not improved by configuration caching yet. ==== [[config_cache:intro:how_does_it_work]] === How does it work? When the configuration cache is enabled and you run Gradle for a particular set of tasks, for example by running `gradlew check`, Gradle checks whether a configuration cache entry is available for the requested set of tasks. If available, Gradle uses this entry instead of running the configuration phase. The cache entry contains information about the set of tasks to run, along with their configuration and dependency information. The first time you run a particular set of tasks, there will be no entry in the configuration cache for these tasks and so Gradle will run the configuration phase as normal: 1. Run init scripts. 2. Run the settings script for the build, applying any requested settings plugins. 3. Configure and build the `buildSrc` project, if present. 4. Run the builds scripts for the build, applying any requested project plugins. 5. Calculate the task graph for the requested tasks, running any deferred configuration actions. Following the configuration phase, Gradle writes the state of the task graph to the configuration cache, taking a snapshot for later Gradle invocations. The execution phase then runs as normal. This means you will not see any build performance improvement the first time you run a particular set of tasks. When you subsequently run Gradle with this same set of tasks, for example by running `gradlew check` again, Gradle will load the tasks and their configuration directly from the configuration cache and skip the configuration phase entirely. Before using a configuration cache entry, Gradle checks that none of the ""build configuration inputs"", such as build scripts, for the entry have changed. If a build configuration input has changed, Gradle will not use the entry and will run the configuration phase again as above, saving the result for later reuse. Build configuration inputs include: - Init scripts, settings scripts, build scripts. - System properties, Gradle properties, environment variables used during the configuration phase - Configuration files accessed using value suppliers such as providers - `buildSrc` build configuration inputs and source files. Gradle uses its own optimized serialization mechanism and format to store the configuration cache entries. It automatically serializes the state of arbitrary object graphs. If your tasks hold references to objects with simple state or of supported types you don't have anything to do to support the serialization. As a fallback and to provide some aid in migrating existing tasks, some semantics of <> are supported. But it is not recommended relying on it, mostly for performance reasons. [[config_cache:intro:performance_improvements]] === Performance improvements Apart from skipping the configuration phase, the configuration cache provides some additional performance improvements: - All tasks run in parallel by default. - Dependency resolution is cached. [[config_cache:in_action]] === Configuration caching in action image::configuration-cache/running-help.gif[] [[config_cache:usage]] == Using the configuration cache It is recommended to get started with the simplest task invocation possible. Running `help` with the configuration cache enabled is a good first step: ---- ❯ gradle --configuration-cache help include::{snippetsPath}/configurationCache/noProblem/tests/store.out[] ... BUILD SUCCESSFUL in 4s 1 actionable task: 1 executed Configuration cache entry stored. ---- Running this for the first time, the configuration phase is executed, calculating the task graph. Then, run the same command again. This will reuse the cached configuration: ---- ❯ gradle --configuration-cache help include::{snippetsPath}/configurationCache/noProblem/tests/load.out[] ... BUILD SUCCESSFUL in 500ms 1 actionable task: 1 executed Configuration cache entry reused. ---- If it succeeds on your build, congratulations, you can now try with more useful tasks. You should target your development loop. A good example is running tests after making incremental changes. If any problem is found caching or reusing the configuration, an HTML report is generated to help you diagnose and fix the issues. The report also shows detected build configuration inputs like system properties, environment variables and value suppliers read during the configuration phase. See the <> section below for more information. Keep reading to learn how to tweak the configuration cache, manually invalidate the state if something goes wrong and use the configuration cache from an IDE. [[config_cache:usage:enable]] === Enabling the configuration cache By default, the configuration cache is not enabled. It can be enabled from the command line: ---- ❯ gradle --configuration-cache ---- It can also be enabled persistently in a `gradle.properties` file: [source,properties] ---- org.gradle.unsafe.configuration-cache=true ---- If it is enabled in a `gradle.properties` file, it can be disabled on the command line for one build invocation: ---- ❯ gradle --no-configuration-cache ---- [[config_cache:usage:ignore_problems]] === Ignoring problems By default, Gradle will fail the build if any configuration cache problems are encountered. When gradually improving your plugin or build logic to support the configuration cache it can be useful to temporarily turn problems into warnings. This can be done from the command line: ---- ❯ gradle --configuration-cache-problems=warn ---- or in a `gradle.properties` file: [source,properties] ---- org.gradle.unsafe.configuration-cache-problems=warn ---- [[config_cache:usage:max_problems]] === Allowing a maximum number of problems When configuration cache problems are turned into warnings, Gradle will fail the build if `512` problems are found by default. This can be adjusted by specifying an allowed maximum number of problems on the command line: ---- ❯ gradle -Dorg.gradle.unsafe.configuration-cache.max-problems=5 ---- or in a `gradle.properties` file: [source,properties] ---- org.gradle.unsafe.configuration-cache.max-problems=5 ---- [[config_cache:usage:invalidate]] === Invalidating the cache The configuration cache is automatically invalidated when inputs to the configuration phase change. However, certain inputs are not tracked yet, so you may have to manually invalidate the configuration cache when untracked inputs to the configuration phase change. This can happen if you <>. See the <> and <> sections below for more information. The configuration cache state is stored on disk in a directory named `.gradle/configuration-cache` in the root directory of the Gradle build in use. If you need to invalidate the cache, simply delete that directory: ---- ❯ rm -rf .gradle/configuration-cache ---- Configuration cache entries are checked periodically (at most every 24 hours) for whether they are still in use. They are deleted if they haven't been used for 7 days. [[config_cache:ide]] == IDE support If you enable and configure the configuration cache from your `gradle.properties` file, then the configuration cache will be enabled when your IDE delegates to Gradle. There's nothing more to do. `gradle.properties` is usually checked in to source control. If you don't want to enable the configuration cache for your whole team yet you can also enable the configuration cache from your IDE only as explained below. Note that syncing a build from an IDE doesn't benefit from the configuration cache, only running tasks does. [[config_cache:ide:intellij]] === IntelliJ based IDEs In IntelliJ IDEA or Android Studio this can be done in two ways, either globally or per run configuration. To enable it for the whole build, go to `Run > Edit configurations...`. This will open the IntelliJ IDEA or Android Studio dialog to configure Run/Debug configurations. Select `Templates > Gradle` and add the necessary system properties to the `VM options` field. For example to enable the configuration cache, turning problems into warnings, add the following: ---- -Dorg.gradle.unsafe.configuration-cache=true -Dorg.gradle.unsafe.configuration-cache-problems=warn ---- You can also choose to only enable it for a given run configuration. In this case, leave the `Templates > Gradle` configuration untouched and edit each run configuration as you see fit. Combining these two ways you can enable globally and disable for certain run configurations, or the opposite. [TIP] ==== You can use the link:https://github.com/JetBrains/gradle-idea-ext-plugin[gradle-idea-ext-plugin] to configure IntelliJ run configurations from your build. This is a good way to enable the configuration cache only for the IDE. ==== [[config_cache:ide:eclipse]] === Eclipse IDEs In Eclipse IDEs you can enable and configure the configuration cache through Buildship in two ways, either globally or per run configuration. To enable it globally, go to `Preferences > Gradle`. You can use the properties described above as system properties. For example to enable the configuration cache, turning problems into warnings, add the following JVM arguments: * `-Dorg.gradle.unsafe.configuration-cache=true` * `-Dorg.gradle.unsafe.configuration-cache-problems=warn` To enable it for a given run configuration, go to `Run configurations...`, find the one you want to change, go to `Project Settings`, tick the `Override project settings` checkbox and add the same system properties as a `JVM argument`. Combining these two ways you can enable globally and disable for certain run configurations, or the opposite. [[config_cache:plugins]] == Supported plugins The configuration cache is brand new and introduces new requirements for plugin implementations. As a result, both core Gradle plugins, and community plugins need to be adjusted. This section provides information about the current support in <> and <>. [[config_cache:plugins:core]] === Core Gradle plugins Not all <> support configuration caching yet. [cols=3*] |=== h| JVM languages and frameworks h| Native languages h| Packaging and distribution a| [horizontal] link:{gradle-issues}13455[[.green]#✓#]:: <> link:{gradle-issues}13455[[.green]#✓#]:: <> link:{gradle-issues}13455[[.green]#✓#]:: <> link:{gradle-issues}13460[[.green]#✓#]:: <> link:{gradle-issues}13461[[.green]#✓#]:: <> link:{gradle-issues}13462[[.yellow]#⚠#]:: <> a| [horizontal] link:{gradle-issues}13484[[.red]#✖#]:: <> link:{gradle-issues}13485[[.red]#✖#]:: <> link:{gradle-issues}13514[[.red]#✖#]:: <> link:{gradle-issues}13515[[.red]#✖#]:: <> link:{gradle-issues}13487[[.red]#✖#]:: <> link:{gradle-issues}13488[[.red]#✖#]:: <> a| [horizontal] link:{gradle-issues}13455[[.green]#✓#]:: <> link:{gradle-issues}13455[[.green]#✓#]:: <> link:{gradle-issues}13455[[.green]#✓#]:: <> link:{gradle-issues}13468[[.yellow]#⚠#]:: <> link:{gradle-issues}13469[[.red]#✖#]:: <> link:{gradle-issues}13455[[.green]#✓#]:: <> link:{gradle-issues}13455[[.green]#✓#]:: <> h| Code analysis h| IDE project files generation h| Utility a| [horizontal] link:{gradle-issues}13475[[.green]#✓#]:: <> link:{gradle-issues}13478[[.green]#✓#]:: <> link:{gradle-issues}13477[[.green]#✓#]:: <> [.green]#✓#:: <> link:{gradle-issues}13476[[.green]#✓#]:: <> [.green]#✓#:: <> a| [horizontal] link:{gradle-issues}13479[[.red]#✖#]:: <> link:{gradle-issues}13480[[.red]#✖#]:: <> link:{gradle-issues}13482[[.red]#✖#]:: <> link:{gradle-issues}13483[[.red]#✖#]:: <> a| [horizontal] link:{gradle-issues}13455[[.green]#✓#]:: <> link:{gradle-issues}13466[[.yellow]#⚠#]:: <> link:{gradle-issues}13470[[.red]#✖#]:: <> link:{gradle-issues}13455[[.green]#✓#]:: <> link:{gradle-issues}13472[[.red]#✖#]:: <> link:{gradle-issues}13472[[.red]#✖#]:: <> link:{gradle-issues}13473[[.red]#✖#]:: <> |=== [horizontal] [.green]#✓#:: Supported plugin [.yellow]#⚠#:: Partially supported plugin [.red]#✖#:: Unsupported plugin [[config_cache:plugins:community]] === Community plugins Please refer to issue link:{gradle-issues}13490[gradle/gradle#13490] to learn about the status of community plugins. [[config_cache:troubleshooting]] == Troubleshooting The following sections will go through some general guidelines on dealing with problems with the configuration cache. This applies to both your build logic and to your Gradle plugins. Upon failure to serialize the state required to run the tasks, an HTML report of detected problems is generated. The Gradle failure output includes a clickable link to the report. This report is useful and allows you to drill down into problems, understand what is causing them. Let's look at a simple example build script that contains a couple problems: ==== include::sample[dir=""snippets/configurationCache/problemsGroovy/groovy"",files=""build.gradle[]""] include::sample[dir=""snippets/configurationCache/problemsKotlin/kotlin"",files=""build.gradle.kts[]""] ==== <1> <> <2> <> Running that task fails and print the following in the console: ---- ❯ gradle --configuration-cache someTask -DsomeDestination=dest ... include::{snippetsPath}/configurationCache/problemsGroovy/tests/fail.out[] Configuration cache entry discarded with 1 problem. ---- The configuration cache entry was discarded because of the found problem failing the build. Details can be found in the linked HTML report: image::configuration-cache/problems-report.png[] The report displays the set of problems twice. First grouped by problem message, then grouped by task. The former allows you to quickly see what classes of problems your build is facing. The latter allows you to quickly see which tasks are problematic. In both cases you can expand the tree in order to discover where the culprit is in the object graph. The report also includes a list of detected build configuration inputs, such as environment variables, system properties and value suppliers that were read at configuration phase: image::configuration-cache/inputs-report.png[] [TIP] ==== Problems displayed in the report have links to the corresponding <> where you can find guidance on how to fix the problem or to the corresponding <> feature. When changing your build or plugin to fix the problems you should consider <>. ==== At this stage, you can decide to either <> and continue exploring how your build reacts to the configuration cache, or fix the problems at hand. Let's ignore the reported problem, and run the same build again twice to see what happens when reusing the cached problematic configuration: ---- ❯ gradle --configuration-cache --configuration-cache-problems=warn someTask -DsomeDestination=dest include::{snippetsPath}/configurationCache/problemsGroovy/tests/store.out[] Configuration cache entry stored with 1 problem. ❯ gradle --configuration-cache --configuration-cache-problems=warn someTask -DsomeDestination=dest include::{snippetsPath}/configurationCache/problemsGroovy/tests/load.out[] Configuration cache entry reused with 1 problem. ---- The two builds succeed reporting the observed problem, storing then reusing the configuration cache. With the help of the links present in the console problem summary and in the HTML report we can fix our problems. Here's a fixed version of the build script: ==== include::sample[dir=""snippets/configurationCache/problemsFixed/groovy"",files=""build.gradle[tags=fixed]""] include::sample[dir=""snippets/configurationCache/problemsFixed/kotlin"",files=""build.gradle.kts[tags=fixed]""] ==== <1> We turned our ad-hoc task into a proper task class, <2> with inputs and outputs declaration, <3> and injected with the `FileSystemOperations` service, a supported replacement for <>. Running the task twice now succeeds without reporting any problem and reuses the configuration cache on the second run: ---- ❯ gradle --configuration-cache someTask -DsomeDestination=dest include::{snippetsPath}/configurationCache/problemsFixed/tests/store.out[] Configuration cache entry stored. ❯ gradle --configuration-cache someTask -DsomeDestination=dest include::{snippetsPath}/configurationCache/problemsFixed/tests/load.out[] Configuration cache entry reused. ---- But, what if we change the value of the system property? ---- ❯ gradle --configuration-cache someTask -DsomeDestination=another include::{snippetsPath}/configurationCache/problemsFixed/tests/store-another.out[] Configuration cache entry stored. ---- The previous configuration cache entry could not be reused, and the task graph had to be calculated and stored again. This is because we read the system property at configuration time, hence requiring Gradle to run the configuration phase again when the value of that property changes. Fixing that is as simple as obtaining the provider of the system property and wiring it to the task input, without reading it at configuration time. ==== include::sample[dir=""snippets/configurationCache/problemsFixedReuse/groovy"",files=""build.gradle[tags=fixed-reuse]""] include::sample[dir=""snippets/configurationCache/problemsFixedReuse/kotlin"",files=""build.gradle.kts[tags=fixed-reuse]""] ==== <1> We wired the system property provider directly, without reading it at configuration time. With this simple change in place we can run the task any number of times, change the system property value, and reuse the configuration cache: ---- ❯ gradle --configuration-cache someTask -DsomeDestination=dest include::{snippetsPath}/configurationCache/problemsFixedReuse/tests/store.out[] Configuration cache entry stored. ❯ gradle --configuration-cache someTask -DsomeDestination=another include::{snippetsPath}/configurationCache/problemsFixedReuse/tests/load-another.out[] Configuration cache entry reused. ---- We're now done with fixing the problems with this simple task. Keep reading to learn how to adopt the configuration cache for your build or your plugins. [[config_cache:task_opt_out]] === Declare a task incompatible with the configuration cache It is possible to declare that a particular task is not compatible with the configuration cache via the link:{javadocPath}/org/gradle/api/Task.html#notCompatibleWithConfigurationCache-java.lang.String-[Task.notCompatibleWithConfigurationCache()] method. Configuration cache problems found in tasks marked incompatible will no longer cause the build to fail. And, when an incompatible task is scheduled to run, Gradle discards the configuration state at the end of the build. You can use this to help with migration, by temporarily opting out certain tasks that are difficult to change to work with the configuration cache. Check the method documentation for more details. [[config_cache:adoption]] == Adoption steps An important prerequisite is to keep your Gradle and plugins versions up to date. The following explores the recommended steps for a successful adoption. It applies both to builds and plugins. While going through these steps, keep in mind the HTML report and the solutions explained in the <> chapter below. Start with `:help`:: Always start by trying your build or plugin with the simplest task `:help`. This will exercise the minimal configuration phase of your build or plugin. Progressively target useful tasks:: Don't go with running `build` right away. You can also use `--dry-run` to discover more configuration time problems first. + When working on a build, progressively target your development feedback loop. For example, running tests after making some changes to the source code. + When working on a plugin, progressively target the contributed or configured tasks. Explore by turning problems into warnings:: Don't stop at the first build failure and <> to discover how your build and plugins behave. If a build fails, use the HTML report to reason about the reported problems related to the failure. Continue running more useful tasks. + This will give you a good overview of the nature of the problems your build and plugins are facing. Remember that when turning problems into warnings you might need to <> in case of troubles. Step back and fix problems iteratively:: When you feel you know enough about what needs to be fixed, take a step back and start iteratively fixing the most important problems. Use the HTML report and this documentation to help you in this journey. + Start with problems reported when _storing_ the configuration cache. Once fixed, you can rely on a valid cached configuration phase and move on to fixing problems reported when _loading_ the configuration cache if any. Report encountered issues:: If you face a problem with a <> or with a <> that is not covered by this documentation, please report an issue on link:https://github.com/gradle/gradle/issues/new/choose[`gradle/gradle`]. + If you face a problem with a community Gradle plugin, see if it is already listed at link:{gradle-issues}13490[gradle/gradle#13490] and consider reporting the issue to the plugin's issue tracker. + A good way to report such issues is by providing information such as: + * a link to this very documentation, * the plugin version you tried, * the custom configuration of the plugin if any, or ideally a reproducer build, * a description of what fails, for example problems with a given task * a copy of the build failure, * the self-contained `configuration-cache-report.html` file. Test, test, test:: Consider adding tests for your build logic. See the below section on <> for the configuration cache. This will help you while iterating on the required changes and prevent future regressions. Roll it out to your team:: Once you have your developer workflow working, for example running tests from the IDE, you can consider enabling it for your team. A faster turnaround when changing code and running tests could be worth it. You'll probably want to do this as an opt-in first. + If needed, turn problems into warnings and set the maximum number of allowed problems in your build `gradle.properties` file. Keep the configuration cache disabled by default. Let your team know they can opt-in by, for example, enabling the configuration cache on their IDE run configurations for the supported workflow. + Later on, when more workflows are working, you can flip this around. Enable the configuration cache by default, configure CI to disable it, and if required communicate the unsupported workflow(s) for which the configuration cache needs to be disabled. [[config_cache:testing]] == Testing your build logic The Gradle TestKit (a.k.a. just TestKit) is a library that aids in testing Gradle plugins and build logic generally. For general guidance on how to use TestKit, see the <>. To enable configuration caching in your tests, you can pass the `--configuration-cache` argument to link:{javadocPath}/org/gradle/testkit/runner/GradleRunner.html[GradleRunner] or use one of the other methods described in <>. You need to run your tasks twice. Once to prime the configuration cache. Once to reuse the configuration cache. .Testing the configuration cache ==== include::sample[dir=""snippets/configurationCache/testKit/groovy"",files=""src/test/groovy/org/example/BuildLogicFunctionalTest.groovy[tags=functional-test-configuration-cache]""] include::sample[dir=""snippets/configurationCache/testKit/kotlin"",files=""src/test/kotlin/org/example/BuildLogicFunctionalTest.kt[tags=functional-test-configuration-cache]""] ==== <1> First run primes the configuration cache. <2> Second run reuses the configuration cache. <3> Assert that the configuration cache gets reused. If problems with the configuration cache are found then Gradle will fail the build reporting the problems, and the test will fail. [TIP] ==== A good testing strategy for a Gradle plugin is to run its whole test suite with the configuration cache enabled. This requires testing the plugin with a supported Gradle version. If the plugin already supports a range of Gradle versions it might already have tests for multiple Gradle versions. In that case we recommend enabling the configuration cache starting with the Gradle version that supports it. If this can’t be done right away, using tests that runs all tasks contributed by the plugin several times, for e.g. asserting the `UP_TO_DATE` and `FROM_CACHE` behavior, is also a good strategy. ==== [[config_cache:requirements]] == Requirements In order to capture the state of the task graph to the configuration cache and reload it again in a later build, Gradle applies certain requirements to tasks and other build logic. Each of these requirements is treated as a configuration cache ""problem"" and fails the build if violations are present. For the most part these requirements are actually surfacing some undeclared inputs. In other words, using the configuration cache is an opt-in to more strictness, correctness and reliability for all builds. The following sections describe each of the requirements and how to change your build to fix the problems. [[config_cache:requirements:disallowed_types]] === Certain types must not be referenced by tasks There are a number of types that task instances must not reference from their fields. The same applies to task actions as closures such as `doFirst {}` or `doLast {}`. These types fall into some categories as follows: * Live JVM state types * Gradle model types * Dependency management types In all cases the reason these types are disallowed is that their state cannot easily be stored or recreated by the configuration cache. Live JVM state types (e.g. `ClassLoader`, `Thread`, `OutputStream`, `Socket` etc...) are simply disallowed. These types almost never represent a task input or output. Gradle model types (e.g. `Gradle`, `Settings`, `Project`, `SourceSet`, `Configuration` etc...) are usually used to carry some task input that should be explicitly and precisely declared instead. For example, if you reference a `Project` in order to get the `project.version` at execution time, you should instead directly declare the _project version_ as an input to your task using a `Property`. Another example would be to reference a `SourceSet` to later get the source files, the compilation classpath or the outputs of the source set. You should instead declare these as a `FileCollection` input and reference just that. The same requirement applies to dependency management types with some nuances. Some types, such as `Configuration` or `SourceDirectorySet`, don't make good task input parameters, as they hold a lot of irrelevant state, and it is better to model these inputs as something more precise. We don't intend to make these types serializable at all. For example, if you reference a `Configuration` to later get the resolved files, you should instead declare a `FileCollection` as an input to your task. In the same vein, if you reference a `SourceDirectorySet` you should instead declare a `FileTree` as an input to your task. Referencing dependency resolution results is also disallowed (e.g. `ArtifactResolutionQuery`, `ResolvedArtifact`, `ArtifactResult` etc...). For example, if you reference some `ResolvedComponentResult` instances, you should instead declare a `Provider` as an input to your task. Such a provider can be obtained by invoking `ResolutionResult.getRootComponent()`. In the same vein, if you reference some `ResolvedArtifactResult` instances, you should instead use `ArtifactCollection.getResolvedArtifacts()` that returns a `Provider>` that can be mapped as an input to your task. The rule of thumb is that tasks must not reference _resolved_ results, but lazy specifications instead, in order to do the dependency resolution at execution time. Some types, such as `Publication` or `Dependency` are not serializable, but could be. We may, if necessary, allow these to be used as task inputs directly. Here's an example of a problematic task type referencing a `SourceSet`: ==== include::sample[dir=""snippets/configurationCache/disallowedTypes/groovy"",files=""build.gradle[tags=task-type]""] include::sample[dir=""snippets/configurationCache/disallowedTypes/kotlin"",files=""build.gradle.kts[tags=task-type]""] ==== <1> this will be reported as a problem because referencing `SourceSet` is not allowed The following is how it should be done instead: ==== include::sample[dir=""snippets/configurationCache/disallowedTypesFixed/groovy"",files=""build.gradle[tags=task-type]""] include::sample[dir=""snippets/configurationCache/disallowedTypesFixed/kotlin"",files=""build.gradle.kts[tags=task-type]""] ==== <1> no more problems reported, we now reference the supported type `FileCollection` In the same vein, if you encounter the same problem with an ad-hoc task declared in a script as follows: ==== include::sample[dir=""snippets/configurationCache/disallowedTypes/groovy"",files=""build.gradle[tags=ad-hoc-task]""] include::sample[dir=""snippets/configurationCache/disallowedTypes/kotlin"",files=""build.gradle.kts[tags=ad-hoc-task]""] ==== <1> this will be reported as a problem because the `doLast {}` closure is capturing a reference to the `SourceSet` You still need to fulfil the same requirement, that is not referencing a disallowed type. Here's how the task declaration above can be fixed: ==== include::sample[dir=""snippets/configurationCache/disallowedTypesFixed/groovy"",files=""build.gradle[tags=ad-hoc-task]""] include::sample[dir=""snippets/configurationCache/disallowedTypesFixed/kotlin"",files=""build.gradle.kts[tags=ad-hoc-task]""] ==== <1> no more problems reported, the `doLast {}` closure now only captures `classpath` which is of the supported `FileCollection` type Note that sometimes the disallowed type is indirectly referenced. For example, you could have a task reference some type from a plugin that is allowed. That type could reference another allowed type that in turn references a disallowed type. The hierarchical view of the object graph provided in the HTML reports for problems should help you pinpoint the offender. [[config_cache:requirements:use_project_during_execution]] === Using the `Project` object A task must not use any `Project` objects at execution time. This includes calling `Task.getProject()` while the task is running. Some cases can be fixed in the same way as for <>. Often, similar things are available on both `Project` and `Task`. For example if you need a `Logger` in your task actions you should use `Task.logger` instead of `Project.logger`. Otherwise, you can use <> instead of the methods of `Project`. Here's an example of a problematic task type using the `Project` object at execution time: ==== include::sample[dir=""snippets/configurationCache/projectAtExecution/groovy"",files=""build.gradle[tags=task-type]""] include::sample[dir=""snippets/configurationCache/projectAtExecution/kotlin"",files=""build.gradle.kts[tags=task-type]""] ==== <1> this will be reported as a problem because the task action is using the `Project` object at execution time The following is how it should be done instead: ==== include::sample[dir=""snippets/configurationCache/projectAtExecutionFixed/groovy"",files=""build.gradle[tags=task-type]""] include::sample[dir=""snippets/configurationCache/projectAtExecutionFixed/kotlin"",files=""build.gradle.kts[tags=task-type]""] ==== <1> no more problem reported, the injected `FileSystemOperations` service is supported as a replacement for `project.copy {}` In the same vein, if you encounter the same problem with an ad-hoc task declared in a script as follows: ==== include::sample[dir=""snippets/configurationCache/projectAtExecution/groovy"",files=""build.gradle[tags=ad-hoc-task]""] include::sample[dir=""snippets/configurationCache/projectAtExecution/kotlin"",files=""build.gradle.kts[tags=ad-hoc-task]""] ==== <1> this will be reported as a problem because the task action is using the `Project` object at execution time Here's how the task declaration above can be fixed: ==== include::sample[dir=""snippets/configurationCache/projectAtExecutionFixed/groovy"",files=""build.gradle[tags=ad-hoc-task]""] include::sample[dir=""snippets/configurationCache/projectAtExecutionFixed/kotlin"",files=""build.gradle.kts[tags=ad-hoc-task]""] ==== <1> services can't be injected directly in scripts, we need an extra type to convey the injection point <2> create an instance of the extra type using `project.object` outside the task action <3> no more problem reported, the task action references `injected` that provides the `FileSystemOperations` service, supported as a replacement for `project.copy {}` As you can see above, fixing ad-hoc tasks declared in scripts requires quite a bit of ceremony. It is a good time to think about extracting your task declaration as a proper task class as shown previously. The following table shows what APIs or injected service should be used as a replacement for each of the `Project` methods. [cols=""a,a"",options=""header""] |=== | Instead of: | Use: | `project.rootDir` | A task input or output property or a script variable to capture the result of using `project.rootDir` to calculate the actual parameter. | `project.projectDir` | A task input or output property or a script variable to capture the result of using `project.projectDir` to calculate the actual parameter. | `project.buildDir` | A task input or output property or a script variable to capture the result of using `project.buildDir` to calculate the actual parameter. | `project.name` | A task input or output property or a script variable to capture the result of using `project.name` to calculate the actual parameter. | `project.description` | A task input or output property or a script variable to capture the result of using `project.description` to calculate the actual parameter. | `project.group` | A task input or output property or a script variable to capture the result of using `project.group` to calculate the actual parameter. | `project.version` | A task input or output property or a script variable to capture the result of using `project.version` to calculate the actual parameter. | `project.properties`, `project.property(name)`, `project.hasProperty(name)`, `project.getProperty(name)` or `project.findProperty(name)` | link:{javadocPath}/org/gradle/api/provider/ProviderFactory.html#gradleProperty-java.lang.String-[Value providers for Gradle properties]. | `project.logger` | link:{javadocPath}/org/gradle/api/Task.html#getLogger--[Task.logger] | `project.provider {}` | link:{javadocPath}/org/gradle/api/provider/ProviderFactory.html#provider-java.util.concurrent.Callable-[ProviderFactory.provider {}] | `project.file(path)` | A task input or output property or a script variable to capture the result of using `project.file(file)` to calculate the actual parameter. | `project.uri(path)` | A task input or output property or a script variable to capture the result of using `project.uri(path)` to calculate the actual parameter. Otherwise, `File.toURI()` or some other JVM API can be used. | `project.relativePath(path)` | link:{javadocPath}/org/gradle/api/file/ProjectLayout.html#getProjectDirectory--[ProjectLayout.projectDirectory].link:{javadocPath}/org/gradle/api/file/Directory.html#file-java.lang.String-[file(path)] | `project.files(paths)` | link:{javadocPath}/org/gradle/api/model/ObjectFactory.html#fileCollection--[ObjectFactory.fileCollection()].link:{javadocPath}/org/gradle/api/file/ConfigurableFileCollection.html#from-java.lang.Object...-[from(paths)] | `project.fileTree(paths)` | link:{javadocPath}/org/gradle/api/model/ObjectFactory.html#fileTree--[ObjectFactory.fileTree()].link:{javadocPath}/org/gradle/api/file/ConfigurableFileTree.html#from-java.lang.Object-[from(dir)] | `project.zipTree(path)` | link:{javadocPath}/org/gradle/api/file/ArchiveOperations.html#zipTree-java.lang.Object-[ArchiveOperations.zipTree(path)] | `project.tarTree(path)` | link:{javadocPath}/org/gradle/api/file/ArchiveOperations.html#tarTree-java.lang.Object-[ArchiveOperations.tarTree(path)] | `project.resources` | A task input or output property or a script variable to capture the result of using `project.resource` to calculate the actual parameter. | `project.copySpec {}` | A task input or output property or a script variable to capture the result of using `project.copySpec {}` to calculate the actual parameter. | `project.copy {}` | link:{javadocPath}/org/gradle/api/file/FileSystemOperations.html#copy-org.gradle.api.Action-[FileSystemOperations.copy {}] | `project.sync {}` | link:{javadocPath}/org/gradle/api/file/FileSystemOperations.html#sync-org.gradle.api.Action-[FileSystemOperations.sync {}] | `project.delete {}` | link:{javadocPath}/org/gradle/api/file/FileSystemOperations.html#delete-org.gradle.api.Action-[FileSystemOperations.delete {}] | `project.mkdir(path)` | The Kotlin, Groovy or Java API available to your build logic. | `project.exec {}` | link:{javadocPath}/org/gradle/process/ExecOperations.html#exec-org.gradle.api.Action-[ExecOperations.exec {}] | `project.javaexec {}` | link:{javadocPath}/org/gradle/process/ExecOperations.html#javaexec-org.gradle.api.Action-[ExecOperations.javaexec {}] | `project.ant {}` | link:{javadocPath}/org/gradle/api/Task.html#getAnt--[Task.ant] | `project.createAntBuilder()` | link:{javadocPath}/org/gradle/api/Task.html#getAnt--[Task.ant] |=== [[config_cache:requirements:task_access]] === Accessing a task instance from another instance Tasks should not directly access the state of another task instance. Instead, tasks should be connected using <>. Note that this requirement makes it unsupported to write tasks that configure other tasks at execution time. [[config_cache:requirements:build_listeners]] === Using build listeners Plugins and build scripts must not register any build listeners. That is listeners registered at configuration time that get notified at execution time. For example a `BuildListener` or a `TaskExecutionListener`. These should be replaced by <>, registered to receive information about <> if needed. [[config_cache:requirements:external_processes]] === Running external processes Plugin and build scripts should avoid running external processes at configuration time. In general, it is preferred to run external processes in tasks with properly declared inputs and outputs to avoid unnecessary work when the task is up-to-date. If necessary, only configuration-cache-compatible APIs should be used instead of Java and Groovy standard APIs or existing `ExecOperations`, `Project.exec`, `Project.javaexec`, and their likes in settings and init scripts. For simpler cases, when grabbing the output of the process is enough, link:{javadocPath}/org/gradle/api/provider/ProviderFactory.html#exec-org.gradle.api.Action-[providers.exec()] and link:{javadocPath}/org/gradle/api/provider/ProviderFactory.html#javaexec-org.gradle.api.Action-[providers.javaExec()] can be used: ==== include::sample[dir=""snippets/valueProviders/externalProcessProvider/groovy"",files=""build.gradle[]""] include::sample[dir=""snippets/valueProviders/externalProcessProvider/kotlin"",files=""build.gradle.kts[]""] ==== For more complex cases a custom link:{javadocPath}/org/gradle/api/provider/ValueSource.html[ValueSource] implementation with injected `ExecOperations` can be used. This `ExecOperations` instance can be used at configuration time without restrictions. ==== include::sample[dir=""snippets/valueProviders/externalProcessValueSource/groovy"",files=""build.gradle[tags=value-source]""] include::sample[dir=""snippets/valueProviders/externalProcessValueSource/kotlin"",files=""build.gradle.kts[tags=value-source]""] ==== The `ValueSource` implementation can then be used to create a provider with link:{javadocPath}/org/gradle/api/provider/ProviderFactory.html#of-java.lang.Class-org.gradle.api.Action-[providers.of]: ==== include::sample[dir=""snippets/valueProviders/externalProcessValueSource/groovy"",files=""build.gradle[tags=create-provider]""] include::sample[dir=""snippets/valueProviders/externalProcessValueSource/kotlin"",files=""build.gradle.kts[tags=create-provider]""] ==== In both approaches, if the value of the provider is used at configuration time then it will become a build configuration input. The external process will be executed for every build to determine if the configuration cache is up-to-date, so it is recommended to only call fast-running processes at configuration time. If the value changes then the cache is invalidated and the process will be run again during this build as part of the configuration phase. [[config_cache:requirements:reading_sys_props_and_env_vars]] === Reading system properties and environment variables Plugins and build scripts may read system properties and environment variables directly at configuration time with standard Java, Groovy, or Kotlin APIs or with the value supplier APIs. Doing so makes such variable or property a build configuration input, so changing the value invalidates the configuration cache. The configuration cache report includes a list of these build configuration inputs to help track them. In general, you should avoid reading the value of system properties and environment variables at configuration time, to avoid cache misses when value changes. Instead, you can connect the `Provider` returned by link:{javadocPath}/org/gradle/api/provider/ProviderFactory.html#systemProperty-java.lang.String-[providers.systemProperty()] or link:{javadocPath}/org/gradle/api/provider/ProviderFactory.html#environmentVariable-java.lang.String-[providers.environmentVariable()] to task properties. Some access patterns that potentially enumerate all environment variables or system properties (for example, calling `System.getenv().forEach()` or using the iterator of its `keySet()`) are discouraged. In this case, Gradle cannot find out what properties are actual build configuration inputs, so every available property becomes one. Even adding a new property will invalidate the cache if this pattern is used. Using a custom predicate to filter environment variables is an example of this discouraged pattern: ==== include::sample[dir=""snippets/valueProviders/envVarsSysPropsDont/groovy"",files=""build.gradle[]""] include::sample[dir=""snippets/valueProviders/envVarsSysPropsDont/kotlin"",files=""build.gradle.kts[]""] ==== The logic in the predicate is opaque to the configuration cache, so all environment variables are considered inputs. One way to reduce the number of inputs is to always use methods that query a concrete variable name, such as `getenv(String)`, or `getenv().get()`: ==== include::sample[dir=""snippets/valueProviders/envVarsSysPropsDo/groovy"",files=""build.gradle[]""] include::sample[dir=""snippets/valueProviders/envVarsSysPropsDo/kotlin"",files=""build.gradle.kts[]""] ==== The fixed code above, however, is not exactly equivalent to the original as only an explicit list of variables is supported. Prefix-based filtering is a common scenario, so there are provider-based APIs to access link:{javadocPath}/org/gradle/api/provider/ProviderFactory.html#systemPropertiesPrefixedBy-java.lang.String-[system properties] and link:{javadocPath}/org/gradle/api/provider/ProviderFactory.html#environmentVariablesPrefixedBy-java.lang.String-[environment variables]: ==== include::sample[dir=""snippets/valueProviders/envVarsSysPropsDoPrefix/groovy"",files=""build.gradle[]""] include::sample[dir=""snippets/valueProviders/envVarsSysPropsDoPrefix/kotlin"",files=""build.gradle.kts[]""] ==== Note that the configuration cache would be invalidated not only when the value of the variable changes or the variable is removed but also when another variable with the matching prefix is added to the environment. For more complex use cases a custom link:{javadocPath}/org/gradle/api/provider/ValueSource.html[ValueSource] implementation can be used. System properties and environment variables referenced in the code of the `ValueSource` do not become build configuration inputs, so any processing can be applied. Instead, the value of the `ValueSource` is recomputed each time the build runs and only if the value changes the configuration cache is invalidated. For example, a `ValueSource` can be used to get all environment variables with names containing the substring `JDK`: ==== include::sample[dir=""snippets/valueProviders/envVarsSysPropsDoValueSource/groovy"",files=""build.gradle[tags=value-source,create-provider]""] include::sample[dir=""snippets/valueProviders/envVarsSysPropsDoValueSource/kotlin"",files=""build.gradle.kts[tags=value-source,create-provider]""] ==== [[config_cache:requirements:undeclared_file_read]] === Undeclared reading of files Plugins and build scripts should not read files directly using the Java, Groovy or Kotlin APIs at configuration time. Instead, declare files as potential build configuration inputs using the value supplier APIs. This problem is caused by build logic similar to this: ==== include::sample[dir=""snippets/valueProviders/fileContentsDont/groovy"",files=""build.gradle[]""] include::sample[dir=""snippets/valueProviders/fileContentsDont/kotlin"",files=""build.gradle.kts[]""] ==== To fix this problem, read files using link:{javadocPath}/org/gradle/api/provider/ProviderFactory.html#fileContents-org.gradle.api.file.RegularFile-[providers.fileContents()] instead: ==== include::sample[dir=""snippets/valueProviders/fileContentsDo/groovy"",files=""build.gradle[]""] include::sample[dir=""snippets/valueProviders/fileContentsDo/kotlin"",files=""build.gradle.kts[]""] ==== In general, you should avoid reading files at configuration time, to avoid invalidating configuration cache entries when the file content changes. Instead, you can connect the `Provider` returned by link:{javadocPath}/org/gradle/api/provider/ProviderFactory.html#fileContents-org.gradle.api.file.RegularFile-[providers.fileContents()] to task properties. [[config_cache:not_yet_implemented]] == Not yet implemented Support for using configuration caching with certain Gradle features is not yet implemented. Support for these features will be added in later Gradle releases. [[config_cache:not_yet_implemented:sharing]] === Sharing the configuration cache The configuration cache is currently stored locally only. It can be reused by hot or cold local Gradle daemons. But it can't be shared between developers or CI machines. See link:{gradle-issues}13510[gradle/gradle#13510]. [[config_cache:not_implemented:store_parallel_execution]] === Parallel task execution on cache misses When there's no configuration cache available and the work graph needs to be calculated, tasks are not executed in parallel by default. Only builds that reuse the configuration cache currently execute all tasks in parallel by default. See link:{gradle-issues}14624[gradle/gradle#14624]. [[config_cache:not_yet_implemented:source_dependencies]] === Source dependencies Support for link:https://blog.gradle.org/introducing-source-dependencies[source dependencies] is not yet implemented. With the configuration cache enabled, no problem will be reported and the build will fail. See link:{gradle-issues}13506[gradle/gradle#13506]. [[config_cache:not_yet_implemented:testkit_build_with_java_agent]] === Using a Java agent with builds run using TestKit When running builds using <>, the configuration cache can interfere with Java agents, such as the Jacoco agent, that are applied to these builds. [[config_cache:not_yet_implemented:fine_grained_tracking_of_gradle_properties]] === Fine-grained tracking of Gradle properties as build configuration inputs Currently, all external sources of Gradle properties (`gradle.properties` in project directories and in the `GRADLE_USER_HOME`, environment variables and system properties that set properties, and properties specified with command-line flags) are considered build configuration inputs regardless of what properties are actually used at configuration time. These sources, however, are not included in the configuration cache report. [[config_cache:not_yet_implemented:java_serialization]] === Java Object Serialization Gradle allows objects that support the link:https://docs.oracle.com/javase/8/docs/platform/serialization/spec/serialTOC.html[Java Object Serialization] protocol to be stored in the configuration cache. The implementation is currently limited to serializable classes that implement the `java.io.Serializable` interface and define one of the following combination of methods: - a `writeObject` method combined with a `readObject` method to control exactly which information to store; - a `writeObject` method with no corresponding `readObject`; `writeObject` must eventually call `ObjectOutputStream.defaultWriteObject`; - a `readObject` method with no corresponding `writeObject`; `readObject` must eventually call `ObjectInputStream.defaultReadObject`; - a `writeReplace` method to allow the class to nominate a replacement to be written; - a `readResolve` method to allow the class to nominate a replacement for the object just read; The following _Java Object Serialization_ features are **not** supported: - serializable classes implementing the `java.io.Externalizable` interface; objects of such classes are discarded by the configuration cache during serialization and reported as problems; - the `serialPersistentFields` member to explicitly declare which fields are serializable; the member, if present, is ignored; the configuration cache considers all but `transient` fields serializable; - the following methods of `ObjectOutputStream` are not supported and will throw `UnsupportedOperationException`: ** `reset()`, `writeFields()`, `putFields()`, `writeChars(String)`, `writeBytes(String)` and `writeUnshared(Any?)`. - the following methods of `ObjectInputStream` are not supported and will throw `UnsupportedOperationException`: ** `readLine()`, `readFully(ByteArray)`, `readFully(ByteArray, Int, Int)`, `readUnshared()`, `readFields()`, `transferTo(OutputStream)` and `readAllBytes()`. - validations registered via `ObjectInputStream.registerValidation` are simply ignored; - the `readObjectNoData` method, if present, is never invoked; See link:{gradle-issues}13588[gradle/gradle#13588]. [[config_cache:not_yet_implemented:storing_lambdas]] === Objects Storing Lambdas Currently, Gradle cannot restore objects from the configuration cache that store user-provided lambdas. For example, if an object provides a method that accepts a Single Abstract Method (SAM) interface argument (e.g. a `Function` argument), it is natural to implement this argument as a lambda. If the lambda is then stored in the object for later invocation, the object will not be compatible with the configuration cache and will cause a failure when restored. Instead of a lambda, the argument should be provided as a typed object implementing the SAM interface. Alternatively, for Kotlin implementations, the Kotlin compiler can be configured to generate classes instead of lambdas during SAM conversion. ==== include::sample[dir=""snippets/configurationCache/samConversion/groovy"",files=""build.gradle[tags=configure]""] include::sample[dir=""snippets/configurationCache/samConversion/kotlin"",files=""build.gradle.kts[tags=configure]""] ==== ",12444,False,2230.7105998858774,median "/**************************************************************************** ** Meta object code from reading C++ file 'ChatContentView.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.3) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include ""../../mainwindow/chat/ChatContentView.h"" #include #include #if !defined(Q_MOC_OUTPUT_REVISION) #error ""The header file 'ChatContentView.h' doesn't include ."" #elif Q_MOC_OUTPUT_REVISION != 67 #error ""This file was generated using the moc from 5.12.3. It"" #error ""cannot be used with the include files from this version of Qt."" #error ""(The moc has changed too much.)"" #endif QT_BEGIN_MOC_NAMESPACE QT_WARNING_PUSH QT_WARNING_DISABLE_DEPRECATED struct qt_meta_stringdata_ui__SendMsgFailureWidgetPrivate_t { QByteArrayData data[6]; char stringdata0[73]; }; #define QT_MOC_LITERAL(idx, ofs, len) \\ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \\ qptrdiff(offsetof(qt_meta_stringdata_ui__SendMsgFailureWidgetPrivate_t, stringdata0) + ofs \\ - idx * sizeof(QByteArrayData)) \\ ) static const qt_meta_stringdata_ui__SendMsgFailureWidgetPrivate_t qt_meta_stringdata_ui__SendMsgFailureWidgetPrivate = { { QT_MOC_LITERAL(0, 0, 31), // ""ui::SendMsgFailureWidgetPrivate"" QT_MOC_LITERAL(1, 32, 7), // ""clicked"" QT_MOC_LITERAL(2, 40, 0), // """" QT_MOC_LITERAL(3, 41, 19), // ""GeneralMessageItem*"" QT_MOC_LITERAL(4, 61, 3), // ""msg"" QT_MOC_LITERAL(5, 65, 7) // ""onClick"" }, ""ui::SendMsgFailureWidgetPrivate\\0clicked\\0"" ""\\0GeneralMessageItem*\\0msg\\0onClick"" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_ui__SendMsgFailureWidgetPrivate[] = { // content: 8, // revision 0, // classname 0, 0, // classinfo 2, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 1, // signalCount // signals: name, argc, parameters, tag, flags 1, 1, 24, 2, 0x06 /* Public */, // slots: name, argc, parameters, tag, flags 5, 0, 27, 2, 0x0a /* Public */, // signals: parameters QMetaType::Void, 0x80000000 | 3, 4, // slots: parameters QMetaType::Void, 0 // eod }; void ui::SendMsgFailureWidgetPrivate::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { auto *_t = static_cast(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->clicked((*reinterpret_cast< GeneralMessageItem*(*)>(_a[1]))); break; case 1: _t->onClick(); break; default: ; } } else if (_c == QMetaObject::IndexOfMethod) { int *result = reinterpret_cast(_a[0]); { using _t = void (SendMsgFailureWidgetPrivate::*)(GeneralMessageItem * ); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&SendMsgFailureWidgetPrivate::clicked)) { *result = 0; return; } } } } QT_INIT_METAOBJECT const QMetaObject ui::SendMsgFailureWidgetPrivate::staticMetaObject = { { &QToolButton::staticMetaObject, qt_meta_stringdata_ui__SendMsgFailureWidgetPrivate.data, qt_meta_data_ui__SendMsgFailureWidgetPrivate, qt_static_metacall, nullptr, nullptr } }; const QMetaObject *ui::SendMsgFailureWidgetPrivate::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *ui::SendMsgFailureWidgetPrivate::qt_metacast(const char *_clname) { if (!_clname) return nullptr; if (!strcmp(_clname, qt_meta_stringdata_ui__SendMsgFailureWidgetPrivate.stringdata0)) return static_cast(this); return QToolButton::qt_metacast(_clname); } int ui::SendMsgFailureWidgetPrivate::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QToolButton::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 2) qt_static_metacall(this, _c, _id, _a); _id -= 2; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 2) *reinterpret_cast(_a[0]) = -1; _id -= 2; } return _id; } // SIGNAL 0 void ui::SendMsgFailureWidgetPrivate::clicked(GeneralMessageItem * _t1) { void *_a[] = { nullptr, const_cast(reinterpret_cast(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 0, _a); } struct qt_meta_stringdata_ui__ChatContentView_t { QByteArrayData data[109]; char stringdata0[1744]; }; #define QT_MOC_LITERAL(idx, ofs, len) \\ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \\ qptrdiff(offsetof(qt_meta_stringdata_ui__ChatContentView_t, stringdata0) + ofs \\ - idx * sizeof(QByteArrayData)) \\ ) static const qt_meta_stringdata_ui__ChatContentView_t qt_meta_stringdata_ui__ChatContentView = { { QT_MOC_LITERAL(0, 0, 19), // ""ui::ChatContentView"" QT_MOC_LITERAL(1, 20, 20), // ""signalSerGetGroupMem"" QT_MOC_LITERAL(2, 41, 0), // """" QT_MOC_LITERAL(3, 42, 4), // ""code"" QT_MOC_LITERAL(4, 47, 13), // ""data::Member&"" QT_MOC_LITERAL(5, 61, 3), // ""mem"" QT_MOC_LITERAL(6, 65, 9), // ""oldAvatar"" QT_MOC_LITERAL(7, 75, 27), // ""signalSerGetBatchMemberByID"" QT_MOC_LITERAL(8, 103, 39), // ""std::vector"" QT_MOC_LITERAL(19, 341, 15), // ""addChatListItem"" QT_MOC_LITERAL(20, 357, 27), // ""CSharedPtr&"" QT_MOC_LITERAL(21, 385, 17), // ""groupAtMessageTip"" QT_MOC_LITERAL(22, 403, 21), // ""CSharedPtr"" QT_MOC_LITERAL(23, 425, 19), // ""signalSerGetAppInfo"" QT_MOC_LITERAL(24, 445, 15), // ""data::UserData&"" QT_MOC_LITERAL(25, 461, 22), // ""signalSerDeleteMsgById"" QT_MOC_LITERAL(26, 484, 20), // ""messageAvatarClicked"" QT_MOC_LITERAL(27, 505, 9), // ""startChat"" QT_MOC_LITERAL(28, 515, 11), // ""viewBurnMsg"" QT_MOC_LITERAL(29, 527, 22), // ""CSharedPtr&"" QT_MOC_LITERAL(30, 550, 3), // ""msg"" QT_MOC_LITERAL(31, 554, 23), // ""signalSerGetDecryptMsgs"" QT_MOC_LITERAL(32, 578, 7), // ""openUrl"" QT_MOC_LITERAL(33, 586, 11), // ""std::string"" QT_MOC_LITERAL(34, 598, 25), // ""signalSerSearchGetMessage"" QT_MOC_LITERAL(35, 624, 31), // ""signalSerSearchSendedGetMessage"" QT_MOC_LITERAL(36, 656, 8), // ""targetid"" QT_MOC_LITERAL(37, 665, 4), // ""msgs"" QT_MOC_LITERAL(38, 670, 18), // ""signalSerMsgReaded"" QT_MOC_LITERAL(39, 689, 19), // ""signalSerRecallEdit"" QT_MOC_LITERAL(40, 709, 8), // ""QString&"" QT_MOC_LITERAL(41, 718, 20), // ""signalSerGetUserInfo"" QT_MOC_LITERAL(42, 739, 2), // ""id"" QT_MOC_LITERAL(43, 742, 4), // ""name"" QT_MOC_LITERAL(44, 747, 6), // ""avatar"" QT_MOC_LITERAL(45, 754, 15), // ""signalSerMsgTop"" QT_MOC_LITERAL(46, 770, 23), // ""data::ZxTopInformation&"" QT_MOC_LITERAL(47, 794, 21), // ""signalSerCancelMsgTop"" QT_MOC_LITERAL(48, 816, 21), // ""signalSercppccTopInfo"" QT_MOC_LITERAL(49, 838, 18), // ""signalSerDeleteMsg"" QT_MOC_LITERAL(50, 857, 9), // ""hideAtWin"" QT_MOC_LITERAL(51, 867, 33), // ""signalSerGetGroupMsgUnreadCou..."" QT_MOC_LITERAL(52, 901, 36), // ""std::vector&"" QT_MOC_LITERAL(55, 993, 29), // ""onSerGetGroupMsgUnreadCounter"" QT_MOC_LITERAL(56, 1023, 7), // ""groupId"" QT_MOC_LITERAL(57, 1031, 8), // ""counters"" QT_MOC_LITERAL(58, 1040, 25), // ""onSerGetContractMaxReadId"" QT_MOC_LITERAL(59, 1066, 8), // ""targetId"" QT_MOC_LITERAL(60, 1075, 8), // ""maxMsgId"" QT_MOC_LITERAL(61, 1084, 16), // ""onSerGetGroupMem"" QT_MOC_LITERAL(62, 1101, 21), // ""onSerSearchGetMessage"" QT_MOC_LITERAL(63, 1123, 27), // ""onSerSearchSendedGetMessage"" QT_MOC_LITERAL(64, 1151, 15), // ""onRevokeMsgItem"" QT_MOC_LITERAL(65, 1167, 15), // ""onRemoveMsgItem"" QT_MOC_LITERAL(66, 1183, 15), // ""onEventFiltered"" QT_MOC_LITERAL(67, 1199, 7), // ""QEvent*"" QT_MOC_LITERAL(68, 1207, 5), // ""event"" QT_MOC_LITERAL(69, 1213, 13), // ""onSizeChanged"" QT_MOC_LITERAL(70, 1227, 23), // ""onSerGetGroupMemberList"" QT_MOC_LITERAL(71, 1251, 3), // ""err"" QT_MOC_LITERAL(72, 1255, 10), // ""memberlist"" QT_MOC_LITERAL(73, 1266, 16), // ""onSerGetMessages"" QT_MOC_LITERAL(74, 1283, 6), // ""chatid"" QT_MOC_LITERAL(75, 1290, 7), // ""msglist"" QT_MOC_LITERAL(76, 1298, 11), // ""unreadcount"" QT_MOC_LITERAL(77, 1310, 4), // ""chat"" QT_MOC_LITERAL(78, 1315, 9), // ""ishisflag"" QT_MOC_LITERAL(79, 1325, 15), // ""onGetHistoryMsg"" QT_MOC_LITERAL(80, 1341, 18), // ""onMsgStatusChanged"" QT_MOC_LITERAL(81, 1360, 9), // ""uilocalid"" QT_MOC_LITERAL(82, 1370, 15), // ""onGetMemberlist"" QT_MOC_LITERAL(83, 1386, 15), // ""onSerGetAppInfo"" QT_MOC_LITERAL(84, 1402, 4), // ""data"" QT_MOC_LITERAL(85, 1407, 18), // ""onReSendMsgClicked"" QT_MOC_LITERAL(86, 1426, 19), // ""GeneralMessageItem*"" QT_MOC_LITERAL(87, 1446, 19), // ""onSerGetDecryptMsgs"" QT_MOC_LITERAL(88, 1466, 5), // ""Rcode"" QT_MOC_LITERAL(89, 1472, 12), // ""DecryptMsgId"" QT_MOC_LITERAL(90, 1485, 12), // ""DecryMsgList"" QT_MOC_LITERAL(91, 1498, 12), // ""onDecryptMsg"" QT_MOC_LITERAL(92, 1511, 19), // ""onUpdateSendMsgTime"" QT_MOC_LITERAL(93, 1531, 7), // ""localId"" QT_MOC_LITERAL(94, 1539, 4), // ""time"" QT_MOC_LITERAL(95, 1544, 18), // ""onSerDeleteMsgById"" QT_MOC_LITERAL(96, 1563, 20), // ""onShowUserInfoWidget"" QT_MOC_LITERAL(97, 1584, 16), // ""onSerGetUserInfo"" QT_MOC_LITERAL(98, 1601, 15), // ""onSerTopMsginfo"" QT_MOC_LITERAL(99, 1617, 10), // ""topInfoMsg"" QT_MOC_LITERAL(100, 1628, 17), // ""onSercppccTopInfo"" QT_MOC_LITERAL(101, 1646, 8), // ""strError"" QT_MOC_LITERAL(102, 1655, 16), // ""onSerHistoryChat"" QT_MOC_LITERAL(103, 1672, 14), // ""onSerDeleteMsg"" QT_MOC_LITERAL(104, 1687, 23), // ""onSerGetBatchMemberByID"" QT_MOC_LITERAL(105, 1711, 4), // ""mems"" QT_MOC_LITERAL(106, 1716, 17), // ""onChangeMsgStatus"" QT_MOC_LITERAL(107, 1734, 3), // ""cnt"" QT_MOC_LITERAL(108, 1738, 5) // ""msgid"" }, ""ui::ChatContentView\\0signalSerGetGroupMem\\0"" ""\\0code\\0data::Member&\\0mem\\0oldAvatar\\0"" ""signalSerGetBatchMemberByID\\0"" ""std::vector >&\\0"" ""addIsReceiptMsg\\0int64\\0noticeInputEditFocus\\0"" ""downLoadImg\\0std::string&\\0signalSerSendMsg\\0"" ""signalSerGetGroupMemberList\\0"" ""signalSerGetMessages\\0"" ""std::vector >&\\0"" ""CSharedPtr\\0addChatListItem\\0"" ""CSharedPtr&\\0"" ""groupAtMessageTip\\0CSharedPtr\\0"" ""signalSerGetAppInfo\\0data::UserData&\\0"" ""signalSerDeleteMsgById\\0messageAvatarClicked\\0"" ""startChat\\0viewBurnMsg\\0CSharedPtr&\\0"" ""msg\\0signalSerGetDecryptMsgs\\0openUrl\\0"" ""std::string\\0signalSerSearchGetMessage\\0"" ""signalSerSearchSendedGetMessage\\0"" ""targetid\\0msgs\\0signalSerMsgReaded\\0"" ""signalSerRecallEdit\\0QString&\\0"" ""signalSerGetUserInfo\\0id\\0name\\0avatar\\0"" ""signalSerMsgTop\\0data::ZxTopInformation&\\0"" ""signalSerCancelMsgTop\\0signalSercppccTopInfo\\0"" ""signalSerDeleteMsg\\0hideAtWin\\0"" ""signalSerGetGroupMsgUnreadCounter\\0"" ""std::vector&\\0"" ""signalSerGetContractMaxReadId\\0"" ""std::vector&\\0"" ""onSerGetGroupMsgUnreadCounter\\0groupId\\0"" ""counters\\0onSerGetContractMaxReadId\\0"" ""targetId\\0maxMsgId\\0onSerGetGroupMem\\0"" ""onSerSearchGetMessage\\0onSerSearchSendedGetMessage\\0"" ""onRevokeMsgItem\\0onRemoveMsgItem\\0"" ""onEventFiltered\\0QEvent*\\0event\\0"" ""onSizeChanged\\0onSerGetGroupMemberList\\0"" ""err\\0memberlist\\0onSerGetMessages\\0chatid\\0"" ""msglist\\0unreadcount\\0chat\\0ishisflag\\0"" ""onGetHistoryMsg\\0onMsgStatusChanged\\0"" ""uilocalid\\0onGetMemberlist\\0onSerGetAppInfo\\0"" ""data\\0onReSendMsgClicked\\0GeneralMessageItem*\\0"" ""onSerGetDecryptMsgs\\0Rcode\\0DecryptMsgId\\0"" ""DecryMsgList\\0onDecryptMsg\\0onUpdateSendMsgTime\\0"" ""localId\\0time\\0onSerDeleteMsgById\\0"" ""onShowUserInfoWidget\\0onSerGetUserInfo\\0"" ""onSerTopMsginfo\\0topInfoMsg\\0onSercppccTopInfo\\0"" ""strError\\0onSerHistoryChat\\0onSerDeleteMsg\\0"" ""onSerGetBatchMemberByID\\0mems\\0"" ""onChangeMsgStatus\\0cnt\\0msgid"" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_ui__ChatContentView[] = { // content: 8, // revision 0, // classname 0, 0, // classinfo 57, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 29, // signalCount // signals: name, argc, parameters, tag, flags 1, 3, 299, 2, 0x06 /* Public */, 7, 2, 306, 2, 0x06 /* Public */, 9, 1, 311, 2, 0x06 /* Public */, 11, 0, 314, 2, 0x06 /* Public */, 12, 5, 315, 2, 0x06 /* Public */, 14, 0, 326, 2, 0x06 /* Public */, 15, 3, 327, 2, 0x06 /* Public */, 16, 7, 334, 2, 0x06 /* Public */, 19, 1, 349, 2, 0x06 /* Public */, 21, 1, 352, 2, 0x06 /* Public */, 23, 2, 355, 2, 0x06 /* Public */, 25, 1, 360, 2, 0x06 /* Public */, 26, 0, 363, 2, 0x06 /* Public */, 27, 1, 364, 2, 0x06 /* Public */, 28, 1, 367, 2, 0x06 /* Public */, 31, 3, 370, 2, 0x06 /* Public */, 32, 1, 377, 2, 0x06 /* Public */, 34, 3, 380, 2, 0x06 /* Public */, 35, 3, 387, 2, 0x06 /* Public */, 38, 1, 394, 2, 0x06 /* Public */, 39, 1, 397, 2, 0x06 /* Public */, 41, 5, 400, 2, 0x06 /* Public */, 45, 1, 411, 2, 0x06 /* Public */, 47, 0, 414, 2, 0x06 /* Public */, 48, 3, 415, 2, 0x06 /* Public */, 49, 1, 422, 2, 0x06 /* Public */, 50, 0, 425, 2, 0x06 /* Public */, 51, 3, 426, 2, 0x06 /* Public */, 53, 4, 433, 2, 0x06 /* Public */, // slots: name, argc, parameters, tag, flags 55, 3, 442, 2, 0x08 /* Private */, 58, 4, 449, 2, 0x08 /* Private */, 61, 3, 458, 2, 0x08 /* Private */, 62, 3, 465, 2, 0x08 /* Private */, 63, 3, 472, 2, 0x08 /* Private */, 64, 1, 479, 2, 0x08 /* Private */, 65, 1, 482, 2, 0x08 /* Private */, 66, 1, 485, 2, 0x08 /* Private */, 69, 0, 488, 2, 0x08 /* Private */, 70, 3, 489, 2, 0x08 /* Private */, 73, 7, 496, 2, 0x08 /* Private */, 79, 0, 511, 2, 0x08 /* Private */, 80, 2, 512, 2, 0x08 /* Private */, 82, 1, 517, 2, 0x08 /* Private */, 83, 2, 520, 2, 0x08 /* Private */, 85, 1, 525, 2, 0x08 /* Private */, 87, 3, 528, 2, 0x08 /* Private */, 91, 1, 535, 2, 0x08 /* Private */, 92, 2, 538, 2, 0x08 /* Private */, 95, 1, 543, 2, 0x08 /* Private */, 96, 3, 546, 2, 0x08 /* Private */, 97, 5, 553, 2, 0x08 /* Private */, 98, 1, 564, 2, 0x08 /* Private */, 100, 3, 567, 2, 0x08 /* Private */, 102, 0, 574, 2, 0x08 /* Private */, 103, 1, 575, 2, 0x08 /* Private */, 104, 2, 578, 2, 0x08 /* Private */, 106, 2, 583, 2, 0x08 /* Private */, // signals: parameters QMetaType::Void, QMetaType::Int, 0x80000000 | 4, QMetaType::QString, 3, 5, 6, QMetaType::Void, QMetaType::Int, 0x80000000 | 8, 2, 2, QMetaType::Void, 0x80000000 | 10, 2, QMetaType::Void, QMetaType::Void, 0x80000000 | 10, 0x80000000 | 10, 0x80000000 | 13, 0x80000000 | 13, QMetaType::Bool, 2, 2, 2, 2, 2, QMetaType::Void, QMetaType::Void, QMetaType::Int, 0x80000000 | 8, QMetaType::LongLong, 2, 2, 2, QMetaType::Void, QMetaType::Int, 0x80000000 | 10, 0x80000000 | 17, 0x80000000 | 10, QMetaType::Int, 0x80000000 | 18, QMetaType::Bool, 2, 2, 2, 2, 2, 2, 2, QMetaType::Void, 0x80000000 | 20, 2, QMetaType::Void, 0x80000000 | 22, 2, QMetaType::Void, QMetaType::Int, 0x80000000 | 24, 2, 2, QMetaType::Void, QMetaType::Int, 2, QMetaType::Void, QMetaType::Void, 0x80000000 | 20, 2, QMetaType::Void, 0x80000000 | 29, 30, QMetaType::Void, QMetaType::Int, 0x80000000 | 10, 0x80000000 | 17, 2, 2, 2, QMetaType::Void, 0x80000000 | 33, 2, QMetaType::Void, QMetaType::Int, 0x80000000 | 10, 0x80000000 | 17, 2, 2, 2, QMetaType::Void, QMetaType::Int, 0x80000000 | 10, 0x80000000 | 17, 3, 36, 37, QMetaType::Void, 0x80000000 | 10, 2, QMetaType::Void, 0x80000000 | 40, 2, QMetaType::Void, QMetaType::Int, 0x80000000 | 24, 0x80000000 | 10, QMetaType::QString, QMetaType::QString, 2, 2, 42, 43, 44, QMetaType::Void, 0x80000000 | 46, 2, QMetaType::Void, QMetaType::Void, QMetaType::Int, 0x80000000 | 33, 0x80000000 | 46, 2, 2, 2, QMetaType::Void, QMetaType::Int, 2, QMetaType::Void, QMetaType::Void, 0x80000000 | 10, QMetaType::Int, 0x80000000 | 52, 2, 2, 2, QMetaType::Void, 0x80000000 | 10, 0x80000000 | 54, QMetaType::Int, 0x80000000 | 10, 2, 2, 2, 2, // slots: parameters QMetaType::Void, 0x80000000 | 10, QMetaType::Int, 0x80000000 | 52, 56, 3, 57, QMetaType::Void, 0x80000000 | 10, 0x80000000 | 54, QMetaType::Int, 0x80000000 | 10, 59, 37, 3, 60, QMetaType::Void, QMetaType::Int, 0x80000000 | 4, QMetaType::QString, 3, 5, 6, QMetaType::Void, QMetaType::Int, 0x80000000 | 10, 0x80000000 | 17, 3, 36, 37, QMetaType::Void, QMetaType::Int, 0x80000000 | 10, 0x80000000 | 17, 3, 36, 37, QMetaType::Void, 0x80000000 | 10, 42, QMetaType::Void, 0x80000000 | 10, 42, QMetaType::Void, 0x80000000 | 67, 68, QMetaType::Void, QMetaType::Void, QMetaType::Int, 0x80000000 | 8, QMetaType::LongLong, 71, 72, 36, QMetaType::Void, QMetaType::Int, 0x80000000 | 10, 0x80000000 | 17, 0x80000000 | 10, QMetaType::Int, 0x80000000 | 18, QMetaType::Bool, 71, 74, 75, 36, 76, 77, 78, QMetaType::Void, QMetaType::Void, QMetaType::Int, QMetaType::LongLong, 71, 81, QMetaType::Void, QMetaType::LongLong, 36, QMetaType::Void, QMetaType::Int, 0x80000000 | 24, 3, 84, QMetaType::Void, 0x80000000 | 86, 30, QMetaType::Void, QMetaType::Int, 0x80000000 | 10, 0x80000000 | 17, 88, 89, 90, QMetaType::Void, 0x80000000 | 40, 2, QMetaType::Void, QMetaType::LongLong, QMetaType::LongLong, 93, 94, QMetaType::Void, QMetaType::Int, 3, QMetaType::Void, 0x80000000 | 10, QMetaType::QString, QMetaType::QString, 42, 43, 44, QMetaType::Void, QMetaType::Int, 0x80000000 | 24, 0x80000000 | 10, QMetaType::QString, QMetaType::QString, 2, 2, 42, 43, 44, QMetaType::Void, 0x80000000 | 46, 99, QMetaType::Void, QMetaType::Int, 0x80000000 | 33, 0x80000000 | 46, 3, 101, 2, QMetaType::Void, QMetaType::Void, QMetaType::Int, 3, QMetaType::Void, QMetaType::Int, 0x80000000 | 8, 3, 105, QMetaType::Void, QMetaType::Int, 0x80000000 | 10, 107, 108, 0 // eod }; void ui::ChatContentView::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { auto *_t = static_cast(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->signalSerGetGroupMem((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< data::Member(*)>(_a[2])),(*reinterpret_cast< QString(*)>(_a[3]))); break; case 1: _t->signalSerGetBatchMemberByID((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< std::vector >(*)>(_a[2]))); break; case 2: _t->addIsReceiptMsg((*reinterpret_cast< int64(*)>(_a[1]))); break; case 3: _t->noticeInputEditFocus(); break; case 4: _t->downLoadImg((*reinterpret_cast< int64(*)>(_a[1])),(*reinterpret_cast< int64(*)>(_a[2])),(*reinterpret_cast< std::string(*)>(_a[3])),(*reinterpret_cast< std::string(*)>(_a[4])),(*reinterpret_cast< bool(*)>(_a[5]))); break; case 5: _t->signalSerSendMsg(); break; case 6: _t->signalSerGetGroupMemberList((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< std::vector >(*)>(_a[2])),(*reinterpret_cast< qint64(*)>(_a[3]))); break; case 7: _t->signalSerGetMessages((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< int64(*)>(_a[2])),(*reinterpret_cast< std::vector >(*)>(_a[3])),(*reinterpret_cast< int64(*)>(_a[4])),(*reinterpret_cast< int(*)>(_a[5])),(*reinterpret_cast< CSharedPtr(*)>(_a[6])),(*reinterpret_cast< bool(*)>(_a[7]))); break; case 8: _t->addChatListItem((*reinterpret_cast< CSharedPtr(*)>(_a[1]))); break; case 9: _t->groupAtMessageTip((*reinterpret_cast< CSharedPtr(*)>(_a[1]))); break; case 10: _t->signalSerGetAppInfo((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< data::UserData(*)>(_a[2]))); break; case 11: _t->signalSerDeleteMsgById((*reinterpret_cast< int(*)>(_a[1]))); break; case 12: _t->messageAvatarClicked(); break; case 13: _t->startChat((*reinterpret_cast< CSharedPtr(*)>(_a[1]))); break; case 14: _t->viewBurnMsg((*reinterpret_cast< CSharedPtr(*)>(_a[1]))); break; case 15: _t->signalSerGetDecryptMsgs((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< int64(*)>(_a[2])),(*reinterpret_cast< std::vector >(*)>(_a[3]))); break; case 16: _t->openUrl((*reinterpret_cast< std::string(*)>(_a[1]))); break; case 17: _t->signalSerSearchGetMessage((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< int64(*)>(_a[2])),(*reinterpret_cast< std::vector >(*)>(_a[3]))); break; case 18: _t->signalSerSearchSendedGetMessage((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< int64(*)>(_a[2])),(*reinterpret_cast< std::vector >(*)>(_a[3]))); break; case 19: _t->signalSerMsgReaded((*reinterpret_cast< int64(*)>(_a[1]))); break; case 20: _t->signalSerRecallEdit((*reinterpret_cast< QString(*)>(_a[1]))); break; case 21: _t->signalSerGetUserInfo((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< data::UserData(*)>(_a[2])),(*reinterpret_cast< int64(*)>(_a[3])),(*reinterpret_cast< QString(*)>(_a[4])),(*reinterpret_cast< QString(*)>(_a[5]))); break; case 22: _t->signalSerMsgTop((*reinterpret_cast< data::ZxTopInformation(*)>(_a[1]))); break; case 23: _t->signalSerCancelMsgTop(); break; case 24: _t->signalSercppccTopInfo((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< const std::string(*)>(_a[2])),(*reinterpret_cast< data::ZxTopInformation(*)>(_a[3]))); break; case 25: _t->signalSerDeleteMsg((*reinterpret_cast< int(*)>(_a[1]))); break; case 26: _t->hideAtWin(); break; case 27: _t->signalSerGetGroupMsgUnreadCounter((*reinterpret_cast< int64(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2])),(*reinterpret_cast< std::vector(*)>(_a[3]))); break; case 28: _t->signalSerGetContractMaxReadId((*reinterpret_cast< int64(*)>(_a[1])),(*reinterpret_cast< std::vector(*)>(_a[2])),(*reinterpret_cast< int(*)>(_a[3])),(*reinterpret_cast< int64(*)>(_a[4]))); break; case 29: _t->onSerGetGroupMsgUnreadCounter((*reinterpret_cast< int64(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2])),(*reinterpret_cast< std::vector(*)>(_a[3]))); break; case 30: _t->onSerGetContractMaxReadId((*reinterpret_cast< int64(*)>(_a[1])),(*reinterpret_cast< std::vector(*)>(_a[2])),(*reinterpret_cast< int(*)>(_a[3])),(*reinterpret_cast< int64(*)>(_a[4]))); break; case 31: _t->onSerGetGroupMem((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< data::Member(*)>(_a[2])),(*reinterpret_cast< QString(*)>(_a[3]))); break; case 32: _t->onSerSearchGetMessage((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< int64(*)>(_a[2])),(*reinterpret_cast< std::vector >(*)>(_a[3]))); break; case 33: _t->onSerSearchSendedGetMessage((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< int64(*)>(_a[2])),(*reinterpret_cast< std::vector >(*)>(_a[3]))); break; case 34: _t->onRevokeMsgItem((*reinterpret_cast< int64(*)>(_a[1]))); break; case 35: _t->onRemoveMsgItem((*reinterpret_cast< int64(*)>(_a[1]))); break; case 36: _t->onEventFiltered((*reinterpret_cast< QEvent*(*)>(_a[1]))); break; case 37: _t->onSizeChanged(); break; case 38: _t->onSerGetGroupMemberList((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< std::vector >(*)>(_a[2])),(*reinterpret_cast< qint64(*)>(_a[3]))); break; case 39: _t->onSerGetMessages((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< int64(*)>(_a[2])),(*reinterpret_cast< std::vector >(*)>(_a[3])),(*reinterpret_cast< int64(*)>(_a[4])),(*reinterpret_cast< int(*)>(_a[5])),(*reinterpret_cast< CSharedPtr(*)>(_a[6])),(*reinterpret_cast< bool(*)>(_a[7]))); break; case 40: _t->onGetHistoryMsg(); break; case 41: _t->onMsgStatusChanged((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< qint64(*)>(_a[2]))); break; case 42: _t->onGetMemberlist((*reinterpret_cast< qint64(*)>(_a[1]))); break; case 43: _t->onSerGetAppInfo((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< data::UserData(*)>(_a[2]))); break; case 44: _t->onReSendMsgClicked((*reinterpret_cast< GeneralMessageItem*(*)>(_a[1]))); break; case 45: _t->onSerGetDecryptMsgs((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< int64(*)>(_a[2])),(*reinterpret_cast< std::vector >(*)>(_a[3]))); break; case 46: _t->onDecryptMsg((*reinterpret_cast< QString(*)>(_a[1]))); break; case 47: _t->onUpdateSendMsgTime((*reinterpret_cast< qint64(*)>(_a[1])),(*reinterpret_cast< qint64(*)>(_a[2]))); break; case 48: _t->onSerDeleteMsgById((*reinterpret_cast< int(*)>(_a[1]))); break; case 49: _t->onShowUserInfoWidget((*reinterpret_cast< int64(*)>(_a[1])),(*reinterpret_cast< QString(*)>(_a[2])),(*reinterpret_cast< QString(*)>(_a[3]))); break; case 50: _t->onSerGetUserInfo((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< data::UserData(*)>(_a[2])),(*reinterpret_cast< int64(*)>(_a[3])),(*reinterpret_cast< QString(*)>(_a[4])),(*reinterpret_cast< QString(*)>(_a[5]))); break; case 51: _t->onSerTopMsginfo((*reinterpret_cast< data::ZxTopInformation(*)>(_a[1]))); break; case 52: _t->onSercppccTopInfo((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< const std::string(*)>(_a[2])),(*reinterpret_cast< data::ZxTopInformation(*)>(_a[3]))); break; case 53: _t->onSerHistoryChat(); break; case 54: _t->onSerDeleteMsg((*reinterpret_cast< int(*)>(_a[1]))); break; case 55: _t->onSerGetBatchMemberByID((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< std::vector >(*)>(_a[2]))); break; case 56: _t->onChangeMsgStatus((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< int64(*)>(_a[2]))); break; default: ; } } else if (_c == QMetaObject::IndexOfMethod) { int *result = reinterpret_cast(_a[0]); { using _t = void (ChatContentView::*)(int , data::Member & , QString ); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ChatContentView::signalSerGetGroupMem)) { *result = 0; return; } } { using _t = void (ChatContentView::*)(int , std::vector > & ); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ChatContentView::signalSerGetBatchMemberByID)) { *result = 1; return; } } { using _t = void (ChatContentView::*)(int64 ); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ChatContentView::addIsReceiptMsg)) { *result = 2; return; } } { using _t = void (ChatContentView::*)(); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ChatContentView::noticeInputEditFocus)) { *result = 3; return; } } { using _t = void (ChatContentView::*)(int64 , int64 , std::string & , std::string & , bool ); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ChatContentView::downLoadImg)) { *result = 4; return; } } { using _t = void (ChatContentView::*)(); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ChatContentView::signalSerSendMsg)) { *result = 5; return; } } { using _t = void (ChatContentView::*)(int , std::vector> & , qint64 ); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ChatContentView::signalSerGetGroupMemberList)) { *result = 6; return; } } { using _t = void (ChatContentView::*)(int , int64 , std::vector> & , int64 , int , CSharedPtr , bool ); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ChatContentView::signalSerGetMessages)) { *result = 7; return; } } { using _t = void (ChatContentView::*)(CSharedPtr & ); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ChatContentView::addChatListItem)) { *result = 8; return; } } { using _t = void (ChatContentView::*)(CSharedPtr ); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ChatContentView::groupAtMessageTip)) { *result = 9; return; } } { using _t = void (ChatContentView::*)(int , data::UserData & ); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ChatContentView::signalSerGetAppInfo)) { *result = 10; return; } } { using _t = void (ChatContentView::*)(int ); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ChatContentView::signalSerDeleteMsgById)) { *result = 11; return; } } { using _t = void (ChatContentView::*)(); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ChatContentView::messageAvatarClicked)) { *result = 12; return; } } { using _t = void (ChatContentView::*)(CSharedPtr & ); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ChatContentView::startChat)) { *result = 13; return; } } { using _t = void (ChatContentView::*)(CSharedPtr & ); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ChatContentView::viewBurnMsg)) { *result = 14; return; } } { using _t = void (ChatContentView::*)(int , int64 , std::vector> & ); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ChatContentView::signalSerGetDecryptMsgs)) { *result = 15; return; } } { using _t = void (ChatContentView::*)(std::string ); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ChatContentView::openUrl)) { *result = 16; return; } } { using _t = void (ChatContentView::*)(int , int64 , std::vector> & ); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ChatContentView::signalSerSearchGetMessage)) { *result = 17; return; } } { using _t = void (ChatContentView::*)(int , int64 , std::vector> & ); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ChatContentView::signalSerSearchSendedGetMessage)) { *result = 18; return; } } { using _t = void (ChatContentView::*)(int64 ); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ChatContentView::signalSerMsgReaded)) { *result = 19; return; } } { using _t = void (ChatContentView::*)(QString & ); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ChatContentView::signalSerRecallEdit)) { *result = 20; return; } } { using _t = void (ChatContentView::*)(int , data::UserData & , int64 , QString , QString ); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ChatContentView::signalSerGetUserInfo)) { *result = 21; return; } } { using _t = void (ChatContentView::*)(data::ZxTopInformation & ); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ChatContentView::signalSerMsgTop)) { *result = 22; return; } } { using _t = void (ChatContentView::*)(); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ChatContentView::signalSerCancelMsgTop)) { *result = 23; return; } } { using _t = void (ChatContentView::*)(int , const std::string & , data::ZxTopInformation & ); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ChatContentView::signalSercppccTopInfo)) { *result = 24; return; } } { using _t = void (ChatContentView::*)(int ); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ChatContentView::signalSerDeleteMsg)) { *result = 25; return; } } { using _t = void (ChatContentView::*)(); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ChatContentView::hideAtWin)) { *result = 26; return; } } { using _t = void (ChatContentView::*)(int64 , int , std::vector & ); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ChatContentView::signalSerGetGroupMsgUnreadCounter)) { *result = 27; return; } } { using _t = void (ChatContentView::*)(int64 , std::vector & , int , int64 ); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ChatContentView::signalSerGetContractMaxReadId)) { *result = 28; return; } } } } QT_INIT_METAOBJECT const QMetaObject ui::ChatContentView::staticMetaObject = { { &QWidget::staticMetaObject, qt_meta_stringdata_ui__ChatContentView.data, qt_meta_data_ui__ChatContentView, qt_static_metacall, nullptr, nullptr } }; const QMetaObject *ui::ChatContentView::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *ui::ChatContentView::qt_metacast(const char *_clname) { if (!_clname) return nullptr; if (!strcmp(_clname, qt_meta_stringdata_ui__ChatContentView.stringdata0)) return static_cast(this); return QWidget::qt_metacast(_clname); } int ui::ChatContentView::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QWidget::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 57) qt_static_metacall(this, _c, _id, _a); _id -= 57; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 57) *reinterpret_cast(_a[0]) = -1; _id -= 57; } return _id; } // SIGNAL 0 void ui::ChatContentView::signalSerGetGroupMem(int _t1, data::Member & _t2, QString _t3) { void *_a[] = { nullptr, const_cast(reinterpret_cast(&_t1)), const_cast(reinterpret_cast(&_t2)), const_cast(reinterpret_cast(&_t3)) }; QMetaObject::activate(this, &staticMetaObject, 0, _a); } // SIGNAL 1 void ui::ChatContentView::signalSerGetBatchMemberByID(int _t1, std::vector > & _t2) { void *_a[] = { nullptr, const_cast(reinterpret_cast(&_t1)), const_cast(reinterpret_cast(&_t2)) }; QMetaObject::activate(this, &staticMetaObject, 1, _a); } // SIGNAL 2 void ui::ChatContentView::addIsReceiptMsg(int64 _t1) { void *_a[] = { nullptr, const_cast(reinterpret_cast(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 2, _a); } // SIGNAL 3 void ui::ChatContentView::noticeInputEditFocus() { QMetaObject::activate(this, &staticMetaObject, 3, nullptr); } // SIGNAL 4 void ui::ChatContentView::downLoadImg(int64 _t1, int64 _t2, std::string & _t3, std::string & _t4, bool _t5) { void *_a[] = { nullptr, const_cast(reinterpret_cast(&_t1)), const_cast(reinterpret_cast(&_t2)), const_cast(reinterpret_cast(&_t3)), const_cast(reinterpret_cast(&_t4)), const_cast(reinterpret_cast(&_t5)) }; QMetaObject::activate(this, &staticMetaObject, 4, _a); } // SIGNAL 5 void ui::ChatContentView::signalSerSendMsg() { QMetaObject::activate(this, &staticMetaObject, 5, nullptr); } // SIGNAL 6 void ui::ChatContentView::signalSerGetGroupMemberList(int _t1, std::vector> & _t2, qint64 _t3) { void *_a[] = { nullptr, const_cast(reinterpret_cast(&_t1)), const_cast(reinterpret_cast(&_t2)), const_cast(reinterpret_cast(&_t3)) }; QMetaObject::activate(this, &staticMetaObject, 6, _a); } // SIGNAL 7 void ui::ChatContentView::signalSerGetMessages(int _t1, int64 _t2, std::vector> & _t3, int64 _t4, int _t5, CSharedPtr _t6, bool _t7) { void *_a[] = { nullptr, const_cast(reinterpret_cast(&_t1)), const_cast(reinterpret_cast(&_t2)), const_cast(reinterpret_cast(&_t3)), const_cast(reinterpret_cast(&_t4)), const_cast(reinterpret_cast(&_t5)), const_cast(reinterpret_cast(&_t6)), const_cast(reinterpret_cast(&_t7)) }; QMetaObject::activate(this, &staticMetaObject, 7, _a); } // SIGNAL 8 void ui::ChatContentView::addChatListItem(CSharedPtr & _t1) { void *_a[] = { nullptr, const_cast(reinterpret_cast(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 8, _a); } // SIGNAL 9 void ui::ChatContentView::groupAtMessageTip(CSharedPtr _t1) { void *_a[] = { nullptr, const_cast(reinterpret_cast(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 9, _a); } // SIGNAL 10 void ui::ChatContentView::signalSerGetAppInfo(int _t1, data::UserData & _t2) { void *_a[] = { nullptr, const_cast(reinterpret_cast(&_t1)), const_cast(reinterpret_cast(&_t2)) }; QMetaObject::activate(this, &staticMetaObject, 10, _a); } // SIGNAL 11 void ui::ChatContentView::signalSerDeleteMsgById(int _t1) { void *_a[] = { nullptr, const_cast(reinterpret_cast(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 11, _a); } // SIGNAL 12 void ui::ChatContentView::messageAvatarClicked() { QMetaObject::activate(this, &staticMetaObject, 12, nullptr); } // SIGNAL 13 void ui::ChatContentView::startChat(CSharedPtr & _t1) { void *_a[] = { nullptr, const_cast(reinterpret_cast(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 13, _a); } // SIGNAL 14 void ui::ChatContentView::viewBurnMsg(CSharedPtr & _t1) { void *_a[] = { nullptr, const_cast(reinterpret_cast(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 14, _a); } // SIGNAL 15 void ui::ChatContentView::signalSerGetDecryptMsgs(int _t1, int64 _t2, std::vector> & _t3) { void *_a[] = { nullptr, const_cast(reinterpret_cast(&_t1)), const_cast(reinterpret_cast(&_t2)), const_cast(reinterpret_cast(&_t3)) }; QMetaObject::activate(this, &staticMetaObject, 15, _a); } // SIGNAL 16 void ui::ChatContentView::openUrl(std::string _t1) { void *_a[] = { nullptr, const_cast(reinterpret_cast(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 16, _a); } // SIGNAL 17 void ui::ChatContentView::signalSerSearchGetMessage(int _t1, int64 _t2, std::vector> & _t3) { void *_a[] = { nullptr, const_cast(reinterpret_cast(&_t1)), const_cast(reinterpret_cast(&_t2)), const_cast(reinterpret_cast(&_t3)) }; QMetaObject::activate(this, &staticMetaObject, 17, _a); } // SIGNAL 18 void ui::ChatContentView::signalSerSearchSendedGetMessage(int _t1, int64 _t2, std::vector> & _t3) { void *_a[] = { nullptr, const_cast(reinterpret_cast(&_t1)), const_cast(reinterpret_cast(&_t2)), const_cast(reinterpret_cast(&_t3)) }; QMetaObject::activate(this, &staticMetaObject, 18, _a); } // SIGNAL 19 void ui::ChatContentView::signalSerMsgReaded(int64 _t1) { void *_a[] = { nullptr, const_cast(reinterpret_cast(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 19, _a); } // SIGNAL 20 void ui::ChatContentView::signalSerRecallEdit(QString & _t1) { void *_a[] = { nullptr, const_cast(reinterpret_cast(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 20, _a); } // SIGNAL 21 void ui::ChatContentView::signalSerGetUserInfo(int _t1, data::UserData & _t2, int64 _t3, QString _t4, QString _t5) { void *_a[] = { nullptr, const_cast(reinterpret_cast(&_t1)), const_cast(reinterpret_cast(&_t2)), const_cast(reinterpret_cast(&_t3)), const_cast(reinterpret_cast(&_t4)), const_cast(reinterpret_cast(&_t5)) }; QMetaObject::activate(this, &staticMetaObject, 21, _a); } // SIGNAL 22 void ui::ChatContentView::signalSerMsgTop(data::ZxTopInformation & _t1) { void *_a[] = { nullptr, const_cast(reinterpret_cast(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 22, _a); } // SIGNAL 23 void ui::ChatContentView::signalSerCancelMsgTop() { QMetaObject::activate(this, &staticMetaObject, 23, nullptr); } // SIGNAL 24 void ui::ChatContentView::signalSercppccTopInfo(int _t1, const std::string & _t2, data::ZxTopInformation & _t3) { void *_a[] = { nullptr, const_cast(reinterpret_cast(&_t1)), const_cast(reinterpret_cast(&_t2)), const_cast(reinterpret_cast(&_t3)) }; QMetaObject::activate(this, &staticMetaObject, 24, _a); } // SIGNAL 25 void ui::ChatContentView::signalSerDeleteMsg(int _t1) { void *_a[] = { nullptr, const_cast(reinterpret_cast(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 25, _a); } // SIGNAL 26 void ui::ChatContentView::hideAtWin() { QMetaObject::activate(this, &staticMetaObject, 26, nullptr); } // SIGNAL 27 void ui::ChatContentView::signalSerGetGroupMsgUnreadCounter(int64 _t1, int _t2, std::vector & _t3) { void *_a[] = { nullptr, const_cast(reinterpret_cast(&_t1)), const_cast(reinterpret_cast(&_t2)), const_cast(reinterpret_cast(&_t3)) }; QMetaObject::activate(this, &staticMetaObject, 27, _a); } // SIGNAL 28 void ui::ChatContentView::signalSerGetContractMaxReadId(int64 _t1, std::vector & _t2, int _t3, int64 _t4) { void *_a[] = { nullptr, const_cast(reinterpret_cast(&_t1)), const_cast(reinterpret_cast(&_t2)), const_cast(reinterpret_cast(&_t3)), const_cast(reinterpret_cast(&_t4)) }; QMetaObject::activate(this, &staticMetaObject, 28, _a); } QT_WARNING_POP QT_END_MOC_NAMESPACE ",16251,True,3935.7139851472166,median "/******************************************************************************* * Copyright 2018-2021 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include ""cpu/x64/jit_avx512_core_x8s8s32x_deconvolution.hpp"" #include ""common/dnnl_thread.hpp"" #define GET_OFF(field) offsetof(jit_deconv_call_s, field) namespace dnnl { namespace impl { namespace cpu { namespace x64 { using namespace dnnl::impl::status; using namespace dnnl::impl::memory_tracking::names; using namespace dnnl::impl::utils; using namespace Xbyak; using namespace nstl; #define wht_blk_off(d, g, ...) \\ (pd()->with_groups() ? (d).blk_off((g), __VA_ARGS__) \\ : (d).blk_off(__VA_ARGS__)) status_t jit_avx512_core_x8s8s32x_deconv_fwd_kernel::init_conf( jit_conv_conf_t &jcp, const deconvolution_desc_t &cd, memory_desc_t &src_md, memory_desc_t &weights_md, memory_desc_t &dst_md, const bool with_bias, memory_desc_t &bias_md, const primitive_attr_t &attr, int nthreads) { const memory_desc_wrapper src_d(&src_md); const memory_desc_wrapper dst_d(&dst_md); const memory_desc_wrapper weights_d(&weights_md); const memory_desc_wrapper bias_d(&bias_md); if (!(mayiuse(avx512_core) && one_of(src_d.data_type(), data_type::u8, data_type::s8) && weights_d.data_type() == data_type::s8 && one_of(dst_d.data_type(), data_type::f32, data_type::s32, data_type::s8, data_type::u8))) return status::unimplemented; jcp = zero(); jcp.nthr = nthreads; const bool with_groups = weights_d.ndims() == src_d.ndims() + 1; jcp.signed_input = src_d.data_type() == data_type::s8; const int ndims = jcp.ndims = dst_d.ndims(); const bool is_1d = ndims == 3; const bool is_3d = ndims == 5; jcp.ngroups = with_groups ? weights_d.dims()[0] : 1; jcp.oc = dst_d.dims()[1] / jcp.ngroups; jcp.ic = src_d.dims()[1] / jcp.ngroups; jcp.id = is_3d ? src_d.dims()[2] : 1; jcp.oc_without_padding = dst_d.dims()[1] / jcp.ngroups; jcp.ic_without_padding = src_d.dims()[1] / jcp.ngroups; jcp.is_depthwise = true && with_groups && utils::everyone_is( 1, jcp.ic_without_padding, jcp.oc_without_padding); /* TODO: future work, on hold until depthwise specialized kernel is * implemented. */ if (jcp.is_depthwise && (jcp.signed_input || is_3d)) return status::unimplemented; format_tag_t dat_tag = utils::pick( ndims - 3, format_tag::nwc, format_tag::nhwc, format_tag::ndhwc); if (src_d.format_kind() == format_kind::any) { CHECK(memory_desc_init_by_tag(src_md, dat_tag)); jcp.src_tag = dat_tag; } else { jcp.src_tag = src_d.matches_one_of_tag(dat_tag); } if (jcp.src_tag != dat_tag) return status::unimplemented; if (dst_d.format_kind() == format_kind::any) { CHECK(memory_desc_init_by_tag(dst_md, dat_tag)); jcp.dst_tag = dat_tag; } else { jcp.dst_tag = dst_d.matches_one_of_tag(dat_tag); } if (jcp.dst_tag != dat_tag) return status::unimplemented; auto set_or_check_wei_format = [&]() { using namespace format_tag; format_tag_t wei_tag; if (is_3d) { wei_tag = with_groups ? gOIdhw4i16o4i : OIdhw4i16o4i; } else { wei_tag = is_1d ? (jcp.is_depthwise ? Goiw16g : (with_groups ? gOIw4i16o4i : OIw4i16o4i)) : (jcp.is_depthwise ? Goihw16g : (with_groups ? gOIhw4i16o4i : OIhw4i16o4i)); } memory_desc_t want_wei_md = weights_md; memory_desc_init_by_tag(want_wei_md, wei_tag); if (jcp.signed_input && !jcp.is_depthwise) { want_wei_md.extra.flags = 0 | memory_extra_flags::compensation_conv_s8s8; want_wei_md.extra.compensation_mask = (1 << 0) + (with_groups && !jcp.is_depthwise ? (1 << 1) : 0); want_wei_md.extra.scale_adjust = 1.f; } if (weights_md.format_kind == format_kind::any) { weights_md = want_wei_md; return true; } return weights_md == want_wei_md; }; if (!set_or_check_wei_format()) return status::unimplemented; jcp.with_bias = with_bias; if (jcp.with_bias) { if (bias_d.format_kind() == format_kind::any) CHECK(memory_desc_init_by_tag(bias_md, format_tag::x)); } jcp.prop_kind = cd.prop_kind; jcp.mb = src_d.dims()[0]; jcp.ih = is_1d ? 1 : src_d.dims()[ndims - 2]; jcp.iw = src_d.dims()[ndims - 1]; jcp.od = is_3d ? dst_d.dims()[2] : 1; jcp.oh = is_1d ? 1 : dst_d.dims()[ndims - 2]; jcp.ow = dst_d.dims()[ndims - 1]; jcp.kd = is_3d ? weights_d.dims()[with_groups + 2] : 1; jcp.kh = is_1d ? 1 : weights_d.dims()[with_groups + ndims - 2]; jcp.kw = weights_d.dims()[with_groups + ndims - 1]; jcp.f_pad = is_3d ? cd.padding[0][0] : 0; jcp.t_pad = is_1d ? 0 : cd.padding[0][ndims - 4]; jcp.l_pad = cd.padding[0][ndims - 3]; jcp.stride_d = is_3d ? cd.strides[0] : 1; jcp.stride_h = is_1d ? 1 : cd.strides[ndims - 4]; jcp.stride_w = cd.strides[ndims - 3]; if (jcp.is_depthwise) { jcp.ch_block = 16; jcp.oc_block = 1; jcp.ic_block = 1; } else { jcp.ch_block = 1; jcp.oc_block = 16; jcp.ic_block = 16; if (jcp.ngroups == 1) { jcp.oc = utils::rnd_up(jcp.oc_without_padding, jcp.oc_block); jcp.ic = utils::rnd_up(jcp.ic_without_padding, jcp.ic_block); } if (jcp.ic % jcp.ic_block != 0) return status::unimplemented; } jcp.dilate_d = is_3d ? cd.dilates[0] : 0; jcp.dilate_h = is_1d ? 0 : cd.dilates[ndims - 4]; jcp.dilate_w = cd.dilates[ndims - 3]; if (!IMPLICATION(jcp.dilate_d, jcp.stride_d == 1) || !IMPLICATION(jcp.dilate_h, jcp.stride_h == 1) || !IMPLICATION(jcp.dilate_w, jcp.stride_w == 1)) return status::unimplemented; int ext_kw = calculate_extended_filter_size(jcp.kw, jcp.dilate_w); int ext_kh = calculate_extended_filter_size(jcp.kh, jcp.dilate_h); int ext_kd = calculate_extended_filter_size(jcp.kd, jcp.dilate_d); jcp.r_pad = calculate_end_padding( jcp.l_pad, jcp.iw, jcp.ow, jcp.stride_w, ext_kw); jcp.b_pad = calculate_end_padding( jcp.t_pad, jcp.ih, jcp.oh, jcp.stride_h, ext_kh); jcp.back_pad = calculate_end_padding( jcp.f_pad, jcp.id, jcp.od, jcp.stride_d, ext_kd); bool kernel_outside_src = false || ext_kw <= jcp.l_pad || ext_kw <= jcp.r_pad || ext_kh <= jcp.t_pad || ext_kh <= jcp.b_pad || ext_kd <= jcp.f_pad || ext_kd <= jcp.back_pad; if (kernel_outside_src) return status::unimplemented; if (!post_ops_ok(jcp, attr)) return status::unimplemented; jcp.ver = ver_avx512_core; if (mayiuse(avx512_core_vnni)) jcp.ver = ver_vnni; int max_regs = jcp.ver == ver_vnni ? 30 : 28; const auto &p = attr.post_ops_; if (p.len() > 0 && !contain_only_eltwise_post_op(attr)) { max_regs -= 2; } const auto &oscales = attr.output_scales_; jcp.is_oc_scale = oscales.mask_ == 1 << 1; // only common and per-oc-channel scales are supported const bool oscales_ok = one_of(oscales.mask_, 0, 1 << 1); if (!oscales_ok) return status::unimplemented; jcp.dst_dt = dst_d.data_type(); jcp.bia_dt = jcp.with_bias ? bias_d.data_type() : data_type::undef; jcp.typesize_bia = jcp.with_bias ? types::data_type_size(bias_d.data_type()) : 0; jcp.typesize_in = types::data_type_size(src_d.data_type()); jcp.typesize_out = types::data_type_size(dst_d.data_type()); jcp.nb_ch = div_up(jcp.ngroups, jcp.ch_block); jcp.nb_oc = jcp.oc / jcp.oc_block; if (jcp.nb_oc == 0) return status::unimplemented; jcp.nb_ic = jcp.ic / jcp.ic_block; /* kernel blocking params */ const int regs = max_regs; jcp.nb_ch_blocking = 1; jcp.nb_oc_blocking = nstl::min(4, jcp.nb_oc); for (; jcp.nb_oc_blocking > 1; jcp.nb_oc_blocking--) if (jcp.nb_oc % jcp.nb_oc_blocking == 0 && jcp.l_pad <= regs / (jcp.nb_oc_blocking + 1)) break; jcp.ur_w = regs / (jcp.nb_oc_blocking + 1); int l_overflow = max( 0, ((jcp.kw - 1) * (jcp.dilate_w + 1) - jcp.l_pad) / jcp.stride_w); if (jcp.ow < jcp.ur_w) { jcp.ur_w = jcp.ow; jcp.ur_w_tail = 0; } else { for (; jcp.ur_w >= 1; jcp.ur_w--) { /* ur_w should be multiple of stride_w in order to simplify logic for get_ow_start and get_ow_end */ bool is_multiple_of_stride = jcp.ur_w % jcp.stride_w == 0; /* boundary conditions: These conditions ensure all elements close to boundary are computed in a single call of compute loop */ bool left_boundary_covered = jcp.ur_w >= l_overflow * jcp.stride_w; jcp.ur_w_tail = jcp.ow % jcp.ur_w; int r_overflow_no_tail = max(0, ((jcp.kw - 1) * (jcp.dilate_w + 1) - max(0, jcp.r_pad) - jcp.ur_w_tail) / jcp.stride_w); bool right_boundary_covered = jcp.ur_w >= r_overflow_no_tail * jcp.stride_w; if (is_multiple_of_stride && left_boundary_covered && right_boundary_covered) break; else if (jcp.ur_w == 1) /* The boundary conditions above are also important to maintain simplicity of calls to icb_loop, if those conditions are not satisfied, then special cases will need to be added to use correct l_overflow/r_overflow values when different iterations of compute loop work on the locations close to boundary. So to keep code simple, return unimplemented for extreme case when a good ur_w cannot be found. */ return status::unimplemented; } } jcp.wei_adj_scale = (weights_d.extra().flags & memory_extra_flags::scale_adjust) ? weights_d.extra().scale_adjust : 1.f; jcp.loop_order = jcp.ngroups > 1 ? loop_ngc : loop_cgn; return status::success; } bool jit_avx512_core_x8s8s32x_deconv_fwd_kernel::contain_only_eltwise_post_op(const primitive_attr_t &attr) { const auto &p = attr.post_ops_; for (int i = 0; i < p.len(); i++) { auto &post_op = p.entry_[i]; if (!post_op.is_eltwise()) { return false; } } return true; } bool jit_avx512_core_x8s8s32x_deconv_fwd_kernel::post_ops_ok( jit_conv_conf_t &jcp, const primitive_attr_t &attr) { using namespace primitive_kind; const auto &p = attr.post_ops_; auto all_post_ops_supported = [&]() { bool ok = true; for (int i = 0; i < p.len(); i++) { ok = ok && utils::one_of(p.entry_[i].kind, primitive_kind::eltwise, primitive_kind::depthwise, primitive_kind::quantization); } return ok; }; return all_post_ops_supported(); } void jit_avx512_core_x8s8s32x_deconv_fwd_kernel::init_scratchpad( memory_tracking::registrar_t &scratchpad, const jit_conv_conf_t &jcp, const primitive_attr_t &attr) { if (jcp.signed_input && jcp.ver != ver_vnni) { dim_t count = nstl::max(attr.output_scales_.count_, 16); scratchpad.book(key_conv_adjusted_scales, count); } } void jit_avx512_core_x8s8s32x_deconv_fwd_kernel::compute_ker(int ur_w, int l_overflow, int r_overflow, ker_block_t last_ic_block_flag, bool h_padded) { const int ch_block_all = jcp.ch_block * jcp.ic_block * jcp.oc_block; const int ur_w_stride = jcp.signed_input ? 1 : jcp.stride_w; auto src_offset = [=](int oj, int icb, int ki) { return jcp.typesize_in * (((oj + jcp.l_pad - ki * (jcp.dilate_w + 1)) / jcp.stride_w) * jcp.ngroups * jcp.ic_without_padding + icb * 4); }; auto kernel_offset = [=](int ocb, int icb, int ki) { return jcp.typesize_in * (ocb * jcp.nb_ic * jcp.kd * jcp.kh * jcp.kw * ch_block_all + icb * jcp.oc_block * jcp.ic_block / 4 + ki * ch_block_all); }; auto compute = [=](zmm_t vreg_acc, zmm_t vreg_wei, zmm_t vreg_src) { if (jcp.ver == ver_vnni) { vpdpbusd(vreg_acc, vreg_src, vreg_wei); } else if (jcp.is_depthwise) { vpmulld(zmm_tmp, vreg_src, vreg_wei); vpaddd(vreg_acc, vreg_acc, zmm_tmp); } else { vpmaddubsw(zmm_tmp, vreg_src, vreg_wei); vpmaddwd(zmm_tmp, zmm_tmp, zmm_one); vpaddd(vreg_acc, vreg_acc, zmm_tmp); } }; for (int ki = 0; ki < jcp.kw; ki++) { int jj_start = get_ow_start(ki, l_overflow); int jj_end = get_ow_end(ur_w, ki, r_overflow); int _start = (jcp.signed_input) ? 0 : jj_start; int _end = (jcp.signed_input) ? ur_w : jj_end; int tail_size = jcp.is_depthwise ? jcp.ngroups % jcp.ch_block : jcp.ic_without_padding % 4; int n_ic_blocks = jcp.is_depthwise ? 1 : (last_ic_block_flag & ~no_last_block ? div_up( jcp.ic_without_padding % jcp.ic_block, 4) : jcp.ic_block / 4); for (int icb1 = 0; icb1 < n_ic_blocks; icb1++) { if (h_padded == true) { /* fill padded area with shifted values */ Zmm inp = zmm_inp(0, jcp.nb_oc_blocking); vpxord(inp, inp, inp); vpsubb(inp, inp, zmm_shift); } else { for (int jj = _start; jj < _end; jj += ur_w_stride) { int aux_src_off = src_offset(jj, icb1, ki); if (jj >= jj_start && jj < jj_end && ((jj + jcp.l_pad - ki) % jcp.stride_w == 0)) { if (jcp.is_depthwise) { auto zmm_src = zmm_inp(jj, jcp.nb_oc_blocking); if (tail_size != 0) { assert(jcp.nb_oc_blocking == 1); zmm_src = zmm_src | ktail_mask | T_z; } vpmovzxbd(zmm_src, EVEX_compress_addr( aux_reg_src, aux_src_off)); } else if ((last_ic_block_flag & last_sp_block) && tail_size != 0 && icb1 == n_ic_blocks - 1) { xmm_t xmm_tmp = xmm_t( zmm_inp(jj, jcp.nb_oc_blocking).getIdx()); for (int r = 0; r < tail_size; ++r) vpinsrb(xmm_tmp, xmm_tmp, ptr[aux_reg_src + aux_src_off + r], r); vpbroadcastd( zmm_inp(jj, jcp.nb_oc_blocking), xmm_tmp); } else { vpbroadcastd(zmm_inp(jj, jcp.nb_oc_blocking), EVEX_compress_addr( aux_reg_src, aux_src_off)); } if (jcp.signed_input) vpsubb(zmm_inp(jj, jcp.nb_oc_blocking), zmm_inp(jj, jcp.nb_oc_blocking), zmm_shift); } else { /* fill padded area with shifted values */ if (jcp.signed_input) { Zmm inp = zmm_inp(jj, jcp.nb_oc_blocking); vpxord(inp, inp, inp); vpsubb(inp, inp, zmm_shift); } } } } for (int ocb = 0; ocb < jcp.nb_oc_blocking; ocb++) { int aux_filt_off = kernel_offset(ocb, icb1, ki); if (_end - _start > 0) { if (jcp.is_depthwise) vpmovsxbd(zmm_wei, EVEX_compress_addr(aux_reg_filt, aux_filt_off)); else vmovups(zmm_wei, EVEX_compress_addr(aux_reg_filt, aux_filt_off)); } for (int jj = _start; jj < _end; jj += ur_w_stride) { Zmm inp = (h_padded == true) ? zmm_inp(0, jcp.nb_oc_blocking) : zmm_inp(jj, jcp.nb_oc_blocking); compute(zmm_out(jj, ocb), zmm_wei, inp); } } } } } void jit_avx512_core_x8s8s32x_deconv_fwd_kernel::kh_loop(int ur_w, int l_overflow, int r_overflow, ker_block_t last_ic_block_flag) { int ch_block_all = jcp.ch_block * jcp.ic_block * jcp.oc_block; int shift_src_ih = jcp.typesize_in * (jcp.dilate_h + 1) * jcp.iw * jcp.ngroups * jcp.ic_without_padding; int shift_src_id = jcp.typesize_in * (jcp.dilate_d + 1) * jcp.ih * jcp.iw * jcp.ngroups * jcp.ic_without_padding; const int stride_h = jcp.signed_input ? 1 : jcp.stride_h; int shift_filt_kh = jcp.typesize_in * jcp.kw * ch_block_all * stride_h; const int stride_d = jcp.signed_input ? 1 : jcp.stride_d; int shift_filt_kd = jcp.typesize_in * jcp.kw * ch_block_all * jcp.kh * stride_d; Label kd_loop_label, kh_loop_label, skip_kh_loop, skip_kd_loop; Label t_overflow_label, no_t_overflow_label, b_overflow_label, no_b_overflow_label; Label back_overflow_label, no_back_overflow_label, d_h_overflow_label, front_overflow_label, no_front_overflow_label, d_h_overflow_label2; if (jcp.ndims == 5) { mov(aux_reg_filt_d, reg_filt); mov(aux_reg_src_d, reg_src); if (jcp.signed_input) { mov(reg_ki, ptr[param1 + GET_OFF(back_overflow)]); cmp(reg_ki, 0); je(no_back_overflow_label, T_NEAR); L(back_overflow_label); { mov(aux_reg_filt, aux_reg_filt_d); mov(reg_kh, jcp.kh); L(d_h_overflow_label); { compute_ker(ur_w, 0, 0, last_ic_block_flag, true); add(aux_reg_filt, shift_filt_kh); dec(reg_kh); jnz(d_h_overflow_label); } add(aux_reg_filt_d, shift_filt_kd); dec(reg_ki); jnz(back_overflow_label); } L(no_back_overflow_label); } mov(reg_ki, ptr[param1 + GET_OFF(kd_padding)]); if ((jcp.signed_input) || (jcp.dilate_d >= jcp.id) || ((!jcp.signed_input) && ((min(jcp.f_pad, jcp.back_pad) < 0) || ((jcp.kd - 1) * (jcp.dilate_d + 1) < nstl::max( jcp.f_pad, jcp.back_pad))))) { cmp(reg_ki, 0); je(skip_kd_loop, T_NEAR); } L(kd_loop_label); mov(aux_reg_src, aux_reg_src_d); mov(aux_reg_filt, aux_reg_filt_d); } else { mov(aux_reg_src, reg_src); mov(aux_reg_filt, reg_filt); } if (jcp.signed_input && jcp.ndims > 3) { /* Weights are transposed, so first compute 'bottom' padding. */ mov(reg_overflow, ptr[param1 + GET_OFF(b_overflow)]); cmp(reg_overflow, 0); je(no_b_overflow_label, T_NEAR); L(b_overflow_label); { compute_ker(ur_w, 0, 0, last_ic_block_flag, true); add(aux_reg_filt, shift_filt_kh); dec(reg_overflow); cmp(reg_overflow, 0); jg(b_overflow_label, T_NEAR); } L(no_b_overflow_label); } mov(reg_kh, ptr[param1 + GET_OFF(kh_padding)]); if ((jcp.signed_input) || (jcp.dilate_h >= jcp.ih) || ((!jcp.signed_input) && ((min(jcp.t_pad, jcp.b_pad) < 0) || ((jcp.kh - 1) * (jcp.dilate_h + 1) < nstl::max(jcp.t_pad, jcp.b_pad))))) { cmp(reg_kh, 0); je(skip_kh_loop, T_NEAR); } L(kh_loop_label); { compute_ker(ur_w, l_overflow, r_overflow, last_ic_block_flag, false); sub(aux_reg_src, shift_src_ih); add(aux_reg_filt, shift_filt_kh); dec(reg_kh); /* Insert weight compensation in stride 'holes' */ if (jcp.signed_input && jcp.stride_h > 1) { Label kh_comp_loop; cmp(reg_kh, 0); je(skip_kh_loop, T_NEAR); mov(reg_comp_strides, jcp.stride_h - 1); L(kh_comp_loop); { compute_ker(ur_w, 0, 0, last_ic_block_flag, true); add(aux_reg_filt, shift_filt_kh); dec(reg_comp_strides); cmp(reg_comp_strides, 0); jg(kh_comp_loop, T_NEAR); } } cmp(reg_kh, 0); jg(kh_loop_label, T_NEAR); } L(skip_kh_loop); if (jcp.signed_input && jcp.ndims > 3) { mov(reg_overflow, ptr[param1 + GET_OFF(t_overflow)]); cmp(reg_overflow, 0); je(no_t_overflow_label, T_NEAR); L(t_overflow_label); { compute_ker(ur_w, 0, 0, last_ic_block_flag, true); add(aux_reg_filt, shift_filt_kh); dec(reg_overflow); cmp(reg_overflow, 0); jg(t_overflow_label, T_NEAR); } L(no_t_overflow_label); } if (jcp.ndims == 5) { sub(aux_reg_src_d, shift_src_id); add(aux_reg_filt_d, shift_filt_kd); dec(reg_ki); /* Insert weight compensation in stride 'holes' */ if (jcp.signed_input && jcp.stride_d > 1) { Label kd_comp_loop, kd_kh_comp_loop; cmp(reg_ki, 0); jz(skip_kd_loop, T_NEAR); mov(reg_comp_strides, jcp.stride_d - 1); L(kd_comp_loop); mov(aux_reg_filt, aux_reg_filt_d); mov(reg_kh, jcp.kh); L(kd_kh_comp_loop); { compute_ker(ur_w, 0, 0, last_ic_block_flag, true); add(aux_reg_filt, shift_filt_kh); dec(reg_kh); jnz(kd_kh_comp_loop, T_NEAR); } add(aux_reg_filt_d, shift_filt_kd); dec(reg_comp_strides); jnz(kd_comp_loop); } cmp(reg_ki, 0); jg(kd_loop_label, T_NEAR); L(skip_kd_loop); if (jcp.signed_input) { mov(reg_ki, ptr[param1 + GET_OFF(f_overflow)]); cmp(reg_ki, 0); jz(no_front_overflow_label, T_NEAR); L(front_overflow_label); { mov(aux_reg_filt, aux_reg_filt_d); mov(reg_kh, jcp.kh); L(d_h_overflow_label2); { compute_ker(ur_w, 0, 0, last_ic_block_flag, true); add(aux_reg_filt, shift_filt_kh); dec(reg_kh); jnz(d_h_overflow_label2); } add(aux_reg_filt_d, shift_filt_kd); dec(reg_ki); jnz(front_overflow_label); } L(no_front_overflow_label); } } } void jit_avx512_core_x8s8s32x_deconv_fwd_kernel::prepare_output(int ur_w) { for (int ocb = 0; ocb < jcp.nb_oc_blocking; ocb++) { for (int ur = 0; ur < ur_w; ur++) { zmm_t zmm = zmm_out(ur, ocb); vpxord(zmm, zmm, zmm); } } if (jcp.signed_input) { xor_(reg_scratch, reg_scratch); Reg8 _t8 = reg_scratch.cvt8(); mov(_t8, (int8_t)-128); vpbroadcastb(zmm_shift, _t8); } } void jit_avx512_core_x8s8s32x_deconv_fwd_kernel::cvt2ps( data_type_t type_in, zmm_t zmm_in, const Operand &op, bool mask_flag) { zmm_t zmm = mask_flag ? zmm_in | ktail_mask | T_z : zmm_in; switch (type_in) { case data_type::f32: case data_type::s32: vmovups(zmm, op); break; case data_type::s8: vpmovsxbd(zmm, op); break; case data_type::u8: vpmovzxbd(zmm, op); break; default: assert(!""unsupported data type""); } if (type_in != data_type::f32) vcvtdq2ps(zmm_in, zmm_in); } void jit_avx512_core_x8s8s32x_deconv_fwd_kernel::store_output( int ur_w, bool last_oc_block) { mov(reg_bias, ptr[param1 + GET_OFF(bias)]); mov(reg_ptr_scales, ptr[param1 + GET_OFF(scales)]); if (jcp.signed_input) mov(reg_compensation, ptr[param1 + GET_OFF(compensation)]); const auto &p = attr_.post_ops_; const int sum_idx = p.find(primitive_kind::sum); const float *p_sum_scale = (sum_idx != -1) ? &p.entry_[sum_idx].sum.scale : nullptr; if (p_sum_scale && *p_sum_scale != 1.f) mov(reg_ptr_sum_scale, (size_t)p_sum_scale); if (jcp.with_bias && jcp.signed_input && jcp.ver != ver_vnni) { mov(reg_bias_alpha, float2int(jcp.wei_adj_scale)); vmovq(xmm_bias_alpha(), reg_bias_alpha); vbroadcastss(zmm_bias_alpha(), xmm_bias_alpha()); } for (int ocb = 0; ocb < jcp.nb_oc_blocking; ocb++) { const bool mask_flag = last_oc_block && ocb == jcp.nb_oc_blocking - 1; int scale_offset = jcp.is_oc_scale * (sizeof(float) * ocb * jcp.oc_block); auto zmm_bias = zmm_tmp; if (jcp.with_bias) { int bias_offset = jcp.typesize_bia * ocb * jcp.oc_block; auto bias_addr = EVEX_compress_addr(reg_bias, bias_offset); cvt2ps(jcp.bia_dt, zmm_bias, bias_addr, mask_flag); if (jcp.signed_input && jcp.ver != ver_vnni) vmulps(zmm_bias, zmm_bias, zmm_bias_alpha()); } if (jcp.signed_input) { int comp_offset = sizeof(int32_t) * ocb * jcp.oc_block; auto comp_addr = EVEX_compress_addr(reg_compensation, comp_offset); cvt2ps(data_type::s32, zmm_comp, comp_addr, mask_flag); } for (int ur = 0; ur < ur_w; ur++) { zmm_t zmm = zmm_out(ur, ocb); vcvtdq2ps(zmm, zmm); if (jcp.signed_input) vaddps(zmm, zmm, zmm_comp); if (jcp.with_bias) vaddps(zmm, zmm, zmm_bias); zmm_t mask_zmm = mask_flag ? zmm | ktail_mask | T_z : zmm; vmulps(mask_zmm, zmm, EVEX_compress_addr(reg_ptr_scales, scale_offset)); } } /* Do post-ops */ int eltwise_inj_idx = 0; int depthwise_inj_idx = 0; int quantization_inj_idx = 0; int nb_oc_block = jcp.nb_oc_blocking; int oc_block = jcp.oc_block; for (int i = 0; i < p.len(); i++) { auto& post_op = p.entry_[i]; if (post_op.is_eltwise()) { eltwise_injectors[eltwise_inj_idx]->compute_vector_range(0, nb_oc_block * ur_w); eltwise_inj_idx++; } else if (post_op.is_depthwise()) { for (int ur = 0; ur < ur_w; ur++) { mov(reg_d_weights, reinterpret_cast(post_op.depthwise.weights_data)); mov(reg_d_bias, reinterpret_cast(post_op.depthwise.biases_data)); add(reg_d_weights, ptr[param1 + GET_OFF(oc_off)]); add(reg_d_bias, ptr[param1 + GET_OFF(oc_off)]); for (int k = 0; k < nb_oc_block; k++) { int s_idx = zmm_out(ur, k).getIdx(); depthwise_injectors[depthwise_inj_idx]->compute_vector_range(s_idx, s_idx + 1, reg_d_weights, reg_d_bias); add(reg_d_weights, oc_block * sizeof(float)); add(reg_d_bias, oc_block * sizeof(float)); } } depthwise_inj_idx++; } else if (post_op.is_quantization()) { for (int ur = 0; ur < ur_w; ur++) { bool do_dequantization = post_op.quantization.alg == alg_kind::quantization_quantize_dequantize; bool do_rounding = do_dequantization || jcp.dst_dt == dnnl_f32 || i != p.len() - 1; quantization_injectors[quantization_inj_idx]->init_crop_ptrs(ptr[param1 + GET_OFF(oc_off)]); for (int k = 0; k < nb_oc_block; k++) { int s_idx = zmm_out(ur, k).getIdx(); quantization_injectors[quantization_inj_idx]->compute_crop(s_idx, s_idx + 1, k * oc_block * sizeof(float)); } quantization_injectors[quantization_inj_idx]->init_input_scale_shift_ptrs(ptr[param1 + GET_OFF(oc_off)]); for (int k = 0; k < nb_oc_block; k++) { int s_idx = zmm_out(ur, k).getIdx(); quantization_injectors[quantization_inj_idx]->compute_input_scale_shift(s_idx, s_idx + 1, k * oc_block * sizeof(float), do_rounding); } quantization_injectors[quantization_inj_idx]->init_output_scale_shift_ptrs(ptr[param1 + GET_OFF(oc_off)]); for (int k = 0; k < nb_oc_block; k++) { int s_idx = zmm_out(ur, k).getIdx(); quantization_injectors[quantization_inj_idx]->compute_output_scale_shift(s_idx, s_idx + 1, k * oc_block * sizeof(float)); } } quantization_inj_idx++; } } // Properly saturate the accumulators for integer datatypes // No need to saturate on lower bound for signed integer types, as // the conversion to int would return INT_MIN, and then proper // saturation will happen when storing data if (jcp.dst_dt == data_type::u8) { vpxord(zmm_zero, zmm_zero, zmm_zero); for (int ocb = 0; ocb < jcp.nb_oc_blocking; ocb++) { for (int ur = 0; ur < ur_w; ur++) { zmm_t zmm = zmm_out(ur, ocb); vmaxps(zmm, zmm_zero, zmm); } } } if (one_of(jcp.dst_dt, data_type::u8, data_type::s8, data_type::s32)) { float saturation_ubound = types::max_value(jcp.dst_dt); Xmm xmm_saturation(zmm_saturation.getIdx()); mov(reg_ptr_saturation_ubound, float2int(saturation_ubound)); vmovq(xmm_saturation, reg_ptr_saturation_ubound); vbroadcastss(zmm_saturation, xmm_saturation); for (int ocb = 0; ocb < jcp.nb_oc_blocking; ocb++) { for (int ur = 0; ur < ur_w; ur++) { zmm_t zmm = zmm_out(ur, ocb); vminps(zmm, zmm, zmm_saturation); } } } if (one_of(jcp.dst_dt, data_type::u8, data_type::s8, data_type::s32)) { for (int ocb = 0; ocb < jcp.nb_oc_blocking; ocb++) { for (int ur = 0; ur < ur_w; ur++) { zmm_t zmm = zmm_out(ur, ocb); vcvtps2dq(zmm, zmm); } } } /* write out register to output_addr */ for (int ocb = 0; ocb < jcp.nb_oc_blocking; ocb++) { const bool mask_flag = last_oc_block && ocb == jcp.nb_oc_blocking - 1; for (int ur = 0; ur < ur_w; ur++) { int aux_dst_off = jcp.typesize_out * (ur * jcp.ngroups * jcp.oc_without_padding + ocb * jcp.oc_block); auto addr = EVEX_compress_addr(reg_dst, aux_dst_off); zmm_t zmm = zmm_out(ur, ocb); zmm_t r_zmm = mask_flag ? zmm | ktail_mask : zmm; switch (jcp.dst_dt) { case data_type::f32: case data_type::s32: vmovups(addr, r_zmm); break; case data_type::s8: vpmovsdb(addr, r_zmm); break; case data_type::u8: vpmovusdb(addr, r_zmm); break; default: assert(!""unknown dst_dt""); } } } } void jit_avx512_core_x8s8s32x_deconv_fwd_kernel::icb_loop( int ur_w, int l_overflow, int r_overflow, bool is_last_sp_block) { int shift_src_icb = jcp.typesize_in * jcp.ic_block; int shift_filt_icb = jcp.typesize_in * jcp.kd * jcp.kh * jcp.kw * jcp.ic_block * jcp.oc_block; prepare_output(ur_w); Label skip_icb_loop, icb_loop_label; mov(reg_icb, jcp.nb_ic); L(icb_loop_label); { if (jcp.ic_without_padding != jcp.ic) { Label common_ker, end_ker; cmp(reg_icb, 1); jg(common_ker, T_NEAR); kh_loop(ur_w, l_overflow, r_overflow, is_last_sp_block ? last_sp_block : last_ic_block); jmp(end_ker, T_NEAR); L(common_ker); kh_loop(ur_w, l_overflow, r_overflow, no_last_block); L(end_ker); } else { kh_loop(ur_w, l_overflow, r_overflow, no_last_block); } add(reg_src, shift_src_icb); add(reg_filt, shift_filt_icb); dec(reg_icb); cmp(reg_icb, 0); jg(icb_loop_label, T_NEAR); } /* come-back pointers */ sub(reg_src, jcp.nb_ic * shift_src_icb); sub(reg_filt, jcp.nb_ic * shift_filt_icb); L(skip_icb_loop); if (jcp.ngroups % jcp.ch_block != 0 || jcp.oc_without_padding != jcp.oc) { Label common_store, end_store; mov(reg_oc_blocks, ptr[param1 + GET_OFF(oc_blocks)]); if (jcp.is_depthwise) cmp(reg_oc_blocks, jcp.nb_ch - 1); else cmp(reg_oc_blocks, jcp.nb_oc - jcp.nb_oc_blocking); jne(common_store, T_NEAR); store_output(ur_w, true); jmp(end_store, T_NEAR); L(common_store); store_output(ur_w, false); L(end_store); } else { store_output(ur_w, false); } } void jit_avx512_core_x8s8s32x_deconv_fwd_kernel::generate() { const auto &p = attr_.post_ops_; if (jcp.ver == ver_vnni) { vmm_d_weights = zmm_t(28); vmm_d_bias = zmm_t(29); } else { vmm_d_weights = zmm_t(26); vmm_d_bias = zmm_t(27); } for (int i = 0; i < p.len(); i++) { auto &post_op = p.entry_[i]; if (post_op.is_eltwise()) { eltwise_injectors.push_back(new jit_uni_eltwise_injector_f32( this, post_op.eltwise, true, eltwise_reserved )); } else if (post_op.is_depthwise()) { depthwise_injectors.push_back(new jit_uni_depthwise_injector_f32( this, post_op.depthwise.alg )); } else if (post_op.is_quantization()) { quantization_injectors.push_back(new jit_uni_quantization_injector_f32( this, post_op, vmm_d_weights, vmm_d_bias, reg_d_weights, reg_d_bias )); } } preamble(); xor_(reg_scratch, reg_scratch); Reg16 _t = reg_scratch.cvt16(); mov(_t, 0x1); vpbroadcastw(zmm_one, _t); if (jcp.ngroups % jcp.ch_block != 0 || jcp.oc_without_padding != jcp.oc) { int tail_size = jcp.is_depthwise ? jcp.ngroups % jcp.ch_block : jcp.oc_without_padding % jcp.oc_block; int mask = (1 << tail_size) - 1; Reg32 regw_tmp = reg_nur_w.cvt32(); Label skip_tail_mask; if (jcp.is_depthwise) { kxnorw(ktail_mask, ktail_mask, ktail_mask); cmp(dword[param1 + GET_OFF(oc_blocks)], jcp.nb_ch - 1); jne(skip_tail_mask, T_NEAR); } mov(regw_tmp, mask); kmovw(ktail_mask, regw_tmp); L(skip_tail_mask); } mov(reg_src, ptr[param1 + GET_OFF(src)]); mov(reg_filt, ptr[param1 + GET_OFF(filt)]); mov(reg_dst, ptr[param1 + GET_OFF(dst)]); int dst_shift = jcp.typesize_out * jcp.ur_w * jcp.ngroups * jcp.oc_without_padding; int src_shift = jcp.typesize_in * (jcp.ur_w / jcp.stride_w) * jcp.ngroups * jcp.ic_without_padding; int l_overflow = max( 0, ((jcp.kw - 1) * (jcp.dilate_w + 1) - jcp.l_pad) / jcp.stride_w); int r_overflow = max(0, ((jcp.kw - 1) * (jcp.dilate_w + 1) - max(0, jcp.r_pad)) / jcp.stride_w); int r_overflow1 = nstl::max(0, ((jcp.kw - 1) * (jcp.dilate_w + 1) - nstl::max(0, jcp.r_pad) - jcp.ur_w_tail) / jcp.stride_w); int nur_w = jcp.ow / jcp.ur_w; if (r_overflow1 > 0) nur_w--; if (jcp.ur_w == jcp.ow) { icb_loop(jcp.ur_w, l_overflow, r_overflow, true); } else if (nur_w == 0) { icb_loop(jcp.ur_w, l_overflow, r_overflow1, jcp.ur_w_tail == 0); add(reg_src, src_shift); add(reg_dst, dst_shift); if (jcp.ur_w_tail != 0) icb_loop(jcp.ur_w_tail, 0, r_overflow, true); } else { xor_(reg_nur_w, reg_nur_w); if (l_overflow > 0) { icb_loop(jcp.ur_w, l_overflow, 0, false); add(reg_src, src_shift); add(reg_dst, dst_shift); inc(reg_nur_w); } if ((l_overflow <= 0 && nur_w > 0) || (l_overflow > 0 && nur_w > 1)) { Label ow_loop_label; L(ow_loop_label); { icb_loop(jcp.ur_w, 0, 0, false); add(reg_src, src_shift); add(reg_dst, dst_shift); inc(reg_nur_w); cmp(reg_nur_w, nur_w); jl(ow_loop_label, T_NEAR); } } if (r_overflow1 > 0) { icb_loop(jcp.ur_w, 0, r_overflow1, jcp.ur_w_tail == 0); add(reg_src, src_shift); add(reg_dst, dst_shift); } if (jcp.ur_w_tail != 0) { icb_loop(jcp.ur_w_tail, 0, r_overflow, true); } } postamble(); for (auto& inj : eltwise_injectors) inj->prepare_table(); } template void _jit_avx512_core_x8s8s32x_deconvolution_fwd_t::execute_forward_1d(const exec_ctx_t &ctx) const { auto src = CTX_IN_MEM(const src_data_t *, DNNL_ARG_SRC); auto weights = CTX_IN_MEM(const wei_data_t *, DNNL_ARG_WEIGHTS); auto bias = CTX_IN_MEM(const char *, DNNL_ARG_BIAS); auto dst = CTX_OUT_MEM(dst_data_t *, DNNL_ARG_DST); const memory_desc_wrapper src_d(pd()->src_md()); const memory_desc_wrapper dst_d(pd()->dst_md()); const memory_desc_wrapper weights_d(pd()->weights_md(0)); const memory_desc_wrapper bias_d(pd()->weights_md(1)); auto &jcp = kernel_->jcp; int oc_chunks = jcp.nb_oc / jcp.nb_oc_blocking; int nb_groups = jcp.nb_ch; const float *oscales = pd()->attr()->output_scales_.scales_; if (jcp.signed_input && jcp.ver != ver_vnni) { auto local_scales = ctx.get_scratchpad_grantor().template get( key_conv_adjusted_scales); size_t count = pd()->attr()->output_scales_.count_; float factor = 1.f / pd()->jcp_.wei_adj_scale; if (count == 1) { utils::array_set(local_scales, oscales[0] * factor, 16); } else { for (size_t c = 0; c < count; c++) local_scales[c] = oscales[c] * factor; } oscales = local_scales; } size_t offset = (size_t)jcp.ngroups * jcp.oc * jcp.ic * jcp.kh * jcp.kw; auto w = const_cast(weights); int32_t *compensation = (jcp.signed_input) ? reinterpret_cast(&w[offset]) : nullptr; parallel(jcp.nthr, [&](const int ithr, const int nthr) { int start {0}, end {0}; int work_amount = jcp.mb * nb_groups * oc_chunks; balance211(work_amount, nthr, ithr, start, end); auto p = jit_deconv_call_s(); int n {0}, g {0}, occ {0}; if (jcp.loop_order == loop_ngc) nd_iterator_init(start, n, jcp.mb, g, nb_groups, occ, oc_chunks); else if (jcp.loop_order == loop_cgn) nd_iterator_init(start, occ, oc_chunks, g, nb_groups, n, jcp.mb); else assert(!""unsupported loop order""); while (start < end) { int ocb = occ * jcp.nb_oc_blocking; int g_oc = (g * jcp.ch_block * jcp.nb_oc + ocb) * jcp.oc_block; int g_ic = g * jcp.ch_block * jcp.ic; p.dst = dst + dst_d.blk_off(n, g_oc); p.src = src + src_d.blk_off(n, g_ic); p.filt = weights + wht_blk_off(weights_d, g, ocb, 0); p.bias = jcp.with_bias ? bias + (bias_d.blk_off(g_oc) * jcp.typesize_bia) : nullptr; p.compensation = (jcp.signed_input) ? compensation + g_oc : nullptr; p.scales = &oscales[jcp.is_oc_scale * g_oc]; p.t_overflow = 0; p.b_overflow = 0; p.kh_padding = jcp.kh; p.oc_blocks = jcp.is_depthwise ? g : ocb; p.oc_off = g_oc * sizeof(float); (*kernel_)(&p); ++start; if (jcp.loop_order == loop_ngc) nd_iterator_step(n, jcp.mb, g, nb_groups, occ, oc_chunks); else if (jcp.loop_order == loop_cgn) nd_iterator_step(occ, oc_chunks, g, nb_groups, n, jcp.mb); else assert(!""unsupported loop order""); } }); } template void _jit_avx512_core_x8s8s32x_deconvolution_fwd_t::execute_forward_2d(const exec_ctx_t &ctx) const { auto src = CTX_IN_MEM(const src_data_t *, DNNL_ARG_SRC); auto weights = CTX_IN_MEM(const wei_data_t *, DNNL_ARG_WEIGHTS); auto bias = CTX_IN_MEM(const char *, DNNL_ARG_BIAS); auto dst = CTX_OUT_MEM(dst_data_t *, DNNL_ARG_DST); const memory_desc_wrapper src_d(pd()->src_md()); const memory_desc_wrapper dst_d(pd()->dst_md()); const memory_desc_wrapper weights_d(pd()->weights_md(0)); const memory_desc_wrapper bias_d(pd()->weights_md(1)); auto &jcp = kernel_->jcp; int oc_chunks = jcp.nb_oc / jcp.nb_oc_blocking; int nb_groups = jcp.nb_ch; size_t src_h_stride = src_d.blk_off(0, 0, 1); size_t dst_h_stride = dst_d.blk_off(0, 0, 1); size_t wht_kh_stride = wht_blk_off(weights_d, 0, 0, 0, 1); const float *oscales = pd()->attr()->output_scales_.scales_; if (jcp.signed_input && jcp.ver != ver_vnni) { auto local_scales = ctx.get_scratchpad_grantor().template get( key_conv_adjusted_scales); size_t count = pd()->attr()->output_scales_.count_; float factor = 1.f / pd()->jcp_.wei_adj_scale; if (count == 1) { utils::array_set(local_scales, oscales[0] * factor, 16); } else { for (size_t c = 0; c < count; c++) local_scales[c] = oscales[c] * factor; } oscales = local_scales; } size_t offset = (size_t)jcp.ngroups * jcp.oc * jcp.ic * jcp.kh * jcp.kw; auto w = const_cast(weights); int32_t *compensation = (jcp.signed_input) ? reinterpret_cast(&w[offset]) : nullptr; parallel(jcp.nthr, [&](const int ithr, const int nthr) { int start {0}, end {0}; int work_amount = jcp.mb * nb_groups * oc_chunks * jcp.oh; balance211(work_amount, nthr, ithr, start, end); auto p = jit_deconv_call_s(); /*loop order = cgn*/ int n {0}, g {0}, occ {0}, oh_s {0}; if (jcp.loop_order == loop_ngc) nd_iterator_init(start, n, jcp.mb, g, nb_groups, occ, oc_chunks, oh_s, jcp.oh); else if (jcp.loop_order == loop_cgn) nd_iterator_init(start, occ, oc_chunks, g, nb_groups, n, jcp.mb, oh_s, jcp.oh); else assert(!""unsupported loop order""); while (start < end) { int ocb = occ * jcp.nb_oc_blocking; int g_oc = (g * jcp.ch_block * jcp.nb_oc + ocb) * jcp.oc_block; int g_ic = g * jcp.ch_block * jcp.ic; int work_rem = end - start; int oh_e = oh_s + work_rem > jcp.oh ? jcp.oh : oh_s + work_rem; auto dst_w = dst + dst_d.blk_off(n, g_oc); auto src_w = src + src_d.blk_off(n, g_ic); auto wht_w = weights + wht_blk_off(weights_d, g, ocb, 0); auto bias_w = jcp.with_bias ? bias + (bias_d.blk_off(g_oc) * jcp.typesize_bia) : nullptr; int32_t *compensation_w = (jcp.signed_input) ? compensation + g_oc : nullptr; auto scales = &oscales[jcp.is_oc_scale * g_oc]; for (int oj = oh_s; oj < oh_e; oj++) { int ih_max = 0, kh_lo = 0, kh_len = 0; if (jcp.dilate_h != 0 && jcp.stride_h == 1) { /* dilation */ int dilate_h = jcp.dilate_h + 1; // Note: use div_up to account for ""holes"" in filter int o_t_overflow = div_up( max(0, (jcp.kh - 1) * dilate_h - oj - jcp.t_pad), dilate_h); int o_b_overflow = div_up(max(0, (jcp.kh - 1) * dilate_h + 1 - jcp.oh + oj - jcp.b_pad), dilate_h); kh_len = jcp.kh - o_t_overflow - o_b_overflow; kh_lo = o_b_overflow; ih_max = oj + jcp.t_pad - o_b_overflow * dilate_h; } else { int o_t_overflow = max( 0, (jcp.kh - (oj + 1 + jcp.t_pad)) / jcp.stride_h); int o_b_overflow = max(0, ((oj + jcp.kh) - (jcp.oh + jcp.b_pad)) / jcp.stride_h); int overflow_kh_hi = jcp.kh - 1 - modulo(jcp.oh + jcp.b_pad - (oj + 1), jcp.stride_h); int overflow_kh_lo = (oj + jcp.t_pad) % jcp.stride_h; kh_len = (overflow_kh_hi - overflow_kh_lo) / jcp.stride_h + 1 - o_t_overflow - o_b_overflow; kh_lo = overflow_kh_lo + o_b_overflow * jcp.stride_h; ih_max = (oj + jcp.t_pad - kh_lo) / jcp.stride_h; } int wei_stride = (!jcp.signed_input) ? kh_lo * wht_kh_stride : 0; p.src = src_w + ih_max * src_h_stride; p.dst = dst_w + oj * dst_h_stride; p.filt = wht_w + wei_stride; p.bias = bias_w; p.compensation = compensation_w; p.t_overflow = jcp.dilate_h > 0 ? jcp.kh - kh_len - kh_lo : max(0, jcp.kh - (kh_lo + max(0, kh_len - 1) * jcp.stride_h + 1)); p.b_overflow = kh_lo; p.kh_padding = kh_len; p.scales = scales; p.oc_blocks = jcp.is_depthwise ? g : ocb; p.oc_off = g_oc * sizeof(float); (*kernel_)(&p); } if (jcp.loop_order == loop_ngc) nd_iterator_jump(start, end, n, jcp.mb, g, nb_groups, occ, oc_chunks, oh_s, jcp.oh); else if (jcp.loop_order == loop_cgn) nd_iterator_jump(start, end, occ, oc_chunks, g, nb_groups, n, jcp.mb, oh_s, jcp.oh); else assert(!""unsupported loop order""); } }); } template void _jit_avx512_core_x8s8s32x_deconvolution_fwd_t::execute_forward_3d(const exec_ctx_t &ctx) const { auto src = CTX_IN_MEM(const src_data_t *, DNNL_ARG_SRC); auto weights = CTX_IN_MEM(const wei_data_t *, DNNL_ARG_WEIGHTS); auto bias = CTX_IN_MEM(const char *, DNNL_ARG_BIAS); auto dst = CTX_OUT_MEM(dst_data_t *, DNNL_ARG_DST); const memory_desc_wrapper src_d(pd()->src_md()); const memory_desc_wrapper dst_d(pd()->dst_md()); const memory_desc_wrapper weights_d(pd()->weights_md(0)); const memory_desc_wrapper bias_d(pd()->weights_md(1)); auto &jcp = kernel_->jcp; int oc_chunks = jcp.nb_oc / jcp.nb_oc_blocking; int nb_groups = jcp.nb_ch; size_t src_d_stride = src_d.blk_off(0, 0, 1); size_t src_h_stride = src_d.blk_off(0, 0, 0, 1); size_t dst_d_stride = dst_d.blk_off(0, 0, 1); size_t dst_h_stride = dst_d.blk_off(0, 0, 0, 1); size_t wht_kd_stride = wht_blk_off(weights_d, 0, 0, 0, 1); size_t wht_kh_stride = wht_blk_off(weights_d, 0, 0, 0, 0, 1); const float *oscales = pd()->attr()->output_scales_.scales_; if (jcp.signed_input && jcp.ver != ver_vnni) { auto local_scales = ctx.get_scratchpad_grantor().template get( key_conv_adjusted_scales); size_t count = pd()->attr()->output_scales_.count_; float factor = 1.f / pd()->jcp_.wei_adj_scale; if (count == 1) { utils::array_set(local_scales, oscales[0] * factor, 16); } else { for (size_t c = 0; c < count; c++) local_scales[c] = oscales[c] * factor; } oscales = local_scales; } size_t offset = weights_d.size() - weights_d.additional_buffer_size(); auto w = const_cast(weights); int32_t *compensation = (jcp.signed_input) ? reinterpret_cast(&w[offset]) : nullptr; parallel(jcp.nthr, [&](const int ithr, const int nthr) { int start {0}, end {0}; int work_amount = jcp.mb * nb_groups * oc_chunks * jcp.od * jcp.oh; balance211(work_amount, nthr, ithr, start, end); auto p = jit_deconv_call_s(); /*loop order = cgn*/ int n {0}, g {0}, occ {0}, od_s {0}, oh_s {0}; if (jcp.loop_order == loop_ngc) nd_iterator_init(start, n, jcp.mb, g, nb_groups, occ, oc_chunks, od_s, jcp.od, oh_s, jcp.oh); else if (jcp.loop_order == loop_cgn) nd_iterator_init(start, occ, oc_chunks, g, nb_groups, n, jcp.mb, od_s, jcp.od, oh_s, jcp.oh); else assert(!""unsupported loop order""); while (start < end) { int ocb = occ * jcp.nb_oc_blocking; int g_oc = (g * jcp.ch_block * jcp.nb_oc + ocb) * jcp.oc_block; int g_ic = g * jcp.ch_block * jcp.ic; int work_rem = end - start; int oh_e = oh_s + work_rem > jcp.oh ? jcp.oh : oh_s + work_rem; int input_d_s = 0, kd_len = 0, kd_lo = 0; int d_t_overflow, d_back_overflow; if (jcp.dilate_d != 0 && jcp.stride_d == 1) { /* dilation */ int dilate_d = jcp.dilate_d + 1; // Note: use div_up to account for ""holes"" in filter d_t_overflow = div_up( max(0, (jcp.kd - 1) * dilate_d - od_s - jcp.f_pad), dilate_d); d_back_overflow = div_up(max(0, (jcp.kd - 1) * dilate_d + 1 - jcp.od + od_s - jcp.back_pad), dilate_d); kd_len = jcp.kd - d_t_overflow - d_back_overflow; kd_lo = d_back_overflow; input_d_s = od_s + jcp.f_pad - d_back_overflow * dilate_d; } else { int d_t_overflow = max( 0, (jcp.kd - (od_s + 1 + jcp.f_pad)) / jcp.stride_d); int d_back_overflow = max(0, ((od_s + jcp.kd) - (jcp.od + jcp.back_pad)) / jcp.stride_d); int overflow_kd_hi = jcp.kd - 1 - modulo(jcp.od + jcp.back_pad - (od_s + 1), jcp.stride_d); int overflow_kd_lo = (od_s + jcp.f_pad) % jcp.stride_d; kd_len = (overflow_kd_hi - overflow_kd_lo) / jcp.stride_d + 1 - d_t_overflow - d_back_overflow; kd_lo = overflow_kd_lo + d_back_overflow * jcp.stride_d; input_d_s = (od_s + jcp.f_pad - kd_lo) / jcp.stride_d; } auto dst_w = dst + dst_d.blk_off(n, g_oc) + od_s * dst_d_stride; auto src_w = src + src_d.blk_off(n, g_ic) + input_d_s * src_d_stride; auto wht_w = weights + wht_blk_off(weights_d, g, ocb, 0) + (jcp.signed_input ? 0 : kd_lo) * wht_kd_stride; auto bias_w = jcp.with_bias ? bias + (bias_d.blk_off(g_oc) * jcp.typesize_bia) : nullptr; int32_t *compensation_w = (jcp.signed_input) ? compensation + g_oc : nullptr; auto scales = &oscales[jcp.is_oc_scale * g_oc]; for (int oj = oh_s; oj < oh_e; oj++) { int ih_max = 0, kh_lo = 0, kh_len = 0; if (jcp.dilate_h != 0 && jcp.stride_h == 1) { /* dilation */ int dilate_h = jcp.dilate_h + 1; // Note: use div_up to account for ""holes"" in filter int o_t_overflow = div_up( max(0, (jcp.kh - 1) * dilate_h - oj - jcp.t_pad), dilate_h); int o_b_overflow = div_up(max(0, (jcp.kh - 1) * dilate_h + 1 - jcp.oh + oj - jcp.b_pad), dilate_h); kh_len = jcp.kh - o_t_overflow - o_b_overflow; kh_lo = o_b_overflow; ih_max = oj + jcp.t_pad - o_b_overflow * dilate_h; } else { int o_t_overflow = max( 0, (jcp.kh - (oj + 1 + jcp.t_pad)) / jcp.stride_h); int o_b_overflow = max(0, ((oj + jcp.kh) - (jcp.oh + jcp.b_pad)) / jcp.stride_h); int overflow_kh_hi = jcp.kh - 1 - modulo(jcp.oh + jcp.b_pad - (oj + 1), jcp.stride_h); int overflow_kh_lo = (oj + jcp.t_pad) % jcp.stride_h; kh_len = (overflow_kh_hi - overflow_kh_lo) / jcp.stride_h + 1 - o_t_overflow - o_b_overflow; kh_lo = overflow_kh_lo + o_b_overflow * jcp.stride_h; ih_max = (oj + jcp.t_pad - kh_lo) / jcp.stride_h; } int wei_stride = (!jcp.signed_input) ? kh_lo * wht_kh_stride : 0; p.src = src_w + ih_max * src_h_stride; p.dst = dst_w + oj * dst_h_stride; p.filt = wht_w + wei_stride; p.bias = bias_w; p.compensation = compensation_w; /* Note: Currently this kernel doesn't support dilations and strides together */ p.t_overflow = jcp.dilate_h > 0 ? jcp.kh - kh_len - kh_lo : max(0, jcp.kh - (kh_lo + max(0, kh_len - 1) * jcp.stride_h + 1)); p.b_overflow = kh_lo; p.f_overflow = jcp.dilate_d > 0 ? jcp.kd - kd_len - kd_lo : max(0, jcp.kd - (kd_lo + max(0, kd_len - 1) * jcp.stride_d + 1)); p.back_overflow = kd_lo; p.kh_padding = kh_len; p.kd_padding = kd_len; p.scales = scales; p.oc_blocks = jcp.is_depthwise ? g : ocb; p.oc_off = g_oc * sizeof(float); (*kernel_)(&p); } if (jcp.loop_order == loop_ngc) nd_iterator_jump(start, end, n, jcp.mb, g, nb_groups, occ, oc_chunks, od_s, jcp.od, oh_s, jcp.oh); else if (jcp.loop_order == loop_cgn) nd_iterator_jump(start, end, occ, oc_chunks, g, nb_groups, n, jcp.mb, od_s, jcp.od, oh_s, jcp.oh); else assert(!""unsupported loop order""); } }); } template struct _jit_avx512_core_x8s8s32x_deconvolution_fwd_t; template struct _jit_avx512_core_x8s8s32x_deconvolution_fwd_t; template struct _jit_avx512_core_x8s8s32x_deconvolution_fwd_t; template struct _jit_avx512_core_x8s8s32x_deconvolution_fwd_t; template struct _jit_avx512_core_x8s8s32x_deconvolution_fwd_t; template struct _jit_avx512_core_x8s8s32x_deconvolution_fwd_t; template struct _jit_avx512_core_x8s8s32x_deconvolution_fwd_t; template struct _jit_avx512_core_x8s8s32x_deconvolution_fwd_t; } // namespace x64 } // namespace cpu } // namespace impl } // namespace dnnl ",16297,True,2878.319043686529,median "[.configuration-legend] icon:lock[title=Fixed at build time] Configuration property fixed at build time - All other configuration properties are overridable at runtime [.configuration-reference.searchable, cols=""80,.^10,.^10""] |=== h|[[quarkus-oidc-client_configuration]]link:#quarkus-oidc-client_configuration[Configuration property] h|Type h|Default a|icon:lock[title=Fixed at build time] [[quarkus-oidc-client_quarkus.oidc-client.enabled]]`link:#quarkus-oidc-client_quarkus.oidc-client.enabled[quarkus.oidc-client.enabled]` [.description] -- If the OIDC client extension is enabled. --|boolean |`true` a| [[quarkus-oidc-client_quarkus.oidc-client.auth-server-url]]`link:#quarkus-oidc-client_quarkus.oidc-client.auth-server-url[quarkus.oidc-client.auth-server-url]` [.description] -- The base URL of the OpenID Connect (OIDC) server, for example, `https://host:port/auth`. OIDC discovery endpoint will be called by default by appending a '.well-known/openid-configuration' path to this URL. Note if you work with Keycloak OIDC server, make sure the base URL is in the following format: `https://host:port/auth/realms/++{++realm++}++` where `++{++realm++}++` has to be replaced by the name of the Keycloak realm. --|string | a| [[quarkus-oidc-client_quarkus.oidc-client.discovery-enabled]]`link:#quarkus-oidc-client_quarkus.oidc-client.discovery-enabled[quarkus.oidc-client.discovery-enabled]` [.description] -- Enables OIDC discovery. If the discovery is disabled then the OIDC endpoint URLs must be configured individually. --|boolean |`true` a| [[quarkus-oidc-client_quarkus.oidc-client.token-path]]`link:#quarkus-oidc-client_quarkus.oidc-client.token-path[quarkus.oidc-client.token-path]` [.description] -- Relative path or absolute URL of the OIDC token endpoint which issues access and refresh tokens. --|string | a| [[quarkus-oidc-client_quarkus.oidc-client.client-id]]`link:#quarkus-oidc-client_quarkus.oidc-client.client-id[quarkus.oidc-client.client-id]` [.description] -- The client-id of the application. Each application has a client-id that is used to identify the application --|string | a| [[quarkus-oidc-client_quarkus.oidc-client.connection-delay]]`link:#quarkus-oidc-client_quarkus.oidc-client.connection-delay[quarkus.oidc-client.connection-delay]` [.description] -- The maximum amount of time connecting to the currently unavailable OIDC server will be attempted for. The number of times the connection request will be repeated is calculated by dividing the value of this property by 2. For example, setting it to `20S` will allow for requesting the connection up to 10 times with a 2 seconds delay between the retries. Note this property is only effective when the initial OIDC connection is created, for example, when requesting a well-known OIDC configuration. Use the 'connection-retry-count' property to support trying to re-establish an already available connection which may have been dropped. --|link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html[Duration] link:#duration-note-anchor[icon:question-circle[], title=More information about the Duration format] | a| [[quarkus-oidc-client_quarkus.oidc-client.connection-retry-count]]`link:#quarkus-oidc-client_quarkus.oidc-client.connection-retry-count[quarkus.oidc-client.connection-retry-count]` [.description] -- The number of times an attempt to re-establish an already available connection will be repeated for. Note this property is different to the `connection-delay` property which is only effective during the initial OIDC connection creation. This property is used to try to recover the existing connection which may have been temporarily lost. For example, if a request to the OIDC token endpoint fails due to a connection exception then the request will be retried for a number of times configured by this property. --|int |`3` a| [[quarkus-oidc-client_quarkus.oidc-client.connection-timeout]]`link:#quarkus-oidc-client_quarkus.oidc-client.connection-timeout[quarkus.oidc-client.connection-timeout]` [.description] -- The amount of time after which the current OIDC connection request will time out. --|link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html[Duration] link:#duration-note-anchor[icon:question-circle[], title=More information about the Duration format] |`10S` a| [[quarkus-oidc-client_quarkus.oidc-client.max-pool-size]]`link:#quarkus-oidc-client_quarkus.oidc-client.max-pool-size[quarkus.oidc-client.max-pool-size]` [.description] -- The maximum size of the connection pool used by the WebClient --|int | a| [[quarkus-oidc-client_quarkus.oidc-client.credentials.secret]]`link:#quarkus-oidc-client_quarkus.oidc-client.credentials.secret[quarkus.oidc-client.credentials.secret]` [.description] -- Client secret which is used for a `client_secret_basic` authentication method. Note that a 'client-secret.value' can be used instead but both properties are mutually exclusive. --|string | a| [[quarkus-oidc-client_quarkus.oidc-client.credentials.client-secret.value]]`link:#quarkus-oidc-client_quarkus.oidc-client.credentials.client-secret.value[quarkus.oidc-client.credentials.client-secret.value]` [.description] -- The client secret value - it will be ignored if 'secret.key' is set --|string | a| [[quarkus-oidc-client_quarkus.oidc-client.credentials.client-secret.provider.name]]`link:#quarkus-oidc-client_quarkus.oidc-client.credentials.client-secret.provider.name[quarkus.oidc-client.credentials.client-secret.provider.name]` [.description] -- The CredentialsProvider name which should only be set if more than one CredentialsProvider is registered --|string | a| [[quarkus-oidc-client_quarkus.oidc-client.credentials.client-secret.provider.key]]`link:#quarkus-oidc-client_quarkus.oidc-client.credentials.client-secret.provider.key[quarkus.oidc-client.credentials.client-secret.provider.key]` [.description] -- The CredentialsProvider client secret key --|string | a| [[quarkus-oidc-client_quarkus.oidc-client.credentials.client-secret.method]]`link:#quarkus-oidc-client_quarkus.oidc-client.credentials.client-secret.method[quarkus.oidc-client.credentials.client-secret.method]` [.description] -- Authentication method. -- a| tooltip:basic[client_secret_basic (default): client id and secret are submitted with the HTTP Authorization Basic scheme], tooltip:post[client_secret_post: client id and secret are submitted as the 'client_id' and 'client_secret' form parameters.], tooltip:post-jwt[client_secret_jwt: client id and generated JWT secret are submitted as the 'client_id' and 'client_secret' form parameters.] | a| [[quarkus-oidc-client_quarkus.oidc-client.credentials.jwt.secret]]`link:#quarkus-oidc-client_quarkus.oidc-client.credentials.jwt.secret[quarkus.oidc-client.credentials.jwt.secret]` [.description] -- If provided, indicates that JWT is signed using a secret key --|string | a| [[quarkus-oidc-client_quarkus.oidc-client.credentials.jwt.secret-provider.name]]`link:#quarkus-oidc-client_quarkus.oidc-client.credentials.jwt.secret-provider.name[quarkus.oidc-client.credentials.jwt.secret-provider.name]` [.description] -- The CredentialsProvider name which should only be set if more than one CredentialsProvider is registered --|string | a| [[quarkus-oidc-client_quarkus.oidc-client.credentials.jwt.secret-provider.key]]`link:#quarkus-oidc-client_quarkus.oidc-client.credentials.jwt.secret-provider.key[quarkus.oidc-client.credentials.jwt.secret-provider.key]` [.description] -- The CredentialsProvider client secret key --|string | a| [[quarkus-oidc-client_quarkus.oidc-client.credentials.jwt.key-file]]`link:#quarkus-oidc-client_quarkus.oidc-client.credentials.jwt.key-file[quarkus.oidc-client.credentials.jwt.key-file]` [.description] -- If provided, indicates that JWT is signed using a private key in PEM or JWK format. You can use the `signature-algorithm` property to specify the key algorithm. --|string | a| [[quarkus-oidc-client_quarkus.oidc-client.credentials.jwt.key-store-file]]`link:#quarkus-oidc-client_quarkus.oidc-client.credentials.jwt.key-store-file[quarkus.oidc-client.credentials.jwt.key-store-file]` [.description] -- If provided, indicates that JWT is signed using a private key from a key store --|string | a| [[quarkus-oidc-client_quarkus.oidc-client.credentials.jwt.key-store-password]]`link:#quarkus-oidc-client_quarkus.oidc-client.credentials.jwt.key-store-password[quarkus.oidc-client.credentials.jwt.key-store-password]` [.description] -- A parameter to specify the password of the key store file. If not given, the default (""password"") is used. --|string |`password` a| [[quarkus-oidc-client_quarkus.oidc-client.credentials.jwt.key-id]]`link:#quarkus-oidc-client_quarkus.oidc-client.credentials.jwt.key-id[quarkus.oidc-client.credentials.jwt.key-id]` [.description] -- The private key id/alias --|string | a| [[quarkus-oidc-client_quarkus.oidc-client.credentials.jwt.key-password]]`link:#quarkus-oidc-client_quarkus.oidc-client.credentials.jwt.key-password[quarkus.oidc-client.credentials.jwt.key-password]` [.description] -- The private key password --|string |`password` a| [[quarkus-oidc-client_quarkus.oidc-client.credentials.jwt.audience]]`link:#quarkus-oidc-client_quarkus.oidc-client.credentials.jwt.audience[quarkus.oidc-client.credentials.jwt.audience]` [.description] -- JWT audience ('aud') claim value. By default the audience is set to the address of the OpenId Connect Provider's token endpoint. --|string | a| [[quarkus-oidc-client_quarkus.oidc-client.credentials.jwt.token-key-id]]`link:#quarkus-oidc-client_quarkus.oidc-client.credentials.jwt.token-key-id[quarkus.oidc-client.credentials.jwt.token-key-id]` [.description] -- Key identifier of the signing key added as a JWT 'kid' header --|string | a| [[quarkus-oidc-client_quarkus.oidc-client.credentials.jwt.issuer]]`link:#quarkus-oidc-client_quarkus.oidc-client.credentials.jwt.issuer[quarkus.oidc-client.credentials.jwt.issuer]` [.description] -- Issuer of the signing key added as a JWT 'iss' claim (default: client id) --|string | a| [[quarkus-oidc-client_quarkus.oidc-client.credentials.jwt.subject]]`link:#quarkus-oidc-client_quarkus.oidc-client.credentials.jwt.subject[quarkus.oidc-client.credentials.jwt.subject]` [.description] -- Subject of the signing key added as a JWT 'sub' claim (default: client id) --|string | a| [[quarkus-oidc-client_quarkus.oidc-client.credentials.jwt.signature-algorithm]]`link:#quarkus-oidc-client_quarkus.oidc-client.credentials.jwt.signature-algorithm[quarkus.oidc-client.credentials.jwt.signature-algorithm]` [.description] -- Signature algorithm, also used for the `key-file` property. Supported values: RS256, RS384, RS512, PS256, PS384, PS512, ES256, ES384, ES512, HS256, HS384, HS512. --|string | a| [[quarkus-oidc-client_quarkus.oidc-client.credentials.jwt.lifespan]]`link:#quarkus-oidc-client_quarkus.oidc-client.credentials.jwt.lifespan[quarkus.oidc-client.credentials.jwt.lifespan]` [.description] -- JWT life-span in seconds. It will be added to the time it was issued at to calculate the expiration time. --|int |`10` a| [[quarkus-oidc-client_quarkus.oidc-client.proxy.host]]`link:#quarkus-oidc-client_quarkus.oidc-client.proxy.host[quarkus.oidc-client.proxy.host]` [.description] -- The host (name or IP address) of the Proxy. Note: If OIDC adapter needs to use a Proxy to talk with OIDC server (Provider), then at least the ""host"" config item must be configured to enable the usage of a Proxy. --|string | a| [[quarkus-oidc-client_quarkus.oidc-client.proxy.port]]`link:#quarkus-oidc-client_quarkus.oidc-client.proxy.port[quarkus.oidc-client.proxy.port]` [.description] -- The port number of the Proxy. Default value is 80. --|int |`80` a| [[quarkus-oidc-client_quarkus.oidc-client.proxy.username]]`link:#quarkus-oidc-client_quarkus.oidc-client.proxy.username[quarkus.oidc-client.proxy.username]` [.description] -- The username, if Proxy needs authentication. --|string | a| [[quarkus-oidc-client_quarkus.oidc-client.proxy.password]]`link:#quarkus-oidc-client_quarkus.oidc-client.proxy.password[quarkus.oidc-client.proxy.password]` [.description] -- The password, if Proxy needs authentication. --|string | a| [[quarkus-oidc-client_quarkus.oidc-client.tls.verification]]`link:#quarkus-oidc-client_quarkus.oidc-client.tls.verification[quarkus.oidc-client.tls.verification]` [.description] -- Certificate validation and hostname verification, which can be one of the following values from enum `Verification`. Default is required. -- a| tooltip:required[Certificates are validated and hostname verification is enabled. This is the default value.], tooltip:certificate-validation[Certificates are validated but hostname verification is disabled.], tooltip:none[All certificated are trusted and hostname verification is disabled.] | a| [[quarkus-oidc-client_quarkus.oidc-client.tls.key-store-file]]`link:#quarkus-oidc-client_quarkus.oidc-client.tls.key-store-file[quarkus.oidc-client.tls.key-store-file]` [.description] -- An optional key store which holds the certificate information instead of specifying separate files. --|path | a| [[quarkus-oidc-client_quarkus.oidc-client.tls.key-store-file-type]]`link:#quarkus-oidc-client_quarkus.oidc-client.tls.key-store-file-type[quarkus.oidc-client.tls.key-store-file-type]` [.description] -- An optional parameter to specify type of the key store file. If not given, the type is automatically detected based on the file name. --|string | a| [[quarkus-oidc-client_quarkus.oidc-client.tls.key-store-provider]]`link:#quarkus-oidc-client_quarkus.oidc-client.tls.key-store-provider[quarkus.oidc-client.tls.key-store-provider]` [.description] -- An optional parameter to specify a provider of the key store file. If not given, the provider is automatically detected based on the key store file type. --|string | a| [[quarkus-oidc-client_quarkus.oidc-client.tls.key-store-password]]`link:#quarkus-oidc-client_quarkus.oidc-client.tls.key-store-password[quarkus.oidc-client.tls.key-store-password]` [.description] -- A parameter to specify the password of the key store file. If not given, the default (""password"") is used. --|string |`password` a| [[quarkus-oidc-client_quarkus.oidc-client.tls.key-store-key-alias]]`link:#quarkus-oidc-client_quarkus.oidc-client.tls.key-store-key-alias[quarkus.oidc-client.tls.key-store-key-alias]` [.description] -- An optional parameter to select a specific key in the key store. When SNI is disabled, if the key store contains multiple keys and no alias is specified, the behavior is undefined. --|string | a| [[quarkus-oidc-client_quarkus.oidc-client.tls.key-store-key-password]]`link:#quarkus-oidc-client_quarkus.oidc-client.tls.key-store-key-password[quarkus.oidc-client.tls.key-store-key-password]` [.description] -- An optional parameter to define the password for the key, in case it's different from `key-store-password`. --|string | a| [[quarkus-oidc-client_quarkus.oidc-client.tls.trust-store-file]]`link:#quarkus-oidc-client_quarkus.oidc-client.tls.trust-store-file[quarkus.oidc-client.tls.trust-store-file]` [.description] -- An optional trust store which holds the certificate information of the certificates to trust --|path | a| [[quarkus-oidc-client_quarkus.oidc-client.tls.trust-store-password]]`link:#quarkus-oidc-client_quarkus.oidc-client.tls.trust-store-password[quarkus.oidc-client.tls.trust-store-password]` [.description] -- A parameter to specify the password of the trust store file. --|string | a| [[quarkus-oidc-client_quarkus.oidc-client.tls.trust-store-cert-alias]]`link:#quarkus-oidc-client_quarkus.oidc-client.tls.trust-store-cert-alias[quarkus.oidc-client.tls.trust-store-cert-alias]` [.description] -- A parameter to specify the alias of the trust store certificate. --|string | a| [[quarkus-oidc-client_quarkus.oidc-client.tls.trust-store-file-type]]`link:#quarkus-oidc-client_quarkus.oidc-client.tls.trust-store-file-type[quarkus.oidc-client.tls.trust-store-file-type]` [.description] -- An optional parameter to specify type of the trust store file. If not given, the type is automatically detected based on the file name. --|string | a| [[quarkus-oidc-client_quarkus.oidc-client.tls.trust-store-provider]]`link:#quarkus-oidc-client_quarkus.oidc-client.tls.trust-store-provider[quarkus.oidc-client.tls.trust-store-provider]` [.description] -- An optional parameter to specify a provider of the trust store file. If not given, the provider is automatically detected based on the trust store file type. --|string | a| [[quarkus-oidc-client_quarkus.oidc-client.id]]`link:#quarkus-oidc-client_quarkus.oidc-client.id[quarkus.oidc-client.id]` [.description] -- A unique OIDC client identifier. It must be set when OIDC clients are created dynamically and is optional in all other cases. --|string | a| [[quarkus-oidc-client_quarkus.oidc-client.client-enabled]]`link:#quarkus-oidc-client_quarkus.oidc-client.client-enabled[quarkus.oidc-client.client-enabled]` [.description] -- If this client configuration is enabled. --|boolean |`true` a| [[quarkus-oidc-client_quarkus.oidc-client.scopes]]`link:#quarkus-oidc-client_quarkus.oidc-client.scopes[quarkus.oidc-client.scopes]` [.description] -- List of access token scopes --|list of string | a| [[quarkus-oidc-client_quarkus.oidc-client.refresh-token-time-skew]]`link:#quarkus-oidc-client_quarkus.oidc-client.refresh-token-time-skew[quarkus.oidc-client.refresh-token-time-skew]` [.description] -- Refresh token time skew in seconds. If this property is enabled then the configured number of seconds is added to the current time when checking whether the access token should be refreshed. If the sum is greater than this access token's expiration time then a refresh is going to happen. --|link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html[Duration] link:#duration-note-anchor[icon:question-circle[], title=More information about the Duration format] | a| [[quarkus-oidc-client_quarkus.oidc-client.absolute-expires-in]]`link:#quarkus-oidc-client_quarkus.oidc-client.absolute-expires-in[quarkus.oidc-client.absolute-expires-in]` [.description] -- If the access token 'expires_in' property should be checked as an absolute time value as opposed to a duration relative to the current time. --|boolean |`false` a| [[quarkus-oidc-client_quarkus.oidc-client.grant.type]]`link:#quarkus-oidc-client_quarkus.oidc-client.grant.type[quarkus.oidc-client.grant.type]` [.description] -- Grant type -- a| tooltip:client['client_credentials' grant requiring an OIDC client authentication only], tooltip:password['password' grant requiring both OIDC client and user ('username' and 'password') authentications], tooltip:code['authorization_code' grant requiring an OIDC client authentication as well as at least 'code' and 'redirect_uri' parameters which must be passed to OidcClient at the token request time.], tooltip:exchange['urn:ietf:params:oauth:grant-type:token-exchange' grant requiring an OIDC client authentication as well as at least 'subject_token' parameter which must be passed to OidcClient at the token request time.], tooltip:refresh['refresh_token' grant requiring an OIDC client authentication and a refresh token. Note, OidcClient supports this grant by default if an access token acquisition response contained a refresh token. However, in some cases, the refresh token is provided out of band, for example, it can be shared between several of the confidential client's services, etc. If 'quarkus.oidc-client.grant-type' is set to 'refresh' then `OidcClient` will only support refreshing the tokens.] |`client` a| [[quarkus-oidc-client_quarkus.oidc-client.grant.access-token-property]]`link:#quarkus-oidc-client_quarkus.oidc-client.grant.access-token-property[quarkus.oidc-client.grant.access-token-property]` [.description] -- Access token property name in a token grant response --|string |`access_token` a| [[quarkus-oidc-client_quarkus.oidc-client.grant.refresh-token-property]]`link:#quarkus-oidc-client_quarkus.oidc-client.grant.refresh-token-property[quarkus.oidc-client.grant.refresh-token-property]` [.description] -- Refresh token property name in a token grant response --|string |`refresh_token` a| [[quarkus-oidc-client_quarkus.oidc-client.grant.expires-in-property]]`link:#quarkus-oidc-client_quarkus.oidc-client.grant.expires-in-property[quarkus.oidc-client.grant.expires-in-property]` [.description] -- Access token expiry property name in a token grant response --|string |`expires_in` a| [[quarkus-oidc-client_quarkus.oidc-client.grant.refresh-expires-in-property]]`link:#quarkus-oidc-client_quarkus.oidc-client.grant.refresh-expires-in-property[quarkus.oidc-client.grant.refresh-expires-in-property]` [.description] -- Refresh token expiry property name in a token grant response --|string |`refresh_expires_in` a| [[quarkus-oidc-client_quarkus.oidc-client.early-tokens-acquisition]]`link:#quarkus-oidc-client_quarkus.oidc-client.early-tokens-acquisition[quarkus.oidc-client.early-tokens-acquisition]` [.description] -- Requires that all filters which use 'OidcClient' acquire the tokens at the post-construct initialization time, possibly long before these tokens are used. This property should be disabled if the access token may expire before it is used for the first time and no refresh token is available. --|boolean |`true` a| [[quarkus-oidc-client_quarkus.oidc-client.grant-options-grant-options]]`link:#quarkus-oidc-client_quarkus.oidc-client.grant-options-grant-options[quarkus.oidc-client.grant-options]` [.description] -- Grant options --|`Map>` | a| [[quarkus-oidc-client_quarkus.oidc-client.headers-headers]]`link:#quarkus-oidc-client_quarkus.oidc-client.headers-headers[quarkus.oidc-client.headers]` [.description] -- Custom HTTP headers which have to be sent to the token endpoint --|`Map` | h|[[quarkus-oidc-client_quarkus.oidc-client.named-clients-additional-named-clients]]link:#quarkus-oidc-client_quarkus.oidc-client.named-clients-additional-named-clients[Additional named clients] h|Type h|Default a| [[quarkus-oidc-client_quarkus.oidc-client.-id-.auth-server-url]]`link:#quarkus-oidc-client_quarkus.oidc-client.-id-.auth-server-url[quarkus.oidc-client.""id"".auth-server-url]` [.description] -- The base URL of the OpenID Connect (OIDC) server, for example, `https://host:port/auth`. OIDC discovery endpoint will be called by default by appending a '.well-known/openid-configuration' path to this URL. Note if you work with Keycloak OIDC server, make sure the base URL is in the following format: `https://host:port/auth/realms/++{++realm++}++` where `++{++realm++}++` has to be replaced by the name of the Keycloak realm. --|string | a| [[quarkus-oidc-client_quarkus.oidc-client.-id-.discovery-enabled]]`link:#quarkus-oidc-client_quarkus.oidc-client.-id-.discovery-enabled[quarkus.oidc-client.""id"".discovery-enabled]` [.description] -- Enables OIDC discovery. If the discovery is disabled then the OIDC endpoint URLs must be configured individually. --|boolean |`true` a| [[quarkus-oidc-client_quarkus.oidc-client.-id-.token-path]]`link:#quarkus-oidc-client_quarkus.oidc-client.-id-.token-path[quarkus.oidc-client.""id"".token-path]` [.description] -- Relative path or absolute URL of the OIDC token endpoint which issues access and refresh tokens. --|string | a| [[quarkus-oidc-client_quarkus.oidc-client.-id-.client-id]]`link:#quarkus-oidc-client_quarkus.oidc-client.-id-.client-id[quarkus.oidc-client.""id"".client-id]` [.description] -- The client-id of the application. Each application has a client-id that is used to identify the application --|string | a| [[quarkus-oidc-client_quarkus.oidc-client.-id-.connection-delay]]`link:#quarkus-oidc-client_quarkus.oidc-client.-id-.connection-delay[quarkus.oidc-client.""id"".connection-delay]` [.description] -- The maximum amount of time connecting to the currently unavailable OIDC server will be attempted for. The number of times the connection request will be repeated is calculated by dividing the value of this property by 2. For example, setting it to `20S` will allow for requesting the connection up to 10 times with a 2 seconds delay between the retries. Note this property is only effective when the initial OIDC connection is created, for example, when requesting a well-known OIDC configuration. Use the 'connection-retry-count' property to support trying to re-establish an already available connection which may have been dropped. --|link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html[Duration] link:#duration-note-anchor[icon:question-circle[], title=More information about the Duration format] | a| [[quarkus-oidc-client_quarkus.oidc-client.-id-.connection-retry-count]]`link:#quarkus-oidc-client_quarkus.oidc-client.-id-.connection-retry-count[quarkus.oidc-client.""id"".connection-retry-count]` [.description] -- The number of times an attempt to re-establish an already available connection will be repeated for. Note this property is different to the `connection-delay` property which is only effective during the initial OIDC connection creation. This property is used to try to recover the existing connection which may have been temporarily lost. For example, if a request to the OIDC token endpoint fails due to a connection exception then the request will be retried for a number of times configured by this property. --|int |`3` a| [[quarkus-oidc-client_quarkus.oidc-client.-id-.connection-timeout]]`link:#quarkus-oidc-client_quarkus.oidc-client.-id-.connection-timeout[quarkus.oidc-client.""id"".connection-timeout]` [.description] -- The amount of time after which the current OIDC connection request will time out. --|link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html[Duration] link:#duration-note-anchor[icon:question-circle[], title=More information about the Duration format] |`10S` a| [[quarkus-oidc-client_quarkus.oidc-client.-id-.max-pool-size]]`link:#quarkus-oidc-client_quarkus.oidc-client.-id-.max-pool-size[quarkus.oidc-client.""id"".max-pool-size]` [.description] -- The maximum size of the connection pool used by the WebClient --|int | a| [[quarkus-oidc-client_quarkus.oidc-client.-id-.credentials.secret]]`link:#quarkus-oidc-client_quarkus.oidc-client.-id-.credentials.secret[quarkus.oidc-client.""id"".credentials.secret]` [.description] -- Client secret which is used for a `client_secret_basic` authentication method. Note that a 'client-secret.value' can be used instead but both properties are mutually exclusive. --|string | a| [[quarkus-oidc-client_quarkus.oidc-client.-id-.credentials.client-secret.value]]`link:#quarkus-oidc-client_quarkus.oidc-client.-id-.credentials.client-secret.value[quarkus.oidc-client.""id"".credentials.client-secret.value]` [.description] -- The client secret value - it will be ignored if 'secret.key' is set --|string | a| [[quarkus-oidc-client_quarkus.oidc-client.-id-.credentials.client-secret.provider.name]]`link:#quarkus-oidc-client_quarkus.oidc-client.-id-.credentials.client-secret.provider.name[quarkus.oidc-client.""id"".credentials.client-secret.provider.name]` [.description] -- The CredentialsProvider name which should only be set if more than one CredentialsProvider is registered --|string | a| [[quarkus-oidc-client_quarkus.oidc-client.-id-.credentials.client-secret.provider.key]]`link:#quarkus-oidc-client_quarkus.oidc-client.-id-.credentials.client-secret.provider.key[quarkus.oidc-client.""id"".credentials.client-secret.provider.key]` [.description] -- The CredentialsProvider client secret key --|string | a| [[quarkus-oidc-client_quarkus.oidc-client.-id-.credentials.client-secret.method]]`link:#quarkus-oidc-client_quarkus.oidc-client.-id-.credentials.client-secret.method[quarkus.oidc-client.""id"".credentials.client-secret.method]` [.description] -- Authentication method. -- a| tooltip:basic[client_secret_basic (default): client id and secret are submitted with the HTTP Authorization Basic scheme], tooltip:post[client_secret_post: client id and secret are submitted as the 'client_id' and 'client_secret' form parameters.], tooltip:post-jwt[client_secret_jwt: client id and generated JWT secret are submitted as the 'client_id' and 'client_secret' form parameters.] | a| [[quarkus-oidc-client_quarkus.oidc-client.-id-.credentials.jwt.secret]]`link:#quarkus-oidc-client_quarkus.oidc-client.-id-.credentials.jwt.secret[quarkus.oidc-client.""id"".credentials.jwt.secret]` [.description] -- If provided, indicates that JWT is signed using a secret key --|string | a| [[quarkus-oidc-client_quarkus.oidc-client.-id-.credentials.jwt.secret-provider.name]]`link:#quarkus-oidc-client_quarkus.oidc-client.-id-.credentials.jwt.secret-provider.name[quarkus.oidc-client.""id"".credentials.jwt.secret-provider.name]` [.description] -- The CredentialsProvider name which should only be set if more than one CredentialsProvider is registered --|string | a| [[quarkus-oidc-client_quarkus.oidc-client.-id-.credentials.jwt.secret-provider.key]]`link:#quarkus-oidc-client_quarkus.oidc-client.-id-.credentials.jwt.secret-provider.key[quarkus.oidc-client.""id"".credentials.jwt.secret-provider.key]` [.description] -- The CredentialsProvider client secret key --|string | a| [[quarkus-oidc-client_quarkus.oidc-client.-id-.credentials.jwt.key-file]]`link:#quarkus-oidc-client_quarkus.oidc-client.-id-.credentials.jwt.key-file[quarkus.oidc-client.""id"".credentials.jwt.key-file]` [.description] -- If provided, indicates that JWT is signed using a private key in PEM or JWK format. You can use the `signature-algorithm` property to specify the key algorithm. --|string | a| [[quarkus-oidc-client_quarkus.oidc-client.-id-.credentials.jwt.key-store-file]]`link:#quarkus-oidc-client_quarkus.oidc-client.-id-.credentials.jwt.key-store-file[quarkus.oidc-client.""id"".credentials.jwt.key-store-file]` [.description] -- If provided, indicates that JWT is signed using a private key from a key store --|string | a| [[quarkus-oidc-client_quarkus.oidc-client.-id-.credentials.jwt.key-store-password]]`link:#quarkus-oidc-client_quarkus.oidc-client.-id-.credentials.jwt.key-store-password[quarkus.oidc-client.""id"".credentials.jwt.key-store-password]` [.description] -- A parameter to specify the password of the key store file. If not given, the default (""password"") is used. --|string |`password` a| [[quarkus-oidc-client_quarkus.oidc-client.-id-.credentials.jwt.key-id]]`link:#quarkus-oidc-client_quarkus.oidc-client.-id-.credentials.jwt.key-id[quarkus.oidc-client.""id"".credentials.jwt.key-id]` [.description] -- The private key id/alias --|string | a| [[quarkus-oidc-client_quarkus.oidc-client.-id-.credentials.jwt.key-password]]`link:#quarkus-oidc-client_quarkus.oidc-client.-id-.credentials.jwt.key-password[quarkus.oidc-client.""id"".credentials.jwt.key-password]` [.description] -- The private key password --|string |`password` a| [[quarkus-oidc-client_quarkus.oidc-client.-id-.credentials.jwt.audience]]`link:#quarkus-oidc-client_quarkus.oidc-client.-id-.credentials.jwt.audience[quarkus.oidc-client.""id"".credentials.jwt.audience]` [.description] -- JWT audience ('aud') claim value. By default the audience is set to the address of the OpenId Connect Provider's token endpoint. --|string | a| [[quarkus-oidc-client_quarkus.oidc-client.-id-.credentials.jwt.token-key-id]]`link:#quarkus-oidc-client_quarkus.oidc-client.-id-.credentials.jwt.token-key-id[quarkus.oidc-client.""id"".credentials.jwt.token-key-id]` [.description] -- Key identifier of the signing key added as a JWT 'kid' header --|string | a| [[quarkus-oidc-client_quarkus.oidc-client.-id-.credentials.jwt.issuer]]`link:#quarkus-oidc-client_quarkus.oidc-client.-id-.credentials.jwt.issuer[quarkus.oidc-client.""id"".credentials.jwt.issuer]` [.description] -- Issuer of the signing key added as a JWT 'iss' claim (default: client id) --|string | a| [[quarkus-oidc-client_quarkus.oidc-client.-id-.credentials.jwt.subject]]`link:#quarkus-oidc-client_quarkus.oidc-client.-id-.credentials.jwt.subject[quarkus.oidc-client.""id"".credentials.jwt.subject]` [.description] -- Subject of the signing key added as a JWT 'sub' claim (default: client id) --|string | a| [[quarkus-oidc-client_quarkus.oidc-client.-id-.credentials.jwt.signature-algorithm]]`link:#quarkus-oidc-client_quarkus.oidc-client.-id-.credentials.jwt.signature-algorithm[quarkus.oidc-client.""id"".credentials.jwt.signature-algorithm]` [.description] -- Signature algorithm, also used for the `key-file` property. Supported values: RS256, RS384, RS512, PS256, PS384, PS512, ES256, ES384, ES512, HS256, HS384, HS512. --|string | a| [[quarkus-oidc-client_quarkus.oidc-client.-id-.credentials.jwt.lifespan]]`link:#quarkus-oidc-client_quarkus.oidc-client.-id-.credentials.jwt.lifespan[quarkus.oidc-client.""id"".credentials.jwt.lifespan]` [.description] -- JWT life-span in seconds. It will be added to the time it was issued at to calculate the expiration time. --|int |`10` a| [[quarkus-oidc-client_quarkus.oidc-client.-id-.proxy.host]]`link:#quarkus-oidc-client_quarkus.oidc-client.-id-.proxy.host[quarkus.oidc-client.""id"".proxy.host]` [.description] -- The host (name or IP address) of the Proxy. Note: If OIDC adapter needs to use a Proxy to talk with OIDC server (Provider), then at least the ""host"" config item must be configured to enable the usage of a Proxy. --|string | a| [[quarkus-oidc-client_quarkus.oidc-client.-id-.proxy.port]]`link:#quarkus-oidc-client_quarkus.oidc-client.-id-.proxy.port[quarkus.oidc-client.""id"".proxy.port]` [.description] -- The port number of the Proxy. Default value is 80. --|int |`80` a| [[quarkus-oidc-client_quarkus.oidc-client.-id-.proxy.username]]`link:#quarkus-oidc-client_quarkus.oidc-client.-id-.proxy.username[quarkus.oidc-client.""id"".proxy.username]` [.description] -- The username, if Proxy needs authentication. --|string | a| [[quarkus-oidc-client_quarkus.oidc-client.-id-.proxy.password]]`link:#quarkus-oidc-client_quarkus.oidc-client.-id-.proxy.password[quarkus.oidc-client.""id"".proxy.password]` [.description] -- The password, if Proxy needs authentication. --|string | a| [[quarkus-oidc-client_quarkus.oidc-client.-id-.tls.verification]]`link:#quarkus-oidc-client_quarkus.oidc-client.-id-.tls.verification[quarkus.oidc-client.""id"".tls.verification]` [.description] -- Certificate validation and hostname verification, which can be one of the following values from enum `Verification`. Default is required. -- a| tooltip:required[Certificates are validated and hostname verification is enabled. This is the default value.], tooltip:certificate-validation[Certificates are validated but hostname verification is disabled.], tooltip:none[All certificated are trusted and hostname verification is disabled.] | a| [[quarkus-oidc-client_quarkus.oidc-client.-id-.tls.key-store-file]]`link:#quarkus-oidc-client_quarkus.oidc-client.-id-.tls.key-store-file[quarkus.oidc-client.""id"".tls.key-store-file]` [.description] -- An optional key store which holds the certificate information instead of specifying separate files. --|path | a| [[quarkus-oidc-client_quarkus.oidc-client.-id-.tls.key-store-file-type]]`link:#quarkus-oidc-client_quarkus.oidc-client.-id-.tls.key-store-file-type[quarkus.oidc-client.""id"".tls.key-store-file-type]` [.description] -- An optional parameter to specify type of the key store file. If not given, the type is automatically detected based on the file name. --|string | a| [[quarkus-oidc-client_quarkus.oidc-client.-id-.tls.key-store-provider]]`link:#quarkus-oidc-client_quarkus.oidc-client.-id-.tls.key-store-provider[quarkus.oidc-client.""id"".tls.key-store-provider]` [.description] -- An optional parameter to specify a provider of the key store file. If not given, the provider is automatically detected based on the key store file type. --|string | a| [[quarkus-oidc-client_quarkus.oidc-client.-id-.tls.key-store-password]]`link:#quarkus-oidc-client_quarkus.oidc-client.-id-.tls.key-store-password[quarkus.oidc-client.""id"".tls.key-store-password]` [.description] -- A parameter to specify the password of the key store file. If not given, the default (""password"") is used. --|string |`password` a| [[quarkus-oidc-client_quarkus.oidc-client.-id-.tls.key-store-key-alias]]`link:#quarkus-oidc-client_quarkus.oidc-client.-id-.tls.key-store-key-alias[quarkus.oidc-client.""id"".tls.key-store-key-alias]` [.description] -- An optional parameter to select a specific key in the key store. When SNI is disabled, if the key store contains multiple keys and no alias is specified, the behavior is undefined. --|string | a| [[quarkus-oidc-client_quarkus.oidc-client.-id-.tls.key-store-key-password]]`link:#quarkus-oidc-client_quarkus.oidc-client.-id-.tls.key-store-key-password[quarkus.oidc-client.""id"".tls.key-store-key-password]` [.description] -- An optional parameter to define the password for the key, in case it's different from `key-store-password`. --|string | a| [[quarkus-oidc-client_quarkus.oidc-client.-id-.tls.trust-store-file]]`link:#quarkus-oidc-client_quarkus.oidc-client.-id-.tls.trust-store-file[quarkus.oidc-client.""id"".tls.trust-store-file]` [.description] -- An optional trust store which holds the certificate information of the certificates to trust --|path | a| [[quarkus-oidc-client_quarkus.oidc-client.-id-.tls.trust-store-password]]`link:#quarkus-oidc-client_quarkus.oidc-client.-id-.tls.trust-store-password[quarkus.oidc-client.""id"".tls.trust-store-password]` [.description] -- A parameter to specify the password of the trust store file. --|string | a| [[quarkus-oidc-client_quarkus.oidc-client.-id-.tls.trust-store-cert-alias]]`link:#quarkus-oidc-client_quarkus.oidc-client.-id-.tls.trust-store-cert-alias[quarkus.oidc-client.""id"".tls.trust-store-cert-alias]` [.description] -- A parameter to specify the alias of the trust store certificate. --|string | a| [[quarkus-oidc-client_quarkus.oidc-client.-id-.tls.trust-store-file-type]]`link:#quarkus-oidc-client_quarkus.oidc-client.-id-.tls.trust-store-file-type[quarkus.oidc-client.""id"".tls.trust-store-file-type]` [.description] -- An optional parameter to specify type of the trust store file. If not given, the type is automatically detected based on the file name. --|string | a| [[quarkus-oidc-client_quarkus.oidc-client.-id-.tls.trust-store-provider]]`link:#quarkus-oidc-client_quarkus.oidc-client.-id-.tls.trust-store-provider[quarkus.oidc-client.""id"".tls.trust-store-provider]` [.description] -- An optional parameter to specify a provider of the trust store file. If not given, the provider is automatically detected based on the trust store file type. --|string | a| [[quarkus-oidc-client_quarkus.oidc-client.-id-.id]]`link:#quarkus-oidc-client_quarkus.oidc-client.-id-.id[quarkus.oidc-client.""id"".id]` [.description] -- A unique OIDC client identifier. It must be set when OIDC clients are created dynamically and is optional in all other cases. --|string | a| [[quarkus-oidc-client_quarkus.oidc-client.-id-.client-enabled]]`link:#quarkus-oidc-client_quarkus.oidc-client.-id-.client-enabled[quarkus.oidc-client.""id"".client-enabled]` [.description] -- If this client configuration is enabled. --|boolean |`true` a| [[quarkus-oidc-client_quarkus.oidc-client.-id-.scopes]]`link:#quarkus-oidc-client_quarkus.oidc-client.-id-.scopes[quarkus.oidc-client.""id"".scopes]` [.description] -- List of access token scopes --|list of string | a| [[quarkus-oidc-client_quarkus.oidc-client.-id-.refresh-token-time-skew]]`link:#quarkus-oidc-client_quarkus.oidc-client.-id-.refresh-token-time-skew[quarkus.oidc-client.""id"".refresh-token-time-skew]` [.description] -- Refresh token time skew in seconds. If this property is enabled then the configured number of seconds is added to the current time when checking whether the access token should be refreshed. If the sum is greater than this access token's expiration time then a refresh is going to happen. --|link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html[Duration] link:#duration-note-anchor[icon:question-circle[], title=More information about the Duration format] | a| [[quarkus-oidc-client_quarkus.oidc-client.-id-.absolute-expires-in]]`link:#quarkus-oidc-client_quarkus.oidc-client.-id-.absolute-expires-in[quarkus.oidc-client.""id"".absolute-expires-in]` [.description] -- If the access token 'expires_in' property should be checked as an absolute time value as opposed to a duration relative to the current time. --|boolean |`false` a| [[quarkus-oidc-client_quarkus.oidc-client.-id-.grant.type]]`link:#quarkus-oidc-client_quarkus.oidc-client.-id-.grant.type[quarkus.oidc-client.""id"".grant.type]` [.description] -- Grant type -- a| tooltip:client['client_credentials' grant requiring an OIDC client authentication only], tooltip:password['password' grant requiring both OIDC client and user ('username' and 'password') authentications], tooltip:code['authorization_code' grant requiring an OIDC client authentication as well as at least 'code' and 'redirect_uri' parameters which must be passed to OidcClient at the token request time.], tooltip:exchange['urn:ietf:params:oauth:grant-type:token-exchange' grant requiring an OIDC client authentication as well as at least 'subject_token' parameter which must be passed to OidcClient at the token request time.], tooltip:refresh['refresh_token' grant requiring an OIDC client authentication and a refresh token. Note, OidcClient supports this grant by default if an access token acquisition response contained a refresh token. However, in some cases, the refresh token is provided out of band, for example, it can be shared between several of the confidential client's services, etc. If 'quarkus.oidc-client.grant-type' is set to 'refresh' then `OidcClient` will only support refreshing the tokens.] |`client` a| [[quarkus-oidc-client_quarkus.oidc-client.-id-.grant.access-token-property]]`link:#quarkus-oidc-client_quarkus.oidc-client.-id-.grant.access-token-property[quarkus.oidc-client.""id"".grant.access-token-property]` [.description] -- Access token property name in a token grant response --|string |`access_token` a| [[quarkus-oidc-client_quarkus.oidc-client.-id-.grant.refresh-token-property]]`link:#quarkus-oidc-client_quarkus.oidc-client.-id-.grant.refresh-token-property[quarkus.oidc-client.""id"".grant.refresh-token-property]` [.description] -- Refresh token property name in a token grant response --|string |`refresh_token` a| [[quarkus-oidc-client_quarkus.oidc-client.-id-.grant.expires-in-property]]`link:#quarkus-oidc-client_quarkus.oidc-client.-id-.grant.expires-in-property[quarkus.oidc-client.""id"".grant.expires-in-property]` [.description] -- Access token expiry property name in a token grant response --|string |`expires_in` a| [[quarkus-oidc-client_quarkus.oidc-client.-id-.grant.refresh-expires-in-property]]`link:#quarkus-oidc-client_quarkus.oidc-client.-id-.grant.refresh-expires-in-property[quarkus.oidc-client.""id"".grant.refresh-expires-in-property]` [.description] -- Refresh token expiry property name in a token grant response --|string |`refresh_expires_in` a| [[quarkus-oidc-client_quarkus.oidc-client.-id-.grant-options-grant-options]]`link:#quarkus-oidc-client_quarkus.oidc-client.-id-.grant-options-grant-options[quarkus.oidc-client.""id"".grant-options]` [.description] -- Grant options --|`Map>` | a| [[quarkus-oidc-client_quarkus.oidc-client.-id-.early-tokens-acquisition]]`link:#quarkus-oidc-client_quarkus.oidc-client.-id-.early-tokens-acquisition[quarkus.oidc-client.""id"".early-tokens-acquisition]` [.description] -- Requires that all filters which use 'OidcClient' acquire the tokens at the post-construct initialization time, possibly long before these tokens are used. This property should be disabled if the access token may expire before it is used for the first time and no refresh token is available. --|boolean |`true` a| [[quarkus-oidc-client_quarkus.oidc-client.-id-.headers-headers]]`link:#quarkus-oidc-client_quarkus.oidc-client.-id-.headers-headers[quarkus.oidc-client.""id"".headers]` [.description] -- Custom HTTP headers which have to be sent to the token endpoint --|`Map` | |=== ifndef::no-duration-note[] [NOTE] [[duration-note-anchor]] .About the Duration format ==== The format for durations uses the standard `java.time.Duration` format. You can learn more about it in the link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html#parse-java.lang.CharSequence-[Duration#parse() javadoc]. You can also provide duration values starting with a number. In this case, if the value consists only of a number, the converter treats the value as seconds. Otherwise, `PT` is implicitly prepended to the value to obtain a standard `java.time.Duration` format. ==== endif::no-duration-note[] ",12454,True,3827.32914955592,median "//****************************************************************************** // // Copyright (c) 2016 Microsoft Corporation. All rights reserved. // // This code is licensed under the MIT License (MIT). // // THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // //****************************************************************************** // clang-format does not like C++/CX // clang-format off #include ""ppltasks.h"" #include ""LoggingNative.h"" #include ""CALayerXaml.h"" #include #include #include #include using namespace concurrency; using namespace Platform; using namespace Strings::Private; using namespace Windows::System::Threading; using namespace Windows::Foundation; using namespace Windows::UI; using namespace Windows::UI::Composition; using namespace Windows::UI::Core; using namespace Windows::UI::Input; using namespace Windows::UI::Xaml; using namespace Windows::UI::Xaml::Automation::Peers; using namespace Windows::UI::Xaml::Controls; using namespace Windows::UI::Xaml::Hosting; using namespace Windows::UI::Xaml::Input; using namespace Windows::UI::Xaml::Media; using namespace Windows::UI::Xaml::Media::Animation; using namespace Windows::UI::Xaml::Media::Imaging; using namespace Windows::UI::Xaml::Shapes; using namespace Windows::Graphics::Display; static const wchar_t* TAG = L""CALayerXaml""; namespace XamlCompositor { namespace Controls { // // ObjectCache // ICacheableObject^ ObjectCache::GetCachableObject() { if (m_objects.size() == 0) { return nullptr; } ICacheableObject^ object = m_objects.front(); m_objects.pop(); return object; }; void ObjectCache::PushCacheableObject(ICacheableObject^ obj) { obj->Reset(); if (m_objects.size() >= m_maxSize) { return; } m_objects.push(obj); }; // // LayerContent // LayerContent::LayerContent() { Name = L""LayerContent""; // Set a name so we can be seen in the live tree viewer IsHitTestVisible = true; // Always be hit testable by default. m_gravity = ContentGravity::Resize; m_scaleFactor = 1.0f; } void LayerContent::Reset() { Children->Clear(); m_image = nullptr; m_content = nullptr; m_imageSize = Size(0, 0); m_contentSize = Size(0, 0); m_contentsCenter = Rect(0, 0, 1.0, 1.0); m_gravity = ContentGravity::Resize; m_scaleFactor = 1.0f; m_origin = Point(); } LayerContent^ LayerContent::CreateLayerContent() { ICacheableObject^ ret = _LayerContentCache->GetCachableObject(); if (ret != nullptr) { return (LayerContent^)ret; } return ref new LayerContent(); } void LayerContent::DestroyLayerContent(LayerContent^ content) { _LayerContentCache->PushCacheableObject(content); } int LayerContent::_IfNegativeMakeZero(int value) { return (value < 0) ? 0 : value; } void LayerContent::_ApplyContentsCenter() { if (m_image == nullptr) { return; } if (m_image->Source == nullptr) { return; } if (m_contentsCenter.X == 0.0 && m_contentsCenter.Y == 0.0 && m_contentsCenter.Width == 1.0 && m_contentsCenter.Height == 1.0) { m_image->NineGrid = Thickness(0, 0, 0, 0); } else { int left = (int)(m_contentsCenter.X * m_imageSize.Width); int top = (int)(m_contentsCenter.Y * m_imageSize.Height); int right = ((int)m_imageSize.Width) - (left + ((int)(m_contentsCenter.Width * m_imageSize.Width))); int bottom = ((int)m_imageSize.Height) - (top + ((int)(m_contentsCenter.Height * m_imageSize.Height))); // Remove edge cases that contentsCenter supports but NineGrid does not. 1/3 for top 1/3 for bottom 1/3 for // the center etc.. left = _IfNegativeMakeZero(left); top = _IfNegativeMakeZero(top); right = _IfNegativeMakeZero(right); bottom = _IfNegativeMakeZero(bottom); int maxWidth = (int)m_imageSize.Width / 3; if (left >= maxWidth) { left = maxWidth; } if (right >= maxWidth) { right = maxWidth; } int maxHeight = (int)m_imageSize.Height / 3; if (top >= maxHeight) { top = maxHeight; } if (bottom >= maxHeight) { bottom = maxHeight; } m_image->NineGrid = Thickness(left, top, right, bottom); } } Rect LayerContent::_GetContentGravityRect(Size size) { float left = 0; float top = 0; float width = 0; float height = 0; double widthAspect = size.Width / m_contentSize.Width; double heightAspect = size.Height / m_contentSize.Height; double minAspect = std::min(widthAspect, heightAspect); double maxAspect = std::max(widthAspect, heightAspect); // Top/bottom switched due to geometric origin switch (m_gravity) { case ContentGravity::Center: left = (size.Width / 2) - (m_contentSize.Width / 2); top = (size.Height / 2) - (m_contentSize.Height / 2); width = m_contentSize.Width; height = m_contentSize.Height; if (m_image != nullptr) { m_image->Stretch = Stretch::Fill; } break; case ContentGravity::Top: left = (size.Width / 2) - (m_contentSize.Width / 2); top = size.Height - m_contentSize.Height; width = m_contentSize.Width; height = m_contentSize.Height; if (m_image != nullptr) { m_image->Stretch = Stretch::Fill; } break; case ContentGravity::Bottom: left = (size.Width / 2) - (m_contentSize.Width / 2); top = 0; width = m_contentSize.Width; height = m_contentSize.Height; if (m_image != nullptr) { m_image->Stretch = Stretch::Fill; } break; case ContentGravity::Left: left = 0; top = (size.Height / 2) - (m_contentSize.Height / 2); width = m_contentSize.Width; height = m_contentSize.Height; if (m_image != nullptr) { m_image->Stretch = Stretch::Fill; } break; case ContentGravity::Right: left = size.Width - m_contentSize.Width; top = (size.Height / 2) - (m_contentSize.Height / 2); width = m_contentSize.Width; height = m_contentSize.Height; if (m_image != nullptr) { m_image->Stretch = Stretch::Fill; } break; case ContentGravity::TopLeft: left = 0; top = size.Height - m_contentSize.Height; width = m_contentSize.Width; height = m_contentSize.Height; if (m_image != nullptr) { m_image->Stretch = Stretch::Fill; } break; case ContentGravity::TopRight: left = size.Width - m_contentSize.Width; top = size.Height - m_contentSize.Height; width = m_contentSize.Width; height = m_contentSize.Height; if (m_image != nullptr) { m_image->Stretch = Stretch::Fill; } break; case ContentGravity::BottomLeft: left = 0; top = 0; width = m_contentSize.Width; height = m_contentSize.Height; if (m_image != nullptr) { m_image->Stretch = Stretch::Fill; } break; case ContentGravity::BottomRight: left = size.Width - m_contentSize.Width; top = 0; width = m_contentSize.Width; height = m_contentSize.Height; if (m_image != nullptr) { m_image->Stretch = Stretch::Fill; } break; case ContentGravity::Resize: // UIViewContentModeScaleToFil; left = 0; top = 0; width = size.Width; height = size.Height; if (m_image != nullptr) { m_image->Stretch = Stretch::Fill; } break; case ContentGravity::ResizeAspect: // UIViewContentModeScaleAspectFit // Scale the image with the smaller aspect. width = m_contentSize.Width * (float)minAspect; height = m_contentSize.Height * (float)minAspect; left = (size.Width / 2) - (width / 2); top = (size.Height / 2) - (height / 2); if (m_image != nullptr) { // Using Fill since we calculate the aspect ourselves because image translates when modifying its scale with Stretch::Uniform. m_image->Stretch = Stretch::Fill; } break; case ContentGravity::ResizeAspectFill: // UIViewContentModeScaleAspectFill // Scale the image with the larger aspect. width = m_contentSize.Width * (float)maxAspect; height = m_contentSize.Height * (float)maxAspect; left = (size.Width / 2) - (width / 2); top = (size.Height / 2) - (height / 2); if (m_image != nullptr) { // Using Fill since we calculate the aspect ourselves because XAML clips when setting UniformToFill. m_image->Stretch = Stretch::Fill; } break; } return Rect(left, top, width, height); } Image^ LayerContent::_GetImage() { if (m_image == nullptr) { m_image = ref new Image(); m_image->Stretch = Stretch::Fill; m_scaleFactor = 1.0f; } SetElementContent(m_image); return m_image; } void LayerContent::SetContentsCenter(Rect rect) { m_contentsCenter = rect; _ApplyContentsCenter(); } void LayerContent::SetGravity(ContentGravity imgGravity) { m_gravity = imgGravity; InvalidateArrange(); } void LayerContent::SetImageContent(ImageSource^ source, float width, float height) { if (source == nullptr) { SetElementContent(nullptr); return; } Image^ imgContents = _GetImage(); imgContents->IsHitTestVisible = false; // Our content should never be HitTestVisible as they are always leaf nodes. if (Util::isInstanceOf(source)) { m_imageSize = Size(width, height); } else { m_imageSize = Size(0, 0); } imgContents->Source = source; _ApplyContentsCenter(); } void LayerContent::_AdjustContentOriginX(Storyboard^ storyboard, DoubleAnimation^ properties, Object^ fromValue, Object^ toValue) { if (toValue != nullptr) { double value = -((double)toValue); m_origin.X = (float)value; } if (m_image != nullptr || m_content == nullptr) { return; } InvalidateArrange(); } void LayerContent::_AdjustContentOriginY(Storyboard^ storyboard, DoubleAnimation^ properties, Object^ fromValue, Object^ toValue) { if (toValue != nullptr) { double value = -((double)toValue); m_origin.Y = (float)value; } if (m_image != nullptr || m_content == nullptr) { return; } InvalidateArrange(); } void LayerContent::SetElementContent(FrameworkElement^ source) { if (m_content == source) { return; } if (m_content != nullptr) { unsigned int index; if (Children->IndexOf(m_content, &index)) { Children->RemoveAt(index); } m_content = nullptr; m_image = nullptr; } if (source != nullptr) { m_content = source; Children->Append(m_content); InvalidateArrange(); m_imageSize = Size(0, 0); } } void LayerContent::SetContentParams(float width, float height, float scale) { Size oldSize = m_contentSize; float oldScale = scale; m_contentSize = Size(width / scale, height / scale); if (m_scaleFactor <= 0.0f) { m_scaleFactor = 1.0f; } if (m_scaleFactor != scale) { m_scaleFactor = scale; if (m_image != nullptr) { if (m_scaleFactor != 1.0f) { ScaleTransform^ trans = ref new ScaleTransform(); trans->ScaleX = 1.0 / m_scaleFactor; trans->ScaleY = 1.0 / m_scaleFactor; m_image->RenderTransform = trans; } else { m_image->RenderTransform = nullptr; } } } if (oldScale != m_scaleFactor || oldSize != m_contentSize) { InvalidateArrange(); } } Size LayerContent::ArrangeOverride(Size finalSize) { if (m_content != nullptr) { Rect newSize = _GetContentGravityRect(finalSize); if (m_image != nullptr) { m_content->Width = newSize.Width * m_scaleFactor; m_content->Height = newSize.Height * m_scaleFactor; } else { double contentWidth = newSize.Width - m_origin.X; double contentHeight = newSize.Height - m_origin.Y; if (contentWidth < 0.0) { contentWidth = 0.0; } if (contentHeight < 0.0) { contentHeight = 0.0; } m_content->Width = contentWidth; m_content->Height = contentHeight; } m_content->Arrange( Rect(newSize.Left + m_origin.X, newSize.Top + m_origin.Y, (float)m_content->Width, (float)m_content->Height)); } return finalSize; } Size LayerContent::MeasureOverride(Size availableSize) { return availableSize; } // // CALayerXaml // double CALayerXaml::s_screenScale = 1.0; DependencyProperty^ CALayerXaml::s_visualWidthProperty = nullptr; DependencyProperty^ CALayerXaml::s_visualHeightProperty = nullptr; std::map CALayerXaml::s_animatableProperties = { { ""position.x"", ref new CALayerXaml::AnimatableProperty( ref new CALayerXaml::ApplyAnimationFunction( [](CALayerXaml^ target, Storyboard^ storyboard, DoubleAnimation^ properties, Object^ from, Object^ to) { target->_CreateTransforms(); CALayerXaml::_AddAnimation(""(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.X)"", (UIElement^)target, storyboard, properties, from, to); }), ref new CALayerXaml::ApplyTransformFunction([](CALayerXaml^ target, Object^ toValue) { double positionX = (double)toValue; target->m_position.X = (float)positionX; if (target->m_createdTransforms) { ((TranslateTransform^)((TransformGroup^)target->RenderTransform)->Children->GetAt(3))->X = (double)toValue; } else { target->_CalcTransforms(); } }), ref new CALayerXaml::GetCurrentValue([](CALayerXaml^ target) -> Object^ { if (!target->m_createdTransforms) { return (double)target->m_position.X; } return CALayerXaml::_GetAnimatedTransformIndex( target, 3, TranslateTransform::XProperty); })) }, { ""position.y"", ref new CALayerXaml::AnimatableProperty( ref new CALayerXaml::ApplyAnimationFunction( [](CALayerXaml^ target, Storyboard^ storyboard, DoubleAnimation^ properties, Object^ from, Object^ to) { target->_CreateTransforms(); CALayerXaml::_AddAnimation(""(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.Y)"", target, storyboard, properties, from, to); }), ref new CALayerXaml::ApplyTransformFunction([](CALayerXaml^ target, Object^ toValue) { double positionY = (double)toValue; target->m_position.Y = (float)positionY; if (target->m_createdTransforms) { ((TranslateTransform^)((TransformGroup^)target->RenderTransform)->Children->GetAt(3))->Y = (double)toValue; } else { target->_CalcTransforms(); } }), ref new CALayerXaml::GetCurrentValue([](CALayerXaml^ target) -> Object^ { if (!target->m_createdTransforms) { return (double)target->m_position.Y; } return CALayerXaml::_GetAnimatedTransformIndex( target, 3, TranslateTransform::YProperty); })) }, { ""position"", ref new CALayerXaml::AnimatableProperty( ref new CALayerXaml::ApplyAnimationFunction( [](CALayerXaml^ target, Storyboard^ storyboard, DoubleAnimation^ properties, Object^ from, Object^ to) { s_animatableProperties[""position.x""]->Animate(target, storyboard, properties, from != nullptr ? (Object^)((Point)from).X : nullptr, (double)((Point)to).X); s_animatableProperties[""position.y""]->Animate(target, storyboard, properties, from != nullptr ? (Object^)((Point)from).Y : nullptr, (double)((Point)to).Y); }), ref new CALayerXaml::ApplyTransformFunction([](CALayerXaml^ target, Object^ toValue) { s_animatableProperties[""position.x""]->Set(target, (double)((Point)toValue).X); s_animatableProperties[""position.y""]->Set(target, (double)((Point)toValue).Y); }), ref new CALayerXaml::GetCurrentValue([](CALayerXaml^ target) -> Object^ { // Unbox x and y values as doubles, before casting them to floats return Point((float)(double)target->Get(""position.x""), (float)(double)target->Get(""position.y"")); })) }, { ""origin.x"", ref new CALayerXaml::AnimatableProperty( ref new CALayerXaml::ApplyAnimationFunction( [](CALayerXaml^ target, Storyboard^ storyboard, DoubleAnimation^ properties, Object^ from, Object^ to) { target->_CreateTransforms(); target->SetupBackground(); double targetFrom = from != nullptr ? (double)from : 0.0; double targetTo = to != nullptr ? (double)to : 0.0; CALayerXaml::_AddAnimation(""(UIElement.RenderTransform).(TransformGroup.Children)[1].(TranslateTransform.X)"", target, storyboard, properties, (from != nullptr) ? (Object^)(-targetFrom) : nullptr, -targetTo); if (target->m_masksToBounds) { CALayerXaml::_AddAnimation(""(UIElement.Clip).(Transform).(TranslateTransform.X)"", target, storyboard, properties, (from != nullptr) ? (Object^)(targetFrom) : nullptr, targetTo); } target->_AdjustContentOriginX(storyboard, properties, targetFrom, targetTo); }), ref new CALayerXaml::ApplyTransformFunction([](CALayerXaml^ target, Object^ toValue) { target->SetupBackground(); double targetValue = (double)toValue; target->m_origin.X = (float)targetValue; if (target->m_createdTransforms) { ((TranslateTransform^)((TransformGroup^)target->RenderTransform)->Children->GetAt(1))->X = -targetValue; } else { target->_CalcTransforms(); } if (target->Clip != nullptr) { ((TranslateTransform^)target->Clip->Transform)->X = targetValue; } target->_AdjustContentOriginX(nullptr, nullptr, nullptr, targetValue); }), ref new CALayerXaml::GetCurrentValue([](CALayerXaml^ target) -> Object^ { if (!target->m_createdTransforms) { return (double)target->m_origin.X; } return -((double)CALayerXaml::_GetAnimatedTransformIndex( target, 1, TranslateTransform::XProperty)); })) }, { ""origin.y"", ref new CALayerXaml::AnimatableProperty( ref new CALayerXaml::ApplyAnimationFunction( [](CALayerXaml^ target, Storyboard^ storyboard, DoubleAnimation^ properties, Object^ from, Object^ to) { target->_CreateTransforms(); target->SetupBackground(); double targetFrom = (from != nullptr) ? (double)from : 0.0; double targetTo = (to != nullptr) ? (double)to : 0.0; CALayerXaml::_AddAnimation(""(UIElement.RenderTransform).(TransformGroup.Children)[1].(TranslateTransform.Y)"", target, storyboard, properties, from != nullptr ? (Object^)(-targetFrom) : nullptr, -targetTo); if (target->m_masksToBounds) { CALayerXaml::_AddAnimation(""(UIElement.Clip).(Transform).(TranslateTransform.Y)"", target, storyboard, properties, (from != nullptr) ? (Object^)(targetFrom) : nullptr, targetTo); } target->_AdjustContentOriginY(storyboard, properties, targetFrom, targetTo); }), ref new CALayerXaml::ApplyTransformFunction([](CALayerXaml^ target, Object^ toValue) { target->SetupBackground(); double targetValue = (double)toValue; target->m_origin.Y = (float)targetValue; if (target->m_createdTransforms) { ((TranslateTransform^)((TransformGroup^)target->RenderTransform)->Children->GetAt(1))->Y = -targetValue; } else { target->_CalcTransforms(); } if (target->Clip != nullptr) { ((TranslateTransform^)target->Clip->Transform)->Y = targetValue; } target->_AdjustContentOriginY(nullptr, nullptr, nullptr, targetValue); }), ref new CALayerXaml::GetCurrentValue([](CALayerXaml^ target) -> Object^ { if (!target->m_createdTransforms) { return (double)target->m_origin.Y; } return -((double)CALayerXaml::_GetAnimatedTransformIndex( target, 1, TranslateTransform::YProperty)); })) }, { ""origin"", ref new CALayerXaml::AnimatableProperty( ref new CALayerXaml::ApplyAnimationFunction( [](CALayerXaml^ target, Storyboard^ storyboard, DoubleAnimation^ properties, Object^ from, Object^ to) { s_animatableProperties[""origin.x""]->Animate(target, storyboard, properties, (from != nullptr) ? (Object^)((Point)from).X : nullptr, (double)((Point)to).X); s_animatableProperties[""origin.y""]->Animate(target, storyboard, properties, (from != nullptr) ? (Object^)((Point)from).Y : nullptr, (double)((Point)to).Y); }), ref new CALayerXaml::ApplyTransformFunction([](CALayerXaml^ target, Object^ toValue) { s_animatableProperties[""origin.x""]->Set(target, (double)((Point)toValue).X); s_animatableProperties[""origin.y""]->Set(target, (double)((Point)toValue).Y); }), ref new CALayerXaml::GetCurrentValue([](CALayerXaml^ target) -> Object^ { // Unbox x and y values as doubles, before casting them to floats return Point((float)(double)target->Get(""origin.x""), (float)(double)target->Get(""origin.y"")); })) }, { ""anchorPoint.x"", ref new CALayerXaml::AnimatableProperty( ref new CALayerXaml::ApplyAnimationFunction( [](CALayerXaml^ target, Storyboard^ storyboard, DoubleAnimation^ properties, Object^ from, Object^ to) { target->_CreateTransforms(); Object^ fromVal = (from != nullptr) ? (Object^)(-target->m_size.Width * (double)from) : nullptr; double destVal = -target->m_size.Width * (double)to; CALayerXaml::_AddAnimation(""(UIElement.RenderTransform).(TransformGroup.Children)[0].(TranslateTransform.X)"", target, storyboard, properties, fromVal, destVal); }), ref new CALayerXaml::ApplyTransformFunction([](CALayerXaml^ target, Object^ toValue) { double anchorPointX = (double)toValue; target->m_anchorPoint.X = (float)anchorPointX; if (target->m_createdTransforms) { double destX = -target->m_size.Width * ((double)toValue); ((TranslateTransform^)((TransformGroup^)target->RenderTransform)->Children->GetAt(0))->X = destX; } else { target->_CalcTransforms(); } }), ref new CALayerXaml::GetCurrentValue([](CALayerXaml^ target) -> Object^ { return (double)target->m_anchorPoint.X; })) }, { ""anchorPoint.y"", ref new CALayerXaml::AnimatableProperty( ref new CALayerXaml::ApplyAnimationFunction( [](CALayerXaml^ target, Storyboard^ storyboard, DoubleAnimation^ properties, Object^ from, Object^ to) { target->_CreateTransforms(); Object^ fromVal = (from != nullptr) ? (Object^)(-target->m_size.Height * (double)from) : nullptr; double destVal = -target->m_size.Height * (double)to; CALayerXaml::_AddAnimation(""(UIElement.RenderTransform).(TransformGroup.Children)[0].(TranslateTransform.Y)"", target, storyboard, properties, fromVal, destVal); }), ref new CALayerXaml::ApplyTransformFunction([](CALayerXaml^ target, Object^ toValue) { double anchorPointY = (double)toValue; target->m_anchorPoint.Y = (float)anchorPointY; if (target->m_createdTransforms) { double destY = -target->m_size.Height * ((double)toValue); ((TranslateTransform^)((TransformGroup^)target->RenderTransform)->Children->GetAt(0))->Y = destY; } else { target->_CalcTransforms(); } }), ref new CALayerXaml::GetCurrentValue([](CALayerXaml^ target) -> Object^ { return (double)target->m_anchorPoint.Y; })) }, { ""anchorPoint"", ref new CALayerXaml::AnimatableProperty( ref new CALayerXaml::ApplyAnimationFunction( [](CALayerXaml^ target, Storyboard^ storyboard, DoubleAnimation^ properties, Object^ from, Object^ to) { s_animatableProperties[""anchorPoint.x""]->Animate(target, storyboard, properties, (from != nullptr) ? (Object^)((Point)from).X : nullptr, (double)((Point)to).X); s_animatableProperties[""anchorPoint.y""]->Animate(target, storyboard, properties, (from != nullptr) ? (Object^)((Point)from).Y : nullptr, (double)((Point)to).Y); }), ref new CALayerXaml::ApplyTransformFunction([](CALayerXaml^ target, Object^ toValue) { s_animatableProperties[""anchorPoint.x""]->Set(target, (double)((Point)toValue).X); s_animatableProperties[""anchorPoint.y""]->Set(target, (double)((Point)toValue).Y); }), ref new CALayerXaml::GetCurrentValue([](CALayerXaml^ target) -> Object^ { // Unbox x and y values as doubles, before casting them to floats return Point((float)(double)target->Get(""anchorPoint.x""), (float)(double)target->Get(""anchorPoint.y"")); })) }, { ""size.width"", ref new CALayerXaml::AnimatableProperty( ref new CALayerXaml::ApplyAnimationFunction( [](CALayerXaml^ target, Storyboard^ storyboard, DoubleAnimation^ properties, Object^ from, Object^ to) { target->_CreateTransforms(); if (from != nullptr) { if ((double)from < 0.0) { from = (double)0.0; } } if (to != nullptr) { if ((double)to < 0.0) { to = (double)0.0; } } Object^ fromVal = (from != nullptr) ? (Object^)((-((double)from)) * target->m_anchorPoint.X) : nullptr; double dest = -((double)to) * target->m_anchorPoint.X; CALayerXaml::_AddAnimation(""(UIElement.RenderTransform).(TransformGroup.Children)[0].(TranslateTransform.X)"", target, storyboard, properties, fromVal, dest); CALayerXaml::_AddAnimation(""VisualWidth"", target, storyboard, properties, from, to, true); }), ref new CALayerXaml::ApplyTransformFunction([](CALayerXaml^ target, Object^ toValue) { if (toValue != nullptr) { if ((double)toValue < 0.0) { toValue = (double)0.0; } } if (target->m_size.Width == (double)toValue) { return; } double width = (double)toValue; target->m_size.Width = (float)width; target->Width = width; if (target->m_createdTransforms) { double destX = -((double)toValue) * target->m_anchorPoint.X; ((TranslateTransform^)((TransformGroup^)target->RenderTransform)->Children->GetAt(0))->X = destX; target->VisualWidth = (double)toValue; } else { target->_CalcTransforms(); } target->InvalidateArrange(); }), ref new CALayerXaml::GetCurrentValue([](CALayerXaml^ target) -> Object^ { if (!target->m_createdTransforms) { return (double)target->m_size.Width; } return target->GetValue(CALayerXaml::VisualWidthProperty); })) }, { ""size.height"", ref new CALayerXaml::AnimatableProperty( ref new CALayerXaml::ApplyAnimationFunction( [](CALayerXaml^ target, Storyboard^ storyboard, DoubleAnimation^ properties, Object^ from, Object^ to) { target->_CreateTransforms(); if (from != nullptr) { if ((double)from < 0.0) { from = (double)0.0; } } if (to != nullptr) { if ((double)to < 0.0) { to = (double)0.0; } } Object^ fromVal = (from != nullptr) ? (Object^)((-((double)from)) * target->m_anchorPoint.Y) : nullptr; double dest = -((double)to) * target->m_anchorPoint.Y; CALayerXaml::_AddAnimation(""(UIElement.RenderTransform).(TransformGroup.Children)[0].(TranslateTransform.Y)"", target, storyboard, properties, fromVal, dest); CALayerXaml::_AddAnimation(""VisualHeight"", target, storyboard, properties, from, to, true); }), ref new CALayerXaml::ApplyTransformFunction([](CALayerXaml^ target, Object^ toValue) { if (toValue != nullptr) { if ((double)toValue < 0.0) { toValue = (double)0.0; } } if (target->m_size.Height == (double)toValue) { return; } double height = (double)toValue; target->m_size.Height = (float)height; target->Height = height; if (target->m_createdTransforms) { double destY = -((double)toValue) * target->m_anchorPoint.Y; ((TranslateTransform^)((TransformGroup^)target->RenderTransform)->Children->GetAt(0))->Y = destY; target->VisualHeight = (double)toValue; } else { target->_CalcTransforms(); } target->InvalidateArrange(); }), ref new CALayerXaml::GetCurrentValue([](CALayerXaml^ target) -> Object^ { if (!target->m_createdTransforms) { return (double)target->m_size.Height; } return target->GetValue(CALayerXaml::VisualHeightProperty); })) }, { ""size"", ref new CALayerXaml::AnimatableProperty( ref new CALayerXaml::ApplyAnimationFunction( [](CALayerXaml^ target, Storyboard^ storyboard, DoubleAnimation^ properties, Object^ from, Object^ to) { s_animatableProperties[""size.width""]->Animate(target, storyboard, properties, (from != nullptr) ? (Object^)((Size)from).Width : nullptr, (double)((Size)to).Width); s_animatableProperties[""size.height""]->Animate(target, storyboard, properties, (from != nullptr) ? (Object^)((Size)from).Height : nullptr, (double)((Size)to).Height); }), ref new CALayerXaml::ApplyTransformFunction([](CALayerXaml^ target, Object^ toValue) { s_animatableProperties[""size.width""]->Set(target, (double)((Size)toValue).Width); s_animatableProperties[""size.height""]->Set(target, (double)((Size)toValue).Height); }), ref new CALayerXaml::GetCurrentValue([](CALayerXaml^ target) -> Object^ { // Unbox width and height values as doubles, before casting them to floats return Size((float)(double)target->Get(""size.width""), (float)(double)target->Get(""size.height"")); })) }, { ""transform.rotation"", ref new CALayerXaml::AnimatableProperty( ref new CALayerXaml::ApplyAnimationFunction( [](CALayerXaml^ target, Storyboard^ storyboard, DoubleAnimation^ properties, Object^ from, Object^ to) { target->_CreateTransforms(); CALayerXaml::_AddAnimation( ""(UIElement.RenderTransform).(TransformGroup.Children)[2].(TransformGroup.Children)[0].(RotateTransform.Angle)"", target, storyboard, properties, from, to); }), ref new CALayerXaml::ApplyTransformFunction([](CALayerXaml^ target, Object^ toValue) { target->_CreateTransforms(); ((RotateTransform^)((TransformGroup^)((TransformGroup^)target->RenderTransform)->Children->GetAt(2)) ->Children->GetAt(0)) ->Angle = (double)toValue; }), ref new CALayerXaml::GetCurrentValue([](CALayerXaml^ target) -> Object^ { if (!target->m_createdTransforms) { return (double)0.0; } return CALayerXaml::_GetGeneralTransformIndex( target, 0, RotateTransform::AngleProperty); })) }, { ""transform.scale.x"", ref new CALayerXaml::AnimatableProperty( ref new CALayerXaml::ApplyAnimationFunction( [](CALayerXaml^ target, Storyboard^ storyboard, DoubleAnimation^ properties, Object^ from, Object^ to) { target->_CreateTransforms(); CALayerXaml::_AddAnimation( ""(UIElement.RenderTransform).(TransformGroup.Children)[2].(TransformGroup.Children)[1].(ScaleTransform.ScaleX)"", target, storyboard, properties, from, to); }), ref new CALayerXaml::ApplyTransformFunction([](CALayerXaml^ target, Object^ toValue) { target->_CreateTransforms(); ((ScaleTransform^)((TransformGroup^)((TransformGroup^)target->RenderTransform)->Children->GetAt(2))->Children->GetAt(1)) ->ScaleX = (double)toValue; }), ref new CALayerXaml::GetCurrentValue([](CALayerXaml^ target) -> Object^ { if (!target->m_createdTransforms) { return (double)0.0; } return CALayerXaml::_GetGeneralTransformIndex( target, 1, ScaleTransform::ScaleXProperty); })) }, { ""transform.scale.y"", ref new CALayerXaml::AnimatableProperty( ref new CALayerXaml::ApplyAnimationFunction( [](CALayerXaml^ target, Storyboard^ storyboard, DoubleAnimation^ properties, Object^ from, Object^ to) { target->_CreateTransforms(); CALayerXaml::_AddAnimation( ""(UIElement.RenderTransform).(TransformGroup.Children)[2].(TransformGroup.Children)[1].(ScaleTransform.ScaleY)"", target, storyboard, properties, from, to); }), ref new CALayerXaml::ApplyTransformFunction([](CALayerXaml^ target, Object^ toValue) { target->_CreateTransforms(); ((ScaleTransform^)((TransformGroup^)((TransformGroup^)target->RenderTransform)->Children->GetAt(2))->Children->GetAt(1)) ->ScaleY = (double)toValue; }), ref new CALayerXaml::GetCurrentValue([](CALayerXaml^ target) -> Object^ { if (!target->m_createdTransforms) { return (double)0.0; } return CALayerXaml::_GetGeneralTransformIndex( target, 1, ScaleTransform::ScaleYProperty); })) }, { ""transform.translation.x"", ref new CALayerXaml::AnimatableProperty( ref new CALayerXaml::ApplyAnimationFunction( [](CALayerXaml^ target, Storyboard^ storyboard, DoubleAnimation^ properties, Object^ from, Object^ to) { target->_CreateTransforms(); CALayerXaml::_AddAnimation( ""(UIElement.RenderTransform).(TransformGroup.Children)[2].(TransformGroup.Children)[2].(TranslateTransform.X)"", target, storyboard, properties, from, to); }), ref new CALayerXaml::ApplyTransformFunction([](CALayerXaml^ target, Object^ toValue) { target->_CreateTransforms(); ((TranslateTransform^)((TransformGroup^)((TransformGroup^)target->RenderTransform)->Children->GetAt(2)) ->Children->GetAt(2)) ->X = (double)toValue; }), ref new CALayerXaml::GetCurrentValue([](CALayerXaml^ target) -> Object^ { if (!target->m_createdTransforms) { return (double)0.0; } return CALayerXaml::_GetGeneralTransformIndex( target, 2, TranslateTransform::XProperty); })) }, { ""transform.translation.y"", ref new CALayerXaml::AnimatableProperty( ref new CALayerXaml::ApplyAnimationFunction( [](CALayerXaml^ target, Storyboard^ storyboard, DoubleAnimation^ properties, Object^ from, Object^ to) { target->_CreateTransforms(); CALayerXaml::_AddAnimation( ""(UIElement.RenderTransform).(TransformGroup.Children)[2].(TransformGroup.Children)[2].(TranslateTransform.Y)"", target, storyboard, properties, from, to); }), ref new CALayerXaml::ApplyTransformFunction([](CALayerXaml^ target, Object^ toValue) { target->_CreateTransforms(); ((TranslateTransform^)((TransformGroup^)((TransformGroup^)target->RenderTransform)->Children->GetAt(2)) ->Children->GetAt(2)) ->Y = (double)toValue; }), ref new CALayerXaml::GetCurrentValue([](CALayerXaml^ target) -> Object^ { if (!target->m_createdTransforms) { return (double)0.0; } return CALayerXaml::_GetGeneralTransformIndex( target, 2, TranslateTransform::YProperty); })) }, { ""opacity"", ref new CALayerXaml::AnimatableProperty( ref new CALayerXaml::ApplyAnimationFunction( [](CALayerXaml^ target, Storyboard^ storyboard, DoubleAnimation^ properties, Object^ from, Object^ to) { CALayerXaml::_AddAnimation(""(UIElement.Opacity)"", target, storyboard, properties, from, to); }), ref new CALayerXaml::ApplyTransformFunction([](CALayerXaml^ target, Object^ toValue) { target->m_opacity = (double)toValue; target->SetOpacity(); }), ref new CALayerXaml::GetCurrentValue([](CALayerXaml^ target) -> Object^ { return target->m_opacity; })) }, { ""gravity"", ref new CALayerXaml::AnimatableProperty( nullptr, ref new CALayerXaml::ApplyTransformFunction( [](CALayerXaml^ target, Object^ toValue) { target->SetContentGravity((ContentGravity)(int)toValue); }), ref new CALayerXaml::GetCurrentValue([](CALayerXaml^ target) -> Object^ { return (int)target->m_contentGravity; })) }, { ""masksToBounds"", ref new CALayerXaml::AnimatableProperty(nullptr, ref new CALayerXaml::ApplyTransformFunction([](CALayerXaml^ target, Object^ toValue) { target->m_masksToBounds = (bool)toValue; target->Clip = target->m_masksToBounds ? target->m_clipGeometry : nullptr; }), ref new CALayerXaml::GetCurrentValue([](CALayerXaml^ target) -> Object^ { return target->m_masksToBounds; })) }, }; void CALayerXaml::Reset() { __super::Children->Clear(); InvalidateArrange(); m_content = nullptr; m_contentsCenter = Rect(0, 0, 1, 1); m_contentGravity = ContentGravity::Resize; Clip = nullptr; m_invOriginTransform = ref new TranslateTransform(); m_clipGeometry = ref new RectangleGeometry(); m_clipGeometry->Transform = m_invOriginTransform; RenderTransform = ref new TranslateTransform(); m_position = Point(0, 0); m_origin = Point(0, 0); m_size = Size(0, 0); m_hidden = false; m_originSet = false; m_createdTransforms = false; LayerOpacity = 1.0; IsHitTestVisible = true; // Always hit-testable by default Set(""anchorPoint"", Point(0.5, 0.5)); m_masksToBounds = false; __super::Background = _TransparentBrush; // Due to the nature of how we lay out our CALayerXamls as 1x1 panels, we need an actual backing element // that we can use for hit testing purposes. Without this backing rectangle, we are unable accept pointer // input at the appropriate location in many instances. For example, we wouldn't be able to click on a UIView // that hasn't set a background or any content, which is incorrect behavior. This will be revisited when // we move the code closer to UI.Composition Visual usage. SetBackgroundColor(0, 0, 0, 0); } CALayerXaml^ CALayerXaml::CreateLayer() { ICacheableObject^ ret = _LayerContentCache->GetCachableObject(); if (ret != nullptr) { return (CALayerXaml^)ret; } CALayerXaml^ newLayer = ref new CALayerXaml(); auto layerVisual = ElementCompositionPreview::GetElementVisual(newLayer); layerVisual->BorderMode = CompositionBorderMode::Hard; return newLayer; } void CALayerXaml::DestroyLayer(CALayerXaml^ layer) { layer->_DiscardContent(); _LayerContentCache->PushCacheableObject(layer); } void CALayerXaml::ApplyMagnificationFactor(Canvas^ windowContainer, float scale, float rotation) { TransformGroup^ globalTransform = ref new TransformGroup(); ScaleTransform^ windowScale = ref new ScaleTransform(); RotateTransform^ orientation = ref new RotateTransform(); windowScale->ScaleX = scale; windowScale->ScaleY = scale; windowScale->CenterX = windowContainer->Width / 2.0; windowScale->CenterY = windowContainer->Height / 2.0; globalTransform->Children->Append(windowScale); if (rotation != 0.0) { orientation->Angle = rotation; orientation->CenterX = windowContainer->Width / 2.0; orientation->CenterY = windowContainer->Height / 2.0; globalTransform->Children->Append(orientation); } windowContainer->RenderTransform = globalTransform; CALayerXaml::s_screenScale = (double)scale; } void CALayerXaml::_AddAnimation(String^ propertyName, UIElement^ target, Storyboard^ storyboard, DoubleAnimation^ copyProperties, Object^ fromValue, Object^ toValue, bool dependent) { DoubleAnimation^ posxAnim = ref new DoubleAnimation(); if (toValue != nullptr) { posxAnim->To = (double)toValue; } if (fromValue != nullptr) { posxAnim->From = (double)fromValue; } posxAnim->Duration = copyProperties->Duration; posxAnim->RepeatBehavior = copyProperties->RepeatBehavior; posxAnim->AutoReverse = copyProperties->AutoReverse; posxAnim->EasingFunction = copyProperties->EasingFunction; posxAnim->EnableDependentAnimation = dependent; posxAnim->FillBehavior = copyProperties->FillBehavior; posxAnim->BeginTime = copyProperties->BeginTime; storyboard->Children->Append(posxAnim); Storyboard::SetTarget(posxAnim, target); Storyboard::SetTargetProperty(posxAnim, propertyName); } Object^ CALayerXaml::_GetAnimatedTransformIndex(UIElement^ element, int idx, DependencyProperty^ property) { TransformGroup^ grp = (TransformGroup^)element->GetValue(UIElement::RenderTransformProperty); TransformCollection^ children = (TransformCollection^)grp->GetValue(TransformGroup::ChildrenProperty); DependencyObject^ transform = (DependencyObject^)children->GetAt(idx); return transform->GetValue(property); } Object^ CALayerXaml::_GetGeneralTransformIndex(UIElement^ element, int idx, DependencyProperty^ property) { TransformGroup^ grp = (TransformGroup^)element->GetValue(UIElement::RenderTransformProperty); TransformCollection^ children = (TransformCollection^)grp->GetValue(TransformGroup::ChildrenProperty); TransformGroup^ transform = (TransformGroup^)children->GetAt(2); TransformCollection^ generalTransformChildren = (TransformCollection^)transform->GetValue(TransformGroup::ChildrenProperty); DependencyObject^ innerTransform = (DependencyObject^)generalTransformChildren->GetAt(idx); return innerTransform->GetValue(property); } void CALayerXaml::_AdjustContentOriginX(Storyboard^ storyboard, DoubleAnimation^ properties, Object^ fromValue, Object^ toValue) { if (m_content == nullptr) { return; } if (storyboard != nullptr) { _AddAnimation(""(UIElement.RenderTransform).(TranslateTransform.X)"", m_content, storyboard, properties, fromValue != nullptr ? (Object^)fromValue : nullptr, toValue); } else { ((TranslateTransform^)m_content->RenderTransform)->X = (double)toValue; } if (Util::isInstanceOf(m_content)) { static_cast(m_content)->_AdjustContentOriginX(storyboard, properties, fromValue, toValue); } } void CALayerXaml::_AdjustContentOriginY(Storyboard^ storyboard, DoubleAnimation^ properties, Object^ fromValue, Object^ toValue) { if (m_content == nullptr) { return; } if (storyboard != nullptr) { _AddAnimation(""(UIElement.RenderTransform).(TranslateTransform.Y)"", m_content, storyboard, properties, fromValue != nullptr ? (Object^)fromValue : nullptr, toValue); } else { ((TranslateTransform^)m_content->RenderTransform)->Y = (double)toValue; } if (Util::isInstanceOf(m_content)) { static_cast(m_content)->_AdjustContentOriginY(storyboard, properties, fromValue, toValue); } } void CALayerXaml::_CalcTransforms() { if (!m_createdTransforms) { Point destTranslation; destTranslation.X = -m_size.Width * m_anchorPoint.X; destTranslation.Y = -m_size.Height * m_anchorPoint.Y; destTranslation.X -= m_origin.X; destTranslation.Y -= m_origin.Y; destTranslation.X += m_position.X; destTranslation.Y += m_position.Y; ((TranslateTransform^)RenderTransform)->X = destTranslation.X; ((TranslateTransform^)RenderTransform)->Y = destTranslation.Y; } } void CALayerXaml::_CreateTransforms() { if (!m_createdTransforms) { TranslateTransform^ SizeAnchorTransform = ref new TranslateTransform(); SizeAnchorTransform->X = -m_size.Width * m_anchorPoint.X; SizeAnchorTransform->Y = -m_size.Height * m_anchorPoint.Y; TranslateTransform^ OriginTransform = ref new TranslateTransform(); OriginTransform->X = -m_origin.X; OriginTransform->Y = -m_origin.Y; TransformGroup^ ContentTransform = ref new TransformGroup(); ContentTransform->Children->Append(ref new RotateTransform()); ContentTransform->Children->Append(ref new ScaleTransform()); ContentTransform->Children->Append(ref new TranslateTransform()); TranslateTransform^ PositionTransform = ref new TranslateTransform(); PositionTransform->X = m_position.X; PositionTransform->Y = m_position.Y; TransformGroup^ LayerTransforms = ref new TransformGroup(); LayerTransforms->Children->Append(SizeAnchorTransform); LayerTransforms->Children->Append(OriginTransform); LayerTransforms->Children->Append(ContentTransform); LayerTransforms->Children->Append(PositionTransform); RenderTransform = LayerTransforms; VisualWidth = m_size.Width; VisualHeight = m_size.Height; m_createdTransforms = true; } } void CALayerXaml::Set(String^ propertyName, Object^ value) { CALayerXaml::s_animatableProperties[propertyName]->Set(this, value); } Object^ CALayerXaml::Get(String^ propertyName) { return CALayerXaml::s_animatableProperties[propertyName]->GetValue(this); } void CALayerXaml::SetOpacity() { if (m_hidden) { __super::Opacity = 0.0; } else { __super::Opacity = m_opacity; } }; void CALayerXaml::SetZIndex(int zIndex) { __super::SetValue(Canvas::ZIndexProperty, zIndex); } /* Disable for now AutomationPeer^ CALayerXaml::OnCreateAutomationPeer() { return ref new CALayerXamlAutomationPeer(this); } */ void CALayerXaml::SizeChangedCallback(DependencyObject^ d, DependencyPropertyChangedEventArgs^ e) { ((CALayerXaml^)d)->InvalidateArrange(); } CALayerXaml::CALayerXaml() { Name = L""LayoutElement""; m_invOriginTransform = ref new TranslateTransform(); m_clipGeometry = ref new RectangleGeometry(); m_clipGeometry->Transform = m_invOriginTransform; RenderTransform = ref new TranslateTransform(); Set(""anchorPoint"", Point(0.5, 0.5)); LayerOpacity = 1.0; Background = _TransparentBrush; // note-nithishm-03252016 - DependencyProperty are registered with Panel class instead of CALayerXaml class, as we found that // while property look up, the code starts with the base class and not the current class. This might be a bug but for now as a // workaround register with the base class. if (s_visualWidthProperty == nullptr) { s_visualWidthProperty = DependencyProperty::Register(""VisualWidth"", double::typeid, Panel::typeid, ref new PropertyMetadata((Platform::Object^ )0.0, ref new PropertyChangedCallback(&CALayerXaml::SizeChangedCallback))); } if (s_visualHeightProperty == nullptr) { s_visualHeightProperty = DependencyProperty::Register(""VisualHeight"", double::typeid, Panel::typeid, ref new PropertyMetadata((Platform::Object^ )0.0, ref new PropertyChangedCallback(&CALayerXaml::SizeChangedCallback))); } // Always start off with a clean slate. Reset(); } void CALayerXaml::_CopyPropertiesFrom(CALayerXaml^ fromLayer) { Set(""opacity"", fromLayer->Get(""opacity"")); Set(""position"", fromLayer->Get(""position"")); Set(""size"", fromLayer->Get(""size"")); Set(""anchorPoint"", fromLayer->Get(""anchorPoint"")); } void CALayerXaml::_DiscardContent() { if (m_content != nullptr) { unsigned int index; if (Children->IndexOf(m_content, &index)) { Children->RemoveAt(index); } InvalidateArrange(); if (Util::isInstanceOf(m_content)) { LayerContent::DestroyLayerContent((LayerContent^)m_content); } m_content = nullptr; } } void CALayerXaml::_SetContent(FrameworkElement^ element) { if (m_content == element) { return; } _DiscardContent(); m_content = element; if (element != nullptr) { m_content->RenderTransform = m_invOriginTransform; this->Children->InsertAt(0, m_content); InvalidateArrange(); } } LayerContent^ CALayerXaml::_GetLayerContent(bool create) { if (!Util::isInstanceOf(m_content)) { if (!create) { return nullptr; } LayerContent^ imageContent = LayerContent::CreateLayerContent(); imageContent->SetGravity(m_contentGravity); imageContent->SetContentsCenter(m_contentsCenter); imageContent->Background = m_backgroundBrush; imageContent->_AdjustContentOriginX(nullptr, nullptr, nullptr, (double)m_origin.X); imageContent->_AdjustContentOriginY(nullptr, nullptr, nullptr, (double)m_origin.Y); __super::Background = _TransparentBrush; _SetContent(imageContent); } return (LayerContent^)m_content; } void CALayerXaml::SetContentGravity(ContentGravity gravity) { m_contentGravity = gravity; auto layoutContent = _GetLayerContent(); if (layoutContent != nullptr) { layoutContent->SetGravity(gravity); } } void CALayerXaml::SetContentsCenter(Rect rect) { m_contentsCenter = rect; auto layoutContent = _GetLayerContent(); if (layoutContent != nullptr) { layoutContent->SetContentsCenter(m_contentsCenter); } } void CALayerXaml::SetupBackground() { if (m_content == nullptr) { Rectangle^ rect = ref new Rectangle(); _SetContent(rect); } if (Util::isInstanceOf(m_content)) { static_cast(m_content)->Fill = m_backgroundBrush; } else { static_cast(m_content)->Background = m_backgroundBrush; } } void CALayerXaml::SetBackgroundColor(float r, float g, float b, float a) { m_backgroundColor.R = (unsigned char)(r * 255.0); m_backgroundColor.G = (unsigned char)(g * 255.0); m_backgroundColor.B = (unsigned char)(b * 255.0); m_backgroundColor.A = (unsigned char)(a * 255.0); if (m_backgroundColor.A == 0) { m_backgroundBrush = _TransparentBrush; } else { m_backgroundBrush = ref new SolidColorBrush(m_backgroundColor); } SetupBackground(); } void CALayerXaml::SetTopMost() { _SetContent(nullptr); __super::Background = nullptr; } void CALayerXaml::SetContentImage(ImageSource^ source, float width, float height, float scale) { if (source == nullptr) { if (Util::isInstanceOf(m_content)) { _SetContent(nullptr); SetupBackground(); } } else { LayerContent^ c = _GetLayerContent(true); c->SetImageContent(source, width, height); c->SetContentParams(width, height, scale); } } void CALayerXaml::SetContentElement(FrameworkElement^ elem, float width, float height, float scale) { if (elem == nullptr) { if (Util::isInstanceOf(m_content)) { _SetContent(nullptr); SetupBackground(); } } else { LayerContent^ c = _GetLayerContent(true); c->SetElementContent(elem); c->SetContentParams(width, height, scale); } } Size CALayerXaml::ArrangeOverride(Size finalSize) { float curWidth = CurrentWidth; float curHeight = CurrentHeight; if (m_clipGeometry->Rect.Width != curWidth || m_clipGeometry->Rect.Height != curHeight) { m_clipGeometry->Rect = Rect(0, 0, curWidth, curHeight); } if (m_content != nullptr) { m_content->Width = curWidth; m_content->Height = curHeight; m_content->Arrange(Rect(0, 0, curWidth, curHeight)); } unsigned int childrenSize = Children->Size; for (unsigned int index = 0; index < childrenSize; index++) { FrameworkElement^ curChild = static_cast(Children->GetAt(index)); if (curChild == m_content) { continue; } CALayerXaml^ subLayer = dynamic_cast(curChild); if (subLayer != nullptr) { subLayer->Arrange(Rect(0, 0, 1.0, 1.0)); } else { curChild->Arrange(Rect(0, 0, curWidth, curHeight)); } } Size ret; if (Util::isInstanceOf(Parent)) { ret = Size(1, 1); } else { ret = Size(curWidth, curHeight); } return ret; } Size CALayerXaml::MeasureOverride(Size availableSize) { unsigned int childrenSize = Children->Size; for (unsigned int index = 0; index < childrenSize; index++) { FrameworkElement^ curChild = (FrameworkElement^)Children->GetAt(index); if (curChild == m_content) { continue; } if (!Util::isInstanceOf(curChild)) { curChild->Measure(availableSize); } } return m_size; } // // EventedStoryboard // static const double c_hundredNanoSeconds = 10000000.0; EventedStoryboard::EventedStoryboard() { // AppxManifest.xml appears to fail to enumerate runtimeclasses with accessors and no default constructor in the Win8.1 SDK. throw ref new Platform::FailureException(""Do not use the default constructor; this is merely here as a bug fix.""); } EventedStoryboard::EventedStoryboard( double beginTime, double duration, bool autoReverse, float repeatCount, float repeatDuration, float speed, double timeOffset) { TimeSpan beginTimeSpan = TimeSpan(); beginTimeSpan.Duration = (long long)(beginTime * c_hundredNanoSeconds); m_container->BeginTime = beginTimeSpan; TimeSpan timeSpan = TimeSpan(); timeSpan.Duration = (long long)(duration * c_hundredNanoSeconds); m_container->Duration = Duration(timeSpan); if (repeatCount != 0) { m_container->RepeatBehavior = RepeatBehavior(repeatCount); } if (repeatDuration != 0) { TimeSpan timeSpan = TimeSpan(); timeSpan.Duration = (long long)(repeatDuration * c_hundredNanoSeconds); m_container->RepeatBehavior = RepeatBehavior(timeSpan); } m_container->SpeedRatio = speed; m_container->AutoReverse = autoReverse; m_container->FillBehavior = FillBehavior::HoldEnd; m_container->Completed += ref new EventHandler([this](Object^ sender, Object^ args) { if (Completed != nullptr) { Completed(this); } m_container->Stop(); }); TimeSpan span = m_container->BeginTime->Value; ThreadPoolTimer^ beginTimer = ThreadPoolTimer::CreateTimer(ref new TimerElapsedHandler([this](ThreadPoolTimer^ timer) { IAsyncAction^ ret = m_container->Dispatcher->RunAsync(CoreDispatcherPriority::High, ref new DispatchedHandler([this]() { if (Started != nullptr) { Started(this); } })); }), m_container->BeginTime->Value); } void EventedStoryboard::Start() { m_container->Begin(); } void EventedStoryboard::Abort() { for (Animation^ curAnim : m_animations) { Object^ curValue = CALayerXaml::s_animatableProperties[curAnim->propertyName]->GetValue(m_animatedLayer); CALayerXaml::s_animatableProperties[curAnim->propertyName]->Set(m_animatedLayer, curValue); } } void EventedStoryboard::_CreateFlip(CALayerXaml^ layer, bool flipRight, bool invert, bool removeFromParent) { if (layer->Projection == nullptr) { layer->Projection = ref new PlaneProjection(); } DoubleAnimation^ rotateAnim = ref new DoubleAnimation(); rotateAnim->Duration = m_container->Duration; if (!invert) { rotateAnim->From = 0.01; if (!flipRight) { rotateAnim->To = (double)180; } else { rotateAnim->To = (double)-180; } } else { if (!flipRight) { rotateAnim->From = (double)180; rotateAnim->To = (double)360; } else { rotateAnim->From = (double)-180; rotateAnim->To = (double)-360; } } ((PlaneProjection^)layer->Projection)->CenterOfRotationX = layer->CurrentWidth / 2; ((PlaneProjection^)layer->Projection)->CenterOfRotationY = layer->CurrentHeight / 2; Storyboard::SetTargetProperty(rotateAnim, ""(UIElement.Projection).(PlaneProjection.RotationY)""); Storyboard::SetTarget(rotateAnim, layer); m_container->Children->Append(rotateAnim); DoubleAnimation^ moveAnim = ref new DoubleAnimation(); moveAnim->Duration = m_container->Duration; moveAnim->From = 0.01; moveAnim->To = (double)-160; moveAnim->SpeedRatio = 2.0; moveAnim->AutoReverse = true; Storyboard::SetTarget(moveAnim, layer); Storyboard::SetTargetProperty(moveAnim, ""(UIElement.Projection).(PlaneProjection.GlobalOffsetZ)""); m_container->Children->Append(moveAnim); DoubleAnimation^ fade1 = ref new DoubleAnimation(); Storyboard::SetTarget(fade1, layer); Storyboard::SetTargetProperty(fade1, ""(UIElement.Opacity)""); if (!invert) { TimeSpan fade1TimeSpan = TimeSpan(); fade1TimeSpan.Duration = m_container->Duration.TimeSpan.Duration / 2; fade1->Duration = Duration(fade1TimeSpan); fade1->From = 1.0; fade1->To = 0.5; fade1->FillBehavior = FillBehavior::HoldEnd; } else { TimeSpan fade1TimeSpan = TimeSpan(); fade1TimeSpan.Duration = m_container->Duration.TimeSpan.Duration / 2; fade1->Duration = Duration(fade1TimeSpan); TimeSpan fade1BeginTimeSpan = TimeSpan(); fade1BeginTimeSpan.Duration = m_container->Duration.TimeSpan.Duration / 2; fade1->BeginTime = fade1BeginTimeSpan; fade1->From = 0.5; fade1->To = 1.0; fade1->FillBehavior = FillBehavior::HoldEnd; fade1->Completed += ref new EventHandler([layer](Object^ sender, Object^ args) { layer->Opacity = 1.0; }); } if (removeFromParent) { fade1->Completed += ref new EventHandler([layer](Object^ sender, Object^ args) { VisualTreeHelper::DisconnectChildrenRecursive(layer); }); } else { rotateAnim->Completed += ref new EventHandler([layer](Object^ sender, Object^ args) { // Using Projection transforms (even Identity) causes less-than-pixel-perfect rendering. layer->Projection = nullptr; }); } m_container->Children->Append(fade1); } void EventedStoryboard::_CreateWoosh(CALayerXaml^ layer, bool fromRight, bool invert, bool removeFromParent) { if (layer->Projection == nullptr) { layer->Projection = ref new PlaneProjection(); } DoubleAnimation^ wooshAnim = ref new DoubleAnimation(); wooshAnim->Duration = m_container->Duration; wooshAnim->EasingFunction = ref new PowerEase(); wooshAnim->EasingFunction->EasingMode = EasingMode::EaseOut; if (!invert) { if (fromRight) { wooshAnim->From = (double)layer->CurrentWidth; wooshAnim->To = 0.01; } else { wooshAnim->From = 0.01; wooshAnim->To = (double)layer->CurrentWidth; } } else { if (fromRight) { wooshAnim->From = 0.01; wooshAnim->To = (double)(-layer->CurrentWidth / 4); } else { wooshAnim->From = (double)(-layer->CurrentWidth / 4); wooshAnim->To = 0.01; } } Storyboard::SetTargetProperty(wooshAnim, ""(UIElement.Projection).(PlaneProjection.LocalOffsetX)""); Storyboard::SetTarget(wooshAnim, layer); if (removeFromParent) { wooshAnim->Completed += ref new EventHandler([layer](Object^ sender, Object^ args) { VisualTreeHelper::DisconnectChildrenRecursive(layer); }); } else { wooshAnim->Completed += ref new EventHandler([layer](Object^ sender, Object^ args) { // Using Projection transforms (even Identity) causes less-than-pixel-perfect rendering. layer->Projection = nullptr; }); } m_container->Children->Append(wooshAnim); } concurrency::task EventedStoryboard::SnapshotLayer(CALayerXaml^ layer) { if (((layer->m_size.Height == 0) && (layer->m_size.Width == 0)) || (layer->Opacity == 0)) { return concurrency::task_from_result(nullptr); } else { RenderTargetBitmap^ snapshot = ref new RenderTargetBitmap(); return concurrency::create_task(snapshot->RenderAsync(layer, (int)(layer->CurrentWidth * CALayerXaml::s_screenScale), 0)) .then([snapshot, layer](concurrency::task result) noexcept { try { result.get(); } catch (Platform::InvalidArgumentException^ ex) { // Handle exceptions related to invalid layer attribute passed to RenderAsync TraceWarning(TAG, L""RenderAsync threw InvalidArgumentException exception - [%ld]%s"", ex->HResult, ex->Message); return (CALayerXaml^)nullptr; } // Return a new 'copy' layer with the rendered content CALayerXaml^ newLayer = CALayerXaml::CreateLayer(); newLayer->_CopyPropertiesFrom(layer); int width = snapshot->PixelWidth; int height = snapshot->PixelHeight; DisplayInformation^ dispInfo = Windows::Graphics::Display::DisplayInformation::GetForCurrentView(); newLayer->SetContentImage(snapshot, (float)width, (float)height, (float)(CALayerXaml::s_screenScale * dispInfo->RawPixelsPerViewPixel)); // There seems to be a bug in Xaml where Render'd layers get sized to their visible content... sort of. // If the UIViewController being transitioned away from has transparent content, the height returned is less the // navigation bar, as though Xaml sizes the buffer to the largest child Visual, and only expands where needed. // Top/bottom switched due to geometric origin of CALayer so read this as UIViewContentModeTopLeft newLayer->SetContentGravity(ContentGravity::BottomLeft); return newLayer; }, concurrency::task_continuation_context::use_current()); } } void EventedStoryboard::AddTransition(CALayerXaml^ realLayer, CALayerXaml^ snapshotLayer, String^ type, String^ subtype) { if (type == ""kCATransitionFlip"") { TimeSpan timeSpan = TimeSpan(); timeSpan.Duration = (long long)(0.75 * c_hundredNanoSeconds); m_container->Duration = Duration(timeSpan); Panel^ parent = (Panel^)VisualTreeHelper::GetParent(realLayer); bool flipToLeft = true; if (subtype != ""kCATransitionFromLeft"") { flipToLeft = false; } // We don't need to animate a snapshot if it doesn't exist if (snapshotLayer) { unsigned int idx; parent->Children->IndexOf(realLayer, &idx); parent->Children->InsertAt(idx + 1, snapshotLayer); parent->InvalidateArrange(); realLayer->Opacity = 0; _CreateFlip(snapshotLayer, flipToLeft, false, true); } _CreateFlip(realLayer, flipToLeft, true, false); } else { TimeSpan timeSpan = TimeSpan(); timeSpan.Duration = (long long)(0.5 * c_hundredNanoSeconds); m_container->Duration = Duration(timeSpan); Panel^ parent = (Panel^)VisualTreeHelper::GetParent(realLayer); bool fromRight = true; if (subtype == ""kCATransitionFromLeft"") { fromRight = false; } if (fromRight) { // We don't need to animate a snapshot if it doesn't exist if (snapshotLayer) { unsigned int idx; parent->Children->IndexOf(realLayer, &idx); parent->Children->InsertAt(idx, snapshotLayer); parent->InvalidateArrange(); _CreateWoosh(snapshotLayer, fromRight, true, true); } _CreateWoosh(realLayer, fromRight, false, false); } else { // We don't need to animate a snapshot if it doesn't exist if (snapshotLayer) { unsigned int idx; parent->Children->IndexOf(realLayer, &idx); parent->Children->InsertAt(idx + 1, snapshotLayer); parent->InvalidateArrange(); _CreateWoosh(snapshotLayer, fromRight, false, true); } _CreateWoosh(realLayer, fromRight, true, false); } } } void EventedStoryboard::Animate(CALayerXaml^ layer, String^ propertyName, Object^ from, Object^ to) { DoubleAnimation^ timeline = ref new DoubleAnimation(); timeline->Duration = m_container->Duration; timeline->EasingFunction = m_animationEase; CALayerXaml::s_animatableProperties[propertyName]->Animate(layer, m_container, timeline, from, to); } Object^ EventedStoryboard::GetStoryboard() { return m_container; } // // CATextLayerXaml // void CATextLayerXaml::Reset() { TextBlock->Text = """"; TextBlock->Width = std::nan(NULL); TextBlock->Height = std::nan(NULL); } CATextLayerXaml^ CATextLayerXaml::CreateTextLayer() { ICacheableObject^ ret = _TextLayerCache->GetCachableObject(); if (ret != nullptr) { return (CATextLayerXaml^)ret; } return ref new CATextLayerXaml(); } void CATextLayerXaml::DestroyTextLayer(CATextLayerXaml^ content) { _TextLayerCache->PushCacheableObject(content); } } // Controls } // XamlCompositor // clang-format on ",16309,True,2945.7602716425927,median "== Raspicam commands `raspistill`, `raspivid` and `raspiyuv` are command line tools for using the camera module. === Enabling the Camera Before using any of the _Raspicam_ applications, the camera must be enabled. ==== On the desktop Select `Preferences` and `Raspberry Pi Configuration` from the desktop menu: a window will appear. Select the `Interfaces` tab, then click on the `enable camera` option. Click `OK`. You will need to reboot for the changes to take effect. ==== With the command line Open the `raspi-config` tool from the terminal: [,bash] ---- sudo raspi-config ---- Select `Interfacing Options` then `Camera` and press `Enter`. Choose `Yes` then `Ok`. Go to `Finish` and you'll be prompted to reboot. To test that the system is installed and working, try the following command: [,bash] ---- raspistill -v -o test.jpg ---- The display should show a five-second preview from the camera and then take a picture, saved to the file `test.jpg`, whilst displaying various informational messages. === `raspistill` `raspistill` is the command line tool for capturing still photographs with a Raspberry Pi camera module. ==== Basic usage of raspistill With a camera module xref:camera.adoc#camera-modules[connected and enabled], enter the following command in the terminal to take a picture: [,bash] ---- raspistill -o cam.jpg ---- image::images/cam.jpg[Upside-down photo] In this example the camera has been positioned upside-down. If the camera is placed in this position, the image must be flipped to appear the right way up. ==== Vertical flip and horizontal flip With the camera placed upside-down, the image must be rotated 180° to be displayed correctly. The way to correct for this is to apply both a vertical and a horizontal flip by passing in the `-vf` and `-hf` flags: [,bash] ---- raspistill -vf -hf -o cam2.jpg ---- image::images/cam2.jpg[Vertical and horizontal flipped photo] Now the photo has been captured correctly. ==== Resolution The camera module takes pictures at a resolution of `2592 x 1944` which is 5,038,848 pixels or 5 megapixels. ==== File size A photo taken with the camera module will be around 2.4MB. This is about 425 photos per GB. Taking 1 photo per minute would take up 1GB in about 7 hours. This is a rate of about 144MB per hour or 3.3GB per day. ==== Bash script You can create a Bash script which takes a picture with the camera. To create a script, open up your editor of choice and write the following example code: [,bash] ---- #!/bin/bash DATE=$(date +""%Y-%m-%d_%H%M"") raspistill -vf -hf -o /home/pi/camera/$DATE.jpg ---- This script will take a picture and name the file with a timestamp. You'll also need to make sure the path exists by creating the `camera` folder: [,bash] ---- mkdir camera ---- Say we saved it as `camera.sh`, we would first make the file executable: [,bash] ---- chmod +x camera.sh ---- Then run with: [,bash] ---- ./camera.sh ---- ==== More options For a full list of possible options, run `raspistill` with no arguments. To scroll, redirect stderr to stdout and pipe the output to `less`: [,bash] ---- raspistill 2>&1 | less ---- Use the arrow keys to scroll and type `q` to exit. === `raspivid` `raspivid` is the command line tool for capturing video with a Raspberry Pi camera module. ==== Basic usage of raspivid With a camera module xref:camera.adoc#camera-modules[connected and enabled], record a video using the following command: [,bash] ---- raspivid -o vid.h264 ---- Remember to use `-hf` and `-vf` to flip the image if required, like with xref:camera.adoc#raspistill[raspistill] This will save a 5 second video file to the path given here as `vid.h264` (default length of time). ==== Specify length of video To specify the length of the video taken, pass in the `-t` flag with a number of milliseconds. For example: [,bash] ---- raspivid -o video.h264 -t 10000 ---- This will record 10 seconds of video. ==== More options For a full list of possible options, run `raspivid` with no arguments, or pipe this command through `less` and scroll through: [,bash] ---- raspivid 2>&1 | less ---- Use the arrow keys to scroll and type `q` to exit. ==== MP4 Video Format The Raspberry Pi captures video as a raw H264 video stream. Many media players will refuse to play it, or play it at an incorrect speed, unless it is ""wrapped"" in a suitable container format like MP4. The easiest way to obtain an MP4 file from the raspivid command is using MP4Box. Install MP4Box with this command: [,bash] ---- sudo apt install -y gpac ---- Capture your raw video with raspivid and wrap it in an MP4 container like this: [,bash] ---- # Capture 30 seconds of raw video at 640x480 and 150kBps bit rate into a pivideo.h264 file: raspivid -t 30000 -w 640 -h 480 -fps 25 -b 1200000 -p 0,0,640,480 -o pivideo.h264 # Wrap the raw video with an MP4 container: MP4Box -add pivideo.h264 pivideo.mp4 # Remove the source raw file, leaving the remaining pivideo.mp4 file to play rm pivideo.h264 ---- Alternatively, wrap MP4 around your existing raspivid output, like this: [,bash] ---- MP4Box -add video.h264 video.mp4 ---- === `raspiyuv` `raspiyuv` has the same set of features as `raspistill` but instead of outputting standard image files such as ``.jpg``s, it generates YUV420 or RGB888 image files from the output of the camera ISP. In most cases using `raspistill` is the best option for standard image capture, but using YUV can be of benefit in certain circumstances. For example if you just need a uncompressed black and white image for computer vision applications, you can simply use the Y channel of a YUV capture. There are some specific points about the YUV420 files that are required in order to use them correctly. Line stride (or pitch) is a multiple of 32, and each plane of YUV is a multiple of 16 in height. This can mean there may be extra pixels at the end of lines, or gaps between planes, depending on the resolution of the captured image. These gaps are unused. === Troubleshooting If the Camera Module isn't working correctly, there are number of things to try: * Is the ribbon cable attached to the Camera Serial Interface (CSI), not the Display Serial Interface (DSI)? The ribbon connector will fit into either port. The Camera port is located near the HDMI connector. * Are the ribbon connectors all firmly seated, and are they the right way round? They must be straight in their sockets. * Is the Camera Module connector, between the smaller black Camera Module itself and the PCB, firmly attached? Sometimes this connection can come loose during transit or when putting the Camera Module in a case. Using a fingernail, flip up the connector on the PCB, then reconnect it with gentle pressure. It engages with a very slight click. Don't force it; if it doesn't engage, it's probably slightly misaligned. * Have `sudo apt update` and `sudo apt full-upgrade` been run? * Has `raspi-config` been run and the Camera Module enabled? * Is your power supply sufficient? The Camera Module adds about 200-250mA to the power requirements of your Raspberry Pi. If things are still not working, try the following: * `Error : raspistill/raspivid command not found`. This probably means your update/upgrade failed in some way. Try it again. * `Error : ENOMEM`. The Camera Module is not starting up. Check all connections again. * `Error : ENOSPC`. The Camera Module is probably running out of GPU memory. Check `config.txt` in the /boot/ folder. The `gpu_mem` option should be at least 128. Alternatively, use the Memory Split option in the Advanced section of `raspi-config` to set this. * If you've checked all the above issues and the Camera Module is still not working, try posting on our forums for more help. === Command Line Options ==== Preview window ---- --preview, -p Preview window settings <'x,y,w,h'> ---- Allows the user to define the size of the preview window and its location on the screen. Note this will be superimposed over the top of any other windows/graphics. ---- --fullscreen, -f Fullscreen preview mode ---- Forces the preview window to use the whole screen. Note that the aspect ratio of the incoming image will be retained, so there may be bars on some edges. ---- --nopreview, -n Do not display a preview window ---- Disables the preview window completely. Note that even though the preview is disabled, the camera will still be producing frames, so will be using power. ---- --opacity, -op Set preview window opacity ---- Sets the opacity of the preview windows. 0 = invisible, 255 = fully opaque. ==== Camera control options ---- --sharpness, -sh Set image sharpness (-100 - 100) ---- Sets the sharpness of the image. 0 is the default. ---- --contrast, -co Set image contrast (-100 - 100) ---- Sets the contrast of the image. 0 is the default. ---- --brightness, -br Set image brightness (0 - 100) ---- Sets the brightness of the image. 50 is the default. 0 is black, 100 is white. ---- --saturation, -sa Set image saturation (-100 - 100) ---- Sets the colour saturation of the image. 0 is the default. ---- --ISO, -ISO Set capture ISO (100 - 800) ---- Sets the ISO to be used for captures. ---- --vstab, -vs Turn on video stabilisation ---- In video mode only, turns on video stabilisation. ---- --ev, -ev Set EV compensation (-10 - 10) ---- Sets the EV compensation of the image. Default is 0. ---- --exposure, -ex Set exposure mode ---- Possible options are: * auto: use automatic exposure mode * night: select setting for night shooting * nightpreview: * backlight: select setting for backlit subject * spotlight: * sports: select setting for sports (fast shutter etc.) * snow: select setting optimised for snowy scenery * beach: select setting optimised for beach * verylong: select setting for long exposures * fixedfps: constrain fps to a fixed value * antishake: antishake mode * fireworks: select setting optimised for fireworks Note that not all of these settings may be implemented, depending on camera tuning. ---- --flicker, -fli Set flicker avoidance mode ---- Set a mode to compensate for lights flickering at the mains frequency, which can be seen as a dark horizontal band across an image. Flicker avoidance locks the exposure time to a multiple of the mains flicker frequency (8.33ms for 60Hz, or 10ms for 50Hz). This means that images can be noisier as the control algorithm has to increase the gain instead of exposure time should it wish for an intermediate exposure value. `auto` can be confused by external factors, therefore it is preferable to leave this setting off unless actually required. Possible options are: * off: turn off flicker avoidance * auto: automatically detect mains frequency * 50hz: set avoidance at 50Hz * 60hz: set avoidance at 60Hz ---- --awb, -awb Set Automatic White Balance (AWB) mode ---- Modes for which colour temperature ranges (K) are available have these settings in brackets. * off: turn off white balance calculation * auto: automatic mode (default) * sun: sunny mode (between 5000K and 6500K) * cloud: cloudy mode (between 6500K and 12000K) * shade: shade mode * tungsten: tungsten lighting mode (between 2500K and 3500K) * fluorescent: fluorescent lighting mode (between 2500K and 4500K) * incandescent: incandescent lighting mode * flash: flash mode * horizon: horizon mode * greyworld: Use this on the NoIR camera to fix incorrect AWB results due to the lack of the IR filter. Note that not all of these settings may be implemented, depending on camera type. ---- --imxfx, -ifx Set image effect ---- Set an effect to be applied to the image: * none: no effect (default) * negative: invert the image colours * solarise: solarise the image * posterise: posterise the image * whiteboard: whiteboard effect * blackboard: blackboard effect * sketch: sketch effect * denoise: denoise the image * emboss: emboss the image * oilpaint: oil paint effect * hatch: hatch sketch effect * gpen: graphite sketch effect * pastel: pastel effect * watercolour: watercolour effect * film: film grain effect * blur: blur the image * saturation: colour saturate the image * colourswap: not fully implemented * washedout: not fully implemented * colourpoint: not fully implemented * colourbalance: not fully implemented * cartoon: not fully implemented Note that not all of these settings may be available in all circumstances. ---- --colfx, -cfx Set colour effect ---- The supplied U and V parameters (range 0 - 255) are applied to the U and Y channels of the image. For example, --colfx 128:128 should result in a monochrome image. ---- --metering, -mm Set metering mode ---- Specify the metering mode used for the preview and capture: * average: average the whole frame for metering * spot: spot metering * backlit: assume a backlit image * matrix: matrix metering ---- --rotation, -rot Set image rotation (0 - 359) ---- Sets the rotation of the image in the viewfinder and resulting image. This can take any value from 0 upwards, but due to hardware constraints only 0, 90, 180, and 270 degree rotations are supported. ---- --hflip, -hf Set horizontal flip ---- Flips the preview and saved image horizontally. ---- --vflip, -vf Set vertical flip ---- Flips the preview and saved image vertically. ---- --roi, -roi Set sensor region of interest ---- Allows the specification of the area of the sensor to be used as the source for the preview and capture. This is defined as x,y for the top-left corner, and a width and height, with all values in normalised coordinates (0.0 - 1.0). So, to set a ROI at halfway across and down the sensor, and a width and height of a quarter of the sensor, use: ---- -roi 0.5,0.5,0.25,0.25 ---- ---- --shutter, -ss Set shutter speed/time ---- Sets the shutter open time to the specified value (in microseconds). Shutter speed limits are as follows: [cols="",^""] |=== | Camera Version | Max (microseconds) | V1 (OV5647) | 6000000 (i.e. 6s) | V2 (IMX219) | 10000000 (i.e. 10s) | HQ (IMX477) | 200000000 (i.e. 200s) |=== Using values above these maximums will result in undefined behaviour. ---- --drc, -drc Enable/disable dynamic range compression ---- DRC changes the images by increasing the range of dark areas, and decreasing the brighter areas. This can improve the image in low light areas. * off * low * med * high By default, DRC is off. ---- --stats, -st Use stills capture frame for image statistics ---- Force recomputation of statistics on stills capture pass. Digital gain and AWB are recomputed based on the actual capture frame statistics, rather than the preceding preview frame. ---- --awbgains, -awbg ---- Sets blue and red gains (as floating point numbers) to be applied when `-awb off` is set e.g. -awbg 1.5,1.2 ---- --analoggain, -ag ---- Sets the analog gain value directly on the sensor (floating point value from 1.0 to 8.0 for the OV5647 sensor on Camera Module V1, and 1.0 to 12.0 for the IMX219 sensor on Camera Module V2 and the IMX447 on the HQ Camera). ---- --digitalgain, -dg ---- Sets the digital gain value applied by the ISP (floating point value from 1.0 to 64.0, but values over about 4.0 will produce overexposed images) ---- --mode, -md ---- Sets a specified sensor mode, disabling the automatic selection. Possible values depend on the version of the Camera Module being used: Version 1.x (OV5647) |=== | Mode | Size | Aspect Ratio | Frame rates | FOV | Binning | 0 | automatic selection | | | | | 1 | 1920x1080 | 16:9 | 1-30fps | Partial | None | 2 | 2592x1944 | 4:3 | 1-15fps | Full | None | 3 | 2592x1944 | 4:3 | 0.1666-1fps | Full | None | 4 | 1296x972 | 4:3 | 1-42fps | Full | 2x2 | 5 | 1296x730 | 16:9 | 1-49fps | Full | 2x2 | 6 | 640x480 | 4:3 | 42.1-60fps | Full | 2x2 plus skip | 7 | 640x480 | 4:3 | 60.1-90fps | Full | 2x2 plus skip |=== Version 2.x (IMX219) |=== | Mode | Size | Aspect Ratio | Frame rates | FOV | Binning | 0 | automatic selection | | | | | 1 | 1920x1080 | 16:9 | 0.1-30fps | Partial | None | 2 | 3280x2464 | 4:3 | 0.1-15fps | Full | None | 3 | 3280x2464 | 4:3 | 0.1-15fps | Full | None | 4 | 1640x1232 | 4:3 | 0.1-40fps | Full | 2x2 | 5 | 1640x922 | 16:9 | 0.1-40fps | Full | 2x2 | 6 | 1280x720 | 16:9 | 40-90fps | Partial | 2x2 | 7 | 640x480 | 4:3 | 40-200fps^1^ | Partial | 2x2 |=== ^1^For frame rates over 120fps, it is necessary to turn off automatic exposure and gain control using `-ex off`. Doing so should achieve the higher frame rates, but exposure time and gains will need to be set to fixed values supplied by the user. HQ Camera |=== | Mode | Size | Aspect Ratio | Frame rates | FOV | Binning/Scaling | 0 | automatic selection | | | | | 1 | 2028x1080 | 169:90 | 0.1-50fps | Partial | 2x2 binned | 2 | 2028x1520 | 4:3 | 0.1-50fps | Full | 2x2 binned | 3 | 4056x3040 | 4:3 | 0.005-10fps | Full | None | 4 | 1332x990 | 74:55 | 50.1-120fps | Partial | 2x2 binned |=== ---- --camselect, -cs ---- Selects which camera to use on a multi-camera system. Use 0 or 1. ---- --annotate, -a Enable/set annotate flags or text ---- Adds some text and/or metadata to the picture. Metadata is indicated using a bitmask notation, so add them together to show multiple parameters. For example, 12 will show time(4) and date(8), since 4+8=12. Text may include date/time placeholders by using the '%' character, as used by http://man7.org/linux/man-pages/man3/strftime.3.html[strftime]. |=== | Value | Meaning | Example Output | -a 4 | Time | 20:09:33 | -a 8 | Date | 10/28/15 | -a 12 | 4+8=12 Show the date(4) and time(8) | 20:09:33 10/28/15 | -a 16 | Shutter Settings | | -a 32 | CAF Settings | | -a 64 | Gain Settings | | -a 128 | Lens Settings | | -a 256 | Motion Settings | | -a 512 | Frame Number | | -a 1024 | Black Background | | -a ""ABC %Y-%m-%d %X"" | Show some text | ABC %Y-%m-%d %X | -a 4 -a ""ABC %Y-%m-%d %X"" | Show custom http://man7.org/linux/man-pages/man3/strftime.3.html[formatted] date/time | ABC 2015-10-28 20:09:33 | -a 8 -a ""ABC %Y-%m-%d %X"" | Show custom http://man7.org/linux/man-pages/man3/strftime.3.html[formatted] date/time | ABC 2015-10-28 20:09:33 |=== ---- --annotateex, -ae Set extra annotation parameters ---- Specifies annotation size, text colour, and background colour. Colours are in hex YUV format. Size ranges from 6 - 160; default is 32. Asking for an invalid size should give you the default. |=== | Example | Explanation | -ae 32,0xff,0x808000 -a ""Annotation text"" | gives size 32 white text on black background | -ae 10,0x00,0x8080FF -a ""Annotation text"" | gives size 10 black text on white background |=== ---- --stereo, -3d ---- Select the specified stereo imaging mode; `sbs` selects side-by-side mode, `tb` selects top/bottom mode; `off` turns off stereo mode (the default). ---- --decimate, -dec ---- Halves the width and height of the stereo image. ---- --3dswap, -3dswap ---- Swaps the camera order used in stereoscopic imaging; NOTE: currently not working. ---- --settings, -set ---- Retrieves the current camera settings and writes them to stdout. === Application-specific Settings ==== `raspistill` ---- --width, -w Set image width --height, -h Set image height --quality, -q Set JPEG quality <0 to 100> ---- Quality 100 is almost completely uncompressed. 75 is a good all-round value. ---- --raw, -r Add raw Bayer data to JPEG metadata ---- This option inserts the raw Bayer data from the camera into the JPEG metadata. ---- --output, -o Output filename ---- Specifies the output filename. If not specified, no file is saved. If the filename is '-', then all output is sent to stdout. ---- --latest, -l Link latest frame to filename ---- Makes a file system link under this name to the latest frame. ---- --verbose, -v Output verbose information during run ---- Outputs debugging/information messages during the program run. ---- --timeout, -t Time before the camera takes picture and shuts down ---- The program will run for the specified length of time, entered in milliseconds. It then takes the capture and saves it if an output is specified. If a timeout value is not specified, then it is set to 5 seconds (-t 5000). Note that low values (less than 500ms, although it can depend on other settings) may not give enough time for the camera to start up and provide enough frames for the automatic algorithms like AWB and AGC to provide accurate results. If set to 0, the preview will run indefinitely, until stopped with CTRL-C. In this case no capture is made. ---- --timelapse, -tl time-lapse mode ---- The specific value is the time between shots in milliseconds. Note that you should specify `%04d` at the point in the filename where you want a frame count number to appear. So, for example, the code below will produce a capture every 2 seconds, over a total period of 30s, named `image0001.jpg`, `image0002.jpg` and so on, through to `image0015.jpg`. ---- -t 30000 -tl 2000 -o image%04d.jpg ---- Note that the `%04d` indicates a 4-digit number, with leading zeroes added to make the required number of digits. So, for example, `%08d` would result in an 8-digit number. If a time-lapse value of 0 is entered, the application will take pictures as fast as possible. Note that there's an minimum enforced pause of 30ms between captures to ensure that exposure calculations can be made. ---- --framestart, -fs ---- Specifies the first frame number in the timelapse. Useful if you have already saved a number of frames, and want to start again at the next frame. ---- --datetime, -dt ---- Instead of a simple frame number, the timelapse file names will use a date/time value of the format `aabbccddee`, where `aa` is the month, `bb` is the day of the month, `cc` is the hour, `dd` is the minute, and `ee` is the second. ---- --timestamp, -ts ---- Instead of a simple frame number, the timelapse file names will use a single number which is the Unix timestamp, i.e. the seconds since 1970. ---- --thumb, -th Set thumbnail parameters (x:y:quality) ---- Allows specification of the thumbnail image inserted into the JPEG file. If not specified, defaults are a size of 64x48 at quality 35. if `--thumb none` is specified, no thumbnail information will be placed in the file. This reduces the file size slightly. ---- --demo, -d Run a demo mode ---- This options cycles through the range of camera options. No capture is taken, and the demo will end at the end of the timeout period, irrespective of whether all the options have been cycled. The time between cycles should be specified as a millisecond value. ---- --encoding, -e Encoding to use for output file ---- Valid options are `jpg`, `bmp`, `gif`, and `png`. Note that unaccelerated image types (GIF, PNG, BMP) will take much longer to save than jpg, which is hardware accelerated. Also note that the filename suffix is completely ignored when deciding the encoding of a file. ---- --restart, -rs ---- Sets the JPEG restart marker interval to a specific value. Can be useful for lossy transport streams because it allows a broken JPEG file to still be partially displayed. ---- --exif, -x EXIF tag to apply to captures (format as 'key=value') ---- Allows the insertion of specific EXIF tags into the JPEG image. You can have up to 32 EXIF tag entries. This is useful for tasks like adding GPS metadata. For example, to set the longitude: ---- --exif GPS.GPSLongitude=5/1,10/1,15/1 ---- would set the longitude to 5 degs, 10 minutes, 15 seconds. See EXIF documentation for more details on the range of tags available; the supported tags are as follows: ---- IFD0.< or IFD1.< ImageWidth, ImageLength, BitsPerSample, Compression, PhotometricInterpretation, ImageDescription, Make, Model, StripOffsets, Orientation, SamplesPerPixel, RowsPerString, StripByteCounts, XResolution, YResolution, PlanarConfiguration, ResolutionUnit, TransferFunction, Software, DateTime, Artist, WhitePoint, PrimaryChromaticities, JPEGInterchangeFormat, JPEGInterchangeFormatLength, YCbCrCoefficients, YCbCrSubSampling, YCbCrPositioning, ReferenceBlackWhite, Copyright> EXIF.< ExposureTime, FNumber, ExposureProgram, SpectralSensitivity, ISOSpeedRatings, OECF, ExifVersion, DateTimeOriginal, DateTimeDigitized, ComponentsConfiguration, CompressedBitsPerPixel, ShutterSpeedValue, ApertureValue, BrightnessValue, ExposureBiasValue, MaxApertureValue, SubjectDistance, MeteringMode, LightSource, Flash, FocalLength, SubjectArea, MakerNote, UserComment, SubSecTime, SubSecTimeOriginal, SubSecTimeDigitized, FlashpixVersion, ColorSpace, PixelXDimension, PixelYDimension, RelatedSoundFile, FlashEnergy, SpatialFrequencyResponse, FocalPlaneXResolution, FocalPlaneYResolution, FocalPlaneResolutionUnit, SubjectLocation, ExposureIndex, SensingMethod, FileSource, SceneType, CFAPattern, CustomRendered, ExposureMode, WhiteBalance, DigitalZoomRatio, FocalLengthIn35mmFilm, SceneCaptureType, GainControl, Contrast, Saturation, Sharpness, DeviceSettingDescription, SubjectDistanceRange, ImageUniqueID> GPS.< GPSVersionID, GPSLatitudeRef, GPSLatitude, GPSLongitudeRef, GPSLongitude, GPSAltitudeRef, GPSAltitude, GPSTimeStamp, GPSSatellites, GPSStatus, GPSMeasureMode, GPSDOP, GPSSpeedRef, GPSSpeed, GPSTrackRef, GPSTrack, GPSImgDirectionRef, GPSImgDirection, GPSMapDatum, GPSDestLatitudeRef, GPSDestLatitude, GPSDestLongitudeRef, GPSDestLongitude, GPSDestBearingRef, GPSDestBearing, GPSDestDistanceRef, GPSDestDistance, GPSProcessingMethod, GPSAreaInformation, GPSDateStamp, GPSDifferential> EINT.< InteroperabilityIndex, InteroperabilityVersion, RelatedImageFileFormat, RelatedImageWidth, RelatedImageLength> ---- Note that a small subset of these tags will be set automatically by the camera system, but will be overridden by any EXIF options on the command line. Setting `--exif none` will prevent any EXIF information being stored in the file. This reduces the file size slightly. ---- --gpsdexif, -gps ---- Applies real-time EXIF information from any attached GPS dongle (using GSPD) to the image; requires `libgps.so` to be installed. ---- --fullpreview, -fp Full preview mode ---- This runs the preview window using the full resolution capture mode. Maximum frames per second in this mode is 15fps, and the preview will have the same field of view as the capture. Captures should happen more quickly, as no mode change should be required. This feature is currently under development. ---- --keypress, -k Keypress mode ---- The camera is run for the requested time (`-t`), and a capture can be initiated throughout that time by pressing the Enter key. Pressing X then Enter will exit the application before the timeout is reached. If the timeout is set to 0, the camera will run indefinitely until the user presses X then Enter. Using the verbose option (`-v`) will display a prompt asking for user input, otherwise no prompt is displayed. ---- --signal, -s Signal mode ---- The camera is run for the requested time (`-t`), and a capture can be initiated throughout that time by sending a `USR1` signal to the camera process. This can be done using the `kill` command. You can find the camera process ID using the `pgrep raspistill` command. `kill -USR1 ` ---- --burst, -bm ---- Sets burst capture mode. This prevents the camera from returning to preview mode in between captures, meaning that captures can be taken closer together. ==== `raspivid` ---- --width, -w Set image width ---- Width of resulting video. This should be between 64 and 1920. ---- --height, -h Set image height ---- Height of resulting video. This should be between 64 and 1080. ---- --bitrate, -b Set bitrate ---- Use bits per second, so 10Mbps would be `-b 10000000`. For H264, 1080p30 a high quality bitrate would be 15Mbps or more. Maximum bitrate is 25Mbps (`-b 25000000`), but much over 17Mbps won't show noticeable improvement at 1080p30. ---- --output, -o Output filename ---- Specify the output filename. If not specified, no file is saved. If the filename is '-', then all output is sent to stdout. To connect to a remote IPv4 host, use `tcp` or `udp` followed by the required IP Address. e.g. `tcp://192.168.1.2:1234` or `udp://192.168.1.2:1234`. To listen on a TCP port (IPv4) and wait for an incoming connection use `--listen (-l)` option, e.g. `raspivid -l -o tcp://0.0.0.0:3333` will bind to all network interfaces, `raspivid -l -o tcp://192.168.1.1:3333` will bind to a local IPv4. ---- --listen, -l ---- When using a network connection as the data sink, this option will make the system wait for a connection from the remote system before sending data. ---- --verbose, -v Output verbose information during run ---- Outputs debugging/information messages during the program run. ---- --timeout, -t Time before the camera takes picture and shuts down ---- The total length of time that the program will run for. If not specified, the default is 5000ms (5 seconds). If set to 0, the application will run indefinitely until stopped with Ctrl-C. ---- --demo, -d Run a demo mode ---- This options cycles through the range of camera options. No recording is done, and the demo will end at the end of the timeout period, irrespective of whether all the options have been cycled. The time between cycles should be specified as a millisecond value. ---- --framerate, -fps Specify the frames per second to record ---- At present, the minimum frame rate allowed is 2fps, and the maximum is 30fps. This is likely to change in the future. ---- --penc, -e Display preview image after encoding ---- Switch on an option to display the preview after compression. This will show any compression artefacts in the preview window. In normal operation, the preview will show the camera output prior to being compressed. This option is not guaranteed to work in future releases. ---- --intra, -g Specify the intra refresh period (key frame rate/GoP) ---- Sets the intra refresh period (GoP) rate for the recorded video. H264 video uses a complete frame (I-frame) every intra refresh period, from which subsequent frames are based. This option specifies the number of frames between each I-frame. Larger numbers here will reduce the size of the resulting video, and smaller numbers make the stream less error-prone. ---- --qp, -qp Set quantisation parameter ---- Sets the initial quantisation parameter for the stream. Varies from approximately 10 to 40, and will greatly affect the quality of the recording. Higher values reduce quality and decrease file size. Combine this setting with a bitrate of 0 to set a completely variable bitrate. ---- --profile, -pf Specify H264 profile to use for encoding ---- Sets the H264 profile to be used for the encoding. Options are: * baseline * main * high ---- --level, -lev ---- Specifies the H264 encoder level to use for encoding. Options are `4`, `4.1`, and `4.2`. ---- --irefresh, -if ---- Sets the H264 intra-refresh type. Possible options are `cyclic`, `adaptive`, `both`, and `cyclicrows`. ---- --inline, -ih Insert PPS, SPS headers ---- Forces the stream to include PPS and SPS headers on every I-frame. Needed for certain streaming cases e.g. Apple HLS. These headers are small, so don't greatly increase the file size. ---- --spstimings, -stm ---- Insert timing information into the SPS block. ---- --timed, -td Do timed switches between capture and pause ---- This options allows the video capture to be paused and restarted at particular time intervals. Two values are required: the on time and the off time. On time is the amount of time the video is captured, and off time is the amount it is paused. The total time of the recording is defined by the `timeout` option. Note that the recording may take slightly over the timeout setting depending on the on and off times. For example: ---- raspivid -o test.h264 -t 25000 -timed 2500,5000 ---- will record for a period of 25 seconds. The recording will be over a timeframe consisting of 2500ms (2.5s) segments with 5000ms (5s) gaps, repeating over the 20s. So the entire recording will actually be only 10s long, since 4 segments of 2.5s = 10s separated by 5s gaps. So: 2.5 record -- 5 pause - 2.5 record -- 5 pause - 2.5 record -- 5 pause -- 2.5 record gives a total recording period of 25s, but only 10s of actual recorded footage. ---- --keypress, -k Toggle between record and pause on Enter keypress ---- On each press of the Enter key, the recording will be paused or restarted. Pressing X then Enter will stop recording and close the application. Note that the timeout value will be used to signal the end of recording, but is only checked after each Enter keypress; so if the system is waiting for a keypress, even if the timeout has expired, it will still wait for the keypress before exiting. ---- --signal, -s Toggle between record and pause according to SIGUSR1 ---- Sending a `USR1` signal to the `raspivid` process will toggle between recording and paused. This can be done using the `kill` command, as below. You can find the `raspivid` process ID using `pgrep raspivid`. `kill -USR1 ` Note that the timeout value will be used to indicate the end of recording, but is only checked after each receipt of the `SIGUSR1` signal; so if the system is waiting for a signal, even if the timeout has expired, it will still wait for the signal before exiting. ---- --split, -sp ---- When in a signal or keypress mode, each time recording is restarted, a new file is created. ---- --circular, -c ---- Select circular buffer mode. All encoded data is stored in a circular buffer until a trigger is activated, then the buffer is saved. ---- --vectors, -x ---- Turns on output of motion vectors from the H264 encoder to the specified file name. ---- --flush, -fl ---- Forces a flush of output data buffers as soon as video data is written. This bypasses any OS caching of written data, and can decrease latency. ---- --save-pts, -pts ---- Saves timestamp information to the specified file. Useful as an input file to `mkvmerge`. ---- --codec, -cd ---- Specifies the encoder codec to use. Options are `H264` and `MJPEG`. H264 can encode up to 1080p, whereas MJPEG can encode up to the sensor size, but at decreased framerates due to the higher processing and storage requirements. ---- --initial, -i Define initial state on startup ---- Define whether the camera will start paused or will immediately start recording. Options are `record` or `pause`. Note that if you are using a simple timeout, and `initial` is set to `pause`, no output will be recorded. ---- --segment, -sg Segment the stream into multiple files ---- Rather than creating a single file, the file is split into segments of approximately the number of milliseconds specified. In order to provide different filenames, you should add `%04d` or similar at the point in the filename where you want a segment count number to appear e.g: ---- --segment 3000 -o video%04d.h264 ---- will produce video clips of approximately 3000ms (3s) long, named `video0001.h264`, `video0002.h264` etc. The clips should be seamless (no frame drops between clips), but the accuracy of each clip length will depend on the intraframe period, as the segments will always start on an I-frame. They will therefore always be equal or longer to the specified period. The most recent version of Raspivid will also allow the file name to be time-based, rather than using a segment number. For example: ---- --segment 3000 -o video_%c.h264 ---- will produce file names formatted like so: `video_Fri Jul 20 16:23:48 2018.h264` There are http://man7.org/linux/man-pages/man3/strftime.3.html[many different formatting options] available. Note than the `%d` and `%u` options are not available, as they are used for the segment number formatting, and that some combinations may produce invalid file names. ---- --wrap, -wr Set the maximum value for segment number ---- When outputting segments, this is the maximum the segment number can reach before it's reset to 1, giving the ability to keep recording segments, but overwriting the oldest one. So if set to 4, in the segment example above, the files produced will be `video0001.h264`, `video0002.h264`, `video0003.h264`, and `video0004.h264`. Once `video0004.h264` is recorded, the count will reset to 1, and `video0001.h264` will be overwritten. ---- --start, -sn Set the initial segment number ---- When outputting segments, this is the initial segment number, giving the ability to resume a previous recording from a given segment. The default value is 1. ---- --raw, -r ---- Specify the output file name for any raw data files requested. ---- --raw-format, -rf ---- Specify the raw format to be used if raw output requested. Options as `yuv`, `rgb`, and `grey`. `grey` simply saves the Y channel of the YUV image. ==== `raspiyuv` Many of the options for `raspiyuv` are the same as those for `raspistill`. This section shows the differences. Unsupported options: ---- --exif, --encoding, --thumb, --raw, --quality ---- Extra options : ---- --rgb, -rgb Save uncompressed data as RGB888 ---- This option forces the image to be saved as RGB data with 8 bits per channel, rather than YUV420. Note that the image buffers saved in `raspiyuv` are padded to a horizontal size divisible by 32, so there may be unused bytes at the end of each line. Buffers are also padded vertically to be divisible by 16, and in the YUV mode, each plane of Y,U,V is padded in this way. ---- --luma, -y ---- Only outputs the luma (Y) channel of the YUV image. This is effectively the black and white, or intensity, part of the image. ---- --bgr, -bgr ---- Saves the image data as BGR data rather than YUV. === Command Line Examples ==== Still Captures By default, captures are done at the highest resolution supported by the sensor. This can be changed using the `-w` and `-h` command line options. Take a default capture after 2s (times are specified in milliseconds) on the viewfinder, saving in `image.jpg`: [,bash] ---- raspistill -t 2000 -o image.jpg ---- Take a capture at a different resolution: [,bash] ---- raspistill -t 2000 -o image.jpg -w 640 -h 480 ---- Reduce the quality considerably to reduce file size: [,bash] ---- raspistill -t 2000 -o image.jpg -q 5 ---- Force the preview to appear at coordinate 100,100, with width 300 pixels and height 200 pixels: [,bash] ---- raspistill -t 2000 -o image.jpg -p 100,100,300,200 ---- Disable preview entirely: [,bash] ---- raspistill -t 2000 -o image.jpg -n ---- Save the image as a PNG file (lossless compression, but slower than JPEG). Note that the filename suffix is ignored when choosing the image encoding: [,bash] ---- raspistill -t 2000 -o image.png –e png ---- Add some EXIF information to the JPEG. This sets the Artist tag name to Boris, and the GPS altitude to 123.5m. Note that if setting GPS tags you should set as a minimum GPSLatitude, GPSLatitudeRef, GPSLongitude, GPSLongitudeRef, GPSAltitude, and GPSAltitudeRef: [,bash] ---- raspistill -t 2000 -o image.jpg -x IFD0.Artist=Boris -x GPS.GPSAltitude=1235/10 ---- Set an emboss image effect: [,bash] ---- raspistill -t 2000 -o image.jpg -ifx emboss ---- Set the U and V channels of the YUV image to specific values (128:128 produces a greyscale image): [,bash] ---- raspistill -t 2000 -o image.jpg -cfx 128:128 ---- Run preview for 2s, with no saved image: [,bash] ---- raspistill -t 2000 ---- Take a time-lapse picture, every 10 seconds for 10 minutes (10 minutes = 600000ms), naming the files `image_num_001_today.jpg`, `image_num_002_today.jpg` and so on, with the latest picture also available under the name `latest.jpg`: [,bash] ---- raspistill -t 600000 -tl 10000 -o image_num_%03d_today.jpg -l latest.jpg ---- Take a picture and send the image data to stdout: [,bash] ---- raspistill -t 2000 -o - ---- Take a picture and send the image data to a file: [,bash] ---- raspistill -t 2000 -o - > my_file.jpg ---- Run the camera forever, taking a picture when Enter is pressed: [,bash] ---- raspistill -t 0 -k -o my_pics%02d.jpg ---- ==== Video captures Image size and preview settings are the same as for stills capture. Default size for video recording is 1080p (1920x1080). Record a 5s clip with default settings (1080p30): [,bash] ---- raspivid -t 5000 -o video.h264 ---- Record a 5s clip at a specified bitrate (3.5Mbps): [,bash] ---- raspivid -t 5000 -o video.h264 -b 3500000 ---- Record a 5s clip at a specified framerate (5fps): [,bash] ---- raspivid -t 5000 -o video.h264 -f 5 ---- Encode a 5s camera stream and send the image data to stdout: [,bash] ---- raspivid -t 5000 -o - ---- Encode a 5s camera stream and send the image data to a file: [,bash] ---- raspivid -t 5000 -o - > my_file.h264 ---- === Shell Error Codes The applications described here will return a standard error code to the shell on completion. Possible error codes are: |=== | C Define | Code | Description | EX_OK | 0 | Application ran successfully | EX_USAGE | 64 | Bad command line parameter | EX_SOFTWARE | 70 | Software or camera error | | 130 | Application terminated by Ctrl-C |=== === Long Exposures The maximum exposure times of the three official Raspberry Pi cameras can be found in xref:camera.adoc#maximum-exposure-times[this table]. Due to the way the ISP works, by default asking for a long exposure can result in the capture process taking up to 7 times the exposure time, so a 200 second exposure on the HQ camera could take 1400 seconds to actually return an image. This is due to the way the camera system works out the correct exposures and gains to use in the image, using it's AGC (automatic gain control) and AWB (automatic white balance) algorithms. The system needs a few frames to calculate these numbers in order to produce a decent image. When combined with frame discards at the start of processing (in case they are corrupt), and the switching between preview and captures modes, this can result in up to 7 frames needed to produce a final image. With long exposures, that can take a long time. Fortunately, the camera parameters can be altered to reduce frame time dramatically; however this means turning off the automatic algorithms and manually providing values for the AGC. The AWB gains can usually be omitted as the legacy stack is able to reprocess the camera data to work them out (the `-st` option), though it is fine to specify them as well. Additionally, burst mode (`-bm`) with a short timeout should be requested to suppress the initial preview phase, and the exposure mode also needs disabling (`-ex off`). The following example will perform a 100 second exposure capture `raspistill -t 10 -bm -ex off -ag 1 -ss 100000000 -st -o long_exposure.jpg` === Shooting RAW using the Camera Modules The definition of raw images can vary. The usual meaning is raw Bayer data directly from the sensor, although some may regard an uncompressed image that has passed through the ISP (and has therefore been processed) as raw. For the latter, we recommend using the term _unencoded_ so as to be clear about the difference. Both options are available from the Raspberry Pi cameras. ==== Processed, Non-Lossy Images The usual output from `raspistill` is a compressed JPEG file that has passed through all the stages of image processing to produce a high-quality image. However, JPEG, being a lossy format does throw away some information that the user may want. `raspistill` has an `encoding` option that allows you to specify the output format: either `jpg`, `bmp`, `png` or `gif`. All but `jpg` are lossless, so no data is thrown away in an effort to improve compression, but do require conversion from the original YUV, and because these formats do not have hardware support they produce images slightly more slowly than JPEG. e.g. `raspistill --encoding png -o fred.png` Another option is to output completely formatted YUV420 or RGB data using the xref:camera.adoc#raspiyuv[`raspiyuv`] application. ==== Unprocessed Images For some applications, such as astrophotography, having the raw Bayer data direct from the sensor can be useful. This data will need to be post-processed to produce a useful image. `raspistill` has a raw option that will cause the Bayer data to be output. `raspistill --raw -o fred.jpg` The raw data is appended to the end of the JPEG file and will https://www.raspberrypi.com/news/processing-raw-image-files-from-a-raspberry-pi-high-quality-camera/[need to be extracted]. ",12451,True,2506.4299194740574,median "/* * Copyright 1993-2010 NVIDIA Corporation. All rights reserved. * * Please refer to the NVIDIA end user license agreement (EULA) associated * with this source code for terms and conditions that govern your use of * this software. Any use, reproduction, disclosure, or distribution of * this software and related documentation outside the terms of the EULA * is strictly prohibited. * */ // ********************************************************************* // Generic Utilities for NVIDIA GPU Computing SDK // ********************************************************************* // includes #include #include #include #include #include #include #include #include #include using namespace std; // size of PGM file header const unsigned int PGMHeaderSize = 0x40; #define MIN_EPSILON_ERROR 1e-3f // Deallocate memory allocated within shrUtils // ********************************************************************* void shrFree(void* ptr) { if( NULL != ptr) free( ptr); } // Helper function to init data arrays // ********************************************************************* void shrFillArray(float* pfData, int iSize) { int i; const float fScale = 1.0f / (float)RAND_MAX; for (i = 0; i < iSize; ++i) { pfData[i] = fScale * rand(); } } // Helper function to print data arrays // ********************************************************************* void shrPrintArray(float* pfData, int iSize) { int i; for (i = 0; i < iSize; ++i) { shrLog(""%d: %.3f\\n"", i, pfData[i]); } } // Helper function to return precision delta time for 3 counters since last call based upon host high performance counter // ********************************************************************* double shrDeltaT(int iCounterID = 0) { // local var for computation of microseconds since last call double DeltaT; #ifdef _WIN32 // Windows version of precision host timer // Variables that need to retain state between calls static LARGE_INTEGER liOldCount[3] = { {0, 0}, {0, 0}, {0, 0} }; // locals for new count, new freq and new time delta LARGE_INTEGER liNewCount, liFreq; if (QueryPerformanceFrequency(&liFreq)) { // Get new counter reading QueryPerformanceCounter(&liNewCount); if (iCounterID >= 0 && iCounterID <= 2) { // Calculate time difference for timer 0. (zero when called the first time) DeltaT = liOldCount[iCounterID].LowPart ? (((double)liNewCount.QuadPart - (double)liOldCount[iCounterID].QuadPart) / (double)liFreq.QuadPart) : 0.0; // Reset old count to new liOldCount[iCounterID] = liNewCount; } else { // Requested counter ID out of range DeltaT = -9999.0; } // Returns time difference in seconds sunce the last call return DeltaT; } else { // No high resolution performance counter return -9999.0; } #elif defined(UNIX) // Linux version of precision host timer. See http://www.informit.com/articles/article.aspx?p=23618&seqNum=8 static struct timeval _NewTime; // new wall clock time (struct representation in seconds and microseconds) static struct timeval _OldTime[3]; // old wall clock timers 0, 1, 2 (struct representation in seconds and microseconds) // Get new counter reading gettimeofday(&_NewTime, NULL); if (iCounterID >= 0 && iCounterID <= 2) { // Calculate time difference for timer (iCounterID). (zero when called the first time) DeltaT = ((double)_NewTime.tv_sec + 1.0e-6 * (double)_NewTime.tv_usec) - ((double)_OldTime[iCounterID].tv_sec + 1.0e-6 * (double)_OldTime[iCounterID].tv_usec); // Reset old timer (iCounterID) to new timer _OldTime[iCounterID].tv_sec = _NewTime.tv_sec; _OldTime[iCounterID].tv_usec = _NewTime.tv_usec; } else { // Requested counterID is out of rangewith respect to available counters DeltaT = -9999.0; } // Returns time difference in seconds sunce the last call return DeltaT; #elif defined (__APPLE__) || defined (MACOSX) static time_t _NewTime; static time_t _OldTime[3]; _NewTime = clock(); if (iCounterID >= 0 && iCounterID <= 2) { // Calculate time difference for timer (iCounterID). (zero when called the first time) DeltaT = double(_NewTime-_OldTime[iCounterID])/CLOCKS_PER_SEC; // Reset old time (iCounterID) to the new one _OldTime[iCounterID].tv_sec = _NewTime.tv_sec; _OldTime[iCounterID].tv_usec = _NewTime.tv_usec; } else { // Requested counter ID out of range DeltaT = -9999.0; } return DeltaT; #else printf(""shrDeltaT returning early\\n""); #endif } // Optional LogFileName Override function // ********************************************************************* char* cLogFilePathAndName = NULL; void shrSetLogFileName (const char* cOverRideName) { if( cLogFilePathAndName != NULL ) { free(cLogFilePathAndName); } cLogFilePathAndName = (char*) malloc(strlen(cOverRideName) + 1); #ifdef WIN32 strcpy_s(cLogFilePathAndName, strlen(cOverRideName) + 1, cOverRideName); #else strcpy(cLogFilePathAndName, cOverRideName); #endif return; } // Function to log standardized information to console, file or both // ********************************************************************* static int shrLogV(int iLogMode, int iErrNum, const char* cFormatString, va_list vaArgList) { static FILE* pFileStream0 = NULL; static FILE* pFileStream1 = NULL; size_t szNumWritten = 0; char cFileMode [3]; // if the sample log file is closed and the call includes a ""write-to-file"", open file for writing if ((pFileStream0 == NULL) && (iLogMode & LOGFILE)) { // if the default filename has not been overriden, set to default if (cLogFilePathAndName == NULL) { shrSetLogFileName(DEFAULTLOGFILE); } #ifdef _WIN32 // Windows version // set the file mode if (iLogMode & APPENDMODE) // append to prexisting file contents { sprintf_s (cFileMode, 3, ""a+""); } else // replace prexisting file contents { sprintf_s (cFileMode, 3, ""w""); } // open the individual sample log file in the requested mode errno_t err = fopen_s(&pFileStream0, cLogFilePathAndName, cFileMode); // if error on attempt to open, be sure the file is null or close it, then return negative error code if (err != 0) { if (pFileStream0) { fclose (pFileStream0); } iLogMode = LOGCONSOLE; // if we can't open a file, we will still output to the console window } #else // Linux & Mac version // set the file mode if (iLogMode & APPENDMODE) // append to prexisting file contents { sprintf (cFileMode, ""a+""); } else // replace prexisting file contents { sprintf (cFileMode, ""w""); } // open the file in the requested mode if ((pFileStream0 = fopen(cLogFilePathAndName, cFileMode)) == 0) { // if error on attempt to open, be sure the file is null or close it, then return negative error code if (pFileStream0) { fclose (pFileStream0); } iLogMode = LOGCONSOLE; // if we can't open a file, we will still output to the console window } #endif } // if the master log file is closed and the call incudes a ""write-to-file"" and MASTER, open master logfile file for writing if ((pFileStream1 == NULL) && (iLogMode & LOGFILE) && (iLogMode & MASTER)) { #ifdef _WIN32 // Windows version // open the master log file in append mode errno_t err = fopen_s(&pFileStream1, MASTERLOGFILE, ""a+""); // if error on attempt to open, be sure the file is null or close it, then return negative error code if (err != 0) { if (pFileStream1) { fclose (pFileStream1); pFileStream1 = NULL; } iLogMode = LOGCONSOLE; // Force to LOGCONSOLE only since the file stream is invalid // return -err; } #else // Linux & Mac version // open the file in the requested mode if ((pFileStream1 = fopen(MASTERLOGFILE, ""a+"")) == 0) { // if error on attempt to open, be sure the file is null or close it, then return negative error code if (pFileStream1) { fclose (pFileStream1); pFileStream1 = NULL; } iLogMode = LOGCONSOLE; // Force to LOGCONSOLE only since the file stream is invalid // return -1; } #endif // If master log file length has become excessive, empty/reopen if (iLogMode != LOGCONSOLE) { fseek(pFileStream1, 0L, SEEK_END); if (ftell(pFileStream1) > 50000L) { fclose (pFileStream1); #ifdef _WIN32 // Windows version fopen_s(&pFileStream1, MASTERLOGFILE, ""w""); #else pFileStream1 = fopen(MASTERLOGFILE, ""w""); #endif } } } // Handle special Error Message code if (iLogMode & ERRORMSG) { // print string to console if flagged if (iLogMode & LOGCONSOLE) { szNumWritten = printf (""\\n !!! Error # %i at "", iErrNum); // console } // print string to file if flagged if (iLogMode & LOGFILE) { szNumWritten = fprintf (pFileStream0, ""\\n !!! Error # %i at "", iErrNum); // sample log file } } // Vars used for variable argument processing const char* pStr; const char* cArg; int iArg; double dArg; unsigned int uiArg; std::string sFormatSpec; const std::string sFormatChars = "" -+#0123456789.dioufnpcsXxEeGgAa""; const std::string sTypeChars = ""dioufnpcsXxEeGgAa""; char cType = 'c'; // Start at the head of the string and scan to the null at the end for (pStr = cFormatString; *pStr; ++pStr) { // Check if the current character is not a formatting specifier ('%') if (*pStr != '%') { // character is not '%', so print it verbatim to console and/or files as flagged if (iLogMode & LOGCONSOLE) { szNumWritten = putc(*pStr, stdout); // console } if (iLogMode & LOGFILE) { szNumWritten = putc(*pStr, pFileStream0); // sample log file if (iLogMode & MASTER) { szNumWritten = putc(*pStr, pFileStream1); // master log file } } } else { // character is '%', so skip over it and read the full format specifier for the argument ++pStr; sFormatSpec = '%'; // special handling for string of %%%% bool bRepeater = (*pStr == '%'); if (bRepeater) { cType = '%'; } // chars after the '%' are part of format if on list of constants... scan until that isn't true or NULL is found while (pStr && ((sFormatChars.find(*pStr) != string::npos) || bRepeater)) { sFormatSpec += *pStr; // If the char is a type specifier, trap it and stop scanning // (a type specifier char is always the last in the format except for string of %%%) if (sTypeChars.find(*pStr) != string::npos) { cType = *pStr; break; } // Special handling for string of %%% // If a string of %%% was started and then it ends, break (There won't be a typical type specifier) if (bRepeater && (*pStr != '%')) { break; } pStr++; } // Now handle the arg according to type switch (cType) { case '%': // special handling for string of %%%% { if (iLogMode & LOGCONSOLE) { szNumWritten = printf(sFormatSpec.c_str()); // console } if (iLogMode & LOGFILE) { szNumWritten = fprintf (pFileStream0, sFormatSpec.c_str()); // sample log file if (iLogMode & MASTER) { szNumWritten = fprintf(pFileStream1, sFormatSpec.c_str()); // master log file } } continue; } case 'c': // single byte char case 's': // string of single byte chars { // Set cArg as the next value in list and print to console and/or files if flagged cArg = va_arg(vaArgList, char*); if (iLogMode & LOGCONSOLE) { szNumWritten = printf(sFormatSpec.c_str(), cArg); // console } if (iLogMode & LOGFILE) { szNumWritten = fprintf (pFileStream0, sFormatSpec.c_str(), cArg); // sample log file if (iLogMode & MASTER) { szNumWritten = fprintf(pFileStream1, sFormatSpec.c_str(), cArg); // master log file } } continue; } case 'd': // signed decimal integer case 'i': // signed decimal integer { // set iArg as the next value in list and print to console and/or files if flagged iArg = va_arg(vaArgList, int); if (iLogMode & LOGCONSOLE) { szNumWritten = printf(sFormatSpec.c_str(), iArg); // console } if (iLogMode & LOGFILE) { szNumWritten = fprintf (pFileStream0, sFormatSpec.c_str(), iArg); // sample log file if (iLogMode & MASTER) { szNumWritten = fprintf(pFileStream1, sFormatSpec.c_str(), iArg); // master log file } } continue; } case 'u': // unsigned decimal integer case 'o': // unsigned octal integer case 'x': // unsigned hexadecimal integer using ""abcdef"" case 'X': // unsigned hexadecimal integer using ""ABCDEF"" { // set uiArg as the next value in list and print to console and/or files if flagged uiArg = va_arg(vaArgList, unsigned int); if (iLogMode & LOGCONSOLE) { szNumWritten = printf(sFormatSpec.c_str(), uiArg); // console } if (iLogMode & LOGFILE) { szNumWritten = fprintf (pFileStream0, sFormatSpec.c_str(), uiArg); // sample log file if (iLogMode & MASTER) { szNumWritten = fprintf(pFileStream1, sFormatSpec.c_str(), uiArg); // master log file } } continue; } case 'f': // float/double case 'e': // scientific double/float case 'E': // scientific double/float case 'g': // scientific double/float case 'G': // scientific double/float case 'a': // signed hexadecimal double precision float case 'A': // signed hexadecimal double precision float { // set dArg as the next value in list and print to console and/or files if flagged dArg = va_arg(vaArgList, double); if (iLogMode & LOGCONSOLE) { szNumWritten = printf(sFormatSpec.c_str(), dArg); // console } if (iLogMode & LOGFILE) { szNumWritten = fprintf (pFileStream0, sFormatSpec.c_str(), dArg); // sample log file if (iLogMode & MASTER) { szNumWritten = fprintf(pFileStream1, sFormatSpec.c_str(), dArg); // master log file } } continue; } default: { // print arg of unknown/unsupported type to console and/or file if flagged if (iLogMode & LOGCONSOLE) // console { szNumWritten = putc(*pStr, stdout); } if (iLogMode & LOGFILE) { szNumWritten = putc(*pStr, pFileStream0); // sample log file if (iLogMode & MASTER) { szNumWritten = putc(*pStr, pFileStream1); // master log file } } } } } } // end the sample log with a horizontal line if closing if (iLogMode & CLOSELOG) { if (iLogMode & LOGCONSOLE) { printf(HDASHLINE); } if (iLogMode & LOGFILE) { fprintf(pFileStream0, HDASHLINE); } } // flush console and/or file buffers if updated if (iLogMode & LOGCONSOLE) { fflush(stdout); } if (iLogMode & LOGFILE) { fflush (pFileStream0); // if the master log file has been updated, flush it too if (iLogMode & MASTER) { fflush (pFileStream1); } } // If the log file is open and the caller requests ""close file"", then close and NULL file handle if ((pFileStream0) && (iLogMode & CLOSELOG)) { fclose (pFileStream0); pFileStream0 = NULL; } if ((pFileStream1) && (iLogMode & CLOSELOG)) { fclose (pFileStream1); pFileStream1 = NULL; } // return error code or OK if (iLogMode & ERRORMSG) { return iErrNum; } else { return 0; } } // Function to log standardized information to console, file or both // ********************************************************************* int shrLogEx(int iLogMode = LOGCONSOLE, int iErrNum = 0, const char* cFormatString = """", ...) { va_list vaArgList; // Prepare variable agument list va_start(vaArgList, cFormatString); int ret = shrLogV(iLogMode, iErrNum, cFormatString, vaArgList); // end variable argument handler va_end(vaArgList); return ret; } // Function to log standardized information to console, file or both // ********************************************************************* int shrLog(const char* cFormatString = """", ...) { va_list vaArgList; // Prepare variable agument list va_start(vaArgList, cFormatString); int ret = shrLogV(LOGBOTH, 0, cFormatString, vaArgList); // end variable argument handler va_end(vaArgList); return ret; } ////////////////////////////////////////////////////////////////////////////// //! Find the path for a file assuming that //! files are found in the searchPath. //! //! @return the path if succeeded, otherwise 0 //! @param filename name of the file //! @param executable_path optional absolute path of the executable ////////////////////////////////////////////////////////////////////////////// char* shrFindFilePath(const char* filename, const char* executable_path) { // defines a variable that is replaced with the name of the executable // Typical relative search paths to locate needed companion files (e.g. sample input data, or JIT source files) // The origin for the relative search may be the .exe file, a .bat file launching an .exe, a browser .exe launching the .exe or .bat, etc const char* searchPath[] = { ""./"", // same dir ""./data/"", // ""/data/"" subdir ""./src/"", // ""/src/"" subdir ""./src//data/"", // ""/src//data/"" subdir ""./inc/"", // ""/inc/"" subdir ""../"", // up 1 in tree ""../data/"", // up 1 in tree, ""/data/"" subdir ""../src/"", // up 1 in tree, ""/src/"" subdir ""../inc/"", // up 1 in tree, ""/inc/"" subdir ""../OpenCL/src//"", // up 1 in tree, ""/OpenCL/src//"" subdir ""../OpenCL/src//data/"", // up 1 in tree, ""/OpenCL/src//data/"" subdir ""../OpenCL/src//src/"", // up 1 in tree, ""/OpenCL/src//src/"" subdir ""../OpenCL/src//inc/"", // up 1 in tree, ""/OpenCL/src//inc/"" subdir ""../C/src//"", // up 1 in tree, ""/C/src//"" subdir ""../C/src//data/"", // up 1 in tree, ""/C/src//data/"" subdir ""../C/src//src/"", // up 1 in tree, ""/C/src//src/"" subdir ""../C/src//inc/"", // up 1 in tree, ""/C/src//inc/"" subdir ""../DirectCompute/src//"", // up 1 in tree, ""/DirectCompute/src//"" subdir ""../DirectCompute/src//data/"", // up 1 in tree, ""/DirectCompute/src//data/"" subdir ""../DirectCompute/src//src/"", // up 1 in tree, ""/DirectCompute/src//src/"" subdir ""../DirectCompute/src//inc/"", // up 1 in tree, ""/DirectCompute/src//inc/"" subdir ""../../"", // up 2 in tree ""../../data/"", // up 2 in tree, ""/data/"" subdir ""../../src/"", // up 2 in tree, ""/src/"" subdir ""../../inc/"", // up 2 in tree, ""/inc/"" subdir ""../../../"", // up 3 in tree ""../../../src//"", // up 3 in tree, ""/src//"" subdir ""../../../src//data/"", // up 3 in tree, ""/src//data/"" subdir ""../../../src//src/"", // up 3 in tree, ""/src//src/"" subdir ""../../../src//inc/"", // up 3 in tree, ""/src//inc/"" subdir ""../../../sandbox//"", // up 3 in tree, ""/sandbox//"" subdir ""../../../sandbox//data/"", // up 3 in tree, ""/sandbox//data/"" subdir ""../../../sandbox//src/"", // up 3 in tree, ""/sandbox//src/"" subdir ""../../../sandbox//inc/"" // up 3 in tree, ""/sandbox//inc/"" subdir }; // Extract the executable name std::string executable_name; if (executable_path != 0) { executable_name = std::string(executable_path); #ifdef _WIN32 // Windows path delimiter size_t delimiter_pos = executable_name.find_last_of('\\\\'); executable_name.erase(0, delimiter_pos + 1); if (executable_name.rfind("".exe"") != string::npos) { // we strip .exe, only if the .exe is found executable_name.resize(executable_name.size() - 4); } #else // Linux & OSX path delimiter size_t delimiter_pos = executable_name.find_last_of('/'); executable_name.erase(0,delimiter_pos+1); #endif } // Loop over all search paths and return the first hit for( unsigned int i = 0; i < sizeof(searchPath)/sizeof(char*); ++i ) { std::string path(searchPath[i]); size_t executable_name_pos = path.find(""""); // If there is executable_name variable in the searchPath // replace it with the value if(executable_name_pos != std::string::npos) { if(executable_path != 0) { path.replace(executable_name_pos, strlen(""""), executable_name); } else { // Skip this path entry if no executable argument is given continue; } } // Test if the file exists path.append(filename); std::fstream fh(path.c_str(), std::fstream::in); if (fh.good()) { // File found // returning an allocated array here for backwards compatibility reasons char* file_path = (char*) malloc(path.length() + 1); #ifdef _WIN32 strcpy_s(file_path, path.length() + 1, path.c_str()); #else strcpy(file_path, path.c_str()); #endif return file_path; } } // File not found return 0; } ////////////////////////////////////////////////////////////////////////////// //! Read file \\filename and return the data //! @return shrTRUE if reading the file succeeded, otherwise shrFALSE //! @param filename name of the source file //! @param data uninitialized pointer, returned initialized and pointing to //! the data read //! @param len number of data elements in data, -1 on error ////////////////////////////////////////////////////////////////////////////// template shrBOOL shrReadFile( const char* filename, T** data, unsigned int* len, bool verbose) { // check input arguments ARGCHECK(NULL != filename); ARGCHECK(NULL != len); // intermediate storage for the data read std::vector data_read; // open file for reading std::fstream fh( filename, std::fstream::in); // check if filestream is valid if(!fh.good()) { if (verbose) std::cerr << ""shrReadFile() : Opening file failed."" << std::endl; return shrFALSE; } // read all data elements T token; while( fh.good()) { fh >> token; data_read.push_back( token); } // the last element is read twice data_read.pop_back(); // check if reading result is consistent if( ! fh.eof()) { if (verbose) std::cerr << ""WARNING : readData() : reading file might have failed."" << std::endl; } fh.close(); // check if the given handle is already initialized if( NULL != *data) { if( *len != data_read.size()) { std::cerr << ""shrReadFile() : Initialized memory given but "" << ""size mismatch with signal read "" << ""(data read / data init = "" << (unsigned int)data_read.size() << "" / "" << *len << "")"" << std::endl; return shrFALSE; } } else { // allocate storage for the data read *data = (T*) malloc( sizeof(T) * data_read.size()); // store signal size *len = static_cast( data_read.size()); } // copy data memcpy( *data, &data_read.front(), sizeof(T) * data_read.size()); return shrTRUE; } ////////////////////////////////////////////////////////////////////////////// //! Write a data file \\filename //! @return shrTRUE if writing the file succeeded, otherwise shrFALSE //! @param filename name of the source file //! @param data data to write //! @param len number of data elements in data, -1 on error //! @param epsilon epsilon for comparison ////////////////////////////////////////////////////////////////////////////// template shrBOOL shrWriteFile( const char* filename, const T* data, unsigned int len, const T epsilon, bool verbose) { ARGCHECK(NULL != filename); ARGCHECK(NULL != data); // open file for writing std::fstream fh( filename, std::fstream::out); // check if filestream is valid if(!fh.good()) { if (verbose) std::cerr << ""shrWriteFile() : Opening file failed."" << std::endl; return shrFALSE; } // first write epsilon fh << ""# "" << epsilon << ""\\n""; // write data for( unsigned int i = 0; (i < len) && (fh.good()); ++i) { fh << data[i] << ' '; } // Check if writing succeeded if( ! fh.good()) { if (verbose) std::cerr << ""shrWriteFile() : Writing file failed."" << std::endl; return shrFALSE; } // file ends with nl fh << std::endl; return shrTRUE; } //////////////////////////////////////////////////////////////////////////////// //! Read file \\filename containg single precision floating point data //! @return shrTRUEif reading the file succeeded, otherwise shrFALSE //! @param filename name of the source file //! @param data uninitialized pointer, returned initialized and pointing to //! the data read //! @param len number of data elements in data, -1 on error //////////////////////////////////////////////////////////////////////////////// shrBOOL shrReadFilef( const char* filename, float** data, unsigned int* len, bool verbose) { return shrReadFile( filename, data, len, verbose); } //////////////////////////////////////////////////////////////////////////////// //! Read file \\filename containg double precision floating point data //! @return shrTRUEif reading the file succeeded, otherwise shrFALSE //! @param filename name of the source file //! @param data uninitialized pointer, returned initialized and pointing to //! the data read //! @param len number of data elements in data, -1 on error //////////////////////////////////////////////////////////////////////////////// shrBOOL shrReadFiled( const char* filename, double** data, unsigned int* len, bool verbose) { return shrReadFile( filename, data, len, verbose); } //////////////////////////////////////////////////////////////////////////////// //! Read file \\filename containg integer data //! @return shrTRUEif reading the file succeeded, otherwise shrFALSE //! @param filename name of the source file //! @param data uninitialized pointer, returned initialized and pointing to //! the data read //! @param len number of data elements in data, -1 on error //////////////////////////////////////////////////////////////////////////////// shrBOOL shrReadFilei( const char* filename, int** data, unsigned int* len, bool verbose) { return shrReadFile( filename, data, len, verbose); } //////////////////////////////////////////////////////////////////////////////// //! Read file \\filename containg unsigned integer data //! @return shrTRUEif reading the file succeeded, otherwise shrFALSE //! @param filename name of the source file //! @param data uninitialized pointer, returned initialized and pointing to //! the data read //! @param len number of data elements in data, -1 on error //////////////////////////////////////////////////////////////////////////////// shrBOOL shrReadFileui( const char* filename, unsigned int** data, unsigned int* len, bool verbose) { return shrReadFile( filename, data, len, verbose); } //////////////////////////////////////////////////////////////////////////////// //! Read file \\filename containg char / byte data //! @return shrTRUEif reading the file succeeded, otherwise shrFALSE //! @param filename name of the source file //! @param data uninitialized pointer, returned initialized and pointing to //! the data read //! @param len number of data elements in data, -1 on error //////////////////////////////////////////////////////////////////////////////// shrBOOL shrReadFileb( const char* filename, char** data, unsigned int* len, bool verbose) { return shrReadFile( filename, data, len, verbose); } //////////////////////////////////////////////////////////////////////////////// //! Read file \\filename containg unsigned char / byte data //! @return shrTRUEif reading the file succeeded, otherwise shrFALSE //! @param filename name of the source file //! @param data uninitialized pointer, returned initialized and pointing to //! the data read //! @param len number of data elements in data, -1 on error //////////////////////////////////////////////////////////////////////////////// shrBOOL shrReadFileub( const char* filename, unsigned char** data, unsigned int* len, bool verbose) { return shrReadFile( filename, data, len, verbose); } //////////////////////////////////////////////////////////////////////////////// //! Write a data file \\filename for single precision floating point data //! @return shrTRUEif writing the file succeeded, otherwise shrFALSE //! @param filename name of the source file //! @param data data to write //! @param len number of data elements in data, -1 on error //! @param epsilon epsilon for comparison //////////////////////////////////////////////////////////////////////////////// shrBOOL shrWriteFilef( const char* filename, const float* data, unsigned int len, const float epsilon, bool verbose) { return shrWriteFile( filename, data, len, epsilon, verbose); } //////////////////////////////////////////////////////////////////////////////// //! Write a data file \\filename for double precision floating point data //! @return shrTRUEif writing the file succeeded, otherwise shrFALSE //! @param filename name of the source file //! @param data data to write //! @param len number of data elements in data, -1 on error //! @param epsilon epsilon for comparison //////////////////////////////////////////////////////////////////////////////// shrBOOL shrWriteFiled( const char* filename, const double* data, unsigned int len, const double epsilon, bool verbose) { return shrWriteFile( filename, data, len, epsilon, verbose); } //////////////////////////////////////////////////////////////////////////////// //! Write a data file \\filename for integer data //! @return shrTRUEif writing the file succeeded, otherwise shrFALSE //! @param filename name of the source file //! @param data data to write //! @param len number of data elements in data, -1 on error //! @param epsilon epsilon for comparison //////////////////////////////////////////////////////////////////////////////// shrBOOL shrWriteFilei( const char* filename, const int* data, unsigned int len, bool verbose) { return shrWriteFile( filename, data, len, 0, verbose); } //////////////////////////////////////////////////////////////////////////////// //! Write a data file \\filename for unsigned integer data //! @return shrTRUEif writing the file succeeded, otherwise shrFALSE //! @param filename name of the source file //! @param data data to write //! @param len number of data elements in data, -1 on error //! @param epsilon epsilon for comparison //////////////////////////////////////////////////////////////////////////////// shrBOOL shrWriteFileui( const char* filename,const unsigned int* data,unsigned int len, bool verbose) { return shrWriteFile( filename, data, len, static_cast(0), verbose); } //////////////////////////////////////////////////////////////////////////////// //! Write a data file \\filename for byte / char data //! @return shrTRUEif writing the file succeeded, otherwise shrFALSE //! @param filename name of the source file //! @param data data to write //! @param len number of data elements in data, -1 on error //! @param epsilon epsilon for comparison //////////////////////////////////////////////////////////////////////////////// shrBOOL shrWriteFileb( const char* filename, const char* data, unsigned int len, bool verbose) { return shrWriteFile( filename, data, len, static_cast(0), verbose); } //////////////////////////////////////////////////////////////////////////////// //! Write a data file \\filename for byte / char data //! @return shrTRUEif writing the file succeeded, otherwise shrFALSE //! @param filename name of the source file //! @param data data to write //! @param len number of data elements in data, -1 on error //! @param epsilon epsilon for comparison //////////////////////////////////////////////////////////////////////////////// shrBOOL shrWriteFileub( const char* filename, const unsigned char* data, unsigned int len, bool verbose) { return shrWriteFile( filename, data, len, static_cast(0), verbose); } //////////////////////////////////////////////////////////////////////////////// //! Write a data file \\filename for unsigned byte / char data //! @return shrTRUEif writing the file succeeded, otherwise shrFALSE //! @param filename name of the source file //! @param data data to write //! @param len number of data elements in data, -1 on error //! @param epsilon epsilon for comparison //////////////////////////////////////////////////////////////////////////////// shrBOOL shrWriteFileb( const char* filename,const unsigned char* data,unsigned int len, bool verbose) { return shrWriteFile( filename, data, len, static_cast(0), verbose); } ////////////////////////////////////////////////////////////////////////////// //! Load PGM or PPM file //! @note if data == NULL then the necessary memory is allocated in the //! function and w and h are initialized to the size of the image //! @return shrTRUE if the file loading succeeded, otherwise shrFALSE //! @param file name of the file to load //! @param data handle to the memory for the image file data //! @param w width of the image //! @param h height of the image //! @param channels number of channels in image ////////////////////////////////////////////////////////////////////////////// shrBOOL loadPPM(const char* file, unsigned char** data, unsigned int *w, unsigned int *h, unsigned int *channels) { FILE* fp = 0; #ifdef _WIN32 // open the file for binary read errno_t err; if ((err = fopen_s(&fp, file, ""rb"")) != 0) #else // open the file for binary read if ((fp = fopen(file, ""rb"")) == 0) #endif { // if error on attempt to open, be sure the file is null or close it, then return negative error code if (fp) { fclose (fp); } std::cerr << ""loadPPM() : Failed to open file: "" << file << std::endl; return shrFALSE; } // check header char header[PGMHeaderSize]; if ((fgets( header, PGMHeaderSize, fp) == NULL) && ferror(fp)) { if (fp) { fclose (fp); } std::cerr << ""loadPPM() : File is not a valid PPM or PGM image"" << std::endl; *channels = 0; return shrFALSE; } if (strncmp(header, ""P5"", 2) == 0) { *channels = 1; } else if (strncmp(header, ""P6"", 2) == 0) { *channels = 3; } else { std::cerr << ""loadPPM() : File is not a PPM or PGM image"" << std::endl; *channels = 0; return shrFALSE; } // parse header, read maxval, width and height unsigned int width = 0; unsigned int height = 0; unsigned int maxval = 0; unsigned int i = 0; while(i < 3) { if ((fgets(header, PGMHeaderSize, fp) == NULL) && ferror(fp)) { if (fp) { fclose (fp); } std::cerr << ""loadPPM() : File is not a valid PPM or PGM image"" << std::endl; return shrFALSE; } if(header[0] == '#') continue; #ifdef _WIN32 if(i == 0) { i += sscanf_s(header, ""%u %u %u"", &width, &height, &maxval); } else if (i == 1) { i += sscanf_s(header, ""%u %u"", &height, &maxval); } else if (i == 2) { i += sscanf_s(header, ""%u"", &maxval); } #else if(i == 0) { i += sscanf(header, ""%u %u %u"", &width, &height, &maxval); } else if (i == 1) { i += sscanf(header, ""%u %u"", &height, &maxval); } else if (i == 2) { i += sscanf(header, ""%u"", &maxval); } #endif } // check if given handle for the data is initialized if(NULL != *data) { if (*w != width || *h != height) { fclose(fp); std::cerr << ""loadPPM() : Invalid image dimensions."" << std::endl; return shrFALSE; } } else { *data = (unsigned char*)malloc( sizeof(unsigned char) * width * height * *channels); *w = width; *h = height; } // read and close file if (fread(*data, sizeof(unsigned char), width * height * *channels, fp) != width * height * *channels) { fclose(fp); std::cerr << ""loadPPM() : Invalid image."" << std::endl; return shrFALSE; } fclose(fp); return shrTRUE; } ////////////////////////////////////////////////////////////////////////////// //! Write / Save PPM or PGM file //! @note Internal usage only //! @param file name of the image file //! @param data handle to the data read //! @param w width of the image //! @param h height of the image ////////////////////////////////////////////////////////////////////////////// shrBOOL savePPM( const char* file, unsigned char *data, unsigned int w, unsigned int h, unsigned int channels) { ARGCHECK(NULL != data); ARGCHECK(w > 0); ARGCHECK(h > 0); std::fstream fh( file, std::fstream::out | std::fstream::binary ); if( fh.bad()) { std::cerr << ""savePPM() : Opening file failed."" << std::endl; return shrFALSE; } if (channels == 1) { fh << ""P5\\n""; } else if (channels == 3) { fh << ""P6\\n""; } else { std::cerr << ""savePPM() : Invalid number of channels."" << std::endl; return shrFALSE; } fh << w << ""\\n"" << h << ""\\n"" << 0xff << std::endl; for( unsigned int i = 0; (i < (w*h*channels)) && fh.good(); ++i) { fh << data[i]; } fh.flush(); if( fh.bad()) { std::cerr << ""savePPM() : Writing data failed."" << std::endl; return shrFALSE; } fh.close(); return shrTRUE; } //////////////////////////////////////////////////////////////////////////////// //! Load PPM image file (with unsigned char as data element type), padding 4th component //! @return shrTrue if reading the file succeeded, otherwise shrFALSE //! @param file name of the image file //! @param data handle to the data read //! @param w width of the image //! @param h height of the image //////////////////////////////////////////////////////////////////////////////// shrBOOL shrLoadPPM4ub( const char* file, unsigned char** OutData, unsigned int *w, unsigned int *h) { // Load file data into a temporary buffer with automatic allocation unsigned char* cLocalData = 0; unsigned int channels; shrBOOL bLoadOK = loadPPM(file, &cLocalData, w, h, &channels); // this allocates cLocalData, which must be freed later // If the data loaded OK from file to temporary buffer, then go ahead with padding and transfer if (shrTRUE == bLoadOK) { // if the receiving buffer is null, allocate it... caller must free this int size = *w * *h; if (*OutData == NULL) { *OutData = (unsigned char*)malloc(sizeof(unsigned char) * size * 4); } // temp pointers for incrementing unsigned char* cTemp = cLocalData; unsigned char* cOutPtr = *OutData; // transfer data, padding 4th element for(int i=0; i( arg_name); if( NULL != v) { // assign value *val = *v; ret_val = shrTRUE; } else { // fail safe val = NULL; } } catch( const std::exception& /*ex*/) { std::cerr << ""Error when parsing command line argument string."" << std::endl; } return ret_val; } //////////////////////////////////////////////////////////////////////////////// //! Get the value of a command line argument of type unsigned int //! @return shrTRUE if command line argument \\a arg_name has been given and //! is of the requested type, otherwise shrFALSE //! @param argc argc as passed to main() //! @param argv argv as passed to main() //! @param arg_name name of the command line argument //! @param val value of the command line argument //////////////////////////////////////////////////////////////////////////////// shrBOOL shrGetCmdLineArgumentu( const int argc, const char** argv, const char* arg_name, unsigned int* val) { shrBOOL ret_val = shrFALSE; try { // initialize CmdArgReader::init( argc, argv); // access argument const int* v = CmdArgReader::getArg( arg_name); if( NULL != v) { // assign value *val = *v; ret_val = shrTRUE; } else { // fail safe val = NULL; } } catch( const std::exception& /*ex*/) { std::cerr << ""Error when parsing command line argument string."" << std::endl; } return ret_val; } //////////////////////////////////////////////////////////////////////////////// //! Get the value of a command line argument of type float //! @return shrTRUE if command line argument \\a arg_name has been given and //! is of the requested type, otherwise shrFALSE //! @param argc argc as passed to main() //! @param argv argv as passed to main() //! @param arg_name name of the command line argument //! @param val value of the command line argument //////////////////////////////////////////////////////////////////////////////// shrBOOL shrGetCmdLineArgumentf( const int argc, const char** argv, const char* arg_name, float* val) { shrBOOL ret_val = shrFALSE; try { // initialize CmdArgReader::init( argc, argv); // access argument const float* v = CmdArgReader::getArg( arg_name); if( NULL != v) { // assign value *val = *v; ret_val = shrTRUE; } else { // fail safe val = NULL; } } catch( const std::exception& /*ex*/) { std::cerr << ""Error when parsing command line argument string."" << std::endl; } return ret_val; } //////////////////////////////////////////////////////////////////////////////// //! Get the value of a command line argument of type string //! @return shrTRUE if command line argument \\a arg_name has been given and //! is of the requested type, otherwise shrFALSE //! @param argc argc as passed to main() //! @param argv argv as passed to main() //! @param arg_name name of the command line argument //! @param val value of the command line argument //////////////////////////////////////////////////////////////////////////////// shrBOOL shrGetCmdLineArgumentstr( const int argc, const char** argv, const char* arg_name, char** val) { shrBOOL ret_val = shrFALSE; try { // initialize CmdArgReader::init( argc, argv); // access argument const std::string* v = CmdArgReader::getArg( arg_name); if( NULL != v) { // allocate memory for the string *val = (char*)malloc(sizeof(char) * (v->length() + 1)); // copy from string to c_str #ifdef WIN32 strcpy_s(*val, v->length() + 1, v->c_str()); #else strcpy(*val, v->c_str()); #endif ret_val = shrTRUE; } else { // fail safe *val = NULL; } } catch( const std::exception& /*ex*/) { std::cerr << ""Error when parsing command line argument string.""<< std::endl; } return ret_val; } ////////////////////////////////////////////////////////////////////////////// //! Compare two arrays of arbitrary type //! @return shrTRUE if \\a reference and \\a data are identical, otherwise shrFALSE //! @param reference handle to the reference data / gold image //! @param data handle to the computed data //! @param len number of elements in reference and data //! @param epsilon epsilon to use for the comparison ////////////////////////////////////////////////////////////////////////////// template shrBOOL compareData( const T* reference, const T* data, const unsigned int len, const S epsilon, const float threshold) { ARGCHECK( epsilon >= 0); bool result = true; unsigned int error_count = 0; for( unsigned int i = 0; i < len; ++i) { T diff = reference[i] - data[i]; bool comp = (diff <= epsilon) && (diff >= -epsilon); result &= comp; error_count += !comp; #ifdef _DEBUG if( ! comp) { std::cerr << ""ERROR, i = "" << i << "",\\t "" << reference[i] << "" / "" << data[i] << "" (reference / data)\\n""; } #endif } if (threshold == 0.0f) { return (result) ? shrTRUE : shrFALSE; } else { return (len*threshold > error_count) ? shrTRUE : shrFALSE; } } ////////////////////////////////////////////////////////////////////////////// //! Compare two arrays of arbitrary type //! @return shrTRUE if \\a reference and \\a data are identical, otherwise shrFALSE //! @param reference handle to the reference data / gold image //! @param data handle to the computed data //! @param len number of elements in reference and data //! @param epsilon epsilon to use for the comparison ////////////////////////////////////////////////////////////////////////////// template shrBOOL compareDataAsFloat( const T* reference, const T* data, const unsigned int len, const S epsilon) { ARGCHECK(epsilon >= 0); // If we set epsilon to be 0, let's set a minimum threshold float max_error = MAX( (float)epsilon, MIN_EPSILON_ERROR ); int error_count = 0; bool result = true; for( unsigned int i = 0; i < len; ++i) { float diff = fabs((float)reference[i] - (float)data[i]); bool comp = (diff < max_error); result &= comp; if( ! comp) { error_count++; #ifdef _DEBUG if (error_count < 50) { shrLog(""\\n ERROR(epsilon=%4.3f), i=%d, (ref)0x%02x / (data)0x%02x / (diff)%d\\n"", max_error, i, reference[i], data[i], (unsigned int)diff); } #endif } } if (error_count) { shrLog(""\\n Total # of errors = %d\\n"", error_count); } return (error_count == 0) ? shrTRUE : shrFALSE; } ////////////////////////////////////////////////////////////////////////////// //! Compare two arrays of arbitrary type //! @return shrTRUE if \\a reference and \\a data are identical, otherwise shrFALSE //! @param reference handle to the reference data / gold image //! @param data handle to the computed data //! @param len number of elements in reference and data //! @param epsilon epsilon to use for the comparison //! @param epsilon threshold % of (# of bytes) for pass/fail ////////////////////////////////////////////////////////////////////////////// template shrBOOL compareDataAsFloatThreshold( const T* reference, const T* data, const unsigned int len, const S epsilon, const float threshold) { ARGCHECK(epsilon >= 0); // If we set epsilon to be 0, let's set a minimum threshold float max_error = MAX( (float)epsilon, MIN_EPSILON_ERROR); int error_count = 0; bool result = true; for( unsigned int i = 0; i < len; ++i) { float diff = fabs((float)reference[i] - (float)data[i]); bool comp = (diff < max_error); result &= comp; if( ! comp) { error_count++; #ifdef _DEBUG if (error_count < 50) { shrLog(""\\n ERROR(epsilon=%4.3f), i=%d, (ref)0x%02x / (data)0x%02x / (diff)%d\\n"", max_error, i, reference[i], data[i], (unsigned int)diff); } #endif } } if (threshold == 0.0f) { if (error_count) { shrLog(""\\n Total # of errors = %d\\n"", error_count); } return (error_count == 0) ? shrTRUE : shrFALSE; } else { if (error_count) { shrLog(""\\n %.2f(%%) of bytes mismatched (count=%d)\\n"", (float)error_count*100/(float)len, error_count); } return ((len*threshold > error_count) ? shrTRUE : shrFALSE); } } //////////////////////////////////////////////////////////////////////////////// //! Compare two float arrays //! @return shrTRUE if \\a reference and \\a data are identical, otherwise shrFALSE //! @param reference handle to the reference data / gold image //! @param data handle to the computed data //! @param len number of elements in reference and data //////////////////////////////////////////////////////////////////////////////// shrBOOL shrComparef( const float* reference, const float* data, const unsigned int len ) { const float epsilon = 0.0; return compareData( reference, data, len, epsilon, 0.0f ); } //////////////////////////////////////////////////////////////////////////////// //! Compare two integer arrays //! @return shrTRUE if \\a reference and \\a data are identical, otherwise shrFALSE //! @param reference handle to the reference data / gold image //! @param data handle to the computed data //! @param len number of elements in reference and data //////////////////////////////////////////////////////////////////////////////// shrBOOL shrComparei( const int* reference, const int* data, const unsigned int len ) { const int epsilon = 0; return compareData( reference, data, len, epsilon, 0.0f); } //////////////////////////////////////////////////////////////////////////////// //! Compare two unsigned integer arrays, with epsilon and threshold //! @return shrTRUE if \\a reference and \\a data are identical, otherwise shrFALSE //! @param reference handle to the reference data / gold image //! @param data handle to the computed data //! @param len number of elements in reference and data //////////////////////////////////////////////////////////////////////////////// shrBOOL shrCompareuit( const unsigned int* reference, const unsigned int* data, const unsigned int len, const float epsilon, const float threshold ) { return compareDataAsFloatThreshold( reference, data, len, epsilon, threshold ); } //////////////////////////////////////////////////////////////////////////////// //! Compare two integer arrays //! @return shrTRUE if \\a reference and \\a data are identical, otherwise shrFALSE //! @param reference handle to the reference data / gold image //! @param data handle to the computed data //! @param len number of elements in reference and data //////////////////////////////////////////////////////////////////////////////// shrBOOL shrCompareub( const unsigned char* reference, const unsigned char* data, const unsigned int len ) { const int epsilon = 0; return compareData( reference, data, len, epsilon, 0.0f); } //////////////////////////////////////////////////////////////////////////////// //! Compare two integer arrays (inc Threshold for # of pixel we can have errors) //! @return shrTRUE if \\a reference and \\a data are identical, otherwise shrFALSE //! @param reference handle to the reference data / gold image //! @param data handle to the computed data //! @param len number of elements in reference and data //////////////////////////////////////////////////////////////////////////////// shrBOOL shrCompareubt( const unsigned char* reference, const unsigned char* data, const unsigned int len, const float epsilon, const float threshold ) { return compareDataAsFloatThreshold( reference, data, len, epsilon, threshold ); } //////////////////////////////////////////////////////////////////////////////// //! Compare two integer arrays //! @return shrTRUE if \\a reference and \\a data are identical, //! otherwise shrFALSE //! @param reference handle to the reference data / gold image //! @param data handle to the computed data //! @param len number of elements in reference and data //////////////////////////////////////////////////////////////////////////////// shrBOOL shrCompareube( const unsigned char* reference, const unsigned char* data, const unsigned int len, const float epsilon ) { return compareDataAsFloat( reference, data, len, epsilon ); } //////////////////////////////////////////////////////////////////////////////// //! Compare two float arrays with an epsilon tolerance for equality //! @return shrTRUE if \\a reference and \\a data are identical, otherwise shrFALSE //! @param reference handle to the reference data / gold image //! @param data handle to the computed data //! @param len number of elements in reference and data //! @param epsilon epsilon to use for the comparison //////////////////////////////////////////////////////////////////////////////// shrBOOL shrComparefe( const float* reference, const float* data, const unsigned int len, const float epsilon ) { return compareData( reference, data, len, epsilon, 0.0f); } //////////////////////////////////////////////////////////////////////////////// //! Compare two float arrays with an epsilon tolerance for equality and a //! threshold for # pixel errors //! @return shrTRUE if \\a reference and \\a data are identical, otherwise shrFALSE //! @param reference handle to the reference data / gold image //! @param data handle to the computed data //! @param len number of elements in reference and data //! @param epsilon epsilon to use for the comparison //////////////////////////////////////////////////////////////////////////////// shrBOOL shrComparefet( const float* reference, const float* data, const unsigned int len, const float epsilon, const float threshold ) { return compareDataAsFloatThreshold( reference, data, len, epsilon, threshold ); } //////////////////////////////////////////////////////////////////////////////// //! Compare two float arrays using L2-norm with an epsilon tolerance for equality //! @return shrTRUE if \\a reference and \\a data are identical, otherwise shrFALSE //! @param reference handle to the reference data / gold image //! @param data handle to the computed data //! @param len number of elements in reference and data //! @param epsilon epsilon to use for the comparison //////////////////////////////////////////////////////////////////////////////// shrBOOL shrCompareL2fe( const float* reference, const float* data, const unsigned int len, const float epsilon ) { ARGCHECK(epsilon >= 0); float error = 0; float ref = 0; for( unsigned int i = 0; i < len; ++i) { float diff = reference[i] - data[i]; error += diff * diff; ref += reference[i] * reference[i]; } float normRef = sqrtf(ref); if (fabs(ref) < 1e-7) { #ifdef _DEBUG std::cerr << ""ERROR, reference l2-norm is 0\\n""; #endif return shrFALSE; } float normError = sqrtf(error); error = normError / normRef; bool result = error < epsilon; #ifdef _DEBUG if( ! result) { std::cerr << ""ERROR, l2-norm error "" << error << "" is greater than epsilon "" << epsilon << ""\\n""; } #endif return result ? shrTRUE : shrFALSE; } //////////////////////////////////////////////////////////////////////////////// //! Compare two PPM image files with an epsilon tolerance for equality //! @return shrTRUE if \\a reference and \\a data are identical, otherwise shrFALSE //! @param src_file filename for the image to be compared //! @param data filename for the reference data / gold image //! @param epsilon epsilon to use for the comparison //! @param threshold threshold of pixels that can still mismatch to pass (i.e. 0.15f = 15% must pass) //! @param verboseErrors output details of image mismatch to std::cerr //////////////////////////////////////////////////////////////////////////////// shrBOOL shrComparePPM( const char *src_file, const char *ref_file, const float epsilon, const float threshold) { unsigned char* src_data = NULL; unsigned char* ref_data = NULL; unsigned long error_count = 0; unsigned int ref_width, ref_height; unsigned int src_width, src_height; // Check sample and reference file pointers if (src_file == NULL || ref_file == NULL) { shrLog(""\\n> shrComparePGM: src_file or ref_file is NULL\\n Aborting comparison !!!\\n\\n""); return shrFALSE; } shrLog(""\\n> shrComparePPM:\\n (a)rendered: <%s>\\n (b)reference: <%s>\\n"", src_file, ref_file); // Load the ref image file if (shrLoadPPM4ub(ref_file, &ref_data, &ref_width, &ref_height) != shrTRUE) { shrLog(""\\n Unable to load ref image file: %s\\n Aborting comparison !!!\\n\\n"", ref_file); return shrFALSE; } // Load the sample image file if (shrLoadPPM4ub(src_file, &src_data, &src_width, &src_height) != shrTRUE) { shrLog(""\\n Unable to load src image file: %s\\n Aborting comparison !!!\\n\\n"", src_file); return shrFALSE; } // check to see if image dimensions match if(src_height != ref_height || src_width != ref_width) { shrLog(""\\n Source and ref size mismatch (%u x %u) vs (%u x %u)\\n Aborting Comparison !!!\\n\\n "", src_width, src_height, ref_width, ref_height); return shrFALSE; } // compare the images if (shrCompareubt(ref_data, src_data, src_width*src_height*4, epsilon, threshold ) == shrFALSE) { error_count=1; } shrLog("" Images %s\\n\\n"", (error_count == 0) ? ""Match"" : ""Don't Match !!!""); return (error_count == 0) ? shrTRUE : shrFALSE; // returns true if all pixels pass } //////////////////////////////////////////////////////////////////////////////// //! Compare two PGM image files with an epsilon tolerance for equality //! @return shrTRUE if \\a reference and \\a data are identical, otherwise shrFALSE //! @param src_file filename for the image to be compared //! @param data filename for the reference data / gold image //! @param epsilon epsilon to use for the comparison //! @param threshold threshold of pixels that can still mismatch to pass (i.e. 0.15f = 15% must pass) //////////////////////////////////////////////////////////////////////////////// shrBOOL shrComparePGM( const char *src_file, const char *ref_file, const float epsilon, const float threshold) { unsigned char* src_data = NULL; unsigned char* ref_data = NULL; unsigned long error_count = 0; unsigned int ref_width, ref_height; unsigned int src_width, src_height; // Check sample and reference file pointers if (src_file == NULL || ref_file == NULL) { shrLog(""\\n> shrComparePGM: src_file or ref_file is NULL\\n Aborting comparison !!!\\n\\n""); return shrFALSE; } shrLog(""\\n> shrComparePGM:\\n (a)rendered: <%s>\\n (b)reference: <%s>\\n"", src_file, ref_file); // Load the ref image file if (shrLoadPPM4ub(ref_file, &ref_data, &ref_width, &ref_height) != shrTRUE) { shrLog(""\\n Unable to load ref image file: %s\\n Aborting comparison !!!\\n\\n"", ref_file); return shrFALSE; } // Load the sample image file if (shrLoadPPM4ub(src_file, &src_data, &src_width, &src_height) != shrTRUE) { shrLog(""\\n Unable to load src image file: %s\\n Aborting comparison !!!\\n\\n"", src_file); return shrFALSE; } // check to see if image dimensions match if(src_height != ref_height || src_width != ref_width) { shrLog(""\\n Source and ref size mismatch (%u x %u) vs (%u x %u)\\n Aborting Comparison !!!\\n\\n "", src_width, src_height, ref_width, ref_height); return shrFALSE; } // compare the images if (shrCompareubt(ref_data, src_data, src_width*src_height*4, epsilon, threshold ) == shrFALSE) { error_count=1; } shrLog("" Images %s\\n\\n"", (error_count == 0) ? ""Match"" : ""Don't Match !!!""); return (error_count == 0) ? shrTRUE : shrFALSE; // returns true if all pixels pass } // Load raw data from disk unsigned char* shrLoadRawFile(const char* filename, size_t size) { FILE *fp = NULL; #ifdef WIN32 errno_t err; if ((err = fopen_s(&fp, filename, ""rb"")) != 0) #else if ((fp = fopen(filename, ""rb"")) == NULL) #endif { shrLog("" Error opening file '%s' !!!\\n"", filename); return 0; } unsigned char* data = (unsigned char*)malloc(size); size_t read = fread(data, 1, size, fp); fclose(fp); shrLog("" Read '%s', %d bytes\\n"", filename, read); return data; } // Round Up Division function size_t shrRoundUp(int group_size, int global_size) { int r = global_size % group_size; if(r == 0) { return global_size; } else { return global_size + group_size - r; } } ",16201,False,2417.0479813702045,median "## FTP Component *Available as of Camel version 1.1* This component provides access to remote file systems over the FTP and SFTP protocols. When consuming from remote FTP server make sure you read the section titled _Default when consuming files_ further below for details related to consuming files. Absolute path is *not* supported. *Camel 2.16* will translate absolute path to relative by trimming all leading slashes from `directoryname`. There'll be WARN message printed in the logs. Maven users will need to add the following dependency to their `pom.xml` for this component: [source,xml] ----------------------------------------------------------------------- org.apache.camel camel-ftp x.x.xSee the documentation of the Apache Commons ----------------------------------------------------------------------- ### URI format [source,java] --------------------------------------------------------- ftp://[username@]hostname[:port]/directoryname[?options] sftp://[username@]hostname[:port]/directoryname[?options] ftps://[username@]hostname[:port]/directoryname[?options] --------------------------------------------------------- Where *directoryname* represents the underlying directory. The directory name is a relative path. Absolute path's is *not* supported. The relative path can contain nested folders, such as /inbox/us. For Camel versions before *Camel 2.16*, the directoryName *must* exist already as this component does not support the `autoCreate` option (which the file component does). The reason is that its the FTP administrator (FTP server) task to properly setup user accounts, and home directories with the right file permissions etc. For *Camel 2.16*, `autoCreate` option is supported. When consumer starts, before polling is scheduled, there's additional FTP operation performed to create the directory configured for endpoint. The default value for `autoCreate` is `true`. If no *username* is provided, then `anonymous` login is attempted using no password. + If no *port* number is provided, Camel will provide default values according to the protocol (ftp = 21, sftp = 22, ftps = 2222). You can append query options to the URI in the following format, `?option=value&option=value&...` This component uses two different libraries for the actual FTP work. FTP and FTPS uses http://commons.apache.org/net/[Apache Commons Net] while SFTP uses http://www.jcraft.com/jsch/[JCraft JSCH]. The FTPS component is only available in Camel 2.2 or newer. + FTPS (also known as FTP Secure) is an extension to FTP that adds support for the Transport Layer Security (TLS) and the Secure Sockets Layer (SSL) cryptographic protocols. ### URI Options The options below are exclusive for the FTP component. // component options: START The FTP component has no options. // component options: END // endpoint options: START The FTP endpoint is configured using URI syntax: ftp:host:port/directoryName with the following path and query parameters: #### Path Parameters (3 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |======================================================================= | Name | Description | Default | Type | **host** | *Required* Hostname of the FTP server | | String | **port** | Port of the FTP server | | int | **directoryName** | The starting directory | | String |======================================================================= #### Query Parameters (102 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |======================================================================= | Name | Description | Default | Type | **binary** (common) | Specifies the file transfer mode BINARY or ASCII. Default is ASCII (false). | false | boolean | **charset** (common) | This option is used to specify the encoding of the file. You can use this on the consumer to specify the encodings of the files which allow Camel to know the charset it should load the file content in case the file content is being accessed. Likewise when writing a file you can use this option to specify which charset to write the file as well. Do mind that when writing the file Camel may have to read the message content into memory to be able to convert the data into the configured charset so do not use this if you have big messages. | | String | **disconnect** (common) | Whether or not to disconnect from remote FTP server right after use. Disconnect will only disconnect the current connection to the FTP server. If you have a consumer which you want to stop then you need to stop the consumer/route instead. | false | boolean | **doneFileName** (common) | Producer: If provided then Camel will write a 2nd done file when the original file has been written. The done file will be empty. This option configures what file name to use. Either you can specify a fixed name. Or you can use dynamic placeholders. The done file will always be written in the same folder as the original file. Consumer: If provided Camel will only consume files if a done file exists. This option configures what file name to use. Either you can specify a fixed name. Or you can use dynamic placeholders.The done file is always expected in the same folder as the original file. Only $file.name and $file.name.noext is supported as dynamic placeholders. | | String | **fileName** (common) | Use Expression such as File Language to dynamically set the filename. For consumers it's used as a filename filter. For producers it's used to evaluate the filename to write. If an expression is set it take precedence over the CamelFileName header. (Note: The header itself can also be an Expression). The expression options support both String and Expression types. If the expression is a String type it is always evaluated using the File Language. If the expression is an Expression type the specified Expression type is used - this allows you for instance to use OGNL expressions. For the consumer you can use it to filter filenames so you can for instance consume today's file using the File Language syntax: mydata-$date:now:yyyyMMdd.txt. The producers support the CamelOverruleFileName header which takes precedence over any existing CamelFileName header; the CamelOverruleFileName is a header that is used only once and makes it easier as this avoids to temporary store CamelFileName and have to restore it afterwards. | | String | **passiveMode** (common) | Sets passive mode connections. Default is active mode connections. | false | boolean | **separator** (common) | Sets the path separator to be used. UNIX = Uses unix style path separator Windows = Uses windows style path separator Auto = (is default) Use existing path separator in file name | UNIX | PathSeparator | **fastExistsCheck** (common) | If set this option to be true camel-ftp will use the list file directly to check if the file exists. Since some FTP server may not support to list the file directly if the option is false camel-ftp will use the old way to list the directory and check if the file exists. This option also influences readLock=changed to control whether it performs a fast check to update file information or not. This can be used to speed up the process if the FTP server has a lot of files. | 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 | **delete** (consumer) | If true the file will be deleted after it is processed successfully. | false | boolean | **moveFailed** (consumer) | Sets the move failure expression based on Simple language. For example to move files into a .error subdirectory use: .error. Note: When moving the files to the fail location Camel will handle the error and will not pick up the file again. | | String | **noop** (consumer) | If true the file is not moved or deleted in any way. This option is good for readonly data or for ETL type requirements. If noop=true Camel will set idempotent=true as well to avoid consuming the same files over and over again. | false | boolean | **preMove** (consumer) | Expression (such as File Language) used to dynamically set the filename when moving it before processing. For example to move in-progress files into the order directory set this value to order. | | String | **recursive** (consumer) | If a directory will look for files in all the sub-directories as well. | false | boolean | **sendEmptyMessageWhenIdle** (consumer) | If the polling consumer did not poll any files you can enable this option to send an empty message (no body) instead. | false | boolean | **streamDownload** (consumer) | Sets the download method to use when not using a local working directory. If set to true the remote files are streamed to the route as they are read. When set to false the remote files are loaded into memory before being sent into the route. | false | boolean | **directoryMustExist** (consumer) | Similar to startingDirectoryMustExist but this applies during polling recursive sub directories. | false | boolean | **download** (consumer) | Whether the FTP consumer should download the file. If this option is set to false then the message body will be null but the consumer will still trigger a Camel Exchange that has details about the file such as file name file size etc. It's just that the file will not be downloaded. | false | boolean | **exceptionHandler** (consumer) | To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this options 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 | **ignoreFileNotFoundOr PermissionError** (consumer) | Whether to ignore when trying to download a file which does not exist or due to permission error. By default when a file does not exists or insufficient permission then an exception is thrown. Setting this option to true allows to ignore that instead. | false | boolean | **inProgressRepository** (consumer) | A pluggable in-progress repository org.apache.camel.spi.IdempotentRepository. The in-progress repository is used to account the current in progress files being consumed. By default a memory based repository is used. | | String> | **localWorkDirectory** (consumer) | When consuming a local work directory can be used to store the remote file content directly in local files to avoid loading the content into memory. This is beneficial if you consume a very big remote file and thus can conserve memory. | | String | **onCompletionException Handler** (consumer) | To use a custom org.apache.camel.spi.ExceptionHandler to handle any thrown exceptions that happens during the file on completion process where the consumer does either a commit or rollback. The default implementation will log any exception at WARN level and ignore. | | ExceptionHandler | **pollStrategy** (consumer) | A pluggable org.apache.camel.PollingConsumerPollingStrategy allowing you to provide your custom implementation to control error handling usually occurred during the poll operation before an Exchange have been created and being routed in Camel. | | PollingConsumerPoll Strategy | **processStrategy** (consumer) | A pluggable org.apache.camel.component.file.GenericFileProcessStrategy allowing you to implement your own readLock option or similar. Can also be used when special conditions must be met before a file can be consumed such as a special ready file exists. If this option is set then the readLock option does not apply. | | GenericFileProcess Strategy | **receiveBufferSize** (consumer) | The receive (download) buffer size Used only by FTPClient | 32768 | int | **startingDirectoryMustExist** (consumer) | Whether the starting directory must exist. Mind that the autoCreate option is default enabled which means the starting directory is normally auto created if it doesn't exist. You can disable autoCreate and enable this to ensure the starting directory must exist. Will thrown an exception if the directory doesn't exist. | false | boolean | **useList** (consumer) | Whether to allow using LIST command when downloading a file. Default is true. In some use cases you may want to download a specific file and are not allowed to use the LIST command and therefore you can set this option to false. | true | boolean | **fileExist** (producer) | What to do if a file already exists with the same name. Override which is the default replaces the existing file. Append - adds content to the existing file. Fail - throws a GenericFileOperationException indicating that there is already an existing file. Ignore - silently ignores the problem and does not override the existing file but assumes everything is okay. Move - option requires to use the moveExisting option to be configured as well. The option eagerDeleteTargetFile can be used to control what to do if an moving the file and there exists already an existing file otherwise causing the move operation to fail. The Move option will move any existing files before writing the target file. TryRename Camel is only applicable if tempFileName option is in use. This allows to try renaming the file from the temporary name to the actual name without doing any exists check.This check may be faster on some file systems and especially FTP servers. | Override | GenericFileExist | **flatten** (producer) | Flatten is used to flatten the file name path to strip any leading paths so it's just the file name. This allows you to consume recursively into sub-directories but when you eg write the files to another directory they will be written in a single directory. Setting this to true on the producer enforces that any file name in CamelFileName header will be stripped for any leading paths. | false | boolean | **moveExisting** (producer) | Expression (such as File Language) used to compute file name to use when fileExist=Move is configured. To move files into a backup subdirectory just enter backup. This option only supports the following File Language tokens: file:name file:name.ext file:name.noext file:onlyname file:onlyname.noext file:ext and file:parent. Notice the file:parent is not supported by the FTP component as the FTP component can only move any existing files to a relative directory based on current dir as base. | | String | **tempFileName** (producer) | The same as tempPrefix option but offering a more fine grained control on the naming of the temporary filename as it uses the File Language. | | String | **tempPrefix** (producer) | This option is used to write the file using a temporary name and then after the write is complete rename it to the real name. Can be used to identify files being written and also avoid consumers (not using exclusive read locks) reading in progress files. Is often used by FTP when uploading big files. | | String | **allowNullBody** (producer) | Used to specify if a null body is allowed during file writing. If set to true then an empty file will be created when set to false and attempting to send a null body to the file component a GenericFileWriteException of 'Cannot write null body to file.' will be thrown. If the fileExist option is set to 'Override' then the file will be truncated and if set to append the file will remain unchanged. | false | boolean | **chmod** (producer) | Allows you to set chmod on the stored file. For example chmod=640. | | String | **disconnectOnBatchComplete** (producer) | Whether or not to disconnect from remote FTP server right after a Batch upload is complete. disconnectOnBatchComplete will only disconnect the current connection to the FTP server. | false | boolean | **eagerDeleteTargetFile** (producer) | Whether or not to eagerly delete any existing target file. This option only applies when you use fileExists=Override and the tempFileName option as well. You can use this to disable (set it to false) deleting the target file before the temp file is written. For example you may write big files and want the target file to exists during the temp file is being written. This ensure the target file is only deleted until the very last moment just before the temp file is being renamed to the target filename. This option is also used to control whether to delete any existing files when fileExist=Move is enabled and an existing file exists. If this option copyAndDeleteOnRenameFails false then an exception will be thrown if an existing file existed if its true then the existing file is deleted before the move operation. | true | boolean | **keepLastModified** (producer) | Will keep the last modified timestamp from the source file (if any). Will use the Exchange.FILE_LAST_MODIFIED header to located the timestamp. This header can contain either a java.util.Date or long with the timestamp. If the timestamp exists and the option is enabled it will set this timestamp on the written file. Note: This option only applies to the file producer. You cannot use this option with any of the ftp producers. | false | boolean | **sendNoop** (producer) | Whether to send a noop command as a pre-write check before uploading files to the FTP server. This is enabled by default as a validation of the connection is still valid which allows to silently re-connect to be able to upload the file. However if this causes problems you can turn this option off. | true | boolean | **activePortRange** (advanced) | Set the client side port range in active mode. The syntax is: minPort-maxPort Both port numbers are inclusive eg 10000-19999 to include all 1xxxx ports. | | String | **autoCreate** (advanced) | Automatically create missing directories in the file's pathname. For the file consumer that means creating the starting directory. For the file producer it means the directory the files should be written to. | true | boolean | **bufferSize** (advanced) | Write buffer sized in bytes. | 131072 | int | **connectTimeout** (advanced) | Sets the connect timeout for waiting for a connection to be established Used by both FTPClient and JSCH | 10000 | int | **ftpClient** (advanced) | To use a custom instance of FTPClient | | FTPClient | **ftpClientConfig** (advanced) | To use a custom instance of FTPClientConfig to configure the FTP client the endpoint should use. | | FTPClientConfig | **ftpClientConfigParameters** (advanced) | Used by FtpComponent to provide additional parameters for the FTPClientConfig | | Map | **ftpClientParameters** (advanced) | Used by FtpComponent to provide additional parameters for the FTPClient | | Map | **maximumReconnectAttempts** (advanced) | Specifies the maximum reconnect attempts Camel performs when it tries to connect to the remote FTP server. Use 0 to disable this behavior. | | int | **reconnectDelay** (advanced) | Delay in millis Camel will wait before performing a reconnect attempt. | | long | **siteCommand** (advanced) | Sets optional site command(s) to be executed after successful login. Multiple site commands can be separated using a new line character (\\n). | | String | **soTimeout** (advanced) | Sets the so timeout Used only by FTPClient | 300000 | int | **stepwise** (advanced) | Sets whether we should stepwise change directories while traversing file structures when downloading files or as well when uploading a file to a directory. You can disable this if you for example are in a situation where you cannot change directory on the FTP server due security reasons. | true | boolean | **synchronous** (advanced) | Sets whether synchronous processing should be strictly used or Camel is allowed to use asynchronous processing (if supported). | false | boolean | **throwExceptionOnConnect Failed** (advanced) | Should an exception be thrown if connection failed (exhausted) By default exception is not thrown and a WARN is logged. You can use this to enable exception being thrown and handle the thrown exception from the org.apache.camel.spi.PollingConsumerPollStrategy rollback method. | false | boolean | **timeout** (advanced) | Sets the data timeout for waiting for reply Used only by FTPClient | 30000 | int | **antExclude** (filter) | Ant style filter exclusion. If both antInclude and antExclude are used antExclude takes precedence over antInclude. Multiple exclusions may be specified in comma-delimited format. | | String | **antFilterCaseSensitive** (filter) | Sets case sensitive flag on ant fiter | true | boolean | **antInclude** (filter) | Ant style filter inclusion. Multiple inclusions may be specified in comma-delimited format. | | String | **eagerMaxMessagesPerPoll** (filter) | Allows for controlling whether the limit from maxMessagesPerPoll is eager or not. If eager then the limit is during the scanning of files. Where as false would scan all files and then perform sorting. Setting this option to false allows for sorting all files first and then limit the poll. Mind that this requires a higher memory usage as all file details are in memory to perform the sorting. | true | boolean | **exclude** (filter) | Is used to exclude files if filename matches the regex pattern (matching is case in-senstive). Notice if you use symbols such as plus sign and others you would need to configure this using the RAW() syntax if configuring this as an endpoint uri. See more details at configuring endpoint uris | | String | **filter** (filter) | Pluggable filter as a org.apache.camel.component.file.GenericFileFilter class. Will skip files if filter returns false in its accept() method. | | GenericFileFilter | **filterDirectory** (filter) | Filters the directory based on Simple language. For example to filter on current date you can use a simple date pattern such as $date:now:yyyMMdd | | String | **filterFile** (filter) | Filters the file based on Simple language. For example to filter on file size you can use $file:size 5000 | | String | **idempotent** (filter) | Option to use the Idempotent Consumer EIP pattern to let Camel skip already processed files. Will by default use a memory based LRUCache that holds 1000 entries. If noop=true then idempotent will be enabled as well to avoid consuming the same files over and over again. | false | Boolean | **idempotentKey** (filter) | To use a custom idempotent key. By default the absolute path of the file is used. You can use the File Language for example to use the file name and file size you can do: idempotentKey=$file:name-$file:size | | String | **idempotentRepository** (filter) | A pluggable repository org.apache.camel.spi.IdempotentRepository which by default use MemoryMessageIdRepository if none is specified and idempotent is true. | | String> | **include** (filter) | Is used to include files if filename matches the regex pattern (matching is case in-sensitive). Notice if you use symbols such as plus sign and others you would need to configure this using the RAW() syntax if configuring this as an endpoint uri. See more details at configuring endpoint uris | | String | **maxDepth** (filter) | The maximum depth to traverse when recursively processing a directory. | 2147483647 | int | **maxMessagesPerPoll** (filter) | To define a maximum messages to gather per poll. By default no maximum is set. Can be used to set a limit of e.g. 1000 to avoid when starting up the server that there are thousands of files. Set a value of 0 or negative to disabled it. Notice: If this option is in use then the File and FTP components will limit before any sorting. For example if you have 100000 files and use maxMessagesPerPoll=500 then only the first 500 files will be picked up and then sorted. You can use the eagerMaxMessagesPerPoll option and set this to false to allow to scan all files first and then sort afterwards. | | int | **minDepth** (filter) | The minimum depth to start processing when recursively processing a directory. Using minDepth=1 means the base directory. Using minDepth=2 means the first sub directory. | | int | **move** (filter) | Expression (such as Simple Language) used to dynamically set the filename when moving it after processing. To move files into a .done subdirectory just enter .done. | | String | **exclusiveReadLockStrategy** (lock) | Pluggable read-lock as a org.apache.camel.component.file.GenericFileExclusiveReadLockStrategy implementation. | | GenericFileExclusive ReadLockStrategy | **readLock** (lock) | Used by consumer to only poll the files if it has exclusive read-lock on the file (i.e. the file is not in-progress or being written). Camel will wait until the file lock is granted. This option provides the build in strategies: none - No read lock is in use markerFile - Camel creates a marker file (fileName.camelLock) and then holds a lock on it. This option is not available for the FTP component changed - Changed is using file length/modification timestamp to detect whether the file is currently being copied or not. Will at least use 1 sec to determine this so this option cannot consume files as fast as the others but can be more reliable as the JDK IO API cannot always determine whether a file is currently being used by another process. The option readLockCheckInterval can be used to set the check frequency. fileLock - is for using java.nio.channels.FileLock. This option is not avail for the FTP component. This approach should be avoided when accessing a remote file system via a mount/share unless that file system supports distributed file locks. rename - rename is for using a try to rename the file as a test if we can get exclusive read-lock. idempotent - (only for file component) idempotent is for using a idempotentRepository as the read-lock. This allows to use read locks that supports clustering if the idempotent repository implementation supports that. idempotent-changed - (only for file component) idempotent-changed is for using a idempotentRepository and changed as the combined read-lock. This allows to use read locks that supports clustering if the idempotent repository implementation supports that. idempotent-rename - (only for file component) idempotent-rename is for using a idempotentRepository and rename as the combined read-lock. This allows to use read locks that supports clustering if the idempotent repository implementation supports that. Notice: The various read locks is not all suited to work in clustered mode where concurrent consumers on different nodes is competing for the same files on a shared file system. The markerFile using a close to atomic operation to create the empty marker file but its not guaranteed to work in a cluster. The fileLock may work better but then the file system need to support distributed file locks and so on. Using the idempotent read lock can support clustering if the idempotent repository supports clustering such as Hazelcast Component or Infinispan. | | String | **readLockCheckInterval** (lock) | Interval in millis for the read-lock if supported by the read lock. This interval is used for sleeping between attempts to acquire the read lock. For example when using the changed read lock you can set a higher interval period to cater for slow writes. The default of 1 sec. may be too fast if the producer is very slow writing the file. Notice: For FTP the default readLockCheckInterval is 5000. The readLockTimeout value must be higher than readLockCheckInterval but a rule of thumb is to have a timeout that is at least 2 or more times higher than the readLockCheckInterval. This is needed to ensure that amble time is allowed for the read lock process to try to grab the lock before the timeout was hit. | 1000 | long | **readLockDeleteOrphanLock Files** (lock) | Whether or not read lock with marker files should upon startup delete any orphan read lock files which may have been left on the file system if Camel was not properly shutdown (such as a JVM crash). If turning this option to false then any orphaned lock file will cause Camel to not attempt to pickup that file this could also be due another node is concurrently reading files from the same shared directory. | true | boolean | **readLockLoggingLevel** (lock) | Logging level used when a read lock could not be acquired. By default a WARN is logged. You can change this level for example to OFF to not have any logging. This option is only applicable for readLock of types: changed fileLock rename. | WARN | LoggingLevel | **readLockMarkerFile** (lock) | Whether to use marker file with the changed rename or exclusive read lock types. By default a marker file is used as well to guard against other processes picking up the same files. This behavior can be turned off by setting this option to false. For example if you do not want to write marker files to the file systems by the Camel application. | true | boolean | **readLockMinAge** (lock) | This option applied only for readLock=change. This option allows to specify a minimum age the file must be before attempting to acquire the read lock. For example use readLockMinAge=300s to require the file is at last 5 minutes old. This can speedup the changed read lock as it will only attempt to acquire files which are at least that given age. | 0 | long | **readLockMinLength** (lock) | This option applied only for readLock=changed. This option allows you to configure a minimum file length. By default Camel expects the file to contain data and thus the default value is 1. You can set this option to zero to allow consuming zero-length files. | 1 | long | **readLockRemoveOnCommit** (lock) | This option applied only for readLock=idempotent. This option allows to specify whether to remove the file name entry from the idempotent repository when processing the file is succeeded and a commit happens. By default the file is not removed which ensures that any race-condition do not occur so another active node may attempt to grab the file. Instead the idempotent repository may support eviction strategies that you can configure to evict the file name entry after X minutes - this ensures no problems with race conditions. | false | boolean | **readLockRemoveOnRollback** (lock) | This option applied only for readLock=idempotent. This option allows to specify whether to remove the file name entry from the idempotent repository when processing the file failed and a rollback happens. If this option is false then the file name entry is confirmed (as if the file did a commit). | true | boolean | **readLockTimeout** (lock) | Optional timeout in millis for the read-lock if supported by the read-lock. If the read-lock could not be granted and the timeout triggered then Camel will skip the file. At next poll Camel will try the file again and this time maybe the read-lock could be granted. Use a value of 0 or lower to indicate forever. Currently fileLock changed and rename support the timeout. Notice: For FTP the default readLockTimeout value is 20000 instead of 10000. The readLockTimeout value must be higher than readLockCheckInterval but a rule of thumb is to have a timeout that is at least 2 or more times higher than the readLockCheckInterval. This is needed to ensure that amble time is allowed for the read lock process to try to grab the lock before the timeout was hit. | 10000 | long | **backoffErrorThreshold** (scheduler) | The number of subsequent error polls (failed due some error) that should happen before the backoffMultipler should kick-in. | | int | **backoffIdleThreshold** (scheduler) | The number of subsequent idle polls that should happen before the backoffMultipler should kick-in. | | int | **backoffMultiplier** (scheduler) | To let the scheduled polling consumer backoff if there has been a number of subsequent idles/errors in a row. The multiplier is then the number of polls that will be skipped before the next actual attempt is happening again. When this option is in use then backoffIdleThreshold and/or backoffErrorThreshold must also be configured. | | int | **delay** (scheduler) | Milliseconds before the next poll. You can also specify time values using units such as 60s (60 seconds) 5m30s (5 minutes and 30 seconds) and 1h (1 hour). | 500 | long | **greedy** (scheduler) | If greedy is enabled then the ScheduledPollConsumer will run immediately again if the previous run polled 1 or more messages. | false | boolean | **initialDelay** (scheduler) | Milliseconds before the first poll starts. You can also specify time values using units such as 60s (60 seconds) 5m30s (5 minutes and 30 seconds) and 1h (1 hour). | 1000 | long | **runLoggingLevel** (scheduler) | The consumer logs a start/complete log line when it polls. This option allows you to configure the logging level for that. | TRACE | LoggingLevel | **scheduledExecutorService** (scheduler) | Allows for configuring a custom/shared thread pool to use for the consumer. By default each consumer has its own single threaded thread pool. | | ScheduledExecutor Service | **scheduler** (scheduler) | To use a cron scheduler from either camel-spring or camel-quartz2 component | none | ScheduledPollConsumer Scheduler | **schedulerProperties** (scheduler) | To configure additional properties when using a custom scheduler or any of the Quartz2 Spring based scheduler. | | Map | **startScheduler** (scheduler) | Whether the scheduler should be auto started. | true | boolean | **timeUnit** (scheduler) | Time unit for initialDelay and delay options. | MILLISECONDS | TimeUnit | **useFixedDelay** (scheduler) | Controls if fixed delay or fixed rate is used. See ScheduledExecutorService in JDK for details. | true | boolean | **shuffle** (sort) | To shuffle the list of files (sort in random order) | false | boolean | **sortBy** (sort) | Built-in sort by using the File Language. Supports nested sorts so you can have a sort by file name and as a 2nd group sort by modified date. | | String | **sorter** (sort) | Pluggable sorter as a java.util.Comparator class. | | GenericFile> | **account** (security) | Account to use for login | | String | **password** (security) | Password to use for login | | String | **username** (security) | Username to use for login | | String |======================================================================= // endpoint options: END ### FTPS component default trust store When using the `ftpClient.` properties related to SSL with the FTPS component, the trust store accept all certificates. If you only want trust selective certificates, you have to configure the trust store with the `ftpClient.trustStore.xxx` options or by configuring a custom `ftpClient`. When using `sslContextParameters`, the trust store is managed by the configuration of the provided SSLContextParameters instance. You can configure additional options on the `ftpClient` and `ftpClientConfig` from the URI directly by using the `ftpClient.` or `ftpClientConfig.` prefix. For example to set the `setDataTimeout` on the `FTPClient` to 30 seconds you can do: [source,java] -------------------------------------------------------------------------------------- from(""ftp://foo@myserver?password=secret&ftpClient.dataTimeout=30000"").to(""bean:foo""); -------------------------------------------------------------------------------------- You can mix and match and have use both prefixes, for example to configure date format or timezones. [source,java] ---------------------------------------------------------------------------------------------------------------------------- from(""ftp://foo@myserver?password=secret&ftpClient.dataTimeout=30000&ftpClientConfig.serverLanguageCode=fr"").to(""bean:foo""); ---------------------------------------------------------------------------------------------------------------------------- You can have as many of these options as you like. See the documentation of the Apache Commons FTP FTPClientConfig for possible options and more details. And as well for Apache Commons FTP FTPClient. If you do not like having many and long configuration in the url you can refer to the `ftpClient` or `ftpClientConfig` to use by letting Camel lookup in the link:registry.html[Registry] for it. For example: [source,java] -------------------------------------------------------------------------- -------------------------------------------------------------------------- And then let Camel lookup this bean when you use the # notation in the url. [source,java] ------------------------------------------------------------------------------------ from(""ftp://foo@myserver?password=secret&ftpClientConfig=#myConfig"").to(""bean:foo""); ------------------------------------------------------------------------------------ ### More URI options ### Examples `ftp://someone@someftpserver.com/public/upload/images/holiday2008?password=secret&binary=true` + `ftp://someoneelse@someotherftpserver.co.uk:12049/reports/2008/password=secret&binary=false` + `ftp://publicftpserver.com/download` ### Concurrency FTP Consumer does not support concurrency The FTP consumer (with the same endpoint) does not support concurrency (the backing FTP client is not thread safe). + You can use multiple FTP consumers to poll from different endpoints. It is only a single endpoint that does not support concurrent consumers. The FTP producer does *not* have this issue, it supports concurrency. ### More information This component is an extension of the link:file2.html[File] component. So there are more samples and details on the link:file2.html[File] component page. ==== ### Default when consuming files The link:ftp2.html[FTP] consumer will by default leave the consumed files untouched on the remote FTP server. You have to configure it explicitly if you want it to delete the files or move them to another location. For example you can use `delete=true` to delete the files, or use `move=.done` to move the files into a hidden done sub directory. The regular link:file2.html[File] consumer is different as it will by default move files to a `.camel` sub directory. The reason Camel does *not* do this by default for the FTP consumer is that it may lack permissions by default to be able to move or delete files. #### limitations The option *readLock* can be used to force Camel *not* to consume files that is currently in the progress of being written. However, this option is turned off by default, as it requires that the user has write access. See the options table at link:file2.html[File2] for more details about read locks. + There are other solutions to avoid consuming files that are currently being written over FTP; for instance, you can write to a temporary destination and move the file after it has been written. When moving files using `move` or `preMove` option the files are restricted to the FTP_ROOT folder. That prevents you from moving files outside the FTP area. If you want to move files to another area you can use soft links and move files into a soft linked folder. ### Message Headers The following message headers can be used to affect the behavior of the component [width=""100%"",cols=""50%,50%"",options=""header"",] |======================================================================= |Header |Description |`CamelFileName` |Specifies the output file name (relative to the endpoint directory) to be used for the output message when sending to the endpoint. If this is not present and no expression either, then a generated message ID is used as the filename instead. |`CamelFileNameProduced` |The actual filepath (path + name) for the output file that was written. This header is set by Camel and its purpose is providing end-users the name of the file that was written. |`CamelFileIndex` |Current index out of total number of files being consumed in this batch. |`CamelFileSize` |Total number of files being consumed in this batch. |`CamelFileHost` |The remote hostname. |`CamelFileLocalWorkPath` |Path to the local work file, if local work directory is used. |======================================================================= In addition the FTP/FTPS consumer and producer will enrich the Camel `Message` with the following headers [width=""100%"",cols=""50%,50%"",options=""header"",] |======================================================================= |Header |Description |`CamelFtpReplyCode` |*Camel 2.11.1:* The FTP client reply code (the type is a integer) |`CamelFtpReplyString` | *Camel 2.11.1:* The FTP client reply string |======================================================================= ### About timeouts The two set of libraries (see top) has different API for setting timeout. You can use the `connectTimeout` option for both of them to set a timeout in millis to establish a network connection. An individual `soTimeout` can also be set on the FTP/FTPS, which corresponds to using `ftpClient.soTimeout`. Notice SFTP will automatically use `connectTimeout` as its `soTimeout`. The `timeout` option only applies for FTP/FTSP as the data timeout, which corresponds to the `ftpClient.dataTimeout` value. All timeout values are in millis. ### Using Local Work Directory Camel supports consuming from remote FTP servers and downloading the files directly into a local work directory. This avoids reading the entire remote file content into memory as it is streamed directly into the local file using `FileOutputStream`. Camel will store to a local file with the same name as the remote file, though with `.inprogress` as extension while the file is being downloaded. Afterwards, the file is renamed to remove the `.inprogress` suffix. And finally, when the link:exchange.html[Exchange] is complete the local file is deleted. So if you want to download files from a remote FTP server and store it as files then you need to route to a file endpoint such as: [source,java] ------------------------------------------------------------------------------------------------ from(""ftp://someone@someserver.com?password=secret&localWorkDirectory=/tmp"").to(""file://inbox""); ------------------------------------------------------------------------------------------------ [Tip] ==== *Optimization by renaming work file* The route above is ultra efficient as it avoids reading the entire file content into memory. It will download the remote file directly to a local file stream. The `java.io.File` handle is then used as the link:exchange.html[Exchange] body. The file producer leverages this fact and can work directly on the work file `java.io.File` handle and perform a `java.io.File.rename` to the target filename. As Camel knows it's a local work file, it can optimize and use a rename instead of a file copy, as the work file is meant to be deleted anyway. ==== ### Stepwise changing directories Camel link:ftp2.html[FTP] can operate in two modes in terms of traversing directories when consuming files (eg downloading) or producing files (eg uploading) * stepwise * not stepwise You may want to pick either one depending on your situation and security issues. Some Camel end users can only download files if they use stepwise, while others can only download if they do not. At least you have the choice to pick (from Camel 2.6 onwards). In Camel 2.0 - 2.5 there is only one mode and it is: * before 2.5 not stepwise * 2.5 stepwise From Camel 2.6 onwards there is now an option `stepwise` you can use to control the behavior. Note that stepwise changing of directory will in most cases only work when the user is confined to it's home directory and when the home directory is reported as `""/""`. The difference between the two of them is best illustrated with an example. Suppose we have the following directory structure on the remote FTP server we need to traverse and download files: [source,java] -------------- / /one /one/two /one/two/sub-a /one/two/sub-b -------------- And that we have a file in each of sub-a (a.txt) and sub-b (b.txt) folder. #### Using stepwise=true (default mode) [source,java] ---------------------------------------------------------- TYPE A 200 Type set to A PWD 257 ""/"" is current directory. CWD one 250 CWD successful. ""/one"" is current directory. CWD two 250 CWD successful. ""/one/two"" is current directory. SYST 215 UNIX emulated by FileZilla PORT 127,0,0,1,17,94 200 Port command successful LIST 150 Opening data channel for directory list. 226 Transfer OK CWD sub-a 250 CWD successful. ""/one/two/sub-a"" is current directory. PORT 127,0,0,1,17,95 200 Port command successful LIST 150 Opening data channel for directory list. 226 Transfer OK CDUP 200 CDUP successful. ""/one/two"" is current directory. CWD sub-b 250 CWD successful. ""/one/two/sub-b"" is current directory. PORT 127,0,0,1,17,96 200 Port command successful LIST 150 Opening data channel for directory list. 226 Transfer OK CDUP 200 CDUP successful. ""/one/two"" is current directory. CWD / 250 CWD successful. ""/"" is current directory. PWD 257 ""/"" is current directory. CWD one 250 CWD successful. ""/one"" is current directory. CWD two 250 CWD successful. ""/one/two"" is current directory. PORT 127,0,0,1,17,97 200 Port command successful RETR foo.txt 150 Opening data channel for file transfer. 226 Transfer OK CWD / 250 CWD successful. ""/"" is current directory. PWD 257 ""/"" is current directory. CWD one 250 CWD successful. ""/one"" is current directory. CWD two 250 CWD successful. ""/one/two"" is current directory. CWD sub-a 250 CWD successful. ""/one/two/sub-a"" is current directory. PORT 127,0,0,1,17,98 200 Port command successful RETR a.txt 150 Opening data channel for file transfer. 226 Transfer OK CWD / 250 CWD successful. ""/"" is current directory. PWD 257 ""/"" is current directory. CWD one 250 CWD successful. ""/one"" is current directory. CWD two 250 CWD successful. ""/one/two"" is current directory. CWD sub-b 250 CWD successful. ""/one/two/sub-b"" is current directory. PORT 127,0,0,1,17,99 200 Port command successful RETR b.txt 150 Opening data channel for file transfer. 226 Transfer OK CWD / 250 CWD successful. ""/"" is current directory. QUIT 221 Goodbye disconnected. ---------------------------------------------------------- As you can see when stepwise is enabled, it will traverse the directory structure using CD xxx. #### Using stepwise=false [source,java] ------------------------------------------- 230 Logged on TYPE A 200 Type set to A SYST 215 UNIX emulated by FileZilla PORT 127,0,0,1,4,122 200 Port command successful LIST one/two 150 Opening data channel for directory list 226 Transfer OK PORT 127,0,0,1,4,123 200 Port command successful LIST one/two/sub-a 150 Opening data channel for directory list 226 Transfer OK PORT 127,0,0,1,4,124 200 Port command successful LIST one/two/sub-b 150 Opening data channel for directory list 226 Transfer OK PORT 127,0,0,1,4,125 200 Port command successful RETR one/two/foo.txt 150 Opening data channel for file transfer. 226 Transfer OK PORT 127,0,0,1,4,126 200 Port command successful RETR one/two/sub-a/a.txt 150 Opening data channel for file transfer. 226 Transfer OK PORT 127,0,0,1,4,127 200 Port command successful RETR one/two/sub-b/b.txt 150 Opening data channel for file transfer. 226 Transfer OK QUIT 221 Goodbye disconnected. ------------------------------------------- As you can see when not using stepwise, there are no CD operation invoked at all. ### Samples In the sample below we set up Camel to download all the reports from the FTP server once every hour (60 min) as BINARY content and store it as files on the local file system. And the route using Spring DSL: [source,xml] ------------------------------------------------------------------------------------------------------ ------------------------------------------------------------------------------------------------------ #### Consuming a remote FTPS server (implicit SSL) and client authentication [source,java] -------------------------------------------------------------------------------------------------- from(""ftps://admin@localhost:2222/public/camel?password=admin&securityProtocol=SSL&isImplicit=true &ftpClient.keyStore.file=./src/test/resources/server.jks &ftpClient.keyStore.password=password&ftpClient.keyStore.keyPassword=password"") .to(""bean:foo""); -------------------------------------------------------------------------------------------------- #### Consuming a remote FTPS server (explicit TLS) and a custom trust store configuration [source,java] ---------------------------------------------------------------------------------------------------------------------------------------------------------------- from(""ftps://admin@localhost:2222/public/camel?password=admin&ftpClient.trustStore.file=./src/test/resources/server.jks&ftpClient.trustStore.password=password"") .to(""bean:foo""); ---------------------------------------------------------------------------------------------------------------------------------------------------------------- ### Filter using `org.apache.camel.component.file.GenericFileFilter` Camel supports pluggable filtering strategies. This strategy it to use the build in `org.apache.camel.component.file.GenericFileFilter` in Java. You can then configure the endpoint with such a filter to skip certain filters before being processed. In the sample we have built our own filter that only accepts files starting with report in the filename. And then we can configure our route using the *filter* attribute to reference our filter (using `#` notation) that we have defined in the spring XML file: [source,xml] --------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------- ### Filtering using ANT path matcher The ANT path matcher is a filter that is shipped out-of-the-box in the *camel-spring* jar. So you need to depend on *camel-spring* if you are using Maven. + The reason is that we leverage Spring's http://static.springsource.org/spring/docs/3.0.x/api/org/springframework/util/AntPathMatcher.html[AntPathMatcher] to do the actual matching. The file paths are matched with the following rules: * `?` matches one character * `*` matches zero or more characters * `**` matches zero or more directories in a path The sample below demonstrates how to use it: ### Using a proxy with SFTP To use an HTTP proxy to connect to your remote host, you can configure your route in the following way: [source,xml] ------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- You can also assign a user name and password to the proxy, if necessary. Please consult the documentation for `com.jcraft.jsch.Proxy` to discover all options. ### Setting preferred SFTP authentication method If you want to explicitly specify the list of authentication methods that should be used by `sftp` component, use `preferredAuthentications` option. If for example you would like Camel to attempt to authenticate with private/public SSH key and fallback to user/password authentication in the case when no public key is available, use the following route configuration: [source,java] ------------------------------------------------------------------------------------------------------------- from(""sftp://localhost:9999/root?username=admin&password=admin&preferredAuthentications=publickey,password""). to(""bean:processFile""); ------------------------------------------------------------------------------------------------------------- ### Consuming a single file using a fixed name When you want to download a single file and knows the file name, you can use `fileName=myFileName.txt` to tell Camel the name of the file to download. By default the consumer will still do a FTP LIST command to do a directory listing and then filter these files based on the `fileName` option. Though in this use-case it may be desirable to turn off the directory listing by setting `useList=false`. For example the user account used to login to the FTP server may not have permission to do a FTP LIST command. So you can turn off this with `useList=false`, and then provide the fixed name of the file to download with `fileName=myFileName.txt`, then the FTP consumer can still download the file. If the file for some reason does not exist, then Camel will by default throw an exception, you can turn this off and ignore this by setting `ignoreFileNotFoundOrPermissionError=true`. For example to have a Camel route that pickup a single file, and delete it after use you can do [source,java] ------------------------------------------------------------------------------------------------------------------------------------------------------------- from(""ftp://admin@localhost:21/nolist/?password=admin&stepwise=false&useList=false&ignoreFileNotFoundOrPermissionError=true&fileName=report.txt&delete=true"") .to(""activemq:queue:report""); ------------------------------------------------------------------------------------------------------------------------------------------------------------- Notice that we have use all the options we talked above above. You can also use this with `ConsumerTemplate`. For example to download a single file (if it exists) and grab the file content as a String type: [source,java] ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- String data = template.retrieveBodyNoWait(""ftp://admin@localhost:21/nolist/?password=admin&stepwise=false&useList=false&ignoreFileNotFoundOrPermissionError=true&fileName=report.txt&delete=true"", String.class); ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ### Debug logging This component has log level *TRACE* that can be helpful if you have problems. ### See Also * link:configuring-camel.html[Configuring Camel] * link:component.html[Component] * link:endpoint.html[Endpoint] * link:getting-started.html[Getting Started] * link:file2.html[File2] ",12222,False,2006.6206139969654,median "= LinkedList `LinkedList` 底层使用的是 双向链表 数据结构(JDK1.6 之前为循环链表,JDK1.7 取消了循环。注意双向链表和双向循环链表的区别。) == 类图 先来看一下 `LinkedList` 的类图: [plantuml,{diagram_attr}] .... @startuml skinparam nodesep 100 'skinparam ranksep 60 interface Iterable interface Collection extends Iterable abstract class AbstractCollection implements Collection interface List extends Collection interface Queue extends Collection interface Deque extends Queue abstract class AbstractList extends AbstractCollection implements List abstract class AbstractSequentialList extends AbstractList class LinkedList extends AbstractSequentialList implements Deque, Cloneable, java.io.Serializable @enduml .... == 初始化 先看看 `LinkedList` 中内部属性和构造函数: [{java_src_attr}] ---- transient int size = 0; /** * Pointer to first node. */ transient Node first; /** * Pointer to last node. */ transient Node last; /* void dataStructureInvariants() { assert (size == 0) ? (first == null && last == null) : (first.prev == null && last.next == null); } */ /** * Constructs an empty list. */ public LinkedList() { } /** * Constructs a list containing the elements of the specified * collection, in the order they are returned by the collection's * iterator. * * @param c the collection whose elements are to be placed into this list * @throws NullPointerException if the specified collection is null */ public LinkedList(Collection c) { this(); addAll(c); } private static class Node { E item; Node next; Node prev; Node(Node prev, E element, Node next) { this.item = element; this.next = next; this.prev = prev; } } ---- 从这里一眼即可看出内部使用一个双向链表来保存数据。初始化工作也及其干净,什么也不干。另外一个构造函数后面再分析。 NOTE: D瓜哥觉得使用初始化的头尾节点更方便代码书写,少了很多繁琐的判断。 == 分析工具 使用反射来获取内部属性,然后做进一步分析。 [{java_src_attr}] ---- include::{sourcedir}/LinkedListBaseTest.java[] ---- == 添加元素 测试代码: [{java_src_attr}] ---- include::{sourcedir}/LinkedListTest.java[tag=testAddAtTail] ---- JDK 源码: [{java_src_attr}] ---- /** * Links e as last element. */ void linkLast(E e) { final Node l = last; final Node newNode = new Node<>(l, e, null); last = newNode; if (l == null) first = newNode; else l.next = newNode; size++; modCount++; } /** * Appends the specified element to the end of this list. * *

This method is equivalent to {@link #addLast}. * * @param e element to be appended to this list * @return {@code true} (as specified by {@link Collection#add}) */ public boolean add(E e) { linkLast(e); return true; } ---- 再来看看从头部插入元素: [{java_src_attr}] ---- include::{sourcedir}/LinkedListTest.java[tag=testAddAtHeader] ---- JDK 源码: [{java_src_attr}] ---- /** * Links e as first element. */ private void linkFirst(E e) { final Node f = first; final Node newNode = new Node<>(null, e, f); first = newNode; if (f == null) last = newNode; else f.prev = newNode; size++; modCount++; } /** * Inserts the specified element at the beginning of this list. * * @param e the element to add */ public void addFirst(E e) { linkFirst(e); } ---- 从这里就能看出,`LinkedList` 在 `add(e)`、`addLast(e)` 或者 `addFirst(e)` 时,都是对链表的首尾进行操作,会比较高效。 == Redis 的 linkedlist Redis 底层也有很多地方使用到 linkedlist,并且也是双向链表。 .adlist.h [source,c,{source_attr}] ---- typedef struct listNode { struct listNode *prev; struct listNode *next; void *value; } listNode; typedef struct listIter { listNode *next; int direction; } listIter; typedef struct list { listNode *head; listNode *tail; void *(*dup)(void *ptr); void (*free)(void *ptr); int (*match)(void *ptr, void *key); unsigned long len; } list; ---- Redis 的 linkedlist 实现特点是: . 双向:节点带有前后指针; . 无环:首尾没有相连,所以没有构成环状; . 链表保存了首尾指针; . 多态:可以保存不同类型的值,这里成为泛型也许更符合 Java 中的语义。 Redis 在 2014 年实现了 <>,并使用 quicklist 代替了 linkedlist。所以,现在 linkedlist 几乎已经是废弃状态。 == Redis 的 ziplist Redis 官方在 ziplist.c 文件的注释中对 ziplist 进行了定义: [quote, ziplist.c] ____ The ziplist is a specially encoded dually linked list that is designed to be very memory efficient. It stores both strings and integer values, where integers are encoded as actual integers instead of a series of characters. It allows push and pop operations on either side of the list in O(1) time. However, because every operation requires a reallocation of the memory used by the ziplist, the actual complexity is related to the amount of memory used by the ziplist. ____ 就是说,ziplist 是一个经过特殊编码的双向链表,它的设计目标就是为了提高存储效率。ziplist 可以用于存储字符串或整数,其中整数是按真正的二进制表示进行编码的,而不是编码成字符串序列。它能以 O(1) 的时间复杂度在表的两端提供 `push` 和 `pop` 操作。 [source,{source_attr}] ---- The general layout of the ziplist is as follows: ... NOTE: all fields are stored in little endian, if not specified otherwise. ---- image::images/redis/redis-ziplist-structure.jpg[] . ``: 32bit,表示ziplist占用的字节总数(也包括本身占用的4个字节)。 . ``: 32bit,表示ziplist表中最后一项(entry)在ziplist中的偏移字节数。 + `` 的存在,使得我们可以很方便地找到最后一项(不用遍历整个ziplist),从而可以在ziplist尾端快速地执行push或pop操作。 + . ``: 16bit, 表示ziplist中数据项(entry)的个数。zllen字段因为只有16bit,所以可以表达的最大值为2^16^-1。`` 等于16bit全为1的情况,那么 `` 就不表示数据项个数了,这时要想知道 ziplist 中数据项总数,那么必须对ziplist从头到尾遍历各个数据项,才能计数出来。 . ``: 表示真正存放数据的数据项,长度不定。一个数据项(entry)也有它自己的内部结构,这个稍后再解释。 . ``: ziplist 最后 1 个字节,是一个结束标记,值固定等于 255。 ziplist 将表中每一项存放在前后连续的地址空间内,一个ziplist整体占用一大块内存。它是一个表(list),但其实不是一个链表(linked list)。 ziplist 为了在细节上节省内存,对于值的存储采用了变长的编码方式。 每一个数据项的构成: [source,{source_attr}] ---- // <1> ---- <1> ``: 表示前一个数据项占用的总字节数。 + . 如果前一个数据项占用字节数小于254,那么 `` 就只用一个字节来表示,这个字节的值就是前一个数据项的占用字节数: ` ` . 如果前一个数据项占用字节数大于等于254,那么 `` 就用5个字节来表示,其中第1个字节的值是254(作为这种情况的一个标记),而后面4个字节组成一个整型值,来真正存储前一个数据项的占用字节数 + [source] ---- 0xFE <4 bytes unsigned little endian prevlen> // <2> <3> ---- + <2> ``: 表示当前数据项的类型,整型或者字符串。 <3> ``: 数据 关于 ` ` 的编码,直接引用官方文档: [quote,ziplist.c] ____ The encoding field of the entry depends on the content of the entry. When the entry is a string, the first 2 bits of the encoding first byte will hold the type of encoding used to store the length of the string, followed by the actual length of the string. When the entry is an integer the first 2 bits are both set to 1. The following 2 bits are used to specify what kind of integer will be stored after this header. An overview of the different types and encodings is as follows. The first byte is always enough to determine the kind of entry. |00pppppp| - 1 byte String value with length less than or equal to 63 bytes (6 bits). ""pppppp"" represents the unsigned 6 bit length. |01pppppp|qqqqqqqq| - 2 bytes String value with length less than or equal to 16383 bytes (14 bits). IMPORTANT: The 14 bit number is stored in big endian. |10000000|qqqqqqqq|rrrrrrrr|ssssssss|tttttttt| - 5 bytes String value with length greater than or equal to 16384 bytes. Only the 4 bytes following the first byte represents the length up to 32^2-1. The 6 lower bits of the first byte are not used and are set to zero. IMPORTANT: The 32 bit number is stored in big endian. |11000000| - 3 bytes Integer encoded as int16_t (2 bytes). |11010000| - 5 bytes Integer encoded as int32_t (4 bytes). |11100000| - 9 bytes Integer encoded as int64_t (8 bytes). |11110000| - 4 bytes Integer encoded as 24 bit signed (3 bytes). |11111110| - 2 bytes Integer encoded as 8 bit signed (1 byte). |1111xxxx| - (with xxxx between 0000 and 1101) immediate 4 bit integer. Unsigned integer from 0 to 12. The encoded value is actually from 1 to 13 because 0000 and 1111 can not be used, so 1 should be subtracted from the encoded 4 bit value to obtain the right value. |11111111| - End of ziplist special entry. ____ 引用在网上找的例子,来做个说明: image::images/redis/redis-ziplist-sample.png[] . 这个ziplist一共包含 33 个字节。字节编号从 `byte[0]` 到 `byte[32]`。图中每个字节的值使用 16 进制表示。 . 头 4 个字节(`0x21000000`)是按小端(little endian)模式存储的 `` 字段。什么是小端呢?就是指数据的低字节保存在内存的低地址中(参见维基百科词条 https://en.wikipedia.org/wiki/Endianness[Endianness^])。因此,这里 `` 的值应该解析成 `0x00000021`,用十进制表示正好就是33。 . 接下来 4 个字节(`byte[4..7]`)是 ``,用小端存储模式来解释,它的值是 `0x0000001D`(值为29),表示最后一个数据项在 `byte[29]` 的位置(那个数据项为 `0x05FE14`)。 . 再接下来 2 个字节(`byte[8..9]`),值为 `0x0004`,表示这个 ziplist 里一共存有4项数据。 . 接下来 6 个字节(`byte[10..15]`)是第 1 个数据项。其中,`prevlen=0`,因为它前面没有数据项;`len=4`,相当于前面定义的9种情况中的第1种,表示后面4个字节按字符串存储数据,数据的值为:`name`。 . 接下来 8 个字节(`byte[16..23]`)是第 2 个数据项,与前面数据项存储格式类似,存储 1 个字符串:`tielei`。 . 接下来 5 个字节(`byte[24..28]`)是第 3 个数据项,与前面数据项存储格式类似,存储 1 个字符串: `age`。 . 接下来3个字节(`byte[29..31]`)是最后一个数据项,它的格式与前面的数据项存储格式不太一样。其中,第 1 个字节 `prevlen=5`,表示前一个数据项占用 5 个字节;第 2 个字节 = `FE`,相当于前面定义的9种情况中的第8种,所以后面还有1个字节用来表示真正的数据,并且以整数表示。它的值是20(0x14)。 . 最后1个字节(`byte[32]`)表示 ``,是固定的值255(0xFF)。 有两个问题需要注意: [qanda] 如何反向遍历 ziplist ?:: ``: 表示前一个数据项占用的总字节数。那么就能找到前一个元素的起始位置,就能实现反向遍历。 如何从 ziplist 中添加/删除数据?删除数据后,对应位置的 Bits 位怎么处理?:: 在某个/某些节点的前面添加新节点之后, 程序必须沿着路径挨个检查后续的节点,是否满足新长度的编码要求, 直到遇到一个能满足要求的节点(如果有一个能满足,则这个节点之后的其他节点也满足), 或者到达 ziplist 的末端 zlend 为止, 这种检查操作的复杂度为 O(N^2^) 。 + 因为只有在新添加节点的后面有连续多个长度接近 254 的节点时, 这种连锁更新才会发生, 所以可以普遍地认为, 这种连锁更新发生的概率非常小, 在一般情况下, 将添加操作看成是 O(N) 复杂度也是可以的。 + 删除元素就进行内存移位,覆盖 target 原本的数据,然后通过内存重分配,收缩多余空间。 // Redis 在下面这个几个地方使用了 ziplist: . 列表包含少量的列表项,并且列表项只是整数或者短小的字符串时。(在下面 <> 小节中,在最新版 Redis 中测试,显示的是 quicklist,而 quicklist 内部使用的是 ziplist 来存储数据,只是外面被 quicklist 包裹着。) . 在哈希键值包含少量键值对,并且每个键值对只包含整数或短小字符串时。 + [source,bash,{source_attr}] ---- $ redis-cli --raw 127.0.0.1:6379> HMSET site domain ""https://www.diguage.com"" owner ""D瓜哥"" OK 127.0.0.1:6379> HGET site domain https://www.diguage.com 127.0.0.1:6379> HGET site owner D瓜哥 127.0.0.1:6379> TYPE site hash 127.0.0.1:6379> OBJECT encoding site ziplist ---- [#quicklist] == quicklist Redis 对外暴露的 list 数据类型,它底层实现所依赖的内部数据结构就是 quicklist。 list 是一个能维持数据项先后顺序的列表(各个数据项的先后顺序由插入位置决定),便于在表的两端追加和删除数据,而对于中间位置的存取具有 O(N) 的时间复杂度。 [quote, redis/quicklist.c] ____ quicklist.c - A doubly linked list of ziplists ____ Redis 在 `quicklist.c` 就说明了,quicklist 是一个双向链表,而且是一个 ziplist 的双向链表。quicklist 的每个节点都是一个 ziplist。这样设计大概又是一个空间和时间的折中: . 双向链表便于在表的两端进行 `push` 和 `pop` 操作,但是它的内存开销比较大。首先,它在每个节点上除了要保存数据之外,还要额外保存两个指针;其次,双向链表的各个节点是单独的内存块,地址不连续,节点多了容易产生内存碎片。 . ziplist 由于是一整块连续内存,所以存储效率很高。但是,它不利于修改操作,每次数据变动都会引发一次内存的 `realloc` 。特别是当 ziplist 长度很长的时候,一次 `realloc` 可能会导致大批量的数据拷贝,进一步降低性能。 于是,结合了双向链表和 ziplist 的优点,quicklist 就应运而生了。 新问题:到底一个 quicklist 节点包含多长的 ziplist 合适呢? . 每个quicklist节点上的ziplist越短,则内存碎片越多。 . 每个quicklist节点上的ziplist越长,则为ziplist分配大块连续内存空间的难度就越大。 Redis 提供了一个配置参数 `list-max-ziplist-size` 让使用者可以来根据自己的情况进行调整: [source] ---- list-max-ziplist-size -2 ---- 这个参数可正可负: * 当取正值的时候,表示按照数据项个数来限定每个 quicklist 节点上的 ziplist 长度。 * 当取负值的时候,表示按照占用字节数来限定每个 quicklist 节点上的 ziplist 长度。这时,它只能取 `-1` 到 `-5` 这五个值,每个值含义如下: ** `-5`: 每个 quicklist 节点上的 ziplist 大小不能超过 64 Kb。(注:1kb => 1024 bytes) ** `-4`: 每个 quicklist 节点上的 ziplist 大小不能超过 32 Kb。 ** `-3`: 每个 quicklist 节点上的 ziplist 大小不能超过 16 Kb。 ** `-2`: 每个 quicklist 节点上的 ziplist 大小不能超过 8 Kb。(-2是Redis给出的默认值) ** `-1`: 每个 quicklist 节点上的 ziplist 大小不能超过 4 Kb。 list的设计目标是能够用来存储很长的数据列表的。当列表很长的时候,最容易被访问的很可能是两端的数据,中间的数据被访问的频率比较低。list 还提供了一个选项,能够把中间的数据节点进行压缩,从而进一步节省内存空间。Redis 的配置参数 `list-compress-depth` 就是用来完成这个设置的。 [source] ---- list-compress-depth 0 // 0 是特殊值,表示都不压缩,默认值。 ---- 这个参数表示一个quicklist两端不被压缩的节点个数。注:这里的节点个数是指quicklist双向链表的节点个数,而不是指ziplist里面的数据项个数。一个 quicklist 节点上的 ziplist,如果被压缩,就是整体被压缩的。 Redis 对于 quicklist 内部节点的压缩算法,采用的 link:++https://en.wikipedia.org/wiki/LZ4_(compression_algorithm)++[LZF^] ——一种无损压缩算法。 **** . 添加过程中,如何处理中间位置的压缩工作? . 头部或者尾部删除,导致 quicklistNode 的非压缩节点不符合设置,怎么处理? . 如果中间删除,节点为压缩节点,怎么处理? **** .quicklist.h [source,c,{source_attr}] ---- /* Node, quicklist, and Iterator are the only data structures used currently. */ /* quicklistNode is a 32 byte struct describing a ziplist for a quicklist. * We use bit fields keep the quicklistNode at 32 bytes. * count: 16 bits, max 65536 (max zl bytes is 65k, so max count actually < 32k). * encoding: 2 bits, RAW=1, LZF=2. * container: 2 bits, NONE=1, ZIPLIST=2. * recompress: 1 bit, bool, true if node is temporarry decompressed for usage. * attempted_compress: 1 bit, boolean, used for verifying during testing. * extra: 10 bits, free for future use; pads out the remainder of 32 bits */ typedef struct quicklistNode { struct quicklistNode *prev; struct quicklistNode *next; unsigned char *zl; unsigned int sz; /* ziplist size in bytes */ unsigned int count : 16; /* count of items in ziplist */ unsigned int encoding : 2; /* RAW==1 or LZF==2 */ unsigned int container : 2; /* NONE==1 or ZIPLIST==2 */ unsigned int recompress : 1; /* was this node previous compressed? */ unsigned int attempted_compress : 1; /* node can't compress; too small */ unsigned int extra : 10; /* more bits to steal for future usage */ } quicklistNode; /* quicklistLZF is a 4+N byte struct holding 'sz' followed by 'compressed'. * 'sz' is byte length of 'compressed' field. * 'compressed' is LZF data with total (compressed) length 'sz' * NOTE: uncompressed length is stored in quicklistNode->sz. * When quicklistNode->zl is compressed, node->zl points to a quicklistLZF */ typedef struct quicklistLZF { unsigned int sz; /* LZF size in bytes*/ char compressed[]; } quicklistLZF; /* Bookmarks are padded with realloc at the end of of the quicklist struct. * They should only be used for very big lists if thousands of nodes were the * excess memory usage is negligible, and there's a real need to iterate on them * in portions. * When not used, they don't add any memory overhead, but when used and then * deleted, some overhead remains (to avoid resonance). * The number of bookmarks used should be kept to minimum since it also adds * overhead on node deletion (searching for a bookmark to update). */ typedef struct quicklistBookmark { quicklistNode *node; char *name; } quicklistBookmark; /* quicklist is a 40 byte struct (on 64-bit systems) describing a quicklist. * 'count' is the number of total entries. * 'len' is the number of quicklist nodes. * 'compress' is: -1 if compression disabled, otherwise it's the number * of quicklistNodes to leave uncompressed at ends of quicklist. * 'fill' is the user-requested (or default) fill factor. * 'bookmakrs are an optional feature that is used by realloc this struct, * so that they don't consume memory when not used. */ typedef struct quicklist { quicklistNode *head; quicklistNode *tail; unsigned long count; /* total count of all entries in all ziplists */ unsigned long len; /* number of quicklistNodes */ int fill : QL_FILL_BITS; /* fill factor for individual nodes */ unsigned int compress : QL_COMP_BITS; /* depth of end nodes not to compress;0=off */ unsigned int bookmark_count: QL_BM_BITS; quicklistBookmark bookmarks[]; } quicklist; typedef struct quicklistIter { const quicklist *quicklist; quicklistNode *current; unsigned char *zi; long offset; /* offset in current ziplist */ int direction; } quicklistIter; typedef struct quicklistEntry { const quicklist *quicklist; quicklistNode *node; unsigned char *zi; unsigned char *value; long long longval; unsigned int sz; int offset; } quicklistEntry; ---- image::images/redis/redis-quicklist-structure.png[] [source,bash,{source_attr}] ---- $ redis-cli --raw 127.0.0.1:6379> RPUSH names diguage ""D瓜哥"" ""https://www.diguage.com/"" 2 127.0.0.1:6379> LRANGE names 0 -1 diguage D瓜哥 https://www.diguage.com/ 127.0.0.1:6379> TYPE names list 127.0.0.1:6379> OBJECT encoding names quicklist ---- == 参考资料 . https://www.diguage.com/post/redis-core-data-structure-1/[Redis 核心数据结构(一) - ""地瓜哥""博客网^] -- 本文中的 Redis 内容是这篇文章的一个拷贝。请以原文为准备,本文尽量同步更新。 . http://zhangtielei.com/posts/blog-redis-ziplist.html[Redis内部数据结构详解(4)——ziplist^] . http://zhangtielei.com/posts/blog-redis-quicklist.html[Redis内部数据结构详解(5)——quicklist^] ArrayList更适合随机访问,而LinkedList更适合插入和删除。 * 对add(E e)方法的分析,可以得知LinkedList添加数据的效率高; * 对remove(int index)方法的分析,可以了解到LinkedList删除数据的效率高; * 对get(int index),set(int index, E element)方法的分析,可以看出LinkdedList查询的效率不高(需要定位,最差要遍历一半); 核心数据结构通过内部类体现,Node就是实际的结点,存放了结点元素和前后结点的引用。 在1.7之前LinkedList是通过headerEntry实现的一个首尾相连的循环链表的。 + 从1.7开始,LinkedList是一个Node实现的非循环链表。 [source,java] ---- private static class Node { E item; Node next; Node prev; Node(Node prev, E element, Node next) { this.item = element; this.next = next; this.prev = prev; } } ---- 代码开始 [source,java] ---- package java.util; import java.util.function.Consumer; ---- == 类的继承关系 image::images/DiagramForLinkedList.png[] 继承自AbstractSequentialList,一个LinkedList抽象的实现; 重点关注实现了Deque接口。 [source,java] ---- public class LinkedList extends AbstractSequentialList implements List, Deque, Cloneable, java.io.Serializable { ---- == 类的属性 [source,java] ---- //存储元素个数 transient int size = 0; //存储头结点 transient Node first; //存储尾结点 transient Node last; ---- == 类的构造器 [source,java] ---- //无参构造器 public LinkedList() { } //通过一个集合初始化LinkedList,元素顺序由这个集合的迭代器返回顺序决定 public LinkedList(Collection c) { //调用无参构造器 this(); //添加元素 addAll(c); } ---- == 类的方法 主要的方法的基础是link和unlink方法组,Node node(int index)定位方法(均不是public) image::images/linkedlist-insert-node.png[] [source,java] ---- //在指定节点前插入节点,节点succ不能为空 void linkBefore(E e, Node succ) { //获取succ的前结点 final Node pred = succ.prev; final Node newNode = new Node<>(pred, e, succ); succ.prev = newNode; if (pred == null)//如果前结点为空 first = newNode; else pred.next = newNode; size++; modCount++; } //把对应参数作为第一个节点,内部使用 private void linkFirst(E e) { //获取头结点 final Node f = first; //定义新结点 final Node newNode = new Node<>(null, e, f); first = newNode; if (f == null)//头结点为null // 赋值尾结点(结果只有一个元素) last = newNode; else //把原来的首结点的引用指向这个新加的结点 f.prev = newNode; size++; modCount++; //LinkedList也采用了“快速失败”的机制,通过记录modCount参数来实现。在面对并发的修改时, //迭代器很快就会完全失败,而不是冒着在将来某个不确定时间发生任意不确定行为的风险。 } //把对应参数作为尾节点(和前一个方法类似) void linkLast(E e) { // 获取尾结点,l为final类型,不可更改 final Node l = last; final Node newNode = new Node<>(l, e, null); last = newNode; if (l == null) first = newNode; else l.next = newNode; size++; modCount++; } ---- image::images/linkedlist-remove-node.png[] [source,java] ---- //删除指定节点并返回被删除的元素值 E unlink(Node x) { // assert x != null; final E element = x.item; final Node next = x.next; final Node prev = x.prev; if (prev == null) { first = next; } else { prev.next = next; x.prev = null; } if (next == null) { last = prev; } else { next.prev = prev; x.next = null; } x.item = null; size--; modCount++; return element; } //删除首节点并返回删除前首节点的值,内部使用 private E unlinkFirst(Node f) { // assert f == first && f != null; final E element = f.item; final Node next = f.next; f.item = null; f.next = null; // help GC first = next; if (next == null) last = null; else next.prev = null; size--; modCount++; return element; } //删除尾节点并返回删除前尾节点的值,内部使用 private E unlinkLast(Node l) { // assert l == last && l != null; final E element = l.item; final Node prev = l.prev; l.item = null; l.prev = null; // help GC last = prev; if (prev == null) first = null; else prev.next = null; size--; modCount++; return element; } ---- [source,java] ---- //获取第一个元素 public E getFirst() { final Node f = first; if (f == null) throw new NoSuchElementException(); return f.item; } //获取最后一个元素 public E getLast() { final Node l = last; if (l == null) throw new NoSuchElementException(); return l.item; } //删除第一个元素并返回删除的元素 public E removeFirst() { final Node f = first; if (f == null) throw new NoSuchElementException(); return unlinkFirst(f); } //删除最后一个元素并返回删除的值 public E removeLast() { final Node l = last; if (l == null) throw new NoSuchElementException(); return unlinkLast(l); } //添加元素作为第一个元素 public void addFirst(E e) { linkFirst(e); } //添加元素作为最后一个元素 public void addLast(E e) { linkLast(e); } //检查是否包含某个元素,返回bool public boolean contains(Object o) { return indexOf(o) != -1; } //返回列表长度 public int size() { return size; } //添加一个元素,默认添加到末尾作为最后一个元素 public boolean add(E e) { linkLast(e); return true; } //删除指定元素,默认从first节点开始,删除第一次出现的那个元素(需要迭代) public boolean remove(Object o) { if (o == null) { for (Node x = first; x != null; x = x.next) { if (x.item == null) { unlink(x); return true; } } } else { for (Node x = first; x != null; x = x.next) { if (o.equals(x.item)) { unlink(x); return true; } } } return false; } //添加指定集合的元素到列表,从最后开始添加 public boolean addAll(Collection c) { //调用addAll(int index, Collection c) return addAll(size, c); } //从指定位置往后追加,index和之后的元素向后顺延 public boolean addAll(int index, Collection c) { checkPositionIndex(index); //转化成数组 Object[] a = c.toArray(); int numNew = a.length; if (numNew == 0) return false; Node pred, succ; if (index == size) { succ = null; pred = last; } else {//如果不是从末尾开始添加,获取新加串的前后结点 succ = node(index); pred = succ.prev; } //遍历数组并添加到列表中 for (Object o : a) { @SuppressWarnings(""unchecked"") E e = (E) o; Node newNode = new Node<>(pred, e, null); if (pred == null) first = newNode; else pred.next = newNode;//如果存在前节点,前节点会向后指向新加的节点 pred = newNode;//新加的节点成为前一个节点 } if (succ == null) { last = pred;//如果是从最后开始添加的,则最后添加的节点成为尾节点 } else { pred.next = succ;//如果不是从最后开始添加的,则最后添加的节点向后指向之前得到的后续第一个节点 succ.prev = pred;//后续的第一个节点也应改为向前指向最后一个添加的节点 } size += numNew; modCount++; return true; } //清空表 public void clear() { //方便gc回收垃圾 for (Node x = first; x != null; ) { Node next = x.next; x.item = null; x.next = null; x.prev = null; x = next; } first = last = null; size = 0; modCount++; } //获取指定索引的节点的值 public E get(int index) { checkElementIndex(index); return node(index).item; } //修改指定索引的值并返回之前的值 public E set(int index, E element) { checkElementIndex(index); Node x = node(index); E oldVal = x.item; //只是把item替换掉 x.item = element; return oldVal; } //在指定位置后面添加元素 public void add(int index, E element) { checkPositionIndex(index); if (index == size) linkLast(element); else linkBefore(element, node(index)); } //删除指定位置的元素 public E remove(int index) { checkElementIndex(index); return unlink(node(index)); } //检查索引是否超出范围(checkElementIndex调用),因为元素索引是0~size-1的,所以index必须满足0<=index= 0 && index < size; } //检查位置是否超出范围(checkPositionIndex调用),index必须在index~size之间(含),如果超出,返回false private boolean isPositionIndex(int index) { return index >= 0 && index <= size; } //异常详情 private String outOfBoundsMsg(int index) { return ""Index: ""+index+"", Size: ""+size; } //检查元素索引是否超出范围(set,get,remove时检查),若已超出,就抛出异常 private void checkElementIndex(int index) { if (!isElementIndex(index)) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } //检查位置是否超出范围(为添加和迭代检查使用),若已超出,就抛出异常 private void checkPositionIndex(int index) { if (!isPositionIndex(index)) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } //获取指定位置的节点 //该方法返回双向链表中指定位置处的节点,而链表中是没有下标索引的,要指定位置出的元素,就要遍历该链表,从源码的实现中,我们看到这里有一个加速动作。 //源码中先将index与长度size的一半比较,如果indexsize/2,就只从位置size往前遍历到位置index处。这样可以减少一部分不必要的遍历。 Node node(int index) { // assert isElementIndex(index); if (index < (size >> 1)) { Node x = first; for (int i = 0; i < index; i++) x = x.next; return x; } else { Node x = last; for (int i = size - 1; i > index; i--) x = x.prev; return x; } } //获取第一个指定元素的索引位置并返回索引,不存在就返回-1 public int indexOf(Object o) { int index = 0; if (o == null) { for (Node x = first; x != null; x = x.next) { if (x.item == null) return index; index++; } } else { for (Node x = first; x != null; x = x.next) { if (o.equals(x.item)) return index; index++; } } return -1; } //获取最后一个指定元素索引的索引并返回索引,不存在就返回-1 public int lastIndexOf(Object o) { int index = size; if (o == null) { for (Node x = last; x != null; x = x.prev) { index--; if (x.item == null) return index; } } else { for (Node x = last; x != null; x = x.prev) { index--; if (o.equals(x.item)) return index; } } return -1; } ---- Queue操作 [source,java] ---- //提供普通队列和双端队列的功能,FIFO //出队(从前端),获得第一个元素,不存在会返回null,不会删除元素(节点) public E peek() { final Node f = first; return (f == null) ? null : f.item; } //出队(从前端),不删除元素,若为null会抛出异常而不是返回null public E element() { return getFirst(); } //出队(从前端),如果不存在会返回null,存在的话会返回值并移除这个元素(节点) public E poll() { final Node f = first; return (f == null) ? null : unlinkFirst(f); } //出队(从前端),如果不存在会抛出异常而不是返回null,存在的话会返回值并移除这个元素(节点) public E remove() { return removeFirst(); } //入队(从后端),始终返回true public boolean offer(E e) { return add(e); } ---- Deque(双端队列)操作 [source,java] ---- //入队(从前端),始终返回true public boolean offerFirst(E e) { addFirst(e); return true; } //入队(从后端),始终返回true public boolean offerLast(E e) { addLast(e); return true; } //出队(从前端),获得第一个元素,不存在会返回null,不会删除元素(节点) public E peekFirst() { final Node f = first; return (f == null) ? null : f.item; } //出队(从后端),获得最后一个元素,不存在会返回null,不会删除元素(节点) public E peekLast() { final Node l = last; return (l == null) ? null : l.item; } //出队(从前端),获得第一个元素,不存在会返回null,会删除元素(节点) public E pollFirst() { final Node f = first; return (f == null) ? null : unlinkFirst(f); } //出队(从后端),获得最后一个元素,不存在会返回null,会删除元素(节点) public E pollLast() { final Node l = last; return (l == null) ? null : unlinkLast(l); } //入栈,从前面添加 public void push(E e) { addFirst(e); } //出栈,返回栈顶元素,从前面移除(会删除) public E pop() { return removeFirst(); } //删除列表中第一出现o的节点 public boolean removeFirstOccurrence(Object o) { return remove(o); } //逆向搜索,删除第一次出现o的节点 public boolean removeLastOccurrence(Object o) { if (o == null) { for (Node x = last; x != null; x = x.prev) { if (x.item == null) { unlink(x); return true; } } } else { for (Node x = last; x != null; x = x.prev) { if (o.equals(x.item)) { unlink(x); return true; } } } return false; } ---- 通用迭代器实现 继承自AbstractSequentialList的方法,AbstractSequentialList抽象类中 public Iterator iterator() { return listIterator(); } 通用迭代器与ArrayList不同,ArrayList自己实现了Iterator,说明linkedlist的迭代器天生支持反向迭代。 ListIterator迭代器实现与ArrayList类似 其中的ListItr继承Itr,实现了ListIterator接口,同时重写了hasPrevious(),nextIndex(), previousIndex(),previous(),set(E e),add(E e)等方法, 所以这也可以看出了Iterator和ListIterator的区别,就是ListIterator在Iterator的基础上增加了添加对象,修改对象, 逆向遍历等方法。 [source,java] ---- public ListIterator listIterator(int index) { checkPositionIndex(index); return new ListItr(index); } private class ListItr implements ListIterator { private Node lastReturned; private Node next; private int nextIndex; private int expectedModCount = modCount; ListItr(int index) { // assert isPositionIndex(index); next = (index == size) ? null : node(index); nextIndex = index; } public boolean hasNext() { return nextIndex < size; } public E next() { checkForComodification(); if (!hasNext()) throw new NoSuchElementException(); lastReturned = next; next = next.next; nextIndex++; return lastReturned.item; } public boolean hasPrevious() { return nextIndex > 0; } public E previous() { checkForComodification(); if (!hasPrevious()) throw new NoSuchElementException(); lastReturned = next = (next == null) ? last : next.prev; nextIndex--; return lastReturned.item; } public int nextIndex() { return nextIndex; } public int previousIndex() { return nextIndex - 1; } public void remove() { checkForComodification(); if (lastReturned == null) throw new IllegalStateException(); Node lastNext = lastReturned.next; unlink(lastReturned); if (next == lastReturned) next = lastNext; else nextIndex--; lastReturned = null; expectedModCount++; } public void set(E e) { if (lastReturned == null) throw new IllegalStateException(); checkForComodification(); lastReturned.item = e; } public void add(E e) { checkForComodification(); lastReturned = null; if (next == null) linkLast(e); else linkBefore(e, next); nextIndex++; expectedModCount++; } public void forEachRemaining(Consumer action) { Objects.requireNonNull(action); while (modCount == expectedModCount && nextIndex < size) { action.accept(next.item); lastReturned = next; next = next.next; nextIndex++; } checkForComodification(); } final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } } ---- [source,java] ---- //节点的数据结构内部类,包含前后节点的引用和当前节点 private static class Node { E item; Node next; Node prev; Node(Node prev, E element, Node next) { this.item = element; this.next = next; this.prev = prev; } } ---- [source,java] ---- //反向迭代器(实现Deque接口) //Deque接口定义的方法,实现Iterator接口,用listIterator迭代器返回一个迭代在此双端队列逆向顺序的元素 public Iterator descendingIterator() { return new DescendingIterator(); } // private class DescendingIterator implements Iterator { private final ListItr itr = new ListItr(size()); public boolean hasNext() { return itr.hasPrevious(); } public E next() { return itr.previous(); } public void remove() { itr.remove(); } } ---- [source,java] ---- @SuppressWarnings(""unchecked"") private LinkedList superClone() { try { return (LinkedList) super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(e); } } //与ArrayList一样都是调用super。clone() //protected native Object clone() throws CloneNotSupportedException; //被复制对象的所有变量都含有与原来的对象相同的值,而所有的对其他对象的引用仍然指向原来的对象。 public Object clone() { LinkedList clone = superClone(); // Put clone into ""virgin"" state clone.first = clone.last = null; clone.size = 0; clone.modCount = 0; // Initialize clone with our elements for (Node x = first; x != null; x = x.next) clone.add(x.item); return clone; } ---- 转换成数组 [source,java] ---- public Object[] toArray() { Object[] result = new Object[size]; int i = 0; for (Node x = first; x != null; x = x.next) result[i++] = x.item; return result; } @SuppressWarnings(""unchecked"") //如果没有参数,就默认生成一个Object数组,如果给了T类型,就将节点内容放入a数组, //如果a的长度小于链表,就使用反射生成一个链表大小的数组,这个时候由于类型是T,所以无法直接实例化。 public T[] toArray(T[] a) { if (a.length < size) a = (T[])java.lang.reflect.Array.newInstance( a.getClass().getComponentType(), size); int i = 0; Object[] result = a; for (Node x = first; x != null; x = x.next) result[i++] = x.item; if (a.length > size) a[size] = null; return a; } ---- 如果声明该方法,它将会被ObjectOutputStream调用而不是默认的序列化进程。如果你是第一次看见它, 你会很惊奇尽管它们被外部类调用但事实上这是两个private的方法。并且它们既不存在于java.lang.Object,也没有在Serializable中声明。 那么ObjectOutputStream如何使用它们的呢?这个吗,ObjectOutputStream使用了反射来寻找是否声明了这两个方法。 因为ObjectOutputStream使用getPrivateMethod,所以这些方法不得不被声明为priate以至于供ObjectOutputStream来使用。 [source,java] ---- private static final long serialVersionUID = 876323262645176354L; //定义了自己的序列化方法,通过反射调用 private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { // Write out any hidden serialization magic s.defaultWriteObject(); // Write out size s.writeInt(size); // Write out all elements in the proper order. for (Node x = first; x != null; x = x.next) s.writeObject(x.item); } @SuppressWarnings(""unchecked"") private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { // Read in any hidden serialization magic s.defaultReadObject(); // Read in size int size = s.readInt(); // Read in all elements in the proper order. for (int i = 0; i < size; i++) linkLast((E)s.readObject()); } ---- [source,java] ---- //以下关于1.8函数式编程 @Override public Spliterator spliterator() { return new LLSpliterator(this, -1, 0); } static final class LLSpliterator implements Spliterator { static final int BATCH_UNIT = 1 << 10; // batch array size increment static final int MAX_BATCH = 1 << 25; // max batch array size; final LinkedList list; // null OK unless traversed Node current; // current node; null until initialized int est; // size estimate; -1 until first needed int expectedModCount; // initialized when est set int batch; // batch size for splits LLSpliterator(LinkedList list, int est, int expectedModCount) { this.list = list; this.est = est; this.expectedModCount = expectedModCount; } final int getEst() { int s; // force initialization final LinkedList lst; if ((s = est) < 0) { if ((lst = list) == null) s = est = 0; else { expectedModCount = lst.modCount; current = lst.first; s = est = lst.size; } } return s; } public long estimateSize() { return (long) getEst(); } public Spliterator trySplit() { Node p; int s = getEst(); if (s > 1 && (p = current) != null) { int n = batch + BATCH_UNIT; if (n > s) n = s; if (n > MAX_BATCH) n = MAX_BATCH; Object[] a = new Object[n]; int j = 0; do { a[j++] = p.item; } while ((p = p.next) != null && j < n); current = p; batch = j; est = s - j; return Spliterators.spliterator(a, 0, j, Spliterator.ORDERED); } return null; } public void forEachRemaining(Consumer action) { Node p; int n; if (action == null) throw new NullPointerException(); if ((n = getEst()) > 0 && (p = current) != null) { current = null; est = 0; do { E e = p.item; p = p.next; action.accept(e); } while (p != null && --n > 0); } if (list.modCount != expectedModCount) throw new ConcurrentModificationException(); } public boolean tryAdvance(Consumer action) { Node p; if (action == null) throw new NullPointerException(); if (getEst() > 0 && (p = current) != null) { --est; E e = p.item; current = p.next; action.accept(e); if (list.modCount != expectedModCount) throw new ConcurrentModificationException(); return true; } return false; } public int characteristics() { return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED; } } } ---- LinkedList与ArrayList的区别: LinkedList与ArrayList在性能上各有优缺点,都有各自适用的地方,总结如下: ArrayList是实现了基于动态数组的数据结构,LinkedList基于链表的数据结构。 + LinkedList不支持高效的随机元素访问。 + ArrayList的空间浪费主要体现在在list列表的结尾预留一定的容量空间, + 而LinkedList的空间花费则体现在它的每一个元素都需要消耗相当的空间(需要附加的空间来表明数据元素的逻辑关系),就存储密度来说,ArrayList是优于LinkedList的。 +   当操作是在一列数据的后面添加数据而不是在前面或中间,并且需要随机地访问其中的元素时,使用ArrayList会提供比较好的性能, + 当你的操作是在一列数据的前面或中间添加或删除数据,并且按照顺序访问其中的元素时,就应该使用LinkedList了。 ",12433,False,2205.570796156612,median "// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include ""ash/system/power/peripheral_battery_listener.h"" #include #include #include #include ""ash/shell.h"" #include ""ash/system/power/peripheral_battery_tests.h"" #include ""ash/test/ash_test_base.h"" #include ""base/scoped_observation.h"" #include ""base/strings/string_number_conversions.h"" #include ""base/strings/string_piece.h"" #include ""base/strings/string_util.h"" #include ""base/strings/utf_string_conversions.h"" #include ""base/test/task_environment.h"" #include ""chromeos/dbus/power/fake_power_manager_client.h"" #include ""device/bluetooth/bluetooth_device.h"" #include ""device/bluetooth/test/mock_bluetooth_adapter.h"" #include ""device/bluetooth/test/mock_bluetooth_device.h"" #include ""testing/gmock/include/gmock/gmock.h"" #include ""third_party/abseil-cpp/absl/types/optional.h"" #include ""ui/events/devices/device_data_manager.h"" #include ""ui/events/devices/device_data_manager_test_api.h"" #include ""ui/events/devices/touchscreen_device.h"" #include ""ui/message_center/public/cpp/notification.h"" using testing::_; using testing::AllOf; using testing::AnyNumber; using testing::Eq; using testing::Expectation; using testing::Field; using testing::Ge; using testing::Gt; using testing::InSequence; using testing::Le; using testing::Lt; using testing::NiceMock; using testing::Optional; using testing::Sequence; using testing::StrictMock; using BI = ash::PeripheralBatteryListener::BatteryInfo; // Annotate testing::Field invocations to improve feedback. #define AFIELD(element, test) testing::Field(#element, element, test) namespace { class MockPeripheralBatteryObserver : public ash::PeripheralBatteryListener::Observer { public: MockPeripheralBatteryObserver() {} // ash::PeripheralBatteryListener::Observer: MOCK_METHOD(void, OnAddingBattery, (const ash::PeripheralBatteryListener::BatteryInfo& battery)); MOCK_METHOD(void, OnRemovingBattery, (const ash::PeripheralBatteryListener::BatteryInfo& battery)); MOCK_METHOD(void, OnUpdatedBatteryLevel, (const ash::PeripheralBatteryListener::BatteryInfo& battery)); }; } // namespace namespace ash { class PeripheralBatteryListenerTest : public AshTestBase { public: // Constants for active field of PeripheralBatteryStylusReceived(). const bool kBluetoothBatteryUpdate = true; const bool kBatteryPolledUpdate = false; const bool kBatteryEventUpdate = true; PeripheralBatteryListenerTest() : AshTestBase(base::test::TaskEnvironment::TimeSource::MOCK_TIME) {} PeripheralBatteryListenerTest(const PeripheralBatteryListenerTest&) = delete; PeripheralBatteryListenerTest& operator=( const PeripheralBatteryListenerTest&) = delete; ~PeripheralBatteryListenerTest() override = default; void SetUp() override { chromeos::PowerManagerClient::InitializeFake(); AshTestBase::SetUp(); ASSERT_TRUE(ui::DeviceDataManager::HasInstance()); // Simulate the complete listing of input devices, required by the listener. if (complete_devices_) ui::DeviceDataManagerTestApi().OnDeviceListsComplete(); mock_adapter_ = base::MakeRefCounted>(); mock_device_1_ = std::make_unique>( mock_adapter_.get(), /*bluetooth_class=*/0, kBluetoothDeviceName1, kBluetoothDeviceAddress1, /*paired=*/true, /*connected=*/true); mock_device_2_ = std::make_unique>( mock_adapter_.get(), /*bluetooth_class=*/0, kBluetoothDeviceName2, kBluetoothDeviceAddress2, /*paired=*/true, /*connected=*/true); battery_listener_ = std::make_unique(); } void TearDown() override { battery_listener_.reset(); AshTestBase::TearDown(); chromeos::PowerManagerClient::Shutdown(); } base::TimeTicks GetTestingClock() { return base::TimeTicks::Now(); } void ClockAdvance(base::TimeDelta delta) { task_environment()->AdvanceClock(delta); } void CreateInternalTouchscreen(bool garage) { // Add an internal stylus to our test device manager. ui::TouchscreenDevice stylus(/*id=*/0, ui::INPUT_DEVICE_INTERNAL, kTestStylusName, gfx::Size(), /*touch_points=*/1, /*has_stylus=*/true, /*has_stylus_garage_switch=*/garage); stylus.sys_path = base::FilePath(kTestStylusBatteryPath); ui::DeviceDataManagerTestApi().SetTouchscreenDevices({stylus}); } void CreateExternalTouchscreen() { // Add an external stylus to our test device manager. ui::TouchscreenDevice stylus(/*id=*/0, ui::INPUT_DEVICE_USB, kTestStylusName, gfx::Size(), /*touch_points=*/1, /*has_stylus=*/true); stylus.sys_path = base::FilePath(kTestStylusBatteryPath); ui::DeviceDataManagerTestApi().SetTouchscreenDevices({stylus}); } protected: scoped_refptr> mock_adapter_; std::unique_ptr mock_device_1_; std::unique_ptr mock_device_2_; std::unique_ptr battery_listener_; void set_complete_devices(bool complete_devices) { complete_devices_ = complete_devices; } // SetUp() doesn't complete devices if this is set to false. bool complete_devices_ = true; }; class PeripheralBatteryListenerIncompleteDevicesTest : public PeripheralBatteryListenerTest { public: PeripheralBatteryListenerIncompleteDevicesTest() { set_complete_devices(false); } ~PeripheralBatteryListenerIncompleteDevicesTest() override {} private: DISALLOW_COPY_AND_ASSIGN(PeripheralBatteryListenerIncompleteDevicesTest); }; TEST_F(PeripheralBatteryListenerTest, Basic) { testing::StrictMock listener_observer_mock; base::ScopedObservation scoped_listener_obs{&listener_observer_mock}; scoped_listener_obs.Observe(battery_listener_.get()); // Level 50 at time 100, listener should be notified. ClockAdvance(base::TimeDelta::FromSeconds(100)); testing::InSequence sequence; EXPECT_CALL(listener_observer_mock, OnAddingBattery(AFIELD(&BI::key, Eq(kTestBatteryId)))); EXPECT_CALL(listener_observer_mock, OnUpdatedBatteryLevel(AllOf( AFIELD(&BI::key, Eq(kTestBatteryId)), AFIELD(&BI::last_update_timestamp, Eq(GetTestingClock())), AFIELD(&BI::last_active_update_timestamp, Eq(absl::nullopt)), AFIELD(&BI::level, Eq(50)), AFIELD(&BI::charge_status, Eq(kTestBatteryStatusOut))))); battery_listener_->PeripheralBatteryStatusReceived( kTestBatteryPath, kTestDeviceName, 50, kTestBatteryStatusIn, kBatteryPolledUpdate); // Level 5 at time 110, listener should be notified. ClockAdvance(base::TimeDelta::FromSeconds(10)); EXPECT_CALL(listener_observer_mock, OnUpdatedBatteryLevel(AllOf( AFIELD(&BI::key, Eq(kTestBatteryId)), AFIELD(&BI::last_update_timestamp, Eq(GetTestingClock())), AFIELD(&BI::last_active_update_timestamp, Eq(absl::nullopt)), AFIELD(&BI::level, Eq(5))))); battery_listener_->PeripheralBatteryStatusReceived( kTestBatteryPath, kTestDeviceName, 5, kTestBatteryStatusIn, kBatteryPolledUpdate); // Level -1 at time 115, listener should be notified. ClockAdvance(base::TimeDelta::FromSeconds(5)); EXPECT_CALL(listener_observer_mock, OnUpdatedBatteryLevel(AllOf( AFIELD(&BI::key, Eq(kTestBatteryId)), AFIELD(&BI::last_update_timestamp, Eq(GetTestingClock())), AFIELD(&BI::last_active_update_timestamp, Eq(absl::nullopt)), AFIELD(&BI::level, Eq(absl::nullopt))))); battery_listener_->PeripheralBatteryStatusReceived( kTestBatteryPath, kTestDeviceName, -1, kTestBatteryStatusIn, kBatteryPolledUpdate); // Level 50 at time 120, listener should be notified. ClockAdvance(base::TimeDelta::FromSeconds(5)); EXPECT_CALL(listener_observer_mock, OnUpdatedBatteryLevel(AllOf( AFIELD(&BI::key, Eq(kTestBatteryId)), AFIELD(&BI::last_update_timestamp, Eq(GetTestingClock())), AFIELD(&BI::last_active_update_timestamp, Eq(absl::nullopt)), AFIELD(&BI::level, Eq(50))))); battery_listener_->PeripheralBatteryStatusReceived( kTestBatteryPath, kTestDeviceName, 50, kTestBatteryStatusIn, kBatteryPolledUpdate); } TEST_F(PeripheralBatteryListenerTest, ActiveUpdates) { testing::StrictMock listener_observer_mock; base::ScopedObservation scoped_listener_obs{&listener_observer_mock}; scoped_listener_obs.Observe(battery_listener_.get()); // Level 50 at time 100, listener should be notified. ClockAdvance(base::TimeDelta::FromSeconds(100)); testing::InSequence sequence; EXPECT_CALL(listener_observer_mock, OnAddingBattery(AFIELD(&BI::key, Eq(kTestBatteryId)))); EXPECT_CALL( listener_observer_mock, OnUpdatedBatteryLevel( AllOf(AFIELD(&BI::key, Eq(kTestBatteryId)), AFIELD(&BI::last_update_timestamp, Eq(GetTestingClock())), AFIELD(&BI::charge_status, Eq(kTestBatteryStatusOut)), AFIELD(&BI::last_active_update_timestamp, Eq(absl::nullopt))))); battery_listener_->PeripheralBatteryStatusReceived( kTestBatteryPath, kTestDeviceName, 50, kTestBatteryStatusIn, kBatteryPolledUpdate); // Level 5 at time 110, listener should be notified. ClockAdvance(base::TimeDelta::FromSeconds(10)); EXPECT_CALL(listener_observer_mock, OnUpdatedBatteryLevel(AllOf( AFIELD(&BI::key, Eq(kTestBatteryId)), AFIELD(&BI::last_update_timestamp, Eq(GetTestingClock())), AFIELD(&BI::last_active_update_timestamp, Optional(GetTestingClock()))))); battery_listener_->PeripheralBatteryStatusReceived( kTestBatteryPath, kTestDeviceName, 5, kTestBatteryStatusIn, kBatteryEventUpdate); // Level -1 at time 115, listener should be notified. ClockAdvance(base::TimeDelta::FromSeconds(5)); EXPECT_CALL(listener_observer_mock, OnUpdatedBatteryLevel(AllOf( AFIELD(&BI::key, Eq(kTestBatteryId)), AFIELD(&BI::last_update_timestamp, Eq(GetTestingClock())), AFIELD(&BI::last_active_update_timestamp, Optional(GetTestingClock()))))); battery_listener_->PeripheralBatteryStatusReceived( kTestBatteryPath, kTestDeviceName, -1, kTestBatteryStatusIn, kBatteryEventUpdate); auto prior_active_update_time = GetTestingClock(); // Level 50 at time 120, listener should be notified. ClockAdvance(base::TimeDelta::FromSeconds(5)); EXPECT_CALL(listener_observer_mock, OnUpdatedBatteryLevel(AllOf( AFIELD(&BI::key, Eq(kTestBatteryId)), AFIELD(&BI::last_update_timestamp, Eq(GetTestingClock())), AFIELD(&BI::last_active_update_timestamp, Optional(prior_active_update_time))))); battery_listener_->PeripheralBatteryStatusReceived( kTestBatteryPath, kTestDeviceName, 50, kTestBatteryStatusIn, kBatteryPolledUpdate); } TEST_F(PeripheralBatteryListenerTest, FirstActiveUpdates) { testing::StrictMock listener_observer_mock; base::ScopedObservation scoped_listener_obs{&listener_observer_mock}; scoped_listener_obs.Observe(battery_listener_.get()); // Level 50 at time 100, listener should be notified. ClockAdvance(base::TimeDelta::FromSeconds(100)); testing::InSequence sequence; EXPECT_CALL(listener_observer_mock, OnAddingBattery(AFIELD(&BI::key, Eq(kTestBatteryId)))); EXPECT_CALL(listener_observer_mock, OnUpdatedBatteryLevel(AllOf( AFIELD(&BI::key, Eq(kTestBatteryId)), AFIELD(&BI::last_update_timestamp, Eq(GetTestingClock())), AFIELD(&BI::last_active_update_timestamp, Optional(GetTestingClock()))))); battery_listener_->PeripheralBatteryStatusReceived( kTestBatteryPath, kTestDeviceName, 50, kTestBatteryStatusIn, kBatteryEventUpdate); } TEST_F(PeripheralBatteryListenerTest, InvalidBatteryInfo) { testing::StrictMock listener_observer_mock; base::ScopedObservation scoped_listener_obs{&listener_observer_mock}; scoped_listener_obs.Observe(battery_listener_.get()); const std::string invalid_path1 = ""invalid-path""; const std::string invalid_path2 = ""/sys/class/power_supply/hid-battery""; EXPECT_CALL(listener_observer_mock, OnAddingBattery(_)).Times(0); EXPECT_CALL(listener_observer_mock, OnUpdatedBatteryLevel(_)).Times(0); battery_listener_->PeripheralBatteryStatusReceived( invalid_path1, kTestDeviceName, 10, kTestBatteryStatusIn, kBatteryPolledUpdate); battery_listener_->PeripheralBatteryStatusReceived( invalid_path2, kTestDeviceName, 10, kTestBatteryStatusIn, kBatteryPolledUpdate); battery_listener_->PeripheralBatteryStatusReceived( kTestBatteryPath, kTestDeviceName, -2, kTestBatteryStatusIn, kBatteryPolledUpdate); battery_listener_->PeripheralBatteryStatusReceived( kTestBatteryPath, kTestDeviceName, 101, kTestBatteryStatusIn, kBatteryPolledUpdate); // Note that -1 is a valid battery level for the Listener, so not checked. } // Verify that for Bluetooth devices, the correct address gets stored in the // BatteryInfo's bluetooth_address member, and for non-Bluetooth devices, that // bluetooth_address member is empty. TEST_F(PeripheralBatteryListenerTest, ExtractBluetoothAddress) { testing::StrictMock listener_observer_mock; base::ScopedObservation scoped_listener_obs{&listener_observer_mock}; scoped_listener_obs.Observe(battery_listener_.get()); const std::string bluetooth_path = ""/sys/class/power_supply/hid-A0:b1:C2:d3:E4:f5-battery""; const std::string expected_bluetooth_address = ""a0:b1:c2:d3:e4:f5""; const std::string expected_bluetooth_id = ""battery_bluetooth-a0:b1:c2:d3:e4:f5""; const std::string non_bluetooth_path = ""/sys/class/power_supply/hid-notbluetooth-battery""; testing::InSequence sequence; EXPECT_CALL(listener_observer_mock, OnAddingBattery(AFIELD(&BI::key, Eq(expected_bluetooth_id)))); EXPECT_CALL( listener_observer_mock, OnUpdatedBatteryLevel(AllOf(AFIELD(&BI::key, Eq(expected_bluetooth_id)), AFIELD(&BI::level, Eq(10))))); battery_listener_->PeripheralBatteryStatusReceived( bluetooth_path, kTestDeviceName, 10, kTestBatteryStatusIn, kBluetoothBatteryUpdate); EXPECT_CALL(listener_observer_mock, OnAddingBattery(AFIELD(&BI::key, Eq(non_bluetooth_path)))); EXPECT_CALL( listener_observer_mock, OnUpdatedBatteryLevel(AllOf(AFIELD(&BI::key, Eq(non_bluetooth_path)), AFIELD(&BI::bluetooth_address, Eq(""""))))); battery_listener_->PeripheralBatteryStatusReceived( non_bluetooth_path, kTestDeviceName, 10, kTestBatteryStatusIn, kBatteryPolledUpdate); } TEST_F(PeripheralBatteryListenerTest, DeviceRemove) { testing::StrictMock listener_observer_mock; base::ScopedObservation scoped_listener_obs{&listener_observer_mock}; scoped_listener_obs.Observe(battery_listener_.get()); testing::InSequence sequence; EXPECT_CALL(listener_observer_mock, OnAddingBattery(AFIELD(&BI::key, Eq(kTestBatteryId)))); EXPECT_CALL(listener_observer_mock, OnUpdatedBatteryLevel(_)); battery_listener_->PeripheralBatteryStatusReceived( kTestBatteryPath, kTestDeviceName, 5, kTestBatteryStatusIn, kBatteryPolledUpdate); EXPECT_CALL(listener_observer_mock, OnRemovingBattery(AFIELD(&BI::key, Eq(kTestBatteryId)))); battery_listener_->RemoveBluetoothBattery(kTestBatteryAddress); } TEST_F(PeripheralBatteryListenerTest, StylusNotification) { testing::StrictMock listener_observer_mock; base::ScopedObservation scoped_listener_obs{&listener_observer_mock}; scoped_listener_obs.Observe(battery_listener_.get()); const std::string kTestStylusBatteryPath = ""/sys/class/power_supply/hid-AAAA:BBBB:CCCC.DDDD-battery""; const std::string kTestStylusName = ""test_stylus""; const auto kTestStylusBatteryStatusDischargingIn = power_manager:: PeripheralBatteryStatus_ChargeStatus_CHARGE_STATUS_DISCHARGING; const auto kTestStylusBatteryStatusDischargingOut = BI::ChargeStatus::kDischarging; // Add an external stylus to our test device manager. ui::TouchscreenDevice stylus(/*id=*/0, ui::INPUT_DEVICE_USB, kTestStylusName, gfx::Size(), /*touch_points=*/1, /*has_stylus=*/true); stylus.sys_path = base::FilePath(kTestStylusBatteryPath); ui::DeviceDataManagerTestApi().SetTouchscreenDevices({stylus}); testing::InSequence sequence; EXPECT_CALL(listener_observer_mock, OnAddingBattery(AFIELD(&BI::key, Eq(kTestStylusBatteryPath)))); EXPECT_CALL(listener_observer_mock, OnUpdatedBatteryLevel(AllOf( AFIELD(&BI::key, Eq(kTestStylusBatteryPath)), AFIELD(&BI::level, Eq(50)), AFIELD(&BI::charge_status, Eq(kTestStylusBatteryStatusDischargingOut)), AFIELD(&BI::type, Eq(BI::PeripheralType::kStylusViaScreen)), AFIELD(&BI::bluetooth_address, Eq(""""))))); battery_listener_->PeripheralBatteryStatusReceived( kTestStylusBatteryPath, kTestStylusName, 50, kTestStylusBatteryStatusDischargingIn, kBatteryPolledUpdate); EXPECT_CALL( listener_observer_mock, OnUpdatedBatteryLevel(AllOf(AFIELD(&BI::key, Eq(kTestStylusBatteryPath)), AFIELD(&BI::level, Eq(5))))); battery_listener_->PeripheralBatteryStatusReceived( kTestStylusBatteryPath, kTestStylusName, 5, kTestStylusBatteryStatusDischargingIn, kBatteryEventUpdate); EXPECT_CALL( listener_observer_mock, OnUpdatedBatteryLevel(AllOf(AFIELD(&BI::key, Eq(kTestStylusBatteryPath)), AFIELD(&BI::level, Eq(absl::nullopt))))); battery_listener_->PeripheralBatteryStatusReceived( kTestStylusBatteryPath, kTestStylusName, -1, kTestStylusBatteryStatusDischargingIn, kBatteryEventUpdate); } TEST_F(PeripheralBatteryListenerTest, Bluetooth_CreatesANotificationForEachDevice) { testing::StrictMock listener_observer_mock; base::ScopedObservation scoped_listener_obs{&listener_observer_mock}; scoped_listener_obs.Observe(battery_listener_.get()); testing::InSequence sequence; EXPECT_CALL(listener_observer_mock, OnAddingBattery(AFIELD(&BI::key, Eq(kBluetoothDeviceId1)))); EXPECT_CALL( listener_observer_mock, OnUpdatedBatteryLevel(AllOf( AFIELD(&BI::key, Eq(kBluetoothDeviceId1)), AFIELD(&BI::level, Eq(5)), AFIELD(&BI::type, Eq(BI::PeripheralType::kOther)), AFIELD(&BI::name, Eq(kBluetoothDeviceName116)), AFIELD(&BI::bluetooth_address, Eq(kBluetoothDeviceAddress1))))); EXPECT_CALL(listener_observer_mock, OnAddingBattery(AFIELD(&BI::key, Eq(kBluetoothDeviceId2)))); EXPECT_CALL( listener_observer_mock, OnUpdatedBatteryLevel(AllOf( AFIELD(&BI::key, Eq(kBluetoothDeviceId2)), AFIELD(&BI::level, Eq(0)), AFIELD(&BI::type, Eq(BI::PeripheralType::kOther)), AFIELD(&BI::name, Eq(kBluetoothDeviceName216)), AFIELD(&BI::bluetooth_address, Eq(kBluetoothDeviceAddress2))))); battery_listener_->DeviceBatteryChanged(mock_adapter_.get(), mock_device_1_.get(), /*new_battery_percentage=*/5); battery_listener_->DeviceBatteryChanged(mock_adapter_.get(), mock_device_2_.get(), /*new_battery_percentage=*/0); } TEST_F(PeripheralBatteryListenerTest, Bluetooth_RemovesNotificationForDisconnectedDevices) { testing::StrictMock listener_observer_mock; base::ScopedObservation scoped_listener_obs{&listener_observer_mock}; scoped_listener_obs.Observe(battery_listener_.get()); testing::InSequence sequence; EXPECT_CALL(listener_observer_mock, OnAddingBattery(AFIELD(&BI::key, Eq(kBluetoothDeviceId1)))); EXPECT_CALL( listener_observer_mock, OnUpdatedBatteryLevel(AllOf( AFIELD(&BI::key, Eq(kBluetoothDeviceId1)), AFIELD(&BI::level, Eq(5)), AFIELD(&BI::type, Eq(BI::PeripheralType::kOther)), AFIELD(&BI::name, Eq(kBluetoothDeviceName116)), AFIELD(&BI::bluetooth_address, Eq(kBluetoothDeviceAddress1))))); EXPECT_CALL(listener_observer_mock, OnAddingBattery(AFIELD(&BI::key, Eq(kBluetoothDeviceId2)))); EXPECT_CALL( listener_observer_mock, OnUpdatedBatteryLevel(AllOf( AFIELD(&BI::key, Eq(kBluetoothDeviceId2)), AFIELD(&BI::level, Eq(0)), AFIELD(&BI::type, Eq(BI::PeripheralType::kOther)), AFIELD(&BI::name, Eq(kBluetoothDeviceName216)), AFIELD(&BI::bluetooth_address, Eq(kBluetoothDeviceAddress2))))); battery_listener_->DeviceBatteryChanged(mock_adapter_.get(), mock_device_1_.get(), /*new_battery_percentage=*/5); battery_listener_->DeviceBatteryChanged(mock_adapter_.get(), mock_device_2_.get(), /*new_battery_percentage=*/0); EXPECT_CALL(listener_observer_mock, OnRemovingBattery(AFIELD(&BI::key, Eq(kBluetoothDeviceId1)))); // Verify only the notification for device 1 gets removed. battery_listener_->DeviceConnectedStateChanged(mock_adapter_.get(), mock_device_1_.get(), false); EXPECT_CALL(listener_observer_mock, OnRemovingBattery(AFIELD(&BI::key, Eq(kBluetoothDeviceId2)))); // Remove the second notification. battery_listener_->DeviceRemoved(mock_adapter_.get(), mock_device_2_.get()); } TEST_F(PeripheralBatteryListenerTest, Bluetooth_RemovesNotificationForDisconnectedDevicesInOtherOrder) { testing::StrictMock listener_observer_mock; base::ScopedObservation scoped_listener_obs{&listener_observer_mock}; scoped_listener_obs.Observe(battery_listener_.get()); testing::InSequence sequence; EXPECT_CALL(listener_observer_mock, OnAddingBattery(AFIELD(&BI::key, Eq(kBluetoothDeviceId1)))); EXPECT_CALL( listener_observer_mock, OnUpdatedBatteryLevel( AllOf(AFIELD(&BI::key, Eq(kBluetoothDeviceId1)), AFIELD(&BI::bluetooth_address, Eq(kBluetoothDeviceAddress1))))); EXPECT_CALL(listener_observer_mock, OnAddingBattery(AFIELD(&BI::key, Eq(kBluetoothDeviceId2)))); EXPECT_CALL( listener_observer_mock, OnUpdatedBatteryLevel( AllOf(AFIELD(&BI::key, Eq(kBluetoothDeviceId2)), AFIELD(&BI::bluetooth_address, Eq(kBluetoothDeviceAddress2))))); battery_listener_->DeviceBatteryChanged(mock_adapter_.get(), mock_device_1_.get(), /*new_battery_percentage=*/5); battery_listener_->DeviceBatteryChanged(mock_adapter_.get(), mock_device_2_.get(), /*new_battery_percentage=*/0); EXPECT_CALL(listener_observer_mock, OnRemovingBattery(AFIELD(&BI::key, Eq(kBluetoothDeviceId2)))); // Remove the second notification. battery_listener_->DeviceRemoved(mock_adapter_.get(), mock_device_2_.get()); EXPECT_CALL(listener_observer_mock, OnRemovingBattery(AFIELD(&BI::key, Eq(kBluetoothDeviceId1)))); // Verify only the notification for device 1 gets removed. battery_listener_->DeviceConnectedStateChanged(mock_adapter_.get(), mock_device_1_.get(), false); } TEST_F(PeripheralBatteryListenerTest, Bluetooth_RemoveAndReconnect) { testing::StrictMock listener_observer_mock; base::ScopedObservation scoped_listener_obs{&listener_observer_mock}; scoped_listener_obs.Observe(battery_listener_.get()); testing::InSequence sequence; EXPECT_CALL(listener_observer_mock, OnAddingBattery(AFIELD(&BI::key, Eq(kBluetoothDeviceId1)))); EXPECT_CALL( listener_observer_mock, OnUpdatedBatteryLevel( AllOf(AFIELD(&BI::key, Eq(kBluetoothDeviceId1)), AFIELD(&BI::bluetooth_address, Eq(kBluetoothDeviceAddress1))))); battery_listener_->DeviceBatteryChanged(mock_adapter_.get(), mock_device_1_.get(), /*new_battery_percentage=*/5); EXPECT_CALL(listener_observer_mock, OnRemovingBattery(AFIELD(&BI::key, Eq(kBluetoothDeviceId1)))); battery_listener_->DeviceConnectedStateChanged(mock_adapter_.get(), mock_device_1_.get(), false); EXPECT_CALL(listener_observer_mock, OnAddingBattery(AFIELD(&BI::key, Eq(kBluetoothDeviceId1)))); EXPECT_CALL( listener_observer_mock, OnUpdatedBatteryLevel( AllOf(AFIELD(&BI::key, Eq(kBluetoothDeviceId1)), AFIELD(&BI::bluetooth_address, Eq(kBluetoothDeviceAddress1))))); battery_listener_->DeviceBatteryChanged(mock_adapter_.get(), mock_device_1_.get(), /*new_battery_percentage=*/5); } TEST_F(PeripheralBatteryListenerTest, Bluetooth_CancelNotificationForInvalidBatteryLevel) { testing::StrictMock listener_observer_mock; base::ScopedObservation scoped_listener_obs{&listener_observer_mock}; scoped_listener_obs.Observe(battery_listener_.get()); testing::InSequence sequence; EXPECT_CALL(listener_observer_mock, OnAddingBattery(AFIELD(&BI::key, Eq(kBluetoothDeviceId1)))); EXPECT_CALL( listener_observer_mock, OnUpdatedBatteryLevel(AllOf(AFIELD(&BI::key, Eq(kBluetoothDeviceId1)), AFIELD(&BI::level, Eq(1))))); battery_listener_->DeviceBatteryChanged(mock_adapter_.get(), mock_device_1_.get(), /*new_battery_percentage=*/1); EXPECT_CALL( listener_observer_mock, OnUpdatedBatteryLevel(AllOf(AFIELD(&BI::key, Eq(kBluetoothDeviceId1)), AFIELD(&BI::level, Eq(absl::nullopt))))); battery_listener_->DeviceBatteryChanged( mock_adapter_.get(), mock_device_1_.get(), /*new_battery_percentage=*/absl::nullopt); } // Do notify observer if the battery level drops again under the // threshold before kNotificationInterval is completed. TEST_F(PeripheralBatteryListenerTest, EnsureUpdatesWithinSmallTimeIntervals) { testing::StrictMock listener_observer_mock; base::ScopedObservation scoped_listener_obs{&listener_observer_mock}; scoped_listener_obs.Observe(battery_listener_.get()); ClockAdvance(base::TimeDelta::FromSeconds(100)); testing::InSequence sequence; EXPECT_CALL(listener_observer_mock, OnAddingBattery(AFIELD(&BI::key, Eq(kBluetoothDeviceId1)))); EXPECT_CALL(listener_observer_mock, OnUpdatedBatteryLevel(AllOf( AFIELD(&BI::key, Eq(kBluetoothDeviceId1)), AFIELD(&BI::last_update_timestamp, Eq(GetTestingClock())), AFIELD(&BI::level, Eq(1))))); battery_listener_->DeviceBatteryChanged(mock_adapter_.get(), mock_device_1_.get(), /*new_battery_percentage=*/1); ClockAdvance(base::TimeDelta::FromSeconds(1)); EXPECT_CALL(listener_observer_mock, OnUpdatedBatteryLevel(AllOf( AFIELD(&BI::key, Eq(kBluetoothDeviceId1)), AFIELD(&BI::last_update_timestamp, Eq(GetTestingClock())), AFIELD(&BI::level, Eq(absl::nullopt))))); battery_listener_->DeviceBatteryChanged( mock_adapter_.get(), mock_device_1_.get(), /*new_battery_percentage=*/absl::nullopt); ClockAdvance(base::TimeDelta::FromSeconds(1)); EXPECT_CALL(listener_observer_mock, OnUpdatedBatteryLevel(AllOf( AFIELD(&BI::key, Eq(kBluetoothDeviceId1)), AFIELD(&BI::last_update_timestamp, Eq(GetTestingClock())), AFIELD(&BI::level, Eq(1))))); battery_listener_->DeviceBatteryChanged(mock_adapter_.get(), mock_device_1_.get(), /*new_battery_percentage=*/1); } // Notify observer if the battery is under threshold, then unknown level and // then is again under the threshold after kNotificationInterval is completed. // (Listener should not pay attention to kNotificationInterval anyway.) TEST_F(PeripheralBatteryListenerTest, PostNotificationIfBatteryGoesFromUnknownLevelToBelowThreshold) { testing::StrictMock listener_observer_mock; base::ScopedObservation scoped_listener_obs{&listener_observer_mock}; scoped_listener_obs.Observe(battery_listener_.get()); ClockAdvance(base::TimeDelta::FromSeconds(100)); testing::InSequence sequence; EXPECT_CALL(listener_observer_mock, OnAddingBattery(AFIELD(&BI::key, Eq(kBluetoothDeviceId1)))); EXPECT_CALL(listener_observer_mock, OnUpdatedBatteryLevel(AllOf( AFIELD(&BI::key, Eq(kBluetoothDeviceId1)), AFIELD(&BI::last_update_timestamp, Eq(GetTestingClock())), AFIELD(&BI::level, Eq(1))))); battery_listener_->DeviceBatteryChanged(mock_adapter_.get(), mock_device_1_.get(), /*new_battery_percentage=*/1); ClockAdvance(base::TimeDelta::FromSeconds(1)); EXPECT_CALL(listener_observer_mock, OnUpdatedBatteryLevel(AllOf( AFIELD(&BI::key, Eq(kBluetoothDeviceId1)), AFIELD(&BI::last_update_timestamp, Eq(GetTestingClock())), AFIELD(&BI::level, Eq(absl::nullopt))))); battery_listener_->DeviceBatteryChanged( mock_adapter_.get(), mock_device_1_.get(), /*new_battery_percentage=*/absl::nullopt); ClockAdvance(base::TimeDelta::FromSeconds(100)); EXPECT_CALL(listener_observer_mock, OnUpdatedBatteryLevel(AllOf( AFIELD(&BI::key, Eq(kBluetoothDeviceId1)), AFIELD(&BI::last_update_timestamp, Eq(GetTestingClock())), AFIELD(&BI::level, Eq(1))))); battery_listener_->DeviceBatteryChanged(mock_adapter_.get(), mock_device_1_.get(), /*new_battery_percentage=*/1); } // If there is an existing notification and the battery level remains low, // update its content. TEST_F(PeripheralBatteryListenerTest, UpdateNotificationIfVisible) { testing::StrictMock listener_observer_mock; base::ScopedObservation scoped_listener_obs{&listener_observer_mock}; scoped_listener_obs.Observe(battery_listener_.get()); testing::InSequence sequence; ClockAdvance(base::TimeDelta::FromSeconds(100)); EXPECT_CALL(listener_observer_mock, OnAddingBattery(AFIELD(&BI::key, Eq(kBluetoothDeviceId1)))); EXPECT_CALL(listener_observer_mock, OnUpdatedBatteryLevel(AllOf( AFIELD(&BI::key, Eq(kBluetoothDeviceId1)), AFIELD(&BI::last_update_timestamp, Eq(GetTestingClock())), AFIELD(&BI::level, Eq(5))))); battery_listener_->DeviceBatteryChanged(mock_adapter_.get(), mock_device_1_.get(), /*new_battery_percentage=*/5); // The battery level remains low, should update the notification. ClockAdvance(base::TimeDelta::FromSeconds(100)); EXPECT_CALL(listener_observer_mock, OnUpdatedBatteryLevel(AllOf( AFIELD(&BI::key, Eq(kBluetoothDeviceId1)), AFIELD(&BI::last_update_timestamp, Eq(GetTestingClock())), AFIELD(&BI::level, Eq(3))))); battery_listener_->DeviceBatteryChanged(mock_adapter_.get(), mock_device_1_.get(), /*new_battery_percentage=*/3); } TEST_F(PeripheralBatteryListenerTest, MultipleObserversCoexist) { testing::StrictMock listener_observer_mock_1; testing::StrictMock listener_observer_mock_2; base::ScopedObservation scoped_listener_obs_1{&listener_observer_mock_1}; base::ScopedObservation scoped_listener_obs_2{&listener_observer_mock_2}; scoped_listener_obs_1.Observe(battery_listener_.get()); scoped_listener_obs_2.Observe(battery_listener_.get()); EXPECT_CALL(listener_observer_mock_1, OnAddingBattery(AFIELD(&BI::key, Eq(kTestBatteryId)))); EXPECT_CALL(listener_observer_mock_2, OnAddingBattery(AFIELD(&BI::key, Eq(kTestBatteryId)))); EXPECT_CALL(listener_observer_mock_1, OnUpdatedBatteryLevel(AllOf(AFIELD(&BI::key, Eq(kTestBatteryId)), AFIELD(&BI::level, Eq(50))))); EXPECT_CALL(listener_observer_mock_2, OnUpdatedBatteryLevel(AllOf(AFIELD(&BI::key, Eq(kTestBatteryId)), AFIELD(&BI::level, Eq(50))))); battery_listener_->PeripheralBatteryStatusReceived( kTestBatteryPath, kTestDeviceName, 50, kTestBatteryStatusIn, kBatteryPolledUpdate); } TEST_F(PeripheralBatteryListenerTest, ObserverationLifetimeObeyed) { testing::StrictMock listener_observer_mock; base::ScopedObservation scoped_listener_obs{&listener_observer_mock}; testing::InSequence sequence; // Connect observer, add and remove battery scoped_listener_obs.Observe(battery_listener_.get()); EXPECT_CALL(listener_observer_mock, OnAddingBattery(AFIELD(&BI::key, Eq(kTestBatteryId)))); EXPECT_CALL(listener_observer_mock, OnUpdatedBatteryLevel(_)); battery_listener_->PeripheralBatteryStatusReceived( kTestBatteryPath, kTestDeviceName, 5, kTestBatteryStatusIn, kBatteryPolledUpdate); EXPECT_CALL(listener_observer_mock, OnRemovingBattery(AFIELD(&BI::key, Eq(kTestBatteryId)))); battery_listener_->RemoveBluetoothBattery(kTestBatteryAddress); // Disconnect observer, add and remove battery scoped_listener_obs.Reset(); battery_listener_->PeripheralBatteryStatusReceived( kTestBatteryPath, kTestDeviceName, 5, kTestBatteryStatusIn, kBatteryPolledUpdate); battery_listener_->RemoveBluetoothBattery(kTestBatteryAddress); // Reconnect observer, add and remove battery scoped_listener_obs.Observe(battery_listener_.get()); EXPECT_CALL(listener_observer_mock, OnAddingBattery(AFIELD(&BI::key, Eq(kTestBatteryId)))); EXPECT_CALL(listener_observer_mock, OnUpdatedBatteryLevel(_)); battery_listener_->PeripheralBatteryStatusReceived( kTestBatteryPath, kTestDeviceName, 5, kTestBatteryStatusIn, kBatteryPolledUpdate); EXPECT_CALL(listener_observer_mock, OnRemovingBattery(AFIELD(&BI::key, Eq(kTestBatteryId)))); battery_listener_->RemoveBluetoothBattery(kTestBatteryAddress); } // Check that observers only see events occuring while they are connected. TEST_F(PeripheralBatteryListenerTest, PartialObserverationLifetimeObeyed) { testing::StrictMock listener_observer_mock; base::ScopedObservation scoped_listener_obs{&listener_observer_mock}; testing::InSequence sequence; // Connect observer, add and remove battery. scoped_listener_obs.Observe(battery_listener_.get()); EXPECT_CALL(listener_observer_mock, OnAddingBattery(_)); EXPECT_CALL(listener_observer_mock, OnUpdatedBatteryLevel(_)); battery_listener_->PeripheralBatteryStatusReceived( kTestBatteryPath, kTestDeviceName, 5, kTestBatteryStatusIn, kBatteryPolledUpdate); // Disconnect observer before we remove battery. scoped_listener_obs.Reset(); battery_listener_->RemoveBluetoothBattery(kTestBatteryAddress); // Reconnect battery. battery_listener_->PeripheralBatteryStatusReceived( kTestBatteryPath, kTestDeviceName, 5, kTestBatteryStatusIn, true); // Reconnect observer, add and remove battery. EXPECT_CALL(listener_observer_mock, OnAddingBattery(_)); EXPECT_CALL(listener_observer_mock, OnUpdatedBatteryLevel(_)); scoped_listener_obs.Observe(battery_listener_.get()); EXPECT_CALL(listener_observer_mock, OnRemovingBattery(_)); battery_listener_->RemoveBluetoothBattery(kTestBatteryAddress); } // Check that observers will get events to 'catch up' on batteries they missed. TEST_F(PeripheralBatteryListenerTest, PartialObserverationLifetimeCatchUp) { testing::StrictMock listener_observer_mock; base::ScopedObservation scoped_listener_obs{&listener_observer_mock}; testing::InSequence sequence; // Connect battery. battery_listener_->PeripheralBatteryStatusReceived( kTestBatteryPath, kTestDeviceName, 5, kTestBatteryStatusIn, kBatteryEventUpdate); EXPECT_CALL(listener_observer_mock, OnAddingBattery(_)); EXPECT_CALL(listener_observer_mock, OnUpdatedBatteryLevel(_)); scoped_listener_obs.Observe(battery_listener_.get()); EXPECT_CALL(listener_observer_mock, OnRemovingBattery(_)); battery_listener_->RemoveBluetoothBattery(kTestBatteryAddress); } TEST_F(PeripheralBatteryListenerTest, MultipleObserverationLifetimeObeyed) { testing::StrictMock listener_observer_mock_1; testing::StrictMock listener_observer_mock_2; base::ScopedObservation scoped_listener_obs_1{&listener_observer_mock_1}; base::ScopedObservation scoped_listener_obs_2{&listener_observer_mock_2}; testing::InSequence sequence; scoped_listener_obs_1.Observe(battery_listener_.get()); EXPECT_CALL(listener_observer_mock_1, OnAddingBattery(_)); EXPECT_CALL(listener_observer_mock_1, OnUpdatedBatteryLevel(_)); battery_listener_->PeripheralBatteryStatusReceived( kTestBatteryPath, kTestDeviceName, 5, kTestBatteryStatusIn, kBatteryPolledUpdate); EXPECT_CALL(listener_observer_mock_2, OnAddingBattery(_)); EXPECT_CALL(listener_observer_mock_2, OnUpdatedBatteryLevel(_)); scoped_listener_obs_2.Observe(battery_listener_.get()); EXPECT_CALL(listener_observer_mock_1, OnRemovingBattery(_)); EXPECT_CALL(listener_observer_mock_2, OnRemovingBattery(_)); battery_listener_->RemoveBluetoothBattery(kTestBatteryAddress); scoped_listener_obs_1.Reset(); EXPECT_CALL(listener_observer_mock_2, OnAddingBattery(_)); EXPECT_CALL(listener_observer_mock_2, OnUpdatedBatteryLevel(_)); battery_listener_->PeripheralBatteryStatusReceived( kTestBatteryPath, kTestDeviceName, 5, kTestBatteryStatusIn, kBatteryPolledUpdate); EXPECT_CALL(listener_observer_mock_2, OnRemovingBattery(_)); battery_listener_->RemoveBluetoothBattery(kTestBatteryAddress); } TEST_F(PeripheralBatteryListenerTest, Charger) { testing::StrictMock listener_observer_mock; base::ScopedObservation scoped_listener_obs{&listener_observer_mock}; scoped_listener_obs.Observe(battery_listener_.get()); testing::InSequence sequence; EXPECT_CALL(listener_observer_mock, OnAddingBattery(AFIELD(&BI::key, Eq(kTestChargerId)))); EXPECT_CALL( listener_observer_mock, OnUpdatedBatteryLevel( AllOf(AFIELD(&BI::key, Eq(kTestChargerId)), AFIELD(&BI::type, Eq(BI::PeripheralType::kStylusViaCharger)), AFIELD(&BI::level, Eq(50)), AFIELD(&BI::charge_status, Eq(BI::ChargeStatus::kCharging))))); battery_listener_->PeripheralBatteryStatusReceived( kTestChargerPath, kTestChargerName, 50, power_manager:: PeripheralBatteryStatus_ChargeStatus_CHARGE_STATUS_CHARGING, kBatteryEventUpdate); } TEST_F(PeripheralBatteryListenerTest, ChargerError) { testing::StrictMock listener_observer_mock; base::ScopedObservation scoped_listener_obs{&listener_observer_mock}; scoped_listener_obs.Observe(battery_listener_.get()); testing::InSequence sequence; EXPECT_CALL(listener_observer_mock, OnAddingBattery(AFIELD(&BI::key, Eq(kTestChargerId)))); EXPECT_CALL( listener_observer_mock, OnUpdatedBatteryLevel(AllOf( AFIELD(&BI::key, Eq(kTestChargerId)), AFIELD(&BI::level, Eq(50)), AFIELD(&BI::charge_status, Eq(BI::ChargeStatus::kError))))); battery_listener_->PeripheralBatteryStatusReceived( kTestChargerPath, kTestChargerName, 50, power_manager::PeripheralBatteryStatus_ChargeStatus_CHARGE_STATUS_ERROR, kBatteryPolledUpdate); } TEST_F(PeripheralBatteryListenerTest, ChargerErrorTransition) { testing::StrictMock listener_observer_mock; base::ScopedObservation scoped_listener_obs{&listener_observer_mock}; scoped_listener_obs.Observe(battery_listener_.get()); testing::InSequence sequence; EXPECT_CALL(listener_observer_mock, OnAddingBattery(AFIELD(&BI::key, Eq(kTestChargerId)))); EXPECT_CALL( listener_observer_mock, OnUpdatedBatteryLevel(AllOf( AFIELD(&BI::key, Eq(kTestChargerId)), AFIELD(&BI::level, Eq(50)), AFIELD(&BI::charge_status, Eq(BI::ChargeStatus::kCharging))))); battery_listener_->PeripheralBatteryStatusReceived( kTestChargerPath, kTestChargerName, 50, power_manager:: PeripheralBatteryStatus_ChargeStatus_CHARGE_STATUS_CHARGING, kBatteryPolledUpdate); EXPECT_CALL( listener_observer_mock, OnUpdatedBatteryLevel(AllOf( AFIELD(&BI::key, Eq(kTestChargerId)), AFIELD(&BI::level, Eq(50)), AFIELD(&BI::charge_status, Eq(BI::ChargeStatus::kError))))); battery_listener_->PeripheralBatteryStatusReceived( kTestChargerPath, kTestChargerName, 50, power_manager::PeripheralBatteryStatus_ChargeStatus_CHARGE_STATUS_ERROR, kBatteryEventUpdate); } // Stylus-via-screen updates of level zero should be translated to // nullopt as zero is not a valid level, but may come through during // boot or other device creation scenarios. TEST_F(PeripheralBatteryListenerTest, StylusDiscardsZeros) { testing::StrictMock listener_observer_mock; base::ScopedObservation scoped_listener_obs{&listener_observer_mock}; scoped_listener_obs.Observe(battery_listener_.get()); CreateExternalTouchscreen(); testing::InSequence sequence; EXPECT_CALL(listener_observer_mock, OnAddingBattery(AFIELD(&BI::key, Eq(kTestStylusBatteryPath)))); EXPECT_CALL(listener_observer_mock, OnUpdatedBatteryLevel(AllOf( AFIELD(&BI::key, Eq(kTestStylusBatteryPath)), AFIELD(&BI::type, Eq(BI::PeripheralType::kStylusViaScreen)), AFIELD(&BI::level, Eq(absl::nullopt)), AFIELD(&BI::charge_status, Eq(kTestStylusBatteryStatusDischargingOut))))); battery_listener_->PeripheralBatteryStatusReceived( kTestStylusBatteryPath, kTestStylusName, 0, kTestStylusBatteryStatusDischargingIn, kBatteryEventUpdate); EXPECT_CALL(listener_observer_mock, OnUpdatedBatteryLevel(AllOf(AFIELD(&BI::level, Eq(50))))); battery_listener_->PeripheralBatteryStatusReceived( kTestStylusBatteryPath, kTestStylusName, 50, kTestStylusBatteryStatusDischargingIn, kBatteryEventUpdate); EXPECT_CALL( listener_observer_mock, OnUpdatedBatteryLevel(AllOf(AFIELD(&BI::level, Eq(absl::nullopt))))); battery_listener_->PeripheralBatteryStatusReceived( kTestStylusBatteryPath, kTestStylusName, 0, kTestStylusBatteryStatusDischargingIn, kBatteryEventUpdate); } // Stylus-via-charger updates of level zero should translate to nullopt if // no value is known; otherwise they should be ignored as not providing // information. TEST_F(PeripheralBatteryListenerTest, StylusChargerDoesNullZeros) { testing::StrictMock listener_observer_mock; base::ScopedObservation scoped_listener_obs{&listener_observer_mock}; scoped_listener_obs.Observe(battery_listener_.get()); testing::InSequence sequence; EXPECT_CALL(listener_observer_mock, OnAddingBattery(AFIELD(&BI::key, Eq(kTestChargerId)))); EXPECT_CALL(listener_observer_mock, OnUpdatedBatteryLevel(AllOf( AFIELD(&BI::key, Eq(kTestChargerId)), AFIELD(&BI::type, Eq(BI::PeripheralType::kStylusViaCharger)), AFIELD(&BI::level, Eq(absl::nullopt)), AFIELD(&BI::charge_status, Eq(kTestBatteryStatusOut))))); battery_listener_->PeripheralBatteryStatusReceived( kTestChargerPath, kTestChargerName, 0, kTestBatteryStatusIn, kBatteryEventUpdate); EXPECT_CALL(listener_observer_mock, OnUpdatedBatteryLevel(AllOf(AFIELD(&BI::level, Eq(50))))); battery_listener_->PeripheralBatteryStatusReceived( kTestChargerPath, kTestChargerName, 50, kTestBatteryStatusIn, kBatteryEventUpdate); EXPECT_CALL(listener_observer_mock, OnUpdatedBatteryLevel(AllOf(AFIELD(&BI::level, Eq(50))))); battery_listener_->PeripheralBatteryStatusReceived( kTestChargerPath, kTestChargerName, 0, kTestBatteryStatusIn, kBatteryEventUpdate); } // Bluetooth/other HID updates of level zero should come through as expected, as // we don't know that 0 is invalid. TEST_F(PeripheralBatteryListenerTest, BluetoothDoesNotDiscardZeros) { testing::StrictMock listener_observer_mock; base::ScopedObservation scoped_listener_obs{&listener_observer_mock}; scoped_listener_obs.Observe(battery_listener_.get()); testing::InSequence sequence; EXPECT_CALL(listener_observer_mock, OnAddingBattery(AFIELD(&BI::key, Eq(kBluetoothDeviceId1)))); EXPECT_CALL( listener_observer_mock, OnUpdatedBatteryLevel(AllOf( AFIELD(&BI::key, Eq(kBluetoothDeviceId1)), AFIELD(&BI::level, Eq(0)), AFIELD(&BI::type, Eq(BI::PeripheralType::kOther)), AFIELD(&BI::name, Eq(kBluetoothDeviceName116)), AFIELD(&BI::bluetooth_address, Eq(kBluetoothDeviceAddress1))))); battery_listener_->DeviceBatteryChanged(mock_adapter_.get(), mock_device_1_.get(), /*new_battery_percentage=*/0); EXPECT_CALL(listener_observer_mock, OnUpdatedBatteryLevel(AllOf(AFIELD(&BI::level, Eq(5))))); battery_listener_->DeviceBatteryChanged(mock_adapter_.get(), mock_device_1_.get(), /*new_battery_percentage=*/5); } // Stylus garage charging TEST_F(PeripheralBatteryListenerIncompleteDevicesTest, DoNotSynthesizeGarageCharger) { // Create touchscreen w/ stylus, w/o dockswitch // Verify Stylus Garage does not exist testing::StrictMock listener_observer_mock; base::ScopedObservation scoped_listener_obs{&listener_observer_mock}; testing::InSequence sequence; CreateInternalTouchscreen(false); ui::DeviceDataManagerTestApi().OnDeviceListsComplete(); scoped_listener_obs.Observe(battery_listener_.get()); // Level 50 at time 100, listener should be notified. ClockAdvance(base::TimeDelta::FromSeconds(100)); EXPECT_CALL(listener_observer_mock, OnAddingBattery(AFIELD(&BI::key, Eq(kTestStylusBatteryPath)))); EXPECT_CALL(listener_observer_mock, OnUpdatedBatteryLevel(AllOf( AFIELD(&BI::key, Eq(kTestStylusBatteryPath)), AFIELD(&BI::level, Eq(50)), AFIELD(&BI::charge_status, Eq(kTestStylusBatteryStatusDischargingOut)), AFIELD(&BI::type, Eq(BI::PeripheralType::kStylusViaScreen)), AFIELD(&BI::bluetooth_address, Eq(""""))))); battery_listener_->PeripheralBatteryStatusReceived( kTestStylusBatteryPath, kTestStylusName, 50, kTestStylusBatteryStatusDischargingIn, kBatteryPolledUpdate); } TEST_F(PeripheralBatteryListenerIncompleteDevicesTest, DoSynthesizeGarageCharger) { // Create touchscreen w/ stylus, w/ dockswitch // Stylus is not garaged at start // Trigger touchscreen stylus update event // Verify Stylus Garage does exist testing::StrictMock listener_observer_mock; base::ScopedObservation scoped_listener_obs{&listener_observer_mock}; CreateInternalTouchscreen(true); ui::DeviceDataManagerTestApi().OnDeviceListsComplete(); scoped_listener_obs.Observe(battery_listener_.get()); // Level 50 at time 100, listener should be notified. ClockAdvance(base::TimeDelta::FromSeconds(100)); Expectation a = EXPECT_CALL( listener_observer_mock, OnAddingBattery(AFIELD(&BI::key, Eq(kStylusChargerDeviceName)))); Expectation b = EXPECT_CALL( listener_observer_mock, OnAddingBattery(AFIELD(&BI::key, Eq(kTestStylusBatteryPath)))); EXPECT_CALL(listener_observer_mock, OnUpdatedBatteryLevel(AllOf( AFIELD(&BI::key, Eq(kStylusChargerDeviceName)), AFIELD(&BI::level, Eq(absl::nullopt)), AFIELD(&BI::charge_status, Eq(BI::ChargeStatus::kUnknown)), AFIELD(&BI::type, Eq(BI::PeripheralType::kStylusViaCharger)), AFIELD(&BI::bluetooth_address, Eq(""""))))) .After(a); EXPECT_CALL(listener_observer_mock, OnUpdatedBatteryLevel(AllOf( AFIELD(&BI::key, Eq(kTestStylusBatteryPath)), AFIELD(&BI::level, Eq(50)), AFIELD(&BI::charge_status, Eq(kTestStylusBatteryStatusDischargingOut)), AFIELD(&BI::type, Eq(BI::PeripheralType::kStylusViaScreen)), AFIELD(&BI::bluetooth_address, Eq(""""))))) .After(b); battery_listener_->PeripheralBatteryStatusReceived( kTestStylusBatteryPath, kTestStylusName, 50, kTestStylusBatteryStatusDischargingIn, kBatteryPolledUpdate); } TEST_F(PeripheralBatteryListenerIncompleteDevicesTest, GarageCharging) { // Create touchscreen w/ stylus, w/ dockswitch // Stylus not in dock at beginning // Put stylus on charger, do not have it touch screen // Wait for it to come to a full charge testing::StrictMock listener_observer_mock; base::ScopedObservation scoped_listener_obs{&listener_observer_mock}; CreateInternalTouchscreen(true); ui::DeviceDataManagerTestApi().OnDeviceListsComplete(); scoped_listener_obs.Observe(battery_listener_.get()); // Level 50 at time 100, listener should be notified. ClockAdvance(base::TimeDelta::FromSeconds(100)); Sequence a, b; EXPECT_CALL(listener_observer_mock, OnAddingBattery(AFIELD(&BI::key, Eq(kStylusChargerDeviceName)))) .InSequence(a); EXPECT_CALL(listener_observer_mock, OnAddingBattery(AFIELD(&BI::key, Eq(kTestStylusBatteryPath)))) .InSequence(b); EXPECT_CALL(listener_observer_mock, OnUpdatedBatteryLevel(AllOf( AFIELD(&BI::key, Eq(kStylusChargerDeviceName)), AFIELD(&BI::level, Eq(absl::nullopt)), AFIELD(&BI::charge_status, Eq(BI::ChargeStatus::kUnknown)), AFIELD(&BI::type, Eq(BI::PeripheralType::kStylusViaCharger)), AFIELD(&BI::bluetooth_address, Eq(""""))))) .InSequence(a); EXPECT_CALL(listener_observer_mock, OnUpdatedBatteryLevel(AllOf( AFIELD(&BI::key, Eq(kTestStylusBatteryPath)), AFIELD(&BI::level, Eq(50)), AFIELD(&BI::charge_status, Eq(kTestStylusBatteryStatusDischargingOut)), AFIELD(&BI::type, Eq(BI::PeripheralType::kStylusViaScreen)), AFIELD(&BI::bluetooth_address, Eq(""""))))) .InSequence(b); battery_listener_->PeripheralBatteryStatusReceived( kTestStylusBatteryPath, kTestStylusName, 50, kTestStylusBatteryStatusDischargingIn, kBatteryPolledUpdate); EXPECT_CALL(listener_observer_mock, OnUpdatedBatteryLevel(AllOf( AFIELD(&BI::key, Eq(kStylusChargerDeviceName)), AFIELD(&BI::level, Eq(absl::nullopt)), AFIELD(&BI::charge_status, Eq(BI::ChargeStatus::kCharging)), AFIELD(&BI::type, Eq(BI::PeripheralType::kStylusViaCharger)), AFIELD(&BI::bluetooth_address, Eq(""""))))) .InSequence(a, b); battery_listener_->OnStylusStateChanged(ui::StylusState::INSERTED); } TEST_F(PeripheralBatteryListenerIncompleteDevicesTest, GarageChargesFully) { testing::StrictMock listener_observer_mock; base::ScopedObservation scoped_listener_obs{&listener_observer_mock}; CreateInternalTouchscreen(true); ui::DeviceDataManagerTestApi().OnDeviceListsComplete(); scoped_listener_obs.Observe(battery_listener_.get()); // Level 50 at time 100, listener should be notified. ClockAdvance(base::TimeDelta::FromSeconds(100)); Sequence a, b; EXPECT_CALL(listener_observer_mock, OnAddingBattery(AFIELD(&BI::key, Eq(kStylusChargerDeviceName)))) .InSequence(a); EXPECT_CALL(listener_observer_mock, OnAddingBattery(AFIELD(&BI::key, Eq(kTestStylusBatteryPath)))) .InSequence(b); EXPECT_CALL(listener_observer_mock, OnUpdatedBatteryLevel(AllOf( AFIELD(&BI::key, Eq(kStylusChargerDeviceName)), AFIELD(&BI::level, Eq(absl::nullopt)), AFIELD(&BI::charge_status, Eq(BI::ChargeStatus::kUnknown)), AFIELD(&BI::type, Eq(BI::PeripheralType::kStylusViaCharger)), AFIELD(&BI::bluetooth_address, Eq(""""))))) .InSequence(a); EXPECT_CALL(listener_observer_mock, OnUpdatedBatteryLevel(AllOf( AFIELD(&BI::key, Eq(kTestStylusBatteryPath)), AFIELD(&BI::level, Eq(50)), AFIELD(&BI::charge_status, Eq(kTestStylusBatteryStatusDischargingOut)), AFIELD(&BI::type, Eq(BI::PeripheralType::kStylusViaScreen)), AFIELD(&BI::bluetooth_address, Eq(""""))))) .InSequence(b); // This is a polled update, so it doesn't count as timely information battery_listener_->PeripheralBatteryStatusReceived( kTestStylusBatteryPath, kTestStylusName, 50, kTestStylusBatteryStatusDischargingIn, kBatteryPolledUpdate); // This will be called once the stylus is inserted, and called repeatedly // until the stylus is estimated to be fully charged. Since we started // without a known level for the stylus, the level will start from 1, counting // up to 99 until the charge is believed complete. EXPECT_CALL( listener_observer_mock, OnUpdatedBatteryLevel( AllOf(AFIELD(&BI::key, Eq(kStylusChargerDeviceName)), AFIELD(&BI::level, Lt(100)), AFIELD(&BI::charge_status, Eq(BI::ChargeStatus::kCharging)), AFIELD(&BI::type, Eq(BI::PeripheralType::kStylusViaCharger))))) .Times(AnyNumber()) .InSequence(a, b); battery_listener_->OnStylusStateChanged(ui::StylusState::INSERTED); // Then we should have one update at 100% charge. EXPECT_CALL(listener_observer_mock, OnUpdatedBatteryLevel(AllOf( AFIELD(&BI::key, Eq(kStylusChargerDeviceName)), AFIELD(&BI::level, Eq(100)), AFIELD(&BI::charge_status, Eq(BI::ChargeStatus::kFull))))) .InSequence(a, b); // Move time forward more than enough to fully charge, ensuring timers fire. task_environment()->FastForwardBy( base::TimeDelta::FromSeconds(kFullGarageChargeTime)); } TEST_F(PeripheralBatteryListenerIncompleteDevicesTest, GarageChargesFullyFromFiftyPercent) { testing::StrictMock listener_observer_mock; base::ScopedObservation scoped_listener_obs{&listener_observer_mock}; CreateInternalTouchscreen(true); ui::DeviceDataManagerTestApi().OnDeviceListsComplete(); scoped_listener_obs.Observe(battery_listener_.get()); // Level 50 at time 100, listener should be notified. ClockAdvance(base::TimeDelta::FromSeconds(100)); Sequence a, b; EXPECT_CALL(listener_observer_mock, OnAddingBattery(AFIELD(&BI::key, Eq(kStylusChargerDeviceName)))) .InSequence(a); EXPECT_CALL(listener_observer_mock, OnAddingBattery(AFIELD(&BI::key, Eq(kTestStylusBatteryPath)))) .InSequence(b); EXPECT_CALL(listener_observer_mock, OnUpdatedBatteryLevel(AllOf( AFIELD(&BI::key, Eq(kStylusChargerDeviceName)), AFIELD(&BI::level, Eq(absl::nullopt)), AFIELD(&BI::charge_status, Eq(BI::ChargeStatus::kUnknown)), AFIELD(&BI::type, Eq(BI::PeripheralType::kStylusViaCharger)), AFIELD(&BI::bluetooth_address, Eq(""""))))) .InSequence(a); EXPECT_CALL(listener_observer_mock, OnUpdatedBatteryLevel(AllOf( AFIELD(&BI::key, Eq(kTestStylusBatteryPath)), AFIELD(&BI::level, Eq(50)), AFIELD(&BI::charge_status, Eq(kTestStylusBatteryStatusDischargingOut)), AFIELD(&BI::type, Eq(BI::PeripheralType::kStylusViaScreen)), AFIELD(&BI::bluetooth_address, Eq(""""))))) .InSequence(b); // This is an active update, so states that the stylus level is definitely // 50%. battery_listener_->PeripheralBatteryStatusReceived( kTestStylusBatteryPath, kTestStylusName, 50, kTestStylusBatteryStatusDischargingIn, kBatteryEventUpdate); // The rest of these are strictly sequential testing::InSequence sequence; // This will be called once the stylus is inserted, and called repeatedly // until the stylus is estimated to be fully charged. Since we started // with a known level for the stylus the level start there, indicating that // original level until the charge is complete. EXPECT_CALL( listener_observer_mock, OnUpdatedBatteryLevel( AllOf(AFIELD(&BI::key, Eq(kStylusChargerDeviceName)), AFIELD(&BI::level, Ge(50)), AFIELD(&BI::level, Le(99)), AFIELD(&BI::charge_status, Eq(BI::ChargeStatus::kCharging)), AFIELD(&BI::type, Eq(BI::PeripheralType::kStylusViaCharger))))) .Times(AnyNumber()); battery_listener_->OnStylusStateChanged(ui::StylusState::INSERTED); // Then we should have one update at 100% charge. EXPECT_CALL(listener_observer_mock, OnUpdatedBatteryLevel(AllOf( AFIELD(&BI::key, Eq(kStylusChargerDeviceName)), AFIELD(&BI::level, Eq(100)), AFIELD(&BI::charge_status, Eq(BI::ChargeStatus::kFull))))); // Move time forward more than enough to fully charge, ensuring timers fire. task_environment()->FastForwardBy( base::TimeDelta::FromSeconds(kFullGarageChargeTime)); } TEST_F(PeripheralBatteryListenerIncompleteDevicesTest, GarageChargingInterrupted) { // Create touchscreen w/ stylus, w/ dockswitch, w/o stylus in garage // Put stylus on in garage // Wait for it to start charging // Remove from charger // Ensure it stops charging testing::StrictMock listener_observer_mock; base::ScopedObservation scoped_listener_obs{&listener_observer_mock}; CreateInternalTouchscreen(true); ui::DeviceDataManagerTestApi().OnDeviceListsComplete(); scoped_listener_obs.Observe(battery_listener_.get()); Sequence a, b; EXPECT_CALL(listener_observer_mock, OnAddingBattery(AFIELD(&BI::key, Eq(kStylusChargerDeviceName)))) .InSequence(a); EXPECT_CALL(listener_observer_mock, OnAddingBattery(AFIELD(&BI::key, Eq(kTestStylusBatteryPath)))) .InSequence(b); EXPECT_CALL(listener_observer_mock, OnUpdatedBatteryLevel(AllOf( AFIELD(&BI::key, Eq(kStylusChargerDeviceName)), AFIELD(&BI::level, Eq(absl::nullopt)), AFIELD(&BI::charge_status, Eq(BI::ChargeStatus::kUnknown)), AFIELD(&BI::type, Eq(BI::PeripheralType::kStylusViaCharger)), AFIELD(&BI::bluetooth_address, Eq(""""))))) .InSequence(a); EXPECT_CALL(listener_observer_mock, OnUpdatedBatteryLevel(AllOf( AFIELD(&BI::key, Eq(kTestStylusBatteryPath)), AFIELD(&BI::level, Eq(1)), AFIELD(&BI::charge_status, Eq(kTestStylusBatteryStatusDischargingOut)), AFIELD(&BI::type, Eq(BI::PeripheralType::kStylusViaScreen)), AFIELD(&BI::bluetooth_address, Eq(""""))))) .InSequence(b); battery_listener_->PeripheralBatteryStatusReceived( kTestStylusBatteryPath, kTestStylusName, 1, kTestStylusBatteryStatusDischargingIn, kBatteryEventUpdate); ClockAdvance(base::TimeDelta::FromSeconds(100)); // The rest of these are strictly sequential testing::InSequence sequence; EXPECT_CALL( listener_observer_mock, OnUpdatedBatteryLevel( AllOf(AFIELD(&BI::key, Eq(kStylusChargerDeviceName)), AFIELD(&BI::level, Eq(1)), AFIELD(&BI::charge_status, Eq(BI::ChargeStatus::kCharging)), AFIELD(&BI::type, Eq(BI::PeripheralType::kStylusViaCharger))))) .Times(AnyNumber()); battery_listener_->OnStylusStateChanged(ui::StylusState::INSERTED); // Move time forward more than enough to start charging. task_environment()->FastForwardBy(base::TimeDelta::FromSeconds(3)); // Remove stylus from garage EXPECT_CALL( listener_observer_mock, OnUpdatedBatteryLevel( AllOf(AFIELD(&BI::key, Eq(kStylusChargerDeviceName)), AFIELD(&BI::level, Eq(1)), AFIELD(&BI::charge_status, Eq(BI::ChargeStatus::kUnknown)), AFIELD(&BI::type, Eq(BI::PeripheralType::kStylusViaCharger))))); battery_listener_->OnStylusStateChanged(ui::StylusState::REMOVED); // Move time forward enough for anything to go wrong with the timers. task_environment()->FastForwardBy( base::TimeDelta::FromSeconds(kPartialGarageChargeTime)); } TEST_F(PeripheralBatteryListenerIncompleteDevicesTest, GarageChargingResumed) { // Create touchscreen w/ stylus, w/ dockswitch, w/o stylus in garage // Put stylus on in garage // Wait for it to start charging // Remove from charger // Replace on charger // Ensure it finishes charging testing::StrictMock listener_observer_mock; base::ScopedObservation scoped_listener_obs{&listener_observer_mock}; CreateInternalTouchscreen(true); ui::DeviceDataManagerTestApi().OnDeviceListsComplete(); scoped_listener_obs.Observe(battery_listener_.get()); Sequence a, b; EXPECT_CALL(listener_observer_mock, OnAddingBattery(AFIELD(&BI::key, Eq(kStylusChargerDeviceName)))) .InSequence(a); EXPECT_CALL(listener_observer_mock, OnAddingBattery(AFIELD(&BI::key, Eq(kTestStylusBatteryPath)))) .InSequence(b); EXPECT_CALL(listener_observer_mock, OnUpdatedBatteryLevel(AllOf( AFIELD(&BI::key, Eq(kStylusChargerDeviceName)), AFIELD(&BI::level, Eq(absl::nullopt)), AFIELD(&BI::charge_status, Eq(BI::ChargeStatus::kUnknown)), AFIELD(&BI::type, Eq(BI::PeripheralType::kStylusViaCharger)), AFIELD(&BI::bluetooth_address, Eq(""""))))) .InSequence(a); EXPECT_CALL(listener_observer_mock, OnUpdatedBatteryLevel(AllOf( AFIELD(&BI::key, Eq(kTestStylusBatteryPath)), AFIELD(&BI::level, Eq(1)), AFIELD(&BI::charge_status, Eq(kTestStylusBatteryStatusDischargingOut)), AFIELD(&BI::type, Eq(BI::PeripheralType::kStylusViaScreen)), AFIELD(&BI::bluetooth_address, Eq(""""))))) .InSequence(b); battery_listener_->PeripheralBatteryStatusReceived( kTestStylusBatteryPath, kTestStylusName, 1, kTestStylusBatteryStatusDischargingIn, kBatteryEventUpdate); ClockAdvance(base::TimeDelta::FromSeconds(100)); // The rest of these are strictly sequential testing::InSequence sequence; EXPECT_CALL( listener_observer_mock, OnUpdatedBatteryLevel( AllOf(AFIELD(&BI::key, Eq(kStylusChargerDeviceName)), AFIELD(&BI::level, Eq(1)), AFIELD(&BI::charge_status, Eq(BI::ChargeStatus::kCharging)), AFIELD(&BI::type, Eq(BI::PeripheralType::kStylusViaCharger))))) .Times(AnyNumber()); battery_listener_->OnStylusStateChanged(ui::StylusState::INSERTED); // Move time forward more than enough to start charging. task_environment()->FastForwardBy( base::TimeDelta::FromSeconds(kPartialGarageChargeTime)); // Remove stylus from garage EXPECT_CALL( listener_observer_mock, OnUpdatedBatteryLevel( AllOf(AFIELD(&BI::key, Eq(kStylusChargerDeviceName)), AFIELD(&BI::level, Eq(1)), AFIELD(&BI::charge_status, Eq(BI::ChargeStatus::kUnknown)), AFIELD(&BI::type, Eq(BI::PeripheralType::kStylusViaCharger))))); battery_listener_->OnStylusStateChanged(ui::StylusState::REMOVED); // Move time forward enough for anything to go wrong with the timers. task_environment()->FastForwardBy( base::TimeDelta::FromSeconds(kPartialGarageChargeTime)); // Replace stylus, let run to full charge. // The level at the start should be unchanged, it's still the last known // level and it won't update until charge is definitely complete. EXPECT_CALL( listener_observer_mock, OnUpdatedBatteryLevel( AllOf(AFIELD(&BI::key, Eq(kStylusChargerDeviceName)), AFIELD(&BI::level, Eq(1)), AFIELD(&BI::charge_status, Eq(BI::ChargeStatus::kCharging)), AFIELD(&BI::type, Eq(BI::PeripheralType::kStylusViaCharger))))) .Times(AnyNumber()); // Then we should have one update at 100% charge. EXPECT_CALL(listener_observer_mock, OnUpdatedBatteryLevel(AllOf( AFIELD(&BI::key, Eq(kStylusChargerDeviceName)), AFIELD(&BI::level, Eq(100)), AFIELD(&BI::charge_status, Eq(BI::ChargeStatus::kFull))))); battery_listener_->OnStylusStateChanged(ui::StylusState::INSERTED); // Move time forward more than enough to fully charge. task_environment()->FastForwardBy( base::TimeDelta::FromSeconds(kFullGarageChargeTime)); } // NOTE: Cannot yet mock OzonePlatform::GetInstance()->GetInputController(), // so cannot test scenarios involving stylus on charger from 'boot'. #if 0 TEST_F(PeripheralBatteryListenerIncompleteDevicesTest, StylusGaragedOnBoot) { // Create touchscreen w/ stylus, w/ dockswitch // Have stylus on charger from boot // Ensure that it starts on full charge } #endif } // namespace ash ",16275,True,3961.6591847073005,median "// Copyright (c) 2014-2019, AEON, The Monero Project // // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are // permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other // materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be // used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers #include #include ""include_base_utils.h"" #include ""string_tools.h"" using namespace epee; #include #include ""cryptonote_core.h"" #include ""common/command_line.h"" #include ""common/util.h"" #include ""common/updates.h"" #include ""common/download.h"" #include ""common/threadpool.h"" #include ""common/command_line.h"" #include ""warnings.h"" #include ""crypto/crypto.h"" #include ""cryptonote_config.h"" #include ""cryptonote_tx_utils.h"" #include ""misc_language.h"" #include ""file_io_utils.h"" #include #include ""checkpoints/checkpoints.h"" #include ""ringct/rctTypes.h"" #include ""blockchain_db/blockchain_db.h"" #include ""ringct/rctSigs.h"" #include ""common/notify.h"" #include ""version.h"" #undef MONERO_DEFAULT_LOG_CATEGORY #define MONERO_DEFAULT_LOG_CATEGORY ""cn"" DISABLE_VS_WARNINGS(4355) #define MERROR_VER(x) MCERROR(""verify"", x) #define BAD_SEMANTICS_TXES_MAX_SIZE 100 namespace cryptonote { const command_line::arg_descriptor arg_testnet_on = { ""testnet"" , ""Run on testnet. The wallet must be launched with --testnet flag."" , false }; const command_line::arg_descriptor arg_stagenet_on = { ""stagenet"" , ""Run on stagenet. The wallet must be launched with --stagenet flag."" , false }; const command_line::arg_descriptor arg_regtest_on = { ""regtest"" , ""Run in a regression testing mode."" , false }; const command_line::arg_descriptor arg_fixed_difficulty = { ""fixed-difficulty"" , ""Fixed difficulty used for testing."" , 0 }; const command_line::arg_descriptor arg_data_dir = { ""data-dir"" , ""Specify data directory"" , tools::get_default_data_dir() , {{ &arg_testnet_on, &arg_stagenet_on }} , [](std::array testnet_stagenet, bool defaulted, std::string val)->std::string { if (testnet_stagenet[0]) return (boost::filesystem::path(val) / ""testnet"").string(); else if (testnet_stagenet[1]) return (boost::filesystem::path(val) / ""stagenet"").string(); return val; } }; const command_line::arg_descriptor arg_offline = { ""offline"" , ""Do not listen for peers, nor connect to any"" }; const command_line::arg_descriptor arg_disable_dns_checkpoints = { ""disable-dns-checkpoints"" , ""Do not retrieve checkpoints from DNS"" }; static const command_line::arg_descriptor arg_test_drop_download = { ""test-drop-download"" , ""For net tests: in download, discard ALL blocks instead checking/saving them (very fast)"" }; static const command_line::arg_descriptor arg_test_drop_download_height = { ""test-drop-download-height"" , ""Like test-drop-download but discards only after around certain height"" , 0 }; static const command_line::arg_descriptor arg_test_dbg_lock_sleep = { ""test-dbg-lock-sleep"" , ""Sleep time in ms, defaults to 0 (off), used to debug before/after locking mutex. Values 100 to 1000 are good for tests."" , 0 }; static const command_line::arg_descriptor arg_dns_checkpoints = { ""enforce-dns-checkpointing"" , ""checkpoints from DNS server will be enforced"" , false }; static const command_line::arg_descriptor arg_fast_block_sync = { ""fast-block-sync"" , ""Sync up most of the way by using embedded, known block hashes."" , 1 }; static const command_line::arg_descriptor arg_prep_blocks_threads = { ""prep-blocks-threads"" , ""Max number of threads to use when preparing block hashes in groups."" , 4 }; static const command_line::arg_descriptor arg_show_time_stats = { ""show-time-stats"" , ""Show time-stats when processing blocks/txs and disk synchronization."" , 0 }; static const command_line::arg_descriptor arg_block_sync_size = { ""block-sync-size"" , ""How many blocks to sync at once during chain synchronization (0 = adaptive)."" , 0 }; static const command_line::arg_descriptor arg_check_updates = { ""check-updates"" , ""Check for new versions of Aeon: [disabled|notify|download|update]"" , ""notify"" }; static const command_line::arg_descriptor arg_fluffy_blocks = { ""fluffy-blocks"" , ""Relay blocks as fluffy blocks (obsolete, now default)"" , true }; static const command_line::arg_descriptor arg_no_fluffy_blocks = { ""no-fluffy-blocks"" , ""Relay blocks as normal blocks"" , false }; static const command_line::arg_descriptor arg_max_txpool_weight = { ""max-txpool-weight"" , ""Set maximum txpool weight in bytes."" , DEFAULT_TXPOOL_MAX_WEIGHT }; static const command_line::arg_descriptor arg_block_notify = { ""block-notify"" , ""Run a program for each new block, '%s' will be replaced by the block hash"" , """" }; static const command_line::arg_descriptor arg_reorg_notify = { ""reorg-notify"" , ""Run a program for each reorg, '%s' will be replaced by the split height, "" ""'%h' will be replaced by the new blockchain height, '%n' will be "" ""replaced by the number of new blocks in the new chain, and '%d' will be "" ""replaced by the number of blocks discarded from the old chain"" , """" }; static const command_line::arg_descriptor arg_block_rate_notify = { ""block-rate-notify"" , ""Run a program when the block rate undergoes large fluctuations. This might "" ""be a sign of large amounts of hash rate going on and off the Aeon network, "" ""and thus be of potential interest in predicting attacks. %t will be replaced "" ""by the number of minutes for the observation window, %b by the number of "" ""blocks observed within that window, and %e by the number of blocks that was "" ""expected in that window. It is suggested that this notification is used to "" ""automatically increase the number of confirmations required before a payment "" ""is acted upon."" , """" }; //----------------------------------------------------------------------------------------------- core::core(i_cryptonote_protocol* pprotocol): m_mempool(m_blockchain_storage), m_blockchain_storage(m_mempool), m_miner(this), m_miner_address(boost::value_initialized()), m_starter_message_showed(false), m_target_blockchain_height(0), m_checkpoints_path(""""), m_last_dns_checkpoints_update(0), m_last_json_checkpoints_update(0), m_disable_dns_checkpoints(false), m_update_download(0), m_nettype(UNDEFINED), m_update_available(false) { m_checkpoints_updating.clear(); set_cryptonote_protocol(pprotocol); } void core::set_cryptonote_protocol(i_cryptonote_protocol* pprotocol) { if(pprotocol) m_pprotocol = pprotocol; else m_pprotocol = &m_protocol_stub; } //----------------------------------------------------------------------------------- void core::set_checkpoints(checkpoints&& chk_pts) { m_blockchain_storage.set_checkpoints(std::move(chk_pts)); } //----------------------------------------------------------------------------------- void core::set_checkpoints_file_path(const std::string& path) { m_checkpoints_path = path; } //----------------------------------------------------------------------------------- void core::set_enforce_dns_checkpoints(bool enforce_dns) { m_blockchain_storage.set_enforce_dns_checkpoints(enforce_dns); } //----------------------------------------------------------------------------------------------- bool core::update_checkpoints() { if (m_nettype != MAINNET || m_disable_dns_checkpoints) return true; if (m_checkpoints_updating.test_and_set()) return true; bool res = true; if (time(NULL) - m_last_dns_checkpoints_update >= 3600) { res = m_blockchain_storage.update_checkpoints(m_checkpoints_path, true); m_last_dns_checkpoints_update = time(NULL); m_last_json_checkpoints_update = time(NULL); } else if (time(NULL) - m_last_json_checkpoints_update >= 600) { res = m_blockchain_storage.update_checkpoints(m_checkpoints_path, false); m_last_json_checkpoints_update = time(NULL); } m_checkpoints_updating.clear(); // if anything fishy happened getting new checkpoints, bring down the house if (!res) { graceful_exit(); } return res; } //----------------------------------------------------------------------------------- void core::stop() { m_blockchain_storage.cancel(); tools::download_async_handle handle; { boost::lock_guard lock(m_update_mutex); handle = m_update_download; m_update_download = 0; } if (handle) tools::download_cancel(handle); } //----------------------------------------------------------------------------------- void core::init_options(boost::program_options::options_description& desc) { command_line::add_arg(desc, arg_data_dir); command_line::add_arg(desc, arg_test_drop_download); command_line::add_arg(desc, arg_test_drop_download_height); command_line::add_arg(desc, arg_testnet_on); command_line::add_arg(desc, arg_stagenet_on); command_line::add_arg(desc, arg_regtest_on); command_line::add_arg(desc, arg_fixed_difficulty); command_line::add_arg(desc, arg_dns_checkpoints); command_line::add_arg(desc, arg_prep_blocks_threads); command_line::add_arg(desc, arg_fast_block_sync); command_line::add_arg(desc, arg_show_time_stats); command_line::add_arg(desc, arg_block_sync_size); command_line::add_arg(desc, arg_check_updates); command_line::add_arg(desc, arg_fluffy_blocks); command_line::add_arg(desc, arg_no_fluffy_blocks); command_line::add_arg(desc, arg_test_dbg_lock_sleep); command_line::add_arg(desc, arg_offline); command_line::add_arg(desc, arg_disable_dns_checkpoints); command_line::add_arg(desc, arg_max_txpool_weight); command_line::add_arg(desc, arg_block_notify); command_line::add_arg(desc, arg_reorg_notify); command_line::add_arg(desc, arg_block_rate_notify); miner::init_options(desc); BlockchainDB::init_options(desc); } //----------------------------------------------------------------------------------------------- bool core::handle_command_line(const boost::program_options::variables_map& vm) { if (m_nettype != FAKECHAIN) { const bool testnet = command_line::get_arg(vm, arg_testnet_on); const bool stagenet = command_line::get_arg(vm, arg_stagenet_on); m_nettype = testnet ? TESTNET : stagenet ? STAGENET : MAINNET; } m_config_folder = command_line::get_arg(vm, arg_data_dir); auto data_dir = boost::filesystem::path(m_config_folder); if (m_nettype == MAINNET) { cryptonote::checkpoints checkpoints; if (!checkpoints.init_default_checkpoints(m_nettype)) { throw std::runtime_error(""Failed to initialize checkpoints""); } set_checkpoints(std::move(checkpoints)); boost::filesystem::path json(JSON_HASH_FILE_NAME); boost::filesystem::path checkpoint_json_hashfile_fullpath = data_dir / json; set_checkpoints_file_path(checkpoint_json_hashfile_fullpath.string()); } set_enforce_dns_checkpoints(command_line::get_arg(vm, arg_dns_checkpoints)); test_drop_download_height(command_line::get_arg(vm, arg_test_drop_download_height)); m_fluffy_blocks_enabled = !get_arg(vm, arg_no_fluffy_blocks); m_offline = get_arg(vm, arg_offline); m_disable_dns_checkpoints = get_arg(vm, arg_disable_dns_checkpoints); if (!command_line::is_arg_defaulted(vm, arg_fluffy_blocks)) MWARNING(arg_fluffy_blocks.name << "" is obsolete, it is now default""); if (command_line::get_arg(vm, arg_test_drop_download) == true) test_drop_download(); epee::debug::g_test_dbg_lock_sleep() = command_line::get_arg(vm, arg_test_dbg_lock_sleep); return true; } //----------------------------------------------------------------------------------------------- uint64_t core::get_current_blockchain_height() const { return m_blockchain_storage.get_current_blockchain_height(); } //----------------------------------------------------------------------------------------------- void core::get_blockchain_top(uint64_t& height, crypto::hash& top_id) const { top_id = m_blockchain_storage.get_tail_id(height); } //----------------------------------------------------------------------------------------------- bool core::get_blocks(uint64_t start_offset, size_t count, std::vector>& blocks, std::vector& txs) const { return m_blockchain_storage.get_blocks(start_offset, count, blocks, txs); } //----------------------------------------------------------------------------------------------- bool core::get_blocks(uint64_t start_offset, size_t count, std::vector>& blocks) const { return m_blockchain_storage.get_blocks(start_offset, count, blocks); } //----------------------------------------------------------------------------------------------- bool core::get_blocks(uint64_t start_offset, size_t count, std::vector& blocks) const { std::vector> bs; if (!m_blockchain_storage.get_blocks(start_offset, count, bs)) return false; for (const auto &b: bs) blocks.push_back(b.second); return true; } //----------------------------------------------------------------------------------------------- bool core::get_transactions(const std::vector& txs_ids, std::vector& txs, std::vector& missed_txs) const { return m_blockchain_storage.get_transactions_blobs(txs_ids, txs, missed_txs); } //----------------------------------------------------------------------------------------------- bool core::get_txpool_backlog(std::vector& backlog) const { m_mempool.get_transaction_backlog(backlog); return true; } //----------------------------------------------------------------------------------------------- bool core::get_transactions(const std::vector& txs_ids, std::vector& txs, std::vector& missed_txs) const { return m_blockchain_storage.get_transactions(txs_ids, txs, missed_txs); } //----------------------------------------------------------------------------------------------- bool core::get_alternative_blocks(std::vector& blocks) const { return m_blockchain_storage.get_alternative_blocks(blocks); } //----------------------------------------------------------------------------------------------- size_t core::get_alternative_blocks_count() const { return m_blockchain_storage.get_alternative_blocks_count(); } //----------------------------------------------------------------------------------------------- bool core::init(const boost::program_options::variables_map& vm, const char *config_subdir, const cryptonote::test_options *test_options) { start_time = std::time(nullptr); const bool regtest = command_line::get_arg(vm, arg_regtest_on); if (test_options != NULL || regtest) { m_nettype = FAKECHAIN; } bool r = handle_command_line(vm); std::string m_config_folder_mempool = m_config_folder; if (config_subdir) m_config_folder_mempool = m_config_folder_mempool + ""/"" + config_subdir; std::string db_type = command_line::get_arg(vm, cryptonote::arg_db_type); std::string db_sync_mode = command_line::get_arg(vm, cryptonote::arg_db_sync_mode); bool db_salvage = command_line::get_arg(vm, cryptonote::arg_db_salvage) != 0; bool fast_sync = command_line::get_arg(vm, arg_fast_block_sync) != 0; uint64_t blocks_threads = command_line::get_arg(vm, arg_prep_blocks_threads); std::string check_updates_string = command_line::get_arg(vm, arg_check_updates); size_t max_txpool_weight = command_line::get_arg(vm, arg_max_txpool_weight); boost::filesystem::path folder(m_config_folder); if (m_nettype == FAKECHAIN) folder /= ""fake""; // make sure the data directory exists, and try to lock it CHECK_AND_ASSERT_MES (boost::filesystem::exists(folder) || boost::filesystem::create_directories(folder), false, std::string(""Failed to create directory "").append(folder.string()).c_str()); // check for blockchain.bin try { const boost::filesystem::path old_files = folder; if (boost::filesystem::exists(old_files / ""blockchain.bin"")) { MWARNING(""Found old-style blockchain.bin in "" << old_files.string()); MWARNING(""Aeon now uses a new format. You can either remove blockchain.bin to start syncing""); MWARNING(""the blockchain anew, or use aeon-blockchain-export and aeon-blockchain-import to""); MWARNING(""convert your existing blockchain.bin to the new format. See README.md for instructions.""); return false; } } // folder might not be a directory, etc, etc catch (...) { } std::unique_ptr db(new_db(db_type)); if (db == NULL) { LOG_ERROR(""Attempted to use non-existent database type""); return false; } folder /= db->get_db_name(); MGINFO(""Loading blockchain from folder "" << folder.string() << "" ...""); const std::string filename = folder.string(); // default to fast:async:1 if overridden blockchain_db_sync_mode sync_mode = db_defaultsync; bool sync_on_blocks = true; uint64_t sync_threshold = 1; if (m_nettype == FAKECHAIN) { // reset the db by removing the database file before opening it if (!db->remove_data_file(filename)) { MERROR(""Failed to remove data file in "" << filename); return false; } } try { uint64_t db_flags = 0; std::vector options; boost::trim(db_sync_mode); boost::split(options, db_sync_mode, boost::is_any_of("" :"")); const bool db_sync_mode_is_default = command_line::is_arg_defaulted(vm, cryptonote::arg_db_sync_mode); for(const auto &option : options) MDEBUG(""option: "" << option); // default to fast:async:1 uint64_t DEFAULT_FLAGS = DBF_FAST; if(options.size() == 0) { // default to fast:async:1 db_flags = DEFAULT_FLAGS; } bool safemode = false; if(options.size() >= 1) { if(options[0] == ""safe"") { safemode = true; db_flags = DBF_SAFE; sync_mode = db_sync_mode_is_default ? db_defaultsync : db_nosync; } else if(options[0] == ""fast"") { db_flags = DBF_FAST; sync_mode = db_sync_mode_is_default ? db_defaultsync : db_async; } else if(options[0] == ""fastest"") { db_flags = DBF_FASTEST; sync_threshold = 1000; // default to fastest:async:1000 sync_mode = db_sync_mode_is_default ? db_defaultsync : db_async; } else db_flags = DEFAULT_FLAGS; } if(options.size() >= 2 && !safemode) { if(options[1] == ""sync"") sync_mode = db_sync_mode_is_default ? db_defaultsync : db_sync; else if(options[1] == ""async"") sync_mode = db_sync_mode_is_default ? db_defaultsync : db_async; } if(options.size() >= 3 && !safemode) { char *endptr; uint64_t threshold = strtoull(options[2].c_str(), &endptr, 0); if (*endptr == '\\0' || !strcmp(endptr, ""blocks"")) { sync_on_blocks = true; sync_threshold = threshold; } else if (!strcmp(endptr, ""bytes"")) { sync_on_blocks = false; sync_threshold = threshold; } else { LOG_ERROR(""Invalid db sync mode: "" << options[2]); return false; } } if (db_salvage) db_flags |= DBF_SALVAGE; db->open(filename, db_flags); if(!db->m_open) return false; } catch (const DB_ERROR& e) { LOG_ERROR(""Error opening database: "" << e.what()); return false; } m_blockchain_storage.set_user_options(blocks_threads, sync_on_blocks, sync_threshold, sync_mode, fast_sync); try { if (!command_line::is_arg_defaulted(vm, arg_block_notify)) m_blockchain_storage.set_block_notify(std::shared_ptr(new tools::Notify(command_line::get_arg(vm, arg_block_notify).c_str()))); } catch (const std::exception &e) { MERROR(""Failed to parse block notify spec: "" << e.what()); } try { if (!command_line::is_arg_defaulted(vm, arg_reorg_notify)) m_blockchain_storage.set_reorg_notify(std::shared_ptr(new tools::Notify(command_line::get_arg(vm, arg_reorg_notify).c_str()))); } catch (const std::exception &e) { MERROR(""Failed to parse reorg notify spec: "" << e.what()); } try { if (!command_line::is_arg_defaulted(vm, arg_block_rate_notify)) m_block_rate_notify.reset(new tools::Notify(command_line::get_arg(vm, arg_block_rate_notify).c_str())); } catch (const std::exception &e) { MERROR(""Failed to parse block rate notify spec: "" << e.what()); } const cryptonote::test_options::hard_fork_t regtest_hard_forks[3] = { {1, 0, 0}, {Blockchain::get_hard_fork_heights(MAINNET).back().version, 1, 0}, {0, 0, 0} }; const cryptonote::test_options regtest_test_options = { regtest_hard_forks, 0 }; const difficulty_type fixed_difficulty = command_line::get_arg(vm, arg_fixed_difficulty); r = m_blockchain_storage.init(db.release(), m_nettype, m_offline, regtest ? ®test_test_options : test_options, fixed_difficulty); r = m_mempool.init(max_txpool_weight); CHECK_AND_ASSERT_MES(r, false, ""Failed to initialize memory pool""); // now that we have a valid m_blockchain_storage, we can clean out any // transactions in the pool that do not conform to the current fork m_mempool.validate(m_blockchain_storage.get_current_hard_fork_version()); bool show_time_stats = command_line::get_arg(vm, arg_show_time_stats) != 0; m_blockchain_storage.set_show_time_stats(show_time_stats); CHECK_AND_ASSERT_MES(r, false, ""Failed to initialize blockchain storage""); block_sync_size = command_line::get_arg(vm, arg_block_sync_size); MGINFO(""Loading checkpoints""); // load json & DNS checkpoints, and verify them // with respect to what blocks we already have CHECK_AND_ASSERT_MES(update_checkpoints(), false, ""One or more checkpoints loaded from json or dns conflicted with existing checkpoints.""); // DNS versions checking if (check_updates_string == ""disabled"") check_updates_level = UPDATES_DISABLED; else if (check_updates_string == ""notify"") check_updates_level = UPDATES_NOTIFY; else if (check_updates_string == ""download"") check_updates_level = UPDATES_DOWNLOAD; else if (check_updates_string == ""update"") check_updates_level = UPDATES_UPDATE; else { MERROR(""Invalid argument to --dns-versions-check: "" << check_updates_string); return false; } r = m_miner.init(vm, m_nettype); CHECK_AND_ASSERT_MES(r, false, ""Failed to initialize miner instance""); return load_state_data(); } //----------------------------------------------------------------------------------------------- bool core::set_genesis_block(const block& b) { return m_blockchain_storage.reset_and_set_genesis_block(b); } //----------------------------------------------------------------------------------------------- bool core::load_state_data() { // may be some code later return true; } //----------------------------------------------------------------------------------------------- bool core::deinit() { m_miner.stop(); m_mempool.deinit(); m_blockchain_storage.deinit(); return true; } //----------------------------------------------------------------------------------------------- void core::test_drop_download() { m_test_drop_download = false; } //----------------------------------------------------------------------------------------------- void core::test_drop_download_height(uint64_t height) { m_test_drop_download_height = height; } //----------------------------------------------------------------------------------------------- bool core::get_test_drop_download() const { return m_test_drop_download; } //----------------------------------------------------------------------------------------------- bool core::get_test_drop_download_height() const { if (m_test_drop_download_height == 0) return true; if (get_blockchain_storage().get_current_blockchain_height() <= m_test_drop_download_height) return true; return false; } //----------------------------------------------------------------------------------------------- bool core::handle_incoming_tx_pre(const blobdata& tx_blob, tx_verification_context& tvc, cryptonote::transaction &tx, crypto::hash &tx_hash, crypto::hash &tx_prefixt_hash, bool keeped_by_block, bool relayed, bool do_not_relay) { tvc = boost::value_initialized(); if(tx_blob.size() > get_max_tx_size()) { LOG_PRINT_L1(""WRONG TRANSACTION BLOB, too big size "" << tx_blob.size() << "", rejected""); tvc.m_verifivation_failed = true; tvc.m_too_big = true; return false; } tx_hash = crypto::null_hash; tx_prefixt_hash = crypto::null_hash; if(!parse_tx_from_blob(tx, tx_hash, tx_prefixt_hash, tx_blob)) { LOG_PRINT_L1(""WRONG TRANSACTION BLOB, Failed to parse, rejected""); tvc.m_verifivation_failed = true; return false; } //std::cout << ""!""<< tx.vin.size() << std::endl; bad_semantics_txes_lock.lock(); for (int idx = 0; idx < 2; ++idx) { if (bad_semantics_txes[idx].find(tx_hash) != bad_semantics_txes[idx].end()) { bad_semantics_txes_lock.unlock(); LOG_PRINT_L1(""Transaction already seen with bad semantics, rejected""); tvc.m_verifivation_failed = true; return false; } } bad_semantics_txes_lock.unlock(); uint8_t version = m_blockchain_storage.get_current_hard_fork_version(); const size_t max_tx_version = version < HF_VERSION_ALLOW_RCT ? 1 : 2; if (tx.version == 0 || tx.version > max_tx_version) { // v2 is the latest one we know tvc.m_verifivation_failed = true; return false; } return true; } //----------------------------------------------------------------------------------------------- bool core::handle_incoming_tx_post(const blobdata& tx_blob, tx_verification_context& tvc, cryptonote::transaction &tx, crypto::hash &tx_hash, crypto::hash &tx_prefixt_hash, bool keeped_by_block, bool relayed, bool do_not_relay) { if(!check_tx_syntax(tx)) { LOG_PRINT_L1(""WRONG TRANSACTION BLOB, Failed to check tx "" << tx_hash << "" syntax, rejected""); tvc.m_verifivation_failed = true; return false; } return true; } //----------------------------------------------------------------------------------------------- void core::set_semantics_failed(const crypto::hash &tx_hash) { LOG_PRINT_L1(""WRONG TRANSACTION BLOB, Failed to check tx "" << tx_hash << "" semantic, rejected""); bad_semantics_txes_lock.lock(); bad_semantics_txes[0].insert(tx_hash); if (bad_semantics_txes[0].size() >= BAD_SEMANTICS_TXES_MAX_SIZE) { std::swap(bad_semantics_txes[0], bad_semantics_txes[1]); bad_semantics_txes[0].clear(); } bad_semantics_txes_lock.unlock(); } //----------------------------------------------------------------------------------------------- static bool is_canonical_bulletproof_layout(const std::vector &proofs) { if (proofs.size() != 1) return false; const size_t sz = proofs[0].V.size(); if (sz == 0 || sz > BULLETPROOF_MAX_OUTPUTS) return false; return true; } //----------------------------------------------------------------------------------------------- bool core::handle_incoming_tx_accumulated_batch(std::vector &tx_info, bool keeped_by_block) { bool ret = true; if (keeped_by_block && get_blockchain_storage().is_within_compiled_block_hash_area()) { MTRACE(""Skipping semantics check for tx kept by block in embedded hash area""); return true; } std::vector rvv; for (size_t n = 0; n < tx_info.size(); ++n) { if (!check_tx_semantic(*tx_info[n].tx, keeped_by_block)) { set_semantics_failed(tx_info[n].tx_hash); tx_info[n].tvc.m_verifivation_failed = true; tx_info[n].result = false; continue; } if (tx_info[n].tx->version < 2) continue; const rct::rctSig &rv = tx_info[n].tx->rct_signatures; switch (rv.type) { case rct::RCTTypeNull: // coinbase should not come here, so we reject for all other types MERROR_VER(""Unexpected Null rctSig type""); set_semantics_failed(tx_info[n].tx_hash); tx_info[n].tvc.m_verifivation_failed = true; tx_info[n].result = false; break; case rct::RCTTypeSimple: if (!rct::verRctSemanticsSimple(rv)) { MERROR_VER(""rct signature semantics check failed""); set_semantics_failed(tx_info[n].tx_hash); tx_info[n].tvc.m_verifivation_failed = true; tx_info[n].result = false; break; } break; case rct::RCTTypeFull: if (!rct::verRct(rv, true)) { MERROR_VER(""rct signature semantics check failed""); set_semantics_failed(tx_info[n].tx_hash); tx_info[n].tvc.m_verifivation_failed = true; tx_info[n].result = false; break; } break; case rct::RCTTypeBulletproof: if (!is_canonical_bulletproof_layout(rv.p.bulletproofs)) { MERROR_VER(""Bulletproof does not have canonical form""); set_semantics_failed(tx_info[n].tx_hash); tx_info[n].tvc.m_verifivation_failed = true; tx_info[n].result = false; break; } rvv.push_back(&rv); // delayed batch verification break; default: MERROR_VER(""Unknown rct type: "" << rv.type); set_semantics_failed(tx_info[n].tx_hash); tx_info[n].tvc.m_verifivation_failed = true; tx_info[n].result = false; break; } } if (!rvv.empty() && !rct::verRctSemanticsSimple(rvv)) { LOG_PRINT_L1(""One transaction among this group has bad semantics, verifying one at a time""); ret = false; const bool assumed_bad = rvv.size() == 1; // if there's only one tx, it must be the bad one for (size_t n = 0; n < tx_info.size(); ++n) { if (!tx_info[n].result) continue; if (tx_info[n].tx->rct_signatures.type != rct::RCTTypeBulletproof) continue; if (assumed_bad || !rct::verRctSemanticsSimple(tx_info[n].tx->rct_signatures)) { set_semantics_failed(tx_info[n].tx_hash); tx_info[n].tvc.m_verifivation_failed = true; tx_info[n].result = false; } } } return ret; } //----------------------------------------------------------------------------------------------- bool core::handle_incoming_txs(const std::vector& tx_blobs, std::vector& tvc, bool keeped_by_block, bool relayed, bool do_not_relay) { TRY_ENTRY(); CRITICAL_REGION_LOCAL(m_incoming_tx_lock); struct result { bool res; cryptonote::transaction tx; crypto::hash hash; crypto::hash prefix_hash; bool in_txpool; bool in_blockchain; }; std::vector results(tx_blobs.size()); tvc.resize(tx_blobs.size()); tools::threadpool& tpool = tools::threadpool::getInstance(); tools::threadpool::waiter waiter; std::vector::const_iterator it = tx_blobs.begin(); for (size_t i = 0; i < tx_blobs.size(); i++, ++it) { tpool.submit(&waiter, [&, i, it] { try { results[i].res = handle_incoming_tx_pre(*it, tvc[i], results[i].tx, results[i].hash, results[i].prefix_hash, keeped_by_block, relayed, do_not_relay); } catch (const std::exception &e) { MERROR_VER(""Exception in handle_incoming_tx_pre: "" << e.what()); results[i].res = false; } }); } waiter.wait(&tpool); it = tx_blobs.begin(); std::vector already_have(tx_blobs.size(), false); for (size_t i = 0; i < tx_blobs.size(); i++, ++it) { if (!results[i].res) continue; if(m_mempool.have_tx(results[i].hash)) { LOG_PRINT_L2(""tx "" << results[i].hash << ""already have transaction in tx_pool""); already_have[i] = true; } else if(m_blockchain_storage.have_tx(results[i].hash)) { LOG_PRINT_L2(""tx "" << results[i].hash << "" already have transaction in blockchain""); already_have[i] = true; } else { tpool.submit(&waiter, [&, i, it] { try { results[i].res = handle_incoming_tx_post(*it, tvc[i], results[i].tx, results[i].hash, results[i].prefix_hash, keeped_by_block, relayed, do_not_relay); } catch (const std::exception &e) { MERROR_VER(""Exception in handle_incoming_tx_post: "" << e.what()); results[i].res = false; } }); } } waiter.wait(&tpool); std::vector tx_info; tx_info.reserve(tx_blobs.size()); for (size_t i = 0; i < tx_blobs.size(); i++) { if (!results[i].res || already_have[i]) continue; tx_info.push_back({&results[i].tx, results[i].hash, tvc[i], results[i].res}); } if (!tx_info.empty()) handle_incoming_tx_accumulated_batch(tx_info, keeped_by_block); bool ok = true; it = tx_blobs.begin(); for (size_t i = 0; i < tx_blobs.size(); i++, ++it) { if (already_have[i]) continue; if (!results[i].res) { ok = false; continue; } const size_t weight = get_transaction_weight(results[i].tx, it->size()); ok &= add_new_tx(results[i].tx, results[i].hash, results[i].prefix_hash, weight, tvc[i], keeped_by_block, relayed, do_not_relay); if(tvc[i].m_verifivation_failed) {MERROR_VER(""Transaction verification failed: "" << results[i].hash);} else if(tvc[i].m_verifivation_impossible) {MERROR_VER(""Transaction verification impossible: "" << results[i].hash);} if(tvc[i].m_added_to_pool) MDEBUG(""tx added: "" << results[i].hash); } return ok; CATCH_ENTRY_L0(""core::handle_incoming_txs()"", false); } //----------------------------------------------------------------------------------------------- bool core::handle_incoming_tx(const blobdata& tx_blob, tx_verification_context& tvc, bool keeped_by_block, bool relayed, bool do_not_relay) { std::vector tx_blobs; tx_blobs.push_back(tx_blob); std::vector tvcv(1); bool r = handle_incoming_txs(tx_blobs, tvcv, keeped_by_block, relayed, do_not_relay); tvc = tvcv[0]; return r; } //----------------------------------------------------------------------------------------------- bool core::get_stat_info(core_stat_info& st_inf) const { st_inf.mining_speed = m_miner.get_speed(); st_inf.alternative_blocks = m_blockchain_storage.get_alternative_blocks_count(); st_inf.blockchain_height = m_blockchain_storage.get_current_blockchain_height(); st_inf.tx_pool_size = m_mempool.get_transactions_count(); st_inf.top_block_id_str = epee::string_tools::pod_to_hex(m_blockchain_storage.get_tail_id()); return true; } //----------------------------------------------------------------------------------------------- bool core::check_tx_semantic(const transaction& tx, bool keeped_by_block) const { if(!tx.vin.size()) { MERROR_VER(""tx with empty inputs, rejected for tx id= "" << get_transaction_hash(tx)); return false; } if(!check_inputs_types_supported(tx)) { MERROR_VER(""unsupported input types for tx id= "" << get_transaction_hash(tx)); return false; } if(!check_outs_valid(tx)) { MERROR_VER(""tx with invalid outputs, rejected for tx id= "" << get_transaction_hash(tx)); return false; } if (tx.version > 1) { if (tx.rct_signatures.outPk.size() != tx.vout.size()) { MERROR_VER(""tx with mismatched vout/outPk count, rejected for tx id= "" << get_transaction_hash(tx)); return false; } } if(!check_money_overflow(tx)) { MERROR_VER(""tx has money overflow, rejected for tx id= "" << get_transaction_hash(tx)); return false; } if (tx.version == 1) { uint64_t amount_in = 0; get_inputs_money_amount(tx, amount_in); uint64_t amount_out = get_outs_money_amount(tx); if(amount_in <= amount_out) { MERROR_VER(""tx with wrong amounts: ins "" << amount_in << "", outs "" << amount_out << "", rejected for tx id= "" << get_transaction_hash(tx)); return false; } } // for version > 1, ringct signatures check verifies amounts match if(!keeped_by_block && get_transaction_weight(tx) >= m_blockchain_storage.get_current_cumulative_block_weight_limit() - CRYPTONOTE_COINBASE_BLOB_RESERVED_SIZE) { MERROR_VER(""tx is too large "" << get_transaction_weight(tx) << "", expected not bigger than "" << m_blockchain_storage.get_current_cumulative_block_weight_limit() - CRYPTONOTE_COINBASE_BLOB_RESERVED_SIZE); return false; } //check if tx use different key images if(!check_tx_inputs_keyimages_diff(tx)) { MERROR_VER(""tx uses a single key image more than once""); return false; } if (!check_tx_inputs_ring_members_diff(tx)) { MERROR_VER(""tx uses duplicate ring members""); return false; } if (!check_tx_inputs_keyimages_domain(tx)) { MERROR_VER(""tx uses key image not in the valid domain""); return false; } return true; } //----------------------------------------------------------------------------------------------- bool core::is_key_image_spent(const crypto::key_image &key_image) const { return m_blockchain_storage.have_tx_keyimg_as_spent(key_image); } //----------------------------------------------------------------------------------------------- bool core::are_key_images_spent(const std::vector& key_im, std::vector &spent) const { spent.clear(); for(auto& ki: key_im) { spent.push_back(m_blockchain_storage.have_tx_keyimg_as_spent(ki)); } return true; } //----------------------------------------------------------------------------------------------- size_t core::get_block_sync_size(uint64_t height) const { if (block_sync_size > 0) return block_sync_size; return BLOCKS_SYNCHRONIZING_DEFAULT_COUNT; } //----------------------------------------------------------------------------------------------- bool core::are_key_images_spent_in_pool(const std::vector& key_im, std::vector &spent) const { spent.clear(); return m_mempool.check_for_key_images(key_im, spent); } //----------------------------------------------------------------------------------------------- std::pair core::get_coinbase_tx_sum(const uint64_t start_offset, const size_t count) { uint64_t emission_amount = 0; uint64_t total_fee_amount = 0; if (count) { const uint64_t end = start_offset + count - 1; m_blockchain_storage.for_blocks_range(start_offset, end, [this, &emission_amount, &total_fee_amount](uint64_t, const crypto::hash& hash, const block& b){ std::vector txs; std::vector missed_txs; uint64_t coinbase_amount = get_outs_money_amount(b.miner_tx); this->get_transactions(b.tx_hashes, txs, missed_txs); uint64_t tx_fee_amount = 0; for(const auto& tx: txs) { tx_fee_amount += get_tx_fee(tx); } emission_amount += coinbase_amount - tx_fee_amount; total_fee_amount += tx_fee_amount; return true; }); } return std::pair(emission_amount, total_fee_amount); } //----------------------------------------------------------------------------------------------- bool core::check_tx_inputs_keyimages_diff(const transaction& tx) const { std::unordered_set ki; for(const auto& in: tx.vin) { CHECKED_GET_SPECIFIC_VARIANT(in, const txin_to_key, tokey_in, false); if(!ki.insert(tokey_in.k_image).second) return false; } return true; } //----------------------------------------------------------------------------------------------- bool core::check_tx_inputs_ring_members_diff(const transaction& tx) const { const uint8_t version = m_blockchain_storage.get_current_hard_fork_version(); if (version >= 6) { for(const auto& in: tx.vin) { CHECKED_GET_SPECIFIC_VARIANT(in, const txin_to_key, tokey_in, false); for (size_t n = 1; n < tokey_in.key_offsets.size(); ++n) if (tokey_in.key_offsets[n] == 0) return false; } } return true; } //----------------------------------------------------------------------------------------------- bool core::check_tx_inputs_keyimages_domain(const transaction& tx) const { std::unordered_set ki; for(const auto& in: tx.vin) { CHECKED_GET_SPECIFIC_VARIANT(in, const txin_to_key, tokey_in, false); if (!(rct::scalarmultKey(rct::ki2rct(tokey_in.k_image), rct::curveOrder()) == rct::identity())) return false; } return true; } //----------------------------------------------------------------------------------------------- bool core::add_new_tx(transaction& tx, tx_verification_context& tvc, bool keeped_by_block, bool relayed, bool do_not_relay) { crypto::hash tx_hash = get_transaction_hash(tx); crypto::hash tx_prefix_hash = get_transaction_prefix_hash(tx); blobdata bl; t_serializable_object_to_blob(tx, bl); size_t tx_weight = get_transaction_weight(tx, bl.size()); return add_new_tx(tx, tx_hash, tx_prefix_hash, tx_weight, tvc, keeped_by_block, relayed, do_not_relay); } //----------------------------------------------------------------------------------------------- size_t core::get_blockchain_total_transactions() const { return m_blockchain_storage.get_total_transactions(); } //----------------------------------------------------------------------------------------------- bool core::add_new_tx(transaction& tx, const crypto::hash& tx_hash, const crypto::hash& tx_prefix_hash, size_t tx_weight, tx_verification_context& tvc, bool keeped_by_block, bool relayed, bool do_not_relay) { if (keeped_by_block) get_blockchain_storage().on_new_tx_from_block(tx); if(m_mempool.have_tx(tx_hash)) { LOG_PRINT_L2(""tx "" << tx_hash << ""already have transaction in tx_pool""); return true; } if(m_blockchain_storage.have_tx(tx_hash)) { LOG_PRINT_L2(""tx "" << tx_hash << "" already have transaction in blockchain""); return true; } uint8_t version = m_blockchain_storage.get_current_hard_fork_version(); return m_mempool.add_tx(tx, tx_hash, tx_weight, tvc, keeped_by_block, relayed, do_not_relay, version); } //----------------------------------------------------------------------------------------------- bool core::relay_txpool_transactions() { // we attempt to relay txes that should be relayed, but were not std::vector> txs; if (m_mempool.get_relayable_transactions(txs) && !txs.empty()) { cryptonote_connection_context fake_context = AUTO_VAL_INIT(fake_context); tx_verification_context tvc = AUTO_VAL_INIT(tvc); NOTIFY_NEW_TRANSACTIONS::request r; for (auto it = txs.begin(); it != txs.end(); ++it) { r.txs.push_back(it->second); } get_protocol()->relay_transactions(r, fake_context); m_mempool.set_relayed(txs); } return true; } //----------------------------------------------------------------------------------------------- void core::on_transaction_relayed(const cryptonote::blobdata& tx_blob) { std::vector> txs; cryptonote::transaction tx; crypto::hash tx_hash, tx_prefix_hash; if (!parse_and_validate_tx_from_blob(tx_blob, tx, tx_hash, tx_prefix_hash)) { LOG_ERROR(""Failed to parse relayed transaction""); return; } txs.push_back(std::make_pair(tx_hash, std::move(tx_blob))); m_mempool.set_relayed(txs); } //----------------------------------------------------------------------------------------------- bool core::get_block_template(block& b, const account_public_address& adr, difficulty_type& diffic, uint64_t& height, uint64_t& expected_reward, const blobdata& ex_nonce) { return m_blockchain_storage.create_block_template(b, adr, diffic, height, expected_reward, ex_nonce); } //----------------------------------------------------------------------------------------------- bool core::find_blockchain_supplement(const std::list& qblock_ids, NOTIFY_RESPONSE_CHAIN_ENTRY::request& resp) const { return m_blockchain_storage.find_blockchain_supplement(qblock_ids, resp); } //----------------------------------------------------------------------------------------------- bool core::find_blockchain_supplement(const uint64_t req_start_block, const std::list& qblock_ids, std::vector, std::vector > > >& blocks, uint64_t& total_height, uint64_t& start_height, bool pruned, bool get_miner_tx_hash, size_t max_count) const { return m_blockchain_storage.find_blockchain_supplement(req_start_block, qblock_ids, blocks, total_height, start_height, pruned, get_miner_tx_hash, max_count); } //----------------------------------------------------------------------------------------------- bool core::get_outs(const COMMAND_RPC_GET_OUTPUTS_BIN::request& req, COMMAND_RPC_GET_OUTPUTS_BIN::response& res) const { return m_blockchain_storage.get_outs(req, res); } //----------------------------------------------------------------------------------------------- bool core::get_output_distribution(uint64_t amount, uint64_t from_height, uint64_t to_height, uint64_t &start_height, std::vector &distribution, uint64_t &base) const { return m_blockchain_storage.get_output_distribution(amount, from_height, to_height, start_height, distribution, base); } //----------------------------------------------------------------------------------------------- bool core::get_tx_outputs_gindexs(const crypto::hash& tx_id, std::vector& indexs) const { return m_blockchain_storage.get_tx_outputs_gindexs(tx_id, indexs); } //----------------------------------------------------------------------------------------------- void core::pause_mine() { m_miner.pause(); } //----------------------------------------------------------------------------------------------- void core::resume_mine() { m_miner.resume(); } //----------------------------------------------------------------------------------------------- block_complete_entry get_block_complete_entry(block& b, tx_memory_pool &pool) { block_complete_entry bce; bce.block = cryptonote::block_to_blob(b); for (const auto &tx_hash: b.tx_hashes) { cryptonote::blobdata txblob; CHECK_AND_ASSERT_THROW_MES(pool.get_transaction(tx_hash, txblob), ""Transaction not found in pool""); bce.txs.push_back(txblob); } return bce; } //----------------------------------------------------------------------------------------------- bool core::handle_block_found(block& b) { block_verification_context bvc = boost::value_initialized(); m_miner.pause(); std::vector blocks; try { blocks.push_back(get_block_complete_entry(b, m_mempool)); } catch (const std::exception &e) { m_miner.resume(); return false; } prepare_handle_incoming_blocks(blocks); m_blockchain_storage.add_new_block(b, bvc); cleanup_handle_incoming_blocks(true); //anyway - update miner template update_miner_block_template(); m_miner.resume(); CHECK_AND_ASSERT_MES(!bvc.m_verifivation_failed, false, ""mined block failed verification""); if(bvc.m_added_to_main_chain) { cryptonote_connection_context exclude_context = boost::value_initialized(); NOTIFY_NEW_BLOCK::request arg = AUTO_VAL_INIT(arg); arg.current_blockchain_height = m_blockchain_storage.get_current_blockchain_height(); std::vector missed_txs; std::vector txs; m_blockchain_storage.get_transactions_blobs(b.tx_hashes, txs, missed_txs); if(missed_txs.size() && m_blockchain_storage.get_block_id_by_height(get_block_height(b)) != get_block_hash(b)) { LOG_PRINT_L1(""Block found but, seems that reorganize just happened after that, do not relay this block""); return true; } CHECK_AND_ASSERT_MES(txs.size() == b.tx_hashes.size() && !missed_txs.size(), false, ""can't find some transactions in found block:"" << get_block_hash(b) << "" txs.size()="" << txs.size() << "", b.tx_hashes.size()="" << b.tx_hashes.size() << "", missed_txs.size()"" << missed_txs.size()); block_to_blob(b, arg.b.block); //pack transactions for(auto& tx: txs) arg.b.txs.push_back(tx); m_pprotocol->relay_block(arg, exclude_context); } return bvc.m_added_to_main_chain; } //----------------------------------------------------------------------------------------------- void core::on_synchronized() { m_miner.on_synchronized(); } //----------------------------------------------------------------------------------------------- void core::safesyncmode(const bool onoff) { m_blockchain_storage.safesyncmode(onoff); } //----------------------------------------------------------------------------------------------- bool core::add_new_block(const block& b, block_verification_context& bvc) { return m_blockchain_storage.add_new_block(b, bvc); } //----------------------------------------------------------------------------------------------- bool core::prepare_handle_incoming_blocks(const std::vector &blocks) { m_incoming_tx_lock.lock(); m_blockchain_storage.prepare_handle_incoming_blocks(blocks); return true; } //----------------------------------------------------------------------------------------------- bool core::cleanup_handle_incoming_blocks(bool force_sync) { bool success = false; try { success = m_blockchain_storage.cleanup_handle_incoming_blocks(force_sync); } catch (...) {} m_incoming_tx_lock.unlock(); return success; } //----------------------------------------------------------------------------------------------- bool core::handle_incoming_block(const blobdata& block_blob, block_verification_context& bvc, bool update_miner_blocktemplate) { TRY_ENTRY(); // load json & DNS checkpoints every 10min/hour respectively, // and verify them with respect to what blocks we already have CHECK_AND_ASSERT_MES(update_checkpoints(), false, ""One or more checkpoints loaded from json or dns conflicted with existing checkpoints.""); bvc = boost::value_initialized(); if(block_blob.size() > get_max_block_size()) { LOG_PRINT_L1(""WRONG BLOCK BLOB, too big size "" << block_blob.size() << "", rejected""); bvc.m_verifivation_failed = true; return false; } block b = AUTO_VAL_INIT(b); if(!parse_and_validate_block_from_blob(block_blob, b)) { LOG_PRINT_L1(""Failed to parse and validate new block""); bvc.m_verifivation_failed = true; return false; } add_new_block(b, bvc); if(update_miner_blocktemplate && bvc.m_added_to_main_chain) update_miner_block_template(); return true; CATCH_ENTRY_L0(""core::handle_incoming_block()"", false); } //----------------------------------------------------------------------------------------------- // Used by the RPC server to check the size of an incoming // block_blob bool core::check_incoming_block_size(const blobdata& block_blob) const { if(block_blob.size() > get_max_block_size()) { LOG_PRINT_L1(""WRONG BLOCK BLOB, too big size "" << block_blob.size() << "", rejected""); return false; } return true; } //----------------------------------------------------------------------------------------------- crypto::hash core::get_tail_id() const { return m_blockchain_storage.get_tail_id(); } //----------------------------------------------------------------------------------------------- difficulty_type core::get_block_cumulative_difficulty(uint64_t height) const { return m_blockchain_storage.get_db().get_block_cumulative_difficulty(height); } //----------------------------------------------------------------------------------------------- size_t core::get_pool_transactions_count() const { return m_mempool.get_transactions_count(); } //----------------------------------------------------------------------------------------------- bool core::have_block(const crypto::hash& id) const { return m_blockchain_storage.have_block(id); } //----------------------------------------------------------------------------------------------- bool core::parse_tx_from_blob(transaction& tx, crypto::hash& tx_hash, crypto::hash& tx_prefix_hash, const blobdata& blob) const { return parse_and_validate_tx_from_blob(blob, tx, tx_hash, tx_prefix_hash); } //----------------------------------------------------------------------------------------------- bool core::check_tx_syntax(const transaction& tx) const { return true; } //----------------------------------------------------------------------------------------------- bool core::get_pool_transactions(std::vector& txs, bool include_sensitive_data) const { m_mempool.get_transactions(txs, include_sensitive_data); return true; } //----------------------------------------------------------------------------------------------- bool core::get_pool_transaction_hashes(std::vector& txs, bool include_sensitive_data) const { m_mempool.get_transaction_hashes(txs, include_sensitive_data); return true; } //----------------------------------------------------------------------------------------------- bool core::get_pool_transaction_stats(struct txpool_stats& stats, bool include_sensitive_data) const { m_mempool.get_transaction_stats(stats, include_sensitive_data); return true; } //----------------------------------------------------------------------------------------------- bool core::get_pool_transaction(const crypto::hash &id, cryptonote::blobdata& tx) const { return m_mempool.get_transaction(id, tx); } //----------------------------------------------------------------------------------------------- bool core::pool_has_tx(const crypto::hash &id) const { return m_mempool.have_tx(id); } //----------------------------------------------------------------------------------------------- bool core::get_pool_transactions_and_spent_keys_info(std::vector& tx_infos, std::vector& key_image_infos, bool include_sensitive_data) const { return m_mempool.get_transactions_and_spent_keys_info(tx_infos, key_image_infos, include_sensitive_data); } //----------------------------------------------------------------------------------------------- bool core::get_pool_for_rpc(std::vector& tx_infos, cryptonote::rpc::key_images_with_tx_hashes& key_image_infos) const { return m_mempool.get_pool_for_rpc(tx_infos, key_image_infos); } //----------------------------------------------------------------------------------------------- bool core::get_short_chain_history(std::list& ids) const { return m_blockchain_storage.get_short_chain_history(ids); } //----------------------------------------------------------------------------------------------- bool core::handle_get_objects(NOTIFY_REQUEST_GET_OBJECTS::request& arg, NOTIFY_RESPONSE_GET_OBJECTS::request& rsp, cryptonote_connection_context& context) { return m_blockchain_storage.handle_get_objects(arg, rsp); } //----------------------------------------------------------------------------------------------- crypto::hash core::get_block_id_by_height(uint64_t height) const { return m_blockchain_storage.get_block_id_by_height(height); } //----------------------------------------------------------------------------------------------- bool core::get_block_by_hash(const crypto::hash &h, block &blk, bool *orphan) const { return m_blockchain_storage.get_block_by_hash(h, blk, orphan); } //----------------------------------------------------------------------------------------------- std::string core::print_pool(bool short_format) const { return m_mempool.print_pool(short_format); } //----------------------------------------------------------------------------------------------- bool core::update_miner_block_template() { m_miner.on_block_chain_update(); return true; } //----------------------------------------------------------------------------------------------- bool core::on_idle() { if(!m_starter_message_showed) { std::string main_message; if (m_offline) main_message = ""The daemon is running offline and will not attempt to sync to the Aeon network.""; else main_message = ""The daemon will start synchronizing with the network. This may take a long time to complete.""; MGINFO_YELLOW(ENDL << ""**********************************************************************"" << ENDL << main_message << ENDL << ENDL << ""You can set the level of process detailization through \\""set_log \\"" command,"" << ENDL << ""where is between 0 (no details) and 4 (very verbose), or custom category based levels (eg, *:WARNING)."" << ENDL << ENDL << ""Use the \\""help\\"" command to see the list of available commands."" << ENDL << ""Use \\""help \\"" to see a command's documentation."" << ENDL << ""**********************************************************************"" << ENDL); m_starter_message_showed = true; } // m_fork_moaner.do_call(boost::bind(&core::check_fork_time, this)); m_txpool_auto_relayer.do_call(boost::bind(&core::relay_txpool_transactions, this)); m_check_updates_interval.do_call(boost::bind(&core::check_updates, this)); m_check_disk_space_interval.do_call(boost::bind(&core::check_disk_space, this)); m_block_rate_interval.do_call(boost::bind(&core::check_block_rate, this)); m_diff_recalc_interval.do_call(boost::bind(&core::recalculate_difficulties, this)); m_miner.on_idle(); m_mempool.on_idle(); return true; } //----------------------------------------------------------------------------------------------- uint8_t core::get_ideal_hard_fork_version() const { return get_blockchain_storage().get_ideal_hard_fork_version(); } //----------------------------------------------------------------------------------------------- uint8_t core::get_ideal_hard_fork_version(uint64_t height) const { return get_blockchain_storage().get_ideal_hard_fork_version(height); } //----------------------------------------------------------------------------------------------- uint8_t core::get_hard_fork_version(uint64_t height) const { return get_blockchain_storage().get_hard_fork_version(height); } //----------------------------------------------------------------------------------------------- uint64_t core::get_earliest_ideal_height_for_version(uint8_t version) const { return get_blockchain_storage().get_earliest_ideal_height_for_version(version); } //----------------------------------------------------------------------------------------------- bool core::check_updates() { static const char software[] = ""aeon""; #ifdef BUILD_TAG static const char buildtag[] = BOOST_PP_STRINGIZE(BUILD_TAG); static const char subdir[] = ""cli""; // because it can never be simple #else static const char buildtag[] = ""source""; static const char subdir[] = ""source""; // because it can never be simple #endif if (m_offline) return true; if (check_updates_level == UPDATES_DISABLED) return true; std::string version, hash; MCDEBUG(""updates"", ""Checking for a new "" << software << "" version for "" << buildtag); if (!tools::check_updates(software, buildtag, version, hash)) return false; if (tools::vercmp(version.c_str(), MONERO_VERSION) <= 0) { m_update_available = false; return true; } std::string url = tools::get_update_url(software, subdir, buildtag, version, true); MCLOG_CYAN(el::Level::Info, ""global"", ""Version "" << version << "" of "" << software << "" for "" << buildtag << "" is available: "" << url << "", SHA256 hash "" << hash); m_update_available = true; if (check_updates_level == UPDATES_NOTIFY) return true; url = tools::get_update_url(software, subdir, buildtag, version, false); std::string filename; const char *slash = strrchr(url.c_str(), '/'); if (slash) filename = slash + 1; else filename = std::string(software) + ""-update-"" + version; boost::filesystem::path path(epee::string_tools::get_current_module_folder()); path /= filename; boost::unique_lock lock(m_update_mutex); if (m_update_download != 0) { MCDEBUG(""updates"", ""Already downloading update""); return true; } crypto::hash file_hash; if (!tools::sha256sum(path.string(), file_hash) || (hash != epee::string_tools::pod_to_hex(file_hash))) { MCDEBUG(""updates"", ""We don't have that file already, downloading""); const std::string tmppath = path.string() + "".tmp""; if (epee::file_io_utils::is_file_exist(tmppath)) { MCDEBUG(""updates"", ""We have part of the file already, resuming download""); } m_last_update_length = 0; m_update_download = tools::download_async(tmppath, url, [this, hash, path](const std::string &tmppath, const std::string &uri, bool success) { bool remove = false, good = true; if (success) { crypto::hash file_hash; if (!tools::sha256sum(tmppath, file_hash)) { MCERROR(""updates"", ""Failed to hash "" << tmppath); remove = true; good = false; } else if (hash != epee::string_tools::pod_to_hex(file_hash)) { MCERROR(""updates"", ""Download from "" << uri << "" does not match the expected hash""); remove = true; good = false; } } else { MCERROR(""updates"", ""Failed to download "" << uri); good = false; } boost::unique_lock lock(m_update_mutex); m_update_download = 0; if (success && !remove) { std::error_code e = tools::replace_file(tmppath, path.string()); if (e) { MCERROR(""updates"", ""Failed to rename downloaded file""); good = false; } } else if (remove) { if (!boost::filesystem::remove(tmppath)) { MCERROR(""updates"", ""Failed to remove invalid downloaded file""); good = false; } } if (good) MCLOG_CYAN(el::Level::Info, ""updates"", ""New version downloaded to "" << path.string()); }, [this](const std::string &path, const std::string &uri, size_t length, ssize_t content_length) { if (length >= m_last_update_length + 1024 * 1024 * 10) { m_last_update_length = length; MCDEBUG(""updates"", ""Downloaded "" << length << ""/"" << (content_length ? std::to_string(content_length) : ""unknown"")); } return true; }); } else { MCDEBUG(""updates"", ""We already have "" << path << "" with expected hash""); } lock.unlock(); if (check_updates_level == UPDATES_DOWNLOAD) return true; MCERROR(""updates"", ""Download/update not implemented yet""); return true; } //----------------------------------------------------------------------------------------------- bool core::check_disk_space() { uint64_t free_space = get_free_space(); if (free_space < 1ull * 1024 * 1024 * 1024) // 1 GB { const el::Level level = el::Level::Warning; MCLOG_RED(level, ""global"", ""Free space is below 1 GB on "" << m_config_folder); } return true; } //----------------------------------------------------------------------------------------------- double factorial(unsigned int n) { if (n <= 1) return 1.0; double f = n; while (n-- > 1) f *= n; return f; } //----------------------------------------------------------------------------------------------- static double probability(unsigned int blocks, unsigned int expected) { // https://www.umass.edu/wsp/resources/poisson/#computing return pow(expected, blocks) / (factorial(blocks) * exp(expected)); } //----------------------------------------------------------------------------------------------- bool core::check_block_rate() { if (m_offline || m_target_blockchain_height > get_current_blockchain_height()) { MDEBUG(""Not checking block rate, offline or syncing""); return true; } static constexpr double threshold = 1. / (864000 / DIFFICULTY_TARGET_V2); // one false positive every 10 days const time_t now = time(NULL); const std::vector timestamps = m_blockchain_storage.get_last_block_timestamps(60); static const unsigned int seconds[] = { 5400, 3600, 1800, 1200, 600 }; for (size_t n = 0; n < sizeof(seconds)/sizeof(seconds[0]); ++n) { unsigned int b = 0; for (time_t ts: timestamps) b += ts >= now - seconds[n]; const double p = probability(b, seconds[n] / DIFFICULTY_TARGET_V2); MDEBUG(""blocks in the last "" << seconds[n] / 60 << "" minutes: "" << b << "" (probability "" << p << "")""); if (p < threshold) { MWARNING(""There were "" << b << "" blocks in the last "" << seconds[n] / 60 << "" minutes, there might be large hash rate changes, or we might be partitioned, cut off from the Aeon network or under attack. Or it could be just sheer bad luck.""); std::shared_ptr block_rate_notify = m_block_rate_notify; if (block_rate_notify) { auto expected = seconds[n] / DIFFICULTY_TARGET_V2; block_rate_notify->notify(""%t"", std::to_string(seconds[n] / 60).c_str(), ""%b"", std::to_string(b).c_str(), ""%e"", std::to_string(expected).c_str(), NULL); } break; // no need to look further } } return true; } //----------------------------------------------------------------------------------------------- bool core::recalculate_difficulties() { m_blockchain_storage.recalculate_difficulties(); return true; } //----------------------------------------------------------------------------------------------- void core::set_target_blockchain_height(uint64_t target_blockchain_height) { m_target_blockchain_height = target_blockchain_height; } //----------------------------------------------------------------------------------------------- uint64_t core::get_target_blockchain_height() const { return m_target_blockchain_height; } //----------------------------------------------------------------------------------------------- uint64_t core::prevalidate_block_hashes(uint64_t height, const std::vector &hashes) { return get_blockchain_storage().prevalidate_block_hashes(height, hashes); } //----------------------------------------------------------------------------------------------- uint64_t core::get_free_space() const { boost::filesystem::path path(m_config_folder); boost::filesystem::space_info si = boost::filesystem::space(path); return si.available; } //----------------------------------------------------------------------------------------------- std::time_t core::get_start_time() const { return start_time; } //----------------------------------------------------------------------------------------------- void core::graceful_exit() { raise(SIGTERM); } } ",16289,True,2852.938327396505,median "/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of the copyright holders may not 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 Intel Corporation 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. // //M*/ #ifndef __OPENCV_IMGPROC_HPP__ #define __OPENCV_IMGPROC_HPP__ #include ""opencv2/core.hpp"" /*! \\namespace cv Namespace where all the C++ OpenCV functionality resides */ namespace cv { //! type of the kernel enum { KERNEL_GENERAL = 0, // the kernel is generic. No any type of symmetry or other properties. KERNEL_SYMMETRICAL = 1, // kernel[i] == kernel[ksize-i-1] , and the anchor is at the center KERNEL_ASYMMETRICAL = 2, // kernel[i] == -kernel[ksize-i-1] , and the anchor is at the center KERNEL_SMOOTH = 4, // all the kernel elements are non-negative and summed to 1 KERNEL_INTEGER = 8 // all the kernel coefficients are integer numbers }; //! type of morphological operation enum { MORPH_ERODE = 0, MORPH_DILATE = 1, MORPH_OPEN = 2, MORPH_CLOSE = 3, MORPH_GRADIENT = 4, MORPH_TOPHAT = 5, MORPH_BLACKHAT = 6 }; //! shape of the structuring element enum { MORPH_RECT = 0, MORPH_CROSS = 1, MORPH_ELLIPSE = 2 }; //! interpolation algorithm enum { INTER_NEAREST = 0, //!< nearest neighbor interpolation INTER_LINEAR = 1, //!< bilinear interpolation INTER_CUBIC = 2, //!< bicubic interpolation INTER_AREA = 3, //!< area-based (or super) interpolation INTER_LANCZOS4 = 4, //!< Lanczos interpolation over 8x8 neighborhood INTER_MAX = 7, //!< mask for interpolation codes WARP_FILL_OUTLIERS = 8, WARP_INVERSE_MAP = 16 }; enum { INTER_BITS = 5, INTER_BITS2 = INTER_BITS * 2, INTER_TAB_SIZE = 1 << INTER_BITS, INTER_TAB_SIZE2 = INTER_TAB_SIZE * INTER_TAB_SIZE }; //! Distance types for Distance Transform and M-estimators enum { DIST_USER = -1, // User defined distance DIST_L1 = 1, // distance = |x1-x2| + |y1-y2| DIST_L2 = 2, // the simple euclidean distance DIST_C = 3, // distance = max(|x1-x2|,|y1-y2|) DIST_L12 = 4, // L1-L2 metric: distance = 2(sqrt(1+x*x/2) - 1)) DIST_FAIR = 5, // distance = c^2(|x|/c-log(1+|x|/c)), c = 1.3998 DIST_WELSCH = 6, // distance = c^2/2(1-exp(-(x/c)^2)), c = 2.9846 DIST_HUBER = 7 // distance = |x| threshold ? max_value : 0 THRESH_BINARY_INV = 1, // value = value > threshold ? 0 : max_value THRESH_TRUNC = 2, // value = value > threshold ? threshold : value THRESH_TOZERO = 3, // value = value > threshold ? value : 0 THRESH_TOZERO_INV = 4, // value = value > threshold ? 0 : value THRESH_MASK = 7, THRESH_OTSU = 8 // use Otsu algorithm to choose the optimal threshold value }; //! adaptive threshold algorithm enum { ADAPTIVE_THRESH_MEAN_C = 0, ADAPTIVE_THRESH_GAUSSIAN_C = 1 }; enum { PROJ_SPHERICAL_ORTHO = 0, PROJ_SPHERICAL_EQRECT = 1 }; //! class of the pixel in GrabCut algorithm enum { GC_BGD = 0, //!< background GC_FGD = 1, //!< foreground GC_PR_BGD = 2, //!< most probably background GC_PR_FGD = 3 //!< most probably foreground }; //! GrabCut algorithm flags enum { GC_INIT_WITH_RECT = 0, GC_INIT_WITH_MASK = 1, GC_EVAL = 2 }; //! distanceTransform algorithm flags enum { DIST_LABEL_CCOMP = 0, DIST_LABEL_PIXEL = 1 }; //! floodfill algorithm flags enum { FLOODFILL_FIXED_RANGE = 1 << 16, FLOODFILL_MASK_ONLY = 1 << 17 }; //! type of the template matching operation enum { TM_SQDIFF = 0, TM_SQDIFF_NORMED = 1, TM_CCORR = 2, TM_CCORR_NORMED = 3, TM_CCOEFF = 4, TM_CCOEFF_NORMED = 5 }; //! connected components algorithm output formats enum { CC_STAT_LEFT = 0, CC_STAT_TOP = 1, CC_STAT_WIDTH = 2, CC_STAT_HEIGHT = 3, CC_STAT_AREA = 4, CC_STAT_MAX = 5 }; //! mode of the contour retrieval algorithm enum { RETR_EXTERNAL = 0, //!< retrieve only the most external (top-level) contours RETR_LIST = 1, //!< retrieve all the contours without any hierarchical information RETR_CCOMP = 2, //!< retrieve the connected components (that can possibly be nested) RETR_TREE = 3, //!< retrieve all the contours and the whole hierarchy RETR_FLOODFILL = 4 }; //! the contour approximation algorithm enum { CHAIN_APPROX_NONE = 1, CHAIN_APPROX_SIMPLE = 2, CHAIN_APPROX_TC89_L1 = 3, CHAIN_APPROX_TC89_KCOS = 4 }; //! Variants of a Hough transform enum { HOUGH_STANDARD = 0, HOUGH_PROBABILISTIC = 1, HOUGH_MULTI_SCALE = 2, HOUGH_GRADIENT = 3 }; //! Variants of Line Segment Detector enum { LSD_REFINE_NONE = 0, LSD_REFINE_STD = 1, LSD_REFINE_ADV = 2 }; //! Histogram comparison methods enum { HISTCMP_CORREL = 0, HISTCMP_CHISQR = 1, HISTCMP_INTERSECT = 2, HISTCMP_BHATTACHARYYA = 3, HISTCMP_HELLINGER = HISTCMP_BHATTACHARYYA, HISTCMP_CHISQR_ALT = 4 }; //! the color conversion code enum { COLOR_BGR2BGRA = 0, COLOR_RGB2RGBA = COLOR_BGR2BGRA, COLOR_BGRA2BGR = 1, COLOR_RGBA2RGB = COLOR_BGRA2BGR, COLOR_BGR2RGBA = 2, COLOR_RGB2BGRA = COLOR_BGR2RGBA, COLOR_RGBA2BGR = 3, COLOR_BGRA2RGB = COLOR_RGBA2BGR, COLOR_BGR2RGB = 4, COLOR_RGB2BGR = COLOR_BGR2RGB, COLOR_BGRA2RGBA = 5, COLOR_RGBA2BGRA = COLOR_BGRA2RGBA, COLOR_BGR2GRAY = 6, COLOR_RGB2GRAY = 7, COLOR_GRAY2BGR = 8, COLOR_GRAY2RGB = COLOR_GRAY2BGR, COLOR_GRAY2BGRA = 9, COLOR_GRAY2RGBA = COLOR_GRAY2BGRA, COLOR_BGRA2GRAY = 10, COLOR_RGBA2GRAY = 11, COLOR_BGR2BGR565 = 12, COLOR_RGB2BGR565 = 13, COLOR_BGR5652BGR = 14, COLOR_BGR5652RGB = 15, COLOR_BGRA2BGR565 = 16, COLOR_RGBA2BGR565 = 17, COLOR_BGR5652BGRA = 18, COLOR_BGR5652RGBA = 19, COLOR_GRAY2BGR565 = 20, COLOR_BGR5652GRAY = 21, COLOR_BGR2BGR555 = 22, COLOR_RGB2BGR555 = 23, COLOR_BGR5552BGR = 24, COLOR_BGR5552RGB = 25, COLOR_BGRA2BGR555 = 26, COLOR_RGBA2BGR555 = 27, COLOR_BGR5552BGRA = 28, COLOR_BGR5552RGBA = 29, COLOR_GRAY2BGR555 = 30, COLOR_BGR5552GRAY = 31, COLOR_BGR2XYZ = 32, COLOR_RGB2XYZ = 33, COLOR_XYZ2BGR = 34, COLOR_XYZ2RGB = 35, COLOR_BGR2YCrCb = 36, COLOR_RGB2YCrCb = 37, COLOR_YCrCb2BGR = 38, COLOR_YCrCb2RGB = 39, COLOR_BGR2HSV = 40, COLOR_RGB2HSV = 41, COLOR_BGR2Lab = 44, COLOR_RGB2Lab = 45, COLOR_BGR2Luv = 50, COLOR_RGB2Luv = 51, COLOR_BGR2HLS = 52, COLOR_RGB2HLS = 53, COLOR_HSV2BGR = 54, COLOR_HSV2RGB = 55, COLOR_Lab2BGR = 56, COLOR_Lab2RGB = 57, COLOR_Luv2BGR = 58, COLOR_Luv2RGB = 59, COLOR_HLS2BGR = 60, COLOR_HLS2RGB = 61, COLOR_BGR2HSV_FULL = 66, COLOR_RGB2HSV_FULL = 67, COLOR_BGR2HLS_FULL = 68, COLOR_RGB2HLS_FULL = 69, COLOR_HSV2BGR_FULL = 70, COLOR_HSV2RGB_FULL = 71, COLOR_HLS2BGR_FULL = 72, COLOR_HLS2RGB_FULL = 73, COLOR_LBGR2Lab = 74, COLOR_LRGB2Lab = 75, COLOR_LBGR2Luv = 76, COLOR_LRGB2Luv = 77, COLOR_Lab2LBGR = 78, COLOR_Lab2LRGB = 79, COLOR_Luv2LBGR = 80, COLOR_Luv2LRGB = 81, COLOR_BGR2YUV = 82, COLOR_RGB2YUV = 83, COLOR_YUV2BGR = 84, COLOR_YUV2RGB = 85, // YUV 4:2:0 family to RGB COLOR_YUV2RGB_NV12 = 90, COLOR_YUV2BGR_NV12 = 91, COLOR_YUV2RGB_NV21 = 92, COLOR_YUV2BGR_NV21 = 93, COLOR_YUV420sp2RGB = COLOR_YUV2RGB_NV21, COLOR_YUV420sp2BGR = COLOR_YUV2BGR_NV21, COLOR_YUV2RGBA_NV12 = 94, COLOR_YUV2BGRA_NV12 = 95, COLOR_YUV2RGBA_NV21 = 96, COLOR_YUV2BGRA_NV21 = 97, COLOR_YUV420sp2RGBA = COLOR_YUV2RGBA_NV21, COLOR_YUV420sp2BGRA = COLOR_YUV2BGRA_NV21, COLOR_YUV2RGB_YV12 = 98, COLOR_YUV2BGR_YV12 = 99, COLOR_YUV2RGB_IYUV = 100, COLOR_YUV2BGR_IYUV = 101, COLOR_YUV2RGB_I420 = COLOR_YUV2RGB_IYUV, COLOR_YUV2BGR_I420 = COLOR_YUV2BGR_IYUV, COLOR_YUV420p2RGB = COLOR_YUV2RGB_YV12, COLOR_YUV420p2BGR = COLOR_YUV2BGR_YV12, COLOR_YUV2RGBA_YV12 = 102, COLOR_YUV2BGRA_YV12 = 103, COLOR_YUV2RGBA_IYUV = 104, COLOR_YUV2BGRA_IYUV = 105, COLOR_YUV2RGBA_I420 = COLOR_YUV2RGBA_IYUV, COLOR_YUV2BGRA_I420 = COLOR_YUV2BGRA_IYUV, COLOR_YUV420p2RGBA = COLOR_YUV2RGBA_YV12, COLOR_YUV420p2BGRA = COLOR_YUV2BGRA_YV12, COLOR_YUV2GRAY_420 = 106, COLOR_YUV2GRAY_NV21 = COLOR_YUV2GRAY_420, COLOR_YUV2GRAY_NV12 = COLOR_YUV2GRAY_420, COLOR_YUV2GRAY_YV12 = COLOR_YUV2GRAY_420, COLOR_YUV2GRAY_IYUV = COLOR_YUV2GRAY_420, COLOR_YUV2GRAY_I420 = COLOR_YUV2GRAY_420, COLOR_YUV420sp2GRAY = COLOR_YUV2GRAY_420, COLOR_YUV420p2GRAY = COLOR_YUV2GRAY_420, // YUV 4:2:2 family to RGB COLOR_YUV2RGB_UYVY = 107, COLOR_YUV2BGR_UYVY = 108, //COLOR_YUV2RGB_VYUY = 109, //COLOR_YUV2BGR_VYUY = 110, COLOR_YUV2RGB_Y422 = COLOR_YUV2RGB_UYVY, COLOR_YUV2BGR_Y422 = COLOR_YUV2BGR_UYVY, COLOR_YUV2RGB_UYNV = COLOR_YUV2RGB_UYVY, COLOR_YUV2BGR_UYNV = COLOR_YUV2BGR_UYVY, COLOR_YUV2RGBA_UYVY = 111, COLOR_YUV2BGRA_UYVY = 112, //COLOR_YUV2RGBA_VYUY = 113, //COLOR_YUV2BGRA_VYUY = 114, COLOR_YUV2RGBA_Y422 = COLOR_YUV2RGBA_UYVY, COLOR_YUV2BGRA_Y422 = COLOR_YUV2BGRA_UYVY, COLOR_YUV2RGBA_UYNV = COLOR_YUV2RGBA_UYVY, COLOR_YUV2BGRA_UYNV = COLOR_YUV2BGRA_UYVY, COLOR_YUV2RGB_YUY2 = 115, COLOR_YUV2BGR_YUY2 = 116, COLOR_YUV2RGB_YVYU = 117, COLOR_YUV2BGR_YVYU = 118, COLOR_YUV2RGB_YUYV = COLOR_YUV2RGB_YUY2, COLOR_YUV2BGR_YUYV = COLOR_YUV2BGR_YUY2, COLOR_YUV2RGB_YUNV = COLOR_YUV2RGB_YUY2, COLOR_YUV2BGR_YUNV = COLOR_YUV2BGR_YUY2, COLOR_YUV2RGBA_YUY2 = 119, COLOR_YUV2BGRA_YUY2 = 120, COLOR_YUV2RGBA_YVYU = 121, COLOR_YUV2BGRA_YVYU = 122, COLOR_YUV2RGBA_YUYV = COLOR_YUV2RGBA_YUY2, COLOR_YUV2BGRA_YUYV = COLOR_YUV2BGRA_YUY2, COLOR_YUV2RGBA_YUNV = COLOR_YUV2RGBA_YUY2, COLOR_YUV2BGRA_YUNV = COLOR_YUV2BGRA_YUY2, COLOR_YUV2GRAY_UYVY = 123, COLOR_YUV2GRAY_YUY2 = 124, //CV_YUV2GRAY_VYUY = CV_YUV2GRAY_UYVY, COLOR_YUV2GRAY_Y422 = COLOR_YUV2GRAY_UYVY, COLOR_YUV2GRAY_UYNV = COLOR_YUV2GRAY_UYVY, COLOR_YUV2GRAY_YVYU = COLOR_YUV2GRAY_YUY2, COLOR_YUV2GRAY_YUYV = COLOR_YUV2GRAY_YUY2, COLOR_YUV2GRAY_YUNV = COLOR_YUV2GRAY_YUY2, // alpha premultiplication COLOR_RGBA2mRGBA = 125, COLOR_mRGBA2RGBA = 126, // RGB to YUV 4:2:0 family COLOR_RGB2YUV_I420 = 127, COLOR_BGR2YUV_I420 = 128, COLOR_RGB2YUV_IYUV = COLOR_RGB2YUV_I420, COLOR_BGR2YUV_IYUV = COLOR_BGR2YUV_I420, COLOR_RGBA2YUV_I420 = 129, COLOR_BGRA2YUV_I420 = 130, COLOR_RGBA2YUV_IYUV = COLOR_RGBA2YUV_I420, COLOR_BGRA2YUV_IYUV = COLOR_BGRA2YUV_I420, COLOR_RGB2YUV_YV12 = 131, COLOR_BGR2YUV_YV12 = 132, COLOR_RGBA2YUV_YV12 = 133, COLOR_BGRA2YUV_YV12 = 134, // Demosaicing COLOR_BayerBG2BGR = 46, COLOR_BayerGB2BGR = 47, COLOR_BayerRG2BGR = 48, COLOR_BayerGR2BGR = 49, COLOR_BayerBG2RGB = COLOR_BayerRG2BGR, COLOR_BayerGB2RGB = COLOR_BayerGR2BGR, COLOR_BayerRG2RGB = COLOR_BayerBG2BGR, COLOR_BayerGR2RGB = COLOR_BayerGB2BGR, COLOR_BayerBG2GRAY = 86, COLOR_BayerGB2GRAY = 87, COLOR_BayerRG2GRAY = 88, COLOR_BayerGR2GRAY = 89, // Demosaicing using Variable Number of Gradients COLOR_BayerBG2BGR_VNG = 62, COLOR_BayerGB2BGR_VNG = 63, COLOR_BayerRG2BGR_VNG = 64, COLOR_BayerGR2BGR_VNG = 65, COLOR_BayerBG2RGB_VNG = COLOR_BayerRG2BGR_VNG, COLOR_BayerGB2RGB_VNG = COLOR_BayerGR2BGR_VNG, COLOR_BayerRG2RGB_VNG = COLOR_BayerBG2BGR_VNG, COLOR_BayerGR2RGB_VNG = COLOR_BayerGB2BGR_VNG, // Edge-Aware Demosaicing COLOR_BayerBG2BGR_EA = 135, COLOR_BayerGB2BGR_EA = 136, COLOR_BayerRG2BGR_EA = 137, COLOR_BayerGR2BGR_EA = 138, COLOR_BayerBG2RGB_EA = COLOR_BayerRG2BGR_EA, COLOR_BayerGB2RGB_EA = COLOR_BayerGR2BGR_EA, COLOR_BayerRG2RGB_EA = COLOR_BayerBG2BGR_EA, COLOR_BayerGR2RGB_EA = COLOR_BayerGB2BGR_EA, COLOR_COLORCVT_MAX = 139 }; //! types of intersection between rectangles enum { INTERSECT_NONE = 0, INTERSECT_PARTIAL = 1, INTERSECT_FULL = 2 }; /*! The Base Class for 1D or Row-wise Filters This is the base class for linear or non-linear filters that process 1D data. In particular, such filters are used for the ""horizontal"" filtering parts in separable filters. Several functions in OpenCV return Ptr for the specific types of filters, and those pointers can be used directly or within cv::FilterEngine. */ class CV_EXPORTS BaseRowFilter { public: //! the default constructor BaseRowFilter(); //! the destructor virtual ~BaseRowFilter(); //! the filtering operator. Must be overrided in the derived classes. The horizontal border interpolation is done outside of the class. virtual void operator()(const uchar* src, uchar* dst, int width, int cn) = 0; int ksize; int anchor; }; /*! The Base Class for Column-wise Filters This is the base class for linear or non-linear filters that process columns of 2D arrays. Such filters are used for the ""vertical"" filtering parts in separable filters. Several functions in OpenCV return Ptr for the specific types of filters, and those pointers can be used directly or within cv::FilterEngine. Unlike cv::BaseRowFilter, cv::BaseColumnFilter may have some context information, i.e. box filter keeps the sliding sum of elements. To reset the state BaseColumnFilter::reset() must be called (e.g. the method is called by cv::FilterEngine) */ class CV_EXPORTS BaseColumnFilter { public: //! the default constructor BaseColumnFilter(); //! the destructor virtual ~BaseColumnFilter(); //! the filtering operator. Must be overrided in the derived classes. The vertical border interpolation is done outside of the class. virtual void operator()(const uchar** src, uchar* dst, int dststep, int dstcount, int width) = 0; //! resets the internal buffers, if any virtual void reset(); int ksize; int anchor; }; /*! The Base Class for Non-Separable 2D Filters. This is the base class for linear or non-linear 2D filters. Several functions in OpenCV return Ptr for the specific types of filters, and those pointers can be used directly or within cv::FilterEngine. Similar to cv::BaseColumnFilter, the class may have some context information, that should be reset using BaseFilter::reset() method before processing the new array. */ class CV_EXPORTS BaseFilter { public: //! the default constructor BaseFilter(); //! the destructor virtual ~BaseFilter(); //! the filtering operator. The horizontal and the vertical border interpolation is done outside of the class. virtual void operator()(const uchar** src, uchar* dst, int dststep, int dstcount, int width, int cn) = 0; //! resets the internal buffers, if any virtual void reset(); Size ksize; Point anchor; }; /*! The Main Class for Image Filtering. The class can be used to apply an arbitrary filtering operation to an image. It contains all the necessary intermediate buffers, it computes extrapolated values of the ""virtual"" pixels outside of the image etc. Pointers to the initialized cv::FilterEngine instances are returned by various OpenCV functions, such as cv::createSeparableLinearFilter(), cv::createLinearFilter(), cv::createGaussianFilter(), cv::createDerivFilter(), cv::createBoxFilter() and cv::createMorphologyFilter(). Using the class you can process large images by parts and build complex pipelines that include filtering as some of the stages. If all you need is to apply some pre-defined filtering operation, you may use cv::filter2D(), cv::erode(), cv::dilate() etc. functions that create FilterEngine internally. Here is the example on how to use the class to implement Laplacian operator, which is the sum of second-order derivatives. More complex variant for different types is implemented in cv::Laplacian(). \\code void laplace_f(const Mat& src, Mat& dst) { CV_Assert( src.type() == CV_32F ); // make sure the destination array has the proper size and type dst.create(src.size(), src.type()); // get the derivative and smooth kernels for d2I/dx2. // for d2I/dy2 we could use the same kernels, just swapped Mat kd, ks; getSobelKernels( kd, ks, 2, 0, ksize, false, ktype ); // let's process 10 source rows at once int DELTA = std::min(10, src.rows); Ptr Fxx = createSeparableLinearFilter(src.type(), dst.type(), kd, ks, Point(-1,-1), 0, borderType, borderType, Scalar() ); Ptr Fyy = createSeparableLinearFilter(src.type(), dst.type(), ks, kd, Point(-1,-1), 0, borderType, borderType, Scalar() ); int y = Fxx->start(src), dsty = 0, dy = 0; Fyy->start(src); const uchar* sptr = src.data + y*src.step; // allocate the buffers for the spatial image derivatives; // the buffers need to have more than DELTA rows, because at the // last iteration the output may take max(kd.rows-1,ks.rows-1) // rows more than the input. Mat Ixx( DELTA + kd.rows - 1, src.cols, dst.type() ); Mat Iyy( DELTA + kd.rows - 1, src.cols, dst.type() ); // inside the loop we always pass DELTA rows to the filter // (note that the ""proceed"" method takes care of possibe overflow, since // it was given the actual image height in the ""start"" method) // on output we can get: // * < DELTA rows (the initial buffer accumulation stage) // * = DELTA rows (settled state in the middle) // * > DELTA rows (then the input image is over, but we generate // ""virtual"" rows using the border mode and filter them) // this variable number of output rows is dy. // dsty is the current output row. // sptr is the pointer to the first input row in the portion to process for( ; dsty < dst.rows; sptr += DELTA*src.step, dsty += dy ) { Fxx->proceed( sptr, (int)src.step, DELTA, Ixx.data, (int)Ixx.step ); dy = Fyy->proceed( sptr, (int)src.step, DELTA, d2y.data, (int)Iyy.step ); if( dy > 0 ) { Mat dstripe = dst.rowRange(dsty, dsty + dy); add(Ixx.rowRange(0, dy), Iyy.rowRange(0, dy), dstripe); } } } \\endcode */ class CV_EXPORTS FilterEngine { public: //! the default constructor FilterEngine(); //! the full constructor. Either _filter2D or both _rowFilter and _columnFilter must be non-empty. FilterEngine(const Ptr& _filter2D, const Ptr& _rowFilter, const Ptr& _columnFilter, int srcType, int dstType, int bufType, int _rowBorderType = BORDER_REPLICATE, int _columnBorderType = -1, const Scalar& _borderValue = Scalar()); //! the destructor virtual ~FilterEngine(); //! reinitializes the engine. The previously assigned filters are released. void init(const Ptr& _filter2D, const Ptr& _rowFilter, const Ptr& _columnFilter, int srcType, int dstType, int bufType, int _rowBorderType = BORDER_REPLICATE, int _columnBorderType = -1, const Scalar& _borderValue = Scalar()); //! starts filtering of the specified ROI of an image of size wholeSize. virtual int start(Size wholeSize, Rect roi, int maxBufRows = -1); //! starts filtering of the specified ROI of the specified image. virtual int start(const Mat& src, const Rect& srcRoi = Rect(0,0,-1,-1), bool isolated = false, int maxBufRows = -1); //! processes the next srcCount rows of the image. virtual int proceed(const uchar* src, int srcStep, int srcCount, uchar* dst, int dstStep); //! applies filter to the specified ROI of the image. if srcRoi=(0,0,-1,-1), the whole image is filtered. virtual void apply( const Mat& src, Mat& dst, const Rect& srcRoi = Rect(0,0,-1,-1), Point dstOfs = Point(0,0), bool isolated = false); //! returns true if the filter is separable bool isSeparable() const { return !filter2D; } //! returns the number int remainingInputRows() const; int remainingOutputRows() const; int srcType; int dstType; int bufType; Size ksize; Point anchor; int maxWidth; Size wholeSize; Rect roi; int dx1; int dx2; int rowBorderType; int columnBorderType; std::vector borderTab; int borderElemSize; std::vector ringBuf; std::vector srcRow; std::vector constBorderValue; std::vector constBorderRow; int bufStep; int startY; int startY0; int endY; int rowCount; int dstY; std::vector rows; Ptr filter2D; Ptr rowFilter; Ptr columnFilter; }; //! finds arbitrary template in the grayscale image using Generalized Hough Transform class CV_EXPORTS GeneralizedHough : public Algorithm { public: //! set template to search virtual void setTemplate(InputArray templ, Point templCenter = Point(-1, -1)) = 0; virtual void setTemplate(InputArray edges, InputArray dx, InputArray dy, Point templCenter = Point(-1, -1)) = 0; //! find template on image virtual void detect(InputArray image, OutputArray positions, OutputArray votes = noArray()) = 0; virtual void detect(InputArray edges, InputArray dx, InputArray dy, OutputArray positions, OutputArray votes = noArray()) = 0; //! Canny low threshold. virtual void setCannyLowThresh(int cannyLowThresh) = 0; virtual int getCannyLowThresh() const = 0; //! Canny high threshold. virtual void setCannyHighThresh(int cannyHighThresh) = 0; virtual int getCannyHighThresh() const = 0; //! Minimum distance between the centers of the detected objects. virtual void setMinDist(double minDist) = 0; virtual double getMinDist() const = 0; //! Inverse ratio of the accumulator resolution to the image resolution. virtual void setDp(double dp) = 0; virtual double getDp() const = 0; //! Maximal size of inner buffers. virtual void setMaxBufferSize(int maxBufferSize) = 0; virtual int getMaxBufferSize() const = 0; }; //! Ballard, D.H. (1981). Generalizing the Hough transform to detect arbitrary shapes. Pattern Recognition 13 (2): 111-122. //! Detects position only without traslation and rotation class CV_EXPORTS GeneralizedHoughBallard : public GeneralizedHough { public: //! R-Table levels. virtual void setLevels(int levels) = 0; virtual int getLevels() const = 0; //! The accumulator threshold for the template centers at the detection stage. The smaller it is, the more false positions may be detected. virtual void setVotesThreshold(int votesThreshold) = 0; virtual int getVotesThreshold() const = 0; }; //! Guil, N., González-Linares, J.M. and Zapata, E.L. (1999). Bidimensional shape detection using an invariant approach. Pattern Recognition 32 (6): 1025-1038. //! Detects position, traslation and rotation class CV_EXPORTS GeneralizedHoughGuil : public GeneralizedHough { public: //! Angle difference in degrees between two points in feature. virtual void setXi(double xi) = 0; virtual double getXi() const = 0; //! Feature table levels. virtual void setLevels(int levels) = 0; virtual int getLevels() const = 0; //! Maximal difference between angles that treated as equal. virtual void setAngleEpsilon(double angleEpsilon) = 0; virtual double getAngleEpsilon() const = 0; //! Minimal rotation angle to detect in degrees. virtual void setMinAngle(double minAngle) = 0; virtual double getMinAngle() const = 0; //! Maximal rotation angle to detect in degrees. virtual void setMaxAngle(double maxAngle) = 0; virtual double getMaxAngle() const = 0; //! Angle step in degrees. virtual void setAngleStep(double angleStep) = 0; virtual double getAngleStep() const = 0; //! Angle votes threshold. virtual void setAngleThresh(int angleThresh) = 0; virtual int getAngleThresh() const = 0; //! Minimal scale to detect. virtual void setMinScale(double minScale) = 0; virtual double getMinScale() const = 0; //! Maximal scale to detect. virtual void setMaxScale(double maxScale) = 0; virtual double getMaxScale() const = 0; //! Scale step. virtual void setScaleStep(double scaleStep) = 0; virtual double getScaleStep() const = 0; //! Scale votes threshold. virtual void setScaleThresh(int scaleThresh) = 0; virtual int getScaleThresh() const = 0; //! Position votes threshold. virtual void setPosThresh(int posThresh) = 0; virtual int getPosThresh() const = 0; }; class CV_EXPORTS_W CLAHE : public Algorithm { public: CV_WRAP virtual void apply(InputArray src, OutputArray dst) = 0; CV_WRAP virtual void setClipLimit(double clipLimit) = 0; CV_WRAP virtual double getClipLimit() const = 0; CV_WRAP virtual void setTilesGridSize(Size tileGridSize) = 0; CV_WRAP virtual Size getTilesGridSize() const = 0; CV_WRAP virtual void collectGarbage() = 0; }; class CV_EXPORTS_W Subdiv2D { public: enum { PTLOC_ERROR = -2, PTLOC_OUTSIDE_RECT = -1, PTLOC_INSIDE = 0, PTLOC_VERTEX = 1, PTLOC_ON_EDGE = 2 }; enum { NEXT_AROUND_ORG = 0x00, NEXT_AROUND_DST = 0x22, PREV_AROUND_ORG = 0x11, PREV_AROUND_DST = 0x33, NEXT_AROUND_LEFT = 0x13, NEXT_AROUND_RIGHT = 0x31, PREV_AROUND_LEFT = 0x20, PREV_AROUND_RIGHT = 0x02 }; CV_WRAP Subdiv2D(); CV_WRAP Subdiv2D(Rect rect); CV_WRAP void initDelaunay(Rect rect); CV_WRAP int insert(Point2f pt); CV_WRAP void insert(const std::vector& ptvec); CV_WRAP int locate(Point2f pt, CV_OUT int& edge, CV_OUT int& vertex); CV_WRAP int findNearest(Point2f pt, CV_OUT Point2f* nearestPt = 0); CV_WRAP void getEdgeList(CV_OUT std::vector& edgeList) const; CV_WRAP void getTriangleList(CV_OUT std::vector& triangleList) const; CV_WRAP void getVoronoiFacetList(const std::vector& idx, CV_OUT std::vector >& facetList, CV_OUT std::vector& facetCenters); CV_WRAP Point2f getVertex(int vertex, CV_OUT int* firstEdge = 0) const; CV_WRAP int getEdge( int edge, int nextEdgeType ) const; CV_WRAP int nextEdge(int edge) const; CV_WRAP int rotateEdge(int edge, int rotate) const; CV_WRAP int symEdge(int edge) const; CV_WRAP int edgeOrg(int edge, CV_OUT Point2f* orgpt = 0) const; CV_WRAP int edgeDst(int edge, CV_OUT Point2f* dstpt = 0) const; protected: int newEdge(); void deleteEdge(int edge); int newPoint(Point2f pt, bool isvirtual, int firstEdge = 0); void deletePoint(int vtx); void setEdgePoints( int edge, int orgPt, int dstPt ); void splice( int edgeA, int edgeB ); int connectEdges( int edgeA, int edgeB ); void swapEdges( int edge ); int isRightOf(Point2f pt, int edge) const; void calcVoronoi(); void clearVoronoi(); void checkSubdiv() const; struct CV_EXPORTS Vertex { Vertex(); Vertex(Point2f pt, bool _isvirtual, int _firstEdge=0); bool isvirtual() const; bool isfree() const; int firstEdge; int type; Point2f pt; }; struct CV_EXPORTS QuadEdge { QuadEdge(); QuadEdge(int edgeidx); bool isfree() const; int next[4]; int pt[4]; }; std::vector vtx; std::vector qedges; int freeQEdge; int freePoint; bool validGeometry; int recentEdge; Point2f topLeft; Point2f bottomRight; }; class CV_EXPORTS_W LineSegmentDetector : public Algorithm { public: /** * Detect lines in the input image. * * @param _image A grayscale(CV_8UC1) input image. * If only a roi needs to be selected, use * lsd_ptr->detect(image(roi), ..., lines); * lines += Scalar(roi.x, roi.y, roi.x, roi.y); * @param _lines Return: A vector of Vec4i elements specifying the beginning and ending point of a line. * Where Vec4i is (x1, y1, x2, y2), point 1 is the start, point 2 - end. * Returned lines are strictly oriented depending on the gradient. * @param width Return: Vector of widths of the regions, where the lines are found. E.g. Width of line. * @param prec Return: Vector of precisions with which the lines are found. * @param nfa Return: Vector containing number of false alarms in the line region, with precision of 10%. * The bigger the value, logarithmically better the detection. * * -1 corresponds to 10 mean false alarms * * 0 corresponds to 1 mean false alarm * * 1 corresponds to 0.1 mean false alarms * This vector will be calculated _only_ when the objects type is REFINE_ADV */ CV_WRAP virtual void detect(InputArray _image, OutputArray _lines, OutputArray width = noArray(), OutputArray prec = noArray(), OutputArray nfa = noArray()) = 0; /** * Draw lines on the given canvas. * * @param image The image, where lines will be drawn. * Should have the size of the image, where the lines were found * @param lines The lines that need to be drawn */ CV_WRAP virtual void drawSegments(InputOutputArray _image, InputArray lines) = 0; /** * Draw both vectors on the image canvas. Uses blue for lines 1 and red for lines 2. * * @param size The size of the image, where lines were found. * @param lines1 The first lines that need to be drawn. Color - Blue. * @param lines2 The second lines that need to be drawn. Color - Red. * @param image Optional image, where lines will be drawn. * Should have the size of the image, where the lines were found * @return The number of mismatching pixels between lines1 and lines2. */ CV_WRAP virtual int compareSegments(const Size& size, InputArray lines1, InputArray lines2, InputOutputArray _image = noArray()) = 0; virtual ~LineSegmentDetector() { } }; //! Returns a pointer to a LineSegmentDetector class. CV_EXPORTS_W Ptr createLineSegmentDetector( int _refine = LSD_REFINE_STD, double _scale = 0.8, double _sigma_scale = 0.6, double _quant = 2.0, double _ang_th = 22.5, double _log_eps = 0, double _density_th = 0.7, int _n_bins = 1024); //! returns type (one of KERNEL_*) of 1D or 2D kernel specified by its coefficients. CV_EXPORTS int getKernelType(InputArray kernel, Point anchor); //! returns the primitive row filter with the specified kernel CV_EXPORTS Ptr getLinearRowFilter(int srcType, int bufType, InputArray kernel, int anchor, int symmetryType); //! returns the primitive column filter with the specified kernel CV_EXPORTS Ptr getLinearColumnFilter(int bufType, int dstType, InputArray kernel, int anchor, int symmetryType, double delta = 0, int bits = 0); //! returns 2D filter with the specified kernel CV_EXPORTS Ptr getLinearFilter(int srcType, int dstType, InputArray kernel, Point anchor = Point(-1,-1), double delta = 0, int bits = 0); //! returns the separable linear filter engine CV_EXPORTS Ptr createSeparableLinearFilter(int srcType, int dstType, InputArray rowKernel, InputArray columnKernel, Point anchor = Point(-1,-1), double delta = 0, int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1, const Scalar& borderValue = Scalar()); //! returns the non-separable linear filter engine CV_EXPORTS Ptr createLinearFilter(int srcType, int dstType, InputArray kernel, Point _anchor = Point(-1,-1), double delta = 0, int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1, const Scalar& borderValue = Scalar()); //! returns the Gaussian kernel with the specified parameters CV_EXPORTS_W Mat getGaussianKernel( int ksize, double sigma, int ktype = CV_64F ); //! returns the Gaussian filter engine CV_EXPORTS Ptr createGaussianFilter( int type, Size ksize, double sigma1, double sigma2 = 0, int borderType = BORDER_DEFAULT); //! initializes kernels of the generalized Sobel operator CV_EXPORTS_W void getDerivKernels( OutputArray kx, OutputArray ky, int dx, int dy, int ksize, bool normalize = false, int ktype = CV_32F ); //! returns filter engine for the generalized Sobel operator CV_EXPORTS Ptr createDerivFilter( int srcType, int dstType, int dx, int dy, int ksize, int borderType = BORDER_DEFAULT ); //! returns horizontal 1D box filter CV_EXPORTS Ptr getRowSumFilter(int srcType, int sumType, int ksize, int anchor = -1); //! returns vertical 1D box filter CV_EXPORTS Ptr getColumnSumFilter( int sumType, int dstType, int ksize, int anchor = -1, double scale = 1); //! returns box filter engine CV_EXPORTS Ptr createBoxFilter( int srcType, int dstType, Size ksize, Point anchor = Point(-1,-1), bool normalize = true, int borderType = BORDER_DEFAULT); //! returns the Gabor kernel with the specified parameters CV_EXPORTS_W Mat getGaborKernel( Size ksize, double sigma, double theta, double lambd, double gamma, double psi = CV_PI*0.5, int ktype = CV_64F ); //! returns horizontal 1D morphological filter CV_EXPORTS Ptr getMorphologyRowFilter(int op, int type, int ksize, int anchor = -1); //! returns vertical 1D morphological filter CV_EXPORTS Ptr getMorphologyColumnFilter(int op, int type, int ksize, int anchor = -1); //! returns 2D morphological filter CV_EXPORTS Ptr getMorphologyFilter(int op, int type, InputArray kernel, Point anchor = Point(-1,-1)); //! returns ""magic"" border value for erosion and dilation. It is automatically transformed to Scalar::all(-DBL_MAX) for dilation. static inline Scalar morphologyDefaultBorderValue() { return Scalar::all(DBL_MAX); } //! returns morphological filter engine. Only MORPH_ERODE and MORPH_DILATE are supported. CV_EXPORTS Ptr createMorphologyFilter(int op, int type, InputArray kernel, Point anchor = Point(-1,-1), int rowBorderType = BORDER_CONSTANT, int columnBorderType = -1, const Scalar& borderValue = morphologyDefaultBorderValue()); //! returns structuring element of the specified shape and size CV_EXPORTS_W Mat getStructuringElement(int shape, Size ksize, Point anchor = Point(-1,-1)); //! smooths the image using median filter. CV_EXPORTS_W void medianBlur( InputArray src, OutputArray dst, int ksize ); //! smooths the image using Gaussian filter. CV_EXPORTS_W void GaussianBlur( InputArray src, OutputArray dst, Size ksize, double sigmaX, double sigmaY = 0, int borderType = BORDER_DEFAULT ); //! smooths the image using bilateral filter CV_EXPORTS_W void bilateralFilter( InputArray src, OutputArray dst, int d, double sigmaColor, double sigmaSpace, int borderType = BORDER_DEFAULT ); //! smooths the image using the box filter. Each pixel is processed in O(1) time CV_EXPORTS_W void boxFilter( InputArray src, OutputArray dst, int ddepth, Size ksize, Point anchor = Point(-1,-1), bool normalize = true, int borderType = BORDER_DEFAULT ); CV_EXPORTS_W void sqrBoxFilter( InputArray _src, OutputArray _dst, int ddepth, Size ksize, Point anchor = Point(-1, -1), bool normalize = true, int borderType = BORDER_DEFAULT ); //! a synonym for normalized box filter CV_EXPORTS_W void blur( InputArray src, OutputArray dst, Size ksize, Point anchor = Point(-1,-1), int borderType = BORDER_DEFAULT ); //! applies non-separable 2D linear filter to the image CV_EXPORTS_W void filter2D( InputArray src, OutputArray dst, int ddepth, InputArray kernel, Point anchor = Point(-1,-1), double delta = 0, int borderType = BORDER_DEFAULT ); //! applies separable 2D linear filter to the image CV_EXPORTS_W void sepFilter2D( InputArray src, OutputArray dst, int ddepth, InputArray kernelX, InputArray kernelY, Point anchor = Point(-1,-1), double delta = 0, int borderType = BORDER_DEFAULT ); //! applies generalized Sobel operator to the image CV_EXPORTS_W void Sobel( InputArray src, OutputArray dst, int ddepth, int dx, int dy, int ksize = 3, double scale = 1, double delta = 0, int borderType = BORDER_DEFAULT ); //! applies the vertical or horizontal Scharr operator to the image CV_EXPORTS_W void Scharr( InputArray src, OutputArray dst, int ddepth, int dx, int dy, double scale = 1, double delta = 0, int borderType = BORDER_DEFAULT ); //! applies Laplacian operator to the image CV_EXPORTS_W void Laplacian( InputArray src, OutputArray dst, int ddepth, int ksize = 1, double scale = 1, double delta = 0, int borderType = BORDER_DEFAULT ); //! applies Canny edge detector and produces the edge map. CV_EXPORTS_W void Canny( InputArray image, OutputArray edges, double threshold1, double threshold2, int apertureSize = 3, bool L2gradient = false ); //! computes minimum eigen value of 2x2 derivative covariation matrix at each pixel - the cornerness criteria CV_EXPORTS_W void cornerMinEigenVal( InputArray src, OutputArray dst, int blockSize, int ksize = 3, int borderType = BORDER_DEFAULT ); //! computes Harris cornerness criteria at each image pixel CV_EXPORTS_W void cornerHarris( InputArray src, OutputArray dst, int blockSize, int ksize, double k, int borderType = BORDER_DEFAULT ); //! computes both eigenvalues and the eigenvectors of 2x2 derivative covariation matrix at each pixel. The output is stored as 6-channel matrix. CV_EXPORTS_W void cornerEigenValsAndVecs( InputArray src, OutputArray dst, int blockSize, int ksize, int borderType = BORDER_DEFAULT ); //! computes another complex cornerness criteria at each pixel CV_EXPORTS_W void preCornerDetect( InputArray src, OutputArray dst, int ksize, int borderType = BORDER_DEFAULT ); //! adjusts the corner locations with sub-pixel accuracy to maximize the certain cornerness criteria CV_EXPORTS_W void cornerSubPix( InputArray image, InputOutputArray corners, Size winSize, Size zeroZone, TermCriteria criteria ); //! finds the strong enough corners where the cornerMinEigenVal() or cornerHarris() report the local maxima CV_EXPORTS_W void goodFeaturesToTrack( InputArray image, OutputArray corners, int maxCorners, double qualityLevel, double minDistance, InputArray mask = noArray(), int blockSize = 3, bool useHarrisDetector = false, double k = 0.04 ); //! finds lines in the black-n-white image using the standard or pyramid Hough transform CV_EXPORTS_W void HoughLines( InputArray image, OutputArray lines, double rho, double theta, int threshold, double srn = 0, double stn = 0, double min_theta = 0, double max_theta = CV_PI ); //! finds line segments in the black-n-white image using probabilistic Hough transform CV_EXPORTS_W void HoughLinesP( InputArray image, OutputArray lines, double rho, double theta, int threshold, double minLineLength = 0, double maxLineGap = 0 ); //! finds circles in the grayscale image using 2+1 gradient Hough transform CV_EXPORTS_W void HoughCircles( InputArray image, OutputArray circles, int method, double dp, double minDist, double param1 = 100, double param2 = 100, int minRadius = 0, int maxRadius = 0 ); //! erodes the image (applies the local minimum operator) CV_EXPORTS_W void erode( InputArray src, OutputArray dst, InputArray kernel, Point anchor = Point(-1,-1), int iterations = 1, int borderType = BORDER_CONSTANT, const Scalar& borderValue = morphologyDefaultBorderValue() ); //! dilates the image (applies the local maximum operator) CV_EXPORTS_W void dilate( InputArray src, OutputArray dst, InputArray kernel, Point anchor = Point(-1,-1), int iterations = 1, int borderType = BORDER_CONSTANT, const Scalar& borderValue = morphologyDefaultBorderValue() ); //! applies an advanced morphological operation to the image CV_EXPORTS_W void morphologyEx( InputArray src, OutputArray dst, int op, InputArray kernel, Point anchor = Point(-1,-1), int iterations = 1, int borderType = BORDER_CONSTANT, const Scalar& borderValue = morphologyDefaultBorderValue() ); //! resizes the image CV_EXPORTS_W void resize( InputArray src, OutputArray dst, Size dsize, double fx = 0, double fy = 0, int interpolation = INTER_LINEAR ); //! warps the image using affine transformation CV_EXPORTS_W void warpAffine( InputArray src, OutputArray dst, InputArray M, Size dsize, int flags = INTER_LINEAR, int borderMode = BORDER_CONSTANT, const Scalar& borderValue = Scalar()); //! warps the image using perspective transformation CV_EXPORTS_W void warpPerspective( InputArray src, OutputArray dst, InputArray M, Size dsize, int flags = INTER_LINEAR, int borderMode = BORDER_CONSTANT, const Scalar& borderValue = Scalar()); //! warps the image using the precomputed maps. The maps are stored in either floating-point or integer fixed-point format CV_EXPORTS_W void remap( InputArray src, OutputArray dst, InputArray map1, InputArray map2, int interpolation, int borderMode = BORDER_CONSTANT, const Scalar& borderValue = Scalar()); //! converts maps for remap from floating-point to fixed-point format or backwards CV_EXPORTS_W void convertMaps( InputArray map1, InputArray map2, OutputArray dstmap1, OutputArray dstmap2, int dstmap1type, bool nninterpolation = false ); //! returns 2x3 affine transformation matrix for the planar rotation. CV_EXPORTS_W Mat getRotationMatrix2D( Point2f center, double angle, double scale ); //! returns 3x3 perspective transformation for the corresponding 4 point pairs. CV_EXPORTS Mat getPerspectiveTransform( const Point2f src[], const Point2f dst[] ); //! returns 2x3 affine transformation for the corresponding 3 point pairs. CV_EXPORTS Mat getAffineTransform( const Point2f src[], const Point2f dst[] ); //! computes 2x3 affine transformation matrix that is inverse to the specified 2x3 affine transformation. CV_EXPORTS_W void invertAffineTransform( InputArray M, OutputArray iM ); CV_EXPORTS_W Mat getPerspectiveTransform( InputArray src, InputArray dst ); CV_EXPORTS_W Mat getAffineTransform( InputArray src, InputArray dst ); //! extracts rectangle from the image at sub-pixel location CV_EXPORTS_W void getRectSubPix( InputArray image, Size patchSize, Point2f center, OutputArray patch, int patchType = -1 ); //! computes the log polar transform CV_EXPORTS_W void logPolar( InputArray src, OutputArray dst, Point2f center, double M, int flags ); //! computes the linear polar transform CV_EXPORTS_W void linearPolar( InputArray src, OutputArray dst, Point2f center, double maxRadius, int flags ); //! computes the integral image CV_EXPORTS_W void integral( InputArray src, OutputArray sum, int sdepth = -1 ); //! computes the integral image and integral for the squared image CV_EXPORTS_AS(integral2) void integral( InputArray src, OutputArray sum, OutputArray sqsum, int sdepth = -1, int sqdepth = -1 ); //! computes the integral image, integral for the squared image and the tilted integral image CV_EXPORTS_AS(integral3) void integral( InputArray src, OutputArray sum, OutputArray sqsum, OutputArray tilted, int sdepth = -1, int sqdepth = -1 ); //! adds image to the accumulator (dst += src). Unlike cv::add, dst and src can have different types. CV_EXPORTS_W void accumulate( InputArray src, InputOutputArray dst, InputArray mask = noArray() ); //! adds squared src image to the accumulator (dst += src*src). CV_EXPORTS_W void accumulateSquare( InputArray src, InputOutputArray dst, InputArray mask = noArray() ); //! adds product of the 2 images to the accumulator (dst += src1*src2). CV_EXPORTS_W void accumulateProduct( InputArray src1, InputArray src2, InputOutputArray dst, InputArray mask=noArray() ); //! updates the running average (dst = dst*(1-alpha) + src*alpha) CV_EXPORTS_W void accumulateWeighted( InputArray src, InputOutputArray dst, double alpha, InputArray mask = noArray() ); CV_EXPORTS_W Point2d phaseCorrelate(InputArray src1, InputArray src2, InputArray window = noArray(), CV_OUT double* response = 0); CV_EXPORTS_W void createHanningWindow(OutputArray dst, Size winSize, int type); //! applies fixed threshold to the image CV_EXPORTS_W double threshold( InputArray src, OutputArray dst, double thresh, double maxval, int type ); //! applies variable (adaptive) threshold to the image CV_EXPORTS_W void adaptiveThreshold( InputArray src, OutputArray dst, double maxValue, int adaptiveMethod, int thresholdType, int blockSize, double C ); //! smooths and downsamples the image CV_EXPORTS_W void pyrDown( InputArray src, OutputArray dst, const Size& dstsize = Size(), int borderType = BORDER_DEFAULT ); //! upsamples and smoothes the image CV_EXPORTS_W void pyrUp( InputArray src, OutputArray dst, const Size& dstsize = Size(), int borderType = BORDER_DEFAULT ); //! builds the gaussian pyramid using pyrDown() as a basic operation CV_EXPORTS void buildPyramid( InputArray src, OutputArrayOfArrays dst, int maxlevel, int borderType = BORDER_DEFAULT ); //! corrects lens distortion for the given camera matrix and distortion coefficients CV_EXPORTS_W void undistort( InputArray src, OutputArray dst, InputArray cameraMatrix, InputArray distCoeffs, InputArray newCameraMatrix = noArray() ); //! initializes maps for cv::remap() to correct lens distortion and optionally rectify the image CV_EXPORTS_W void initUndistortRectifyMap( InputArray cameraMatrix, InputArray distCoeffs, InputArray R, InputArray newCameraMatrix, Size size, int m1type, OutputArray map1, OutputArray map2 ); //! initializes maps for cv::remap() for wide-angle CV_EXPORTS_W float initWideAngleProjMap( InputArray cameraMatrix, InputArray distCoeffs, Size imageSize, int destImageWidth, int m1type, OutputArray map1, OutputArray map2, int projType = PROJ_SPHERICAL_EQRECT, double alpha = 0); //! returns the default new camera matrix (by default it is the same as cameraMatrix unless centerPricipalPoint=true) CV_EXPORTS_W Mat getDefaultNewCameraMatrix( InputArray cameraMatrix, Size imgsize = Size(), bool centerPrincipalPoint = false ); //! returns points' coordinates after lens distortion correction CV_EXPORTS_W void undistortPoints( InputArray src, OutputArray dst, InputArray cameraMatrix, InputArray distCoeffs, InputArray R = noArray(), InputArray P = noArray()); //! computes the joint dense histogram for a set of images. CV_EXPORTS void calcHist( const Mat* images, int nimages, const int* channels, InputArray mask, OutputArray hist, int dims, const int* histSize, const float** ranges, bool uniform = true, bool accumulate = false ); //! computes the joint sparse histogram for a set of images. CV_EXPORTS void calcHist( const Mat* images, int nimages, const int* channels, InputArray mask, SparseMat& hist, int dims, const int* histSize, const float** ranges, bool uniform = true, bool accumulate = false ); CV_EXPORTS_W void calcHist( InputArrayOfArrays images, const std::vector& channels, InputArray mask, OutputArray hist, const std::vector& histSize, const std::vector& ranges, bool accumulate = false ); //! computes back projection for the set of images CV_EXPORTS void calcBackProject( const Mat* images, int nimages, const int* channels, InputArray hist, OutputArray backProject, const float** ranges, double scale = 1, bool uniform = true ); //! computes back projection for the set of images CV_EXPORTS void calcBackProject( const Mat* images, int nimages, const int* channels, const SparseMat& hist, OutputArray backProject, const float** ranges, double scale = 1, bool uniform = true ); CV_EXPORTS_W void calcBackProject( InputArrayOfArrays images, const std::vector& channels, InputArray hist, OutputArray dst, const std::vector& ranges, double scale ); //! compares two histograms stored in dense arrays CV_EXPORTS_W double compareHist( InputArray H1, InputArray H2, int method ); //! compares two histograms stored in sparse arrays CV_EXPORTS double compareHist( const SparseMat& H1, const SparseMat& H2, int method ); //! normalizes the grayscale image brightness and contrast by normalizing its histogram CV_EXPORTS_W void equalizeHist( InputArray src, OutputArray dst ); CV_EXPORTS float EMD( InputArray signature1, InputArray signature2, int distType, InputArray cost=noArray(), float* lowerBound = 0, OutputArray flow = noArray() ); //! segments the image using watershed algorithm CV_EXPORTS_W void watershed( InputArray image, InputOutputArray markers ); //! filters image using meanshift algorithm CV_EXPORTS_W void pyrMeanShiftFiltering( InputArray src, OutputArray dst, double sp, double sr, int maxLevel = 1, TermCriteria termcrit=TermCriteria(TermCriteria::MAX_ITER+TermCriteria::EPS,5,1) ); //! segments the image using GrabCut algorithm CV_EXPORTS_W void grabCut( InputArray img, InputOutputArray mask, Rect rect, InputOutputArray bgdModel, InputOutputArray fgdModel, int iterCount, int mode = GC_EVAL ); //! builds the discrete Voronoi diagram CV_EXPORTS_AS(distanceTransformWithLabels) void distanceTransform( InputArray src, OutputArray dst, OutputArray labels, int distanceType, int maskSize, int labelType = DIST_LABEL_CCOMP ); //! computes the distance transform map CV_EXPORTS_W void distanceTransform( InputArray src, OutputArray dst, int distanceType, int maskSize ); //! fills the semi-uniform image region starting from the specified seed point CV_EXPORTS int floodFill( InputOutputArray image, Point seedPoint, Scalar newVal, CV_OUT Rect* rect = 0, Scalar loDiff = Scalar(), Scalar upDiff = Scalar(), int flags = 4 ); //! fills the semi-uniform image region and/or the mask starting from the specified seed point CV_EXPORTS_W int floodFill( InputOutputArray image, InputOutputArray mask, Point seedPoint, Scalar newVal, CV_OUT Rect* rect=0, Scalar loDiff = Scalar(), Scalar upDiff = Scalar(), int flags = 4 ); //! converts image from one color space to another CV_EXPORTS_W void cvtColor( InputArray src, OutputArray dst, int code, int dstCn = 0 ); // main function for all demosaicing procceses CV_EXPORTS_W void demosaicing(InputArray _src, OutputArray _dst, int code, int dcn = 0); //! computes moments of the rasterized shape or a vector of points CV_EXPORTS_W Moments moments( InputArray array, bool binaryImage = false ); //! computes 7 Hu invariants from the moments CV_EXPORTS void HuMoments( const Moments& moments, double hu[7] ); CV_EXPORTS_W void HuMoments( const Moments& m, OutputArray hu ); //! computes the proximity map for the raster template and the image where the template is searched for CV_EXPORTS_W void matchTemplate( InputArray image, InputArray templ, OutputArray result, int method ); // computes the connected components labeled image of boolean image ``image`` // with 4 or 8 way connectivity - returns N, the total // number of labels [0, N-1] where 0 represents the background label. // ltype specifies the output label image type, an important // consideration based on the total number of labels or // alternatively the total number of pixels in the source image. CV_EXPORTS_W int connectedComponents(InputArray image, OutputArray labels, int connectivity = 8, int ltype = CV_32S); CV_EXPORTS_W int connectedComponentsWithStats(InputArray image, OutputArray labels, OutputArray stats, OutputArray centroids, int connectivity = 8, int ltype = CV_32S); //! retrieves contours and the hierarchical information from black-n-white image. CV_EXPORTS_W void findContours( InputOutputArray image, OutputArrayOfArrays contours, OutputArray hierarchy, int mode, int method, Point offset = Point()); //! retrieves contours from black-n-white image. CV_EXPORTS void findContours( InputOutputArray image, OutputArrayOfArrays contours, int mode, int method, Point offset = Point()); //! approximates contour or a curve using Douglas-Peucker algorithm CV_EXPORTS_W void approxPolyDP( InputArray curve, OutputArray approxCurve, double epsilon, bool closed ); //! computes the contour perimeter (closed=true) or a curve length CV_EXPORTS_W double arcLength( InputArray curve, bool closed ); //! computes the bounding rectangle for a contour CV_EXPORTS_W Rect boundingRect( InputArray points ); //! computes the contour area CV_EXPORTS_W double contourArea( InputArray contour, bool oriented = false ); //! computes the minimal rotated rectangle for a set of points CV_EXPORTS_W RotatedRect minAreaRect( InputArray points ); //! computes boxpoints CV_EXPORTS_W void boxPoints(RotatedRect box, OutputArray points); //! computes the minimal enclosing circle for a set of points CV_EXPORTS_W void minEnclosingCircle( InputArray points, CV_OUT Point2f& center, CV_OUT float& radius ); //! computes the minimal enclosing triangle for a set of points and returns its area CV_EXPORTS_W double minEnclosingTriangle( InputArray points, CV_OUT OutputArray triangle ); //! matches two contours using one of the available algorithms CV_EXPORTS_W double matchShapes( InputArray contour1, InputArray contour2, int method, double parameter ); //! computes convex hull for a set of 2D points. CV_EXPORTS_W void convexHull( InputArray points, OutputArray hull, bool clockwise = false, bool returnPoints = true ); //! computes the contour convexity defects CV_EXPORTS_W void convexityDefects( InputArray contour, InputArray convexhull, OutputArray convexityDefects ); //! returns true if the contour is convex. Does not support contours with self-intersection CV_EXPORTS_W bool isContourConvex( InputArray contour ); //! finds intersection of two convex polygons CV_EXPORTS_W float intersectConvexConvex( InputArray _p1, InputArray _p2, OutputArray _p12, bool handleNested = true ); //! fits ellipse to the set of 2D points CV_EXPORTS_W RotatedRect fitEllipse( InputArray points ); //! fits line to the set of 2D points using M-estimator algorithm CV_EXPORTS_W void fitLine( InputArray points, OutputArray line, int distType, double param, double reps, double aeps ); //! checks if the point is inside the contour. Optionally computes the signed distance from the point to the contour boundary CV_EXPORTS_W double pointPolygonTest( InputArray contour, Point2f pt, bool measureDist ); //! computes whether two rotated rectangles intersect and returns the vertices of the intersecting region CV_EXPORTS_W int rotatedRectangleIntersection( const RotatedRect& rect1, const RotatedRect& rect2, OutputArray intersectingRegion ); CV_EXPORTS_W Ptr createCLAHE(double clipLimit = 40.0, Size tileGridSize = Size(8, 8)); //! Ballard, D.H. (1981). Generalizing the Hough transform to detect arbitrary shapes. Pattern Recognition 13 (2): 111-122. //! Detects position only without traslation and rotation CV_EXPORTS Ptr createGeneralizedHoughBallard(); //! Guil, N., González-Linares, J.M. and Zapata, E.L. (1999). Bidimensional shape detection using an invariant approach. Pattern Recognition 32 (6): 1025-1038. //! Detects position, traslation and rotation CV_EXPORTS Ptr createGeneralizedHoughGuil(); //! Performs linear blending of two images CV_EXPORTS void blendLinear(InputArray src1, InputArray src2, InputArray weights1, InputArray weights2, OutputArray dst); } // cv #endif ",16217,False,2301.7094116851404,median "*&---------------------------------------------------------------------* *& Include ZABAPGIT_OBJECTS *&---------------------------------------------------------------------* *----------------------------------------------------------------------* * CLASS lcl_objects_activation DEFINITION *----------------------------------------------------------------------* * *----------------------------------------------------------------------* CLASS lcl_objects_activation DEFINITION FINAL. PUBLIC SECTION. CLASS-METHODS add IMPORTING iv_type TYPE trobjtype iv_name TYPE clike RAISING lcx_exception. CLASS-METHODS add_item IMPORTING is_item TYPE ty_item RAISING lcx_exception. CLASS-METHODS activate IMPORTING iv_ddic TYPE abap_bool DEFAULT abap_false RAISING lcx_exception. CLASS-METHODS clear. PRIVATE SECTION. CLASS-METHODS fix_class_methods IMPORTING iv_obj_name TYPE trobj_name CHANGING ct_objects TYPE dwinactiv_tab. CLASS-DATA: gt_objects TYPE TABLE OF dwinactiv. ENDCLASS. ""lcl_objects_activation DEFINITION *----------------------------------------------------------------------* * CLASS lcl_objects_activation IMPLEMENTATION *----------------------------------------------------------------------* * *----------------------------------------------------------------------* CLASS lcl_objects_activation IMPLEMENTATION. METHOD add_item. add( iv_type = is_item-obj_type iv_name = is_item-obj_name ). ENDMETHOD. ""add_item METHOD clear. CLEAR gt_objects. ENDMETHOD. ""clear METHOD activate. IF NOT gt_objects IS INITIAL. CALL FUNCTION 'RS_WORKING_OBJECTS_ACTIVATE' EXPORTING activate_ddic_objects = iv_ddic with_popup = abap_true TABLES objects = gt_objects EXCEPTIONS excecution_error = 1 cancelled = 2 insert_into_corr_error = 3 OTHERS = 4. IF sy-subrc <> 0. lcx_exception=>raise( 'error from RS_WORKING_OBJECTS_ACTIVATE' ). ENDIF. ENDIF. ENDMETHOD. ""activate METHOD fix_class_methods. * function module RS_WORKING_OBJECTS_ACTIVATE assumes that * METH lines contains spaces between class and method name * however, classes named with 30 characters * eg. ZCL_CLAS_TESTTESTTESTTESTTESTT * this will not be true, so find all the method includes instead DATA: lt_methods TYPE seop_methods_w_include, lv_class TYPE seoclsname. FIELD-SYMBOLS: LIKE LINE OF lt_methods, LIKE LINE OF ct_objects. lv_class = iv_obj_name. cl_oo_classname_service=>get_all_method_includes( EXPORTING clsname = lv_class RECEIVING result = lt_methods EXCEPTIONS class_not_existing = 1 OTHERS = 2 ). ASSERT sy-subrc = 0. DELETE ct_objects WHERE object = 'METH'. LOOP AT lt_methods ASSIGNING . APPEND INITIAL LINE TO ct_objects ASSIGNING . -object = 'METH'. -obj_name = -incname. ENDLOOP. ENDMETHOD. METHOD add. * function group SEWORKINGAREA * function module RS_INSERT_INTO_WORKING_AREA * class CL_WB_ACTIVATION_WORK_AREA DATA: lt_objects TYPE dwinactiv_tab, lv_obj_name TYPE dwinactiv-obj_name. FIELD-SYMBOLS: LIKE LINE OF lt_objects. lv_obj_name = iv_name. CASE iv_type. WHEN 'CLAS' OR 'WDYN'. * todo, move this to the object type include instead CALL FUNCTION 'RS_INACTIVE_OBJECTS_IN_OBJECT' EXPORTING obj_name = lv_obj_name object = iv_type TABLES inactive_objects = lt_objects EXCEPTIONS object_not_found = 1 OTHERS = 2. IF sy-subrc <> 0. lcx_exception=>raise( 'Error from RS_INACTIVE_OBJECTS_IN_OBJECT' ). ENDIF. IF iv_type = 'CLAS'. fix_class_methods( EXPORTING iv_obj_name = lv_obj_name CHANGING ct_objects = lt_objects ). ENDIF. APPEND LINES OF lt_objects TO gt_objects. WHEN OTHERS. APPEND INITIAL LINE TO gt_objects ASSIGNING . -object = iv_type. -obj_name = lv_obj_name. ENDCASE. ENDMETHOD. ""activate ENDCLASS. ""lcl_objects_activation IMPLEMENTATION *----------------------------------------------------------------------* * CLASS lcl_objects_files DEFINITION *----------------------------------------------------------------------* * *----------------------------------------------------------------------* CLASS lcl_objects_files DEFINITION. PUBLIC SECTION. METHODS: constructor IMPORTING is_item TYPE ty_item, add_string IMPORTING iv_extra TYPE clike OPTIONAL iv_ext TYPE string iv_string TYPE string RAISING lcx_exception, read_string IMPORTING iv_extra TYPE clike OPTIONAL iv_ext TYPE string RETURNING VALUE(rv_string) TYPE string RAISING lcx_exception, add_xml IMPORTING iv_extra TYPE clike OPTIONAL io_xml TYPE REF TO lcl_xml_output iv_normalize TYPE sap_bool DEFAULT abap_true is_metadata TYPE ty_metadata OPTIONAL RAISING lcx_exception, * needed since type-check during dynamic call fails even if the object is compatible add_xml_from_plugin IMPORTING iv_extra TYPE clike OPTIONAL io_xml TYPE REF TO object iv_normalize TYPE sap_bool DEFAULT abap_true RAISING lcx_exception ##called, read_xml IMPORTING iv_extra TYPE clike OPTIONAL RETURNING VALUE(ro_xml) TYPE REF TO lcl_xml_input RAISING lcx_exception, read_abap IMPORTING iv_extra TYPE clike OPTIONAL iv_error TYPE sap_bool DEFAULT abap_true RETURNING VALUE(rt_abap) TYPE abaptxt255_tab RAISING lcx_exception, add_abap IMPORTING iv_extra TYPE clike OPTIONAL it_abap TYPE STANDARD TABLE RAISING lcx_exception, add IMPORTING is_file TYPE ty_file, add_raw IMPORTING iv_extra TYPE clike OPTIONAL iv_ext TYPE string iv_data TYPE xstring RAISING lcx_exception, read_raw IMPORTING iv_extra TYPE clike OPTIONAL iv_ext TYPE string RETURNING VALUE(rv_data) TYPE xstring RAISING lcx_exception, get_files RETURNING VALUE(rt_files) TYPE ty_files_tt, set_files IMPORTING it_files TYPE ty_files_tt, get_accessed_files RETURNING VALUE(rt_files) TYPE ty_file_signatures_tt. PRIVATE SECTION. DATA: ms_item TYPE ty_item, mt_accessed_files TYPE ty_file_signatures_tt, mt_files TYPE ty_files_tt. METHODS: read_file IMPORTING iv_filename TYPE string iv_error TYPE abap_bool DEFAULT abap_true EXPORTING ev_data TYPE xstring RAISING lcx_exception, filename IMPORTING iv_extra TYPE clike OPTIONAL iv_ext TYPE string RETURNING VALUE(rv_filename) TYPE string. ENDCLASS. ""lcl_objects_files DEFINITION INTERFACE lif_object_comparison_result. METHODS: show_confirmation_dialog, is_result_complete_halt RETURNING VALUE(rv_response) TYPE abap_bool. ENDINTERFACE. ""Null Object Pattern CLASS lcl_null_comparison_result DEFINITION FINAL. PUBLIC SECTION. INTERFACES lif_object_comparison_result. ENDCLASS. CLASS lcl_null_comparison_result IMPLEMENTATION. METHOD lif_object_comparison_result~is_result_complete_halt. rv_response = abap_false. ENDMETHOD. METHOD lif_object_comparison_result~show_confirmation_dialog. RETURN. ENDMETHOD. ENDCLASS. *----------------------------------------------------------------------* * INTERFACE lif_object DEFINITION *----------------------------------------------------------------------* * *----------------------------------------------------------------------* INTERFACE lif_object. METHODS: serialize IMPORTING io_xml TYPE REF TO lcl_xml_output RAISING lcx_exception, deserialize IMPORTING iv_package TYPE devclass io_xml TYPE REF TO lcl_xml_input RAISING lcx_exception, delete RAISING lcx_exception, exists RETURNING VALUE(rv_bool) TYPE abap_bool RAISING lcx_exception, changed_by RETURNING VALUE(rv_user) TYPE xubname RAISING lcx_exception, jump RAISING lcx_exception, get_metadata RETURNING VALUE(rs_metadata) TYPE ty_metadata, has_changed_since IMPORTING iv_timestamp TYPE timestamp RETURNING VALUE(rv_changed) TYPE abap_bool RAISING lcx_exception. METHODS: compare_to_remote_version IMPORTING io_remote_version_xml TYPE REF TO lcl_xml_input RETURNING VALUE(ro_comparison_result) TYPE REF TO lif_object_comparison_result RAISING lcx_exception. DATA: mo_files TYPE REF TO lcl_objects_files. ENDINTERFACE. ""lif_object DEFINITION *----------------------------------------------------------------------* * CLASS lcl_objects_files IMPLEMENTATION *----------------------------------------------------------------------* * *----------------------------------------------------------------------* CLASS lcl_objects_files IMPLEMENTATION. METHOD constructor. ms_item = is_item. ENDMETHOD. ""constructor METHOD add. APPEND is_file TO mt_files. ENDMETHOD. ""add METHOD get_files. rt_files = mt_files. ENDMETHOD. ""get_files METHOD set_files. mt_files = it_files. ENDMETHOD. ""set_files METHOD get_accessed_files. rt_files = mt_accessed_files. ENDMETHOD. "" get_accessed_files. METHOD read_string. DATA: lv_filename TYPE string, lv_data TYPE xstring. lv_filename = filename( iv_extra = iv_extra iv_ext = iv_ext ). ""#EC NOTEXT read_file( EXPORTING iv_filename = lv_filename IMPORTING ev_data = lv_data ). rv_string = lcl_convert=>xstring_to_string_utf8( lv_data ). ENDMETHOD. ""read_string METHOD read_abap. DATA: lv_filename TYPE string, lv_data TYPE xstring, lv_abap TYPE string. lv_filename = filename( iv_extra = iv_extra iv_ext = 'abap' ). ""#EC NOTEXT read_file( EXPORTING iv_filename = lv_filename iv_error = iv_error IMPORTING ev_data = lv_data ). IF lv_data IS INITIAL. "" Post-handling of iv_error = false RETURN. ENDIF. lv_abap = lcl_convert=>xstring_to_string_utf8( lv_data ). SPLIT lv_abap AT gc_newline INTO TABLE rt_abap. ENDMETHOD. ""read_abap METHOD add_abap. DATA: lv_source TYPE string, ls_file TYPE ty_file. CONCATENATE LINES OF it_abap INTO lv_source SEPARATED BY gc_newline. * when editing files via eg. GitHub web interface it adds a newline at end of file lv_source = lv_source && gc_newline. ls_file-path = '/'. ls_file-filename = filename( iv_extra = iv_extra iv_ext = 'abap' ). ""#EC NOTEXT ls_file-data = lcl_convert=>string_to_xstring_utf8( lv_source ). APPEND ls_file TO mt_files. ENDMETHOD. ""abap_to_file METHOD add_string. DATA: ls_file TYPE ty_file. ls_file-path = '/'. ls_file-filename = filename( iv_extra = iv_extra iv_ext = iv_ext ). ""#EC NOTEXT ls_file-data = lcl_convert=>string_to_xstring_utf8( iv_string ). APPEND ls_file TO mt_files. ENDMETHOD. ""add_string METHOD add_xml. DATA: lv_xml TYPE string, ls_file TYPE ty_file. lv_xml = io_xml->render( iv_normalize = iv_normalize is_metadata = is_metadata ). ls_file-path = '/'. ls_file-filename = filename( iv_extra = iv_extra iv_ext = 'xml' ). ""#EC NOTEXT REPLACE FIRST OCCURRENCE OF REGEX '<\\?xml version=""1\\.0"" encoding=""[\\w-]+""\\?>' IN lv_xml WITH ''. ASSERT sy-subrc = 0. ls_file-data = lcl_convert=>string_to_xstring_utf8( lv_xml ). APPEND ls_file TO mt_files. ENDMETHOD. ""do METHOD read_xml. DATA: lv_filename TYPE string, lv_data TYPE xstring, lv_xml TYPE string. lv_filename = filename( iv_extra = iv_extra iv_ext = 'xml' ). ""#EC NOTEXT read_file( EXPORTING iv_filename = lv_filename IMPORTING ev_data = lv_data ). lv_xml = lcl_convert=>xstring_to_string_utf8( lv_data ). CREATE OBJECT ro_xml EXPORTING iv_xml = lv_xml. ENDMETHOD. ""read_xml METHOD filename. DATA: lv_obj_name TYPE string. IF ms_item-obj_type = 'SICF'. * multiple SICF nodes with same name cannot be added to repository lv_obj_name = ms_item-obj_name(15). ELSE. lv_obj_name = ms_item-obj_name. ENDIF. * handle namespaces REPLACE ALL OCCURRENCES OF '/' IN lv_obj_name WITH '#'. IF iv_extra IS INITIAL. CONCATENATE lv_obj_name '.' ms_item-obj_type '.' iv_ext INTO rv_filename. ""#EC NOTEXT ELSE. CONCATENATE lv_obj_name '.' ms_item-obj_type '.' iv_extra '.' iv_ext INTO rv_filename. ""#EC NOTEXT ENDIF. TRANSLATE rv_filename TO LOWER CASE. ENDMETHOD. ""filename METHOD add_xml_from_plugin. * this method wraps add_xml as in the plugin. This is necessary as the wrapped * xml-object in the plugin can only be typed to object. * ABAP does not perform implicit type casts (also if compatible) in signatures, * therefore this method's signature is typed ref to object DATA lo_xml TYPE REF TO lcl_xml_output. lo_xml ?= io_xml. me->add_xml( iv_extra = iv_extra io_xml = lo_xml iv_normalize = iv_normalize ). ENDMETHOD. ""add_xml_from_plugin METHOD read_file. FIELD-SYMBOLS: LIKE LINE OF mt_files, LIKE LINE OF mt_accessed_files. CLEAR ev_data. READ TABLE mt_files ASSIGNING WITH KEY filename = iv_filename. IF sy-subrc <> 0. IF iv_error = abap_true. lcx_exception=>raise( |File not found: { iv_filename }| ). ELSE. RETURN. ENDIF. ENDIF. "" Update access table READ TABLE mt_accessed_files TRANSPORTING NO FIELDS WITH KEY path = -path filename = -filename. IF sy-subrc > 0. "" Not found ? -> Add APPEND INITIAL LINE TO mt_accessed_files ASSIGNING . MOVE-CORRESPONDING TO . ENDIF. ev_data = -data. ENDMETHOD. "" read_file. METHOD add_raw. DATA: ls_file TYPE ty_file. ls_file-path = '/'. ls_file-data = iv_data. ls_file-filename = filename( iv_extra = iv_extra iv_ext = iv_ext ). APPEND ls_file TO mt_files. ENDMETHOD. ""add_raw METHOD read_raw. DATA: lv_filename TYPE string. lv_filename = filename( iv_extra = iv_extra iv_ext = iv_ext ). read_file( EXPORTING iv_filename = lv_filename IMPORTING ev_data = rv_data ). ENDMETHOD. ""read_raw ENDCLASS. ""lcl_objects_files IMPLEMENTATION *----------------------------------------------------------------------* * CLASS lcl_objects_super DEFINITION *----------------------------------------------------------------------* * *----------------------------------------------------------------------* CLASS lcl_objects_super DEFINITION ABSTRACT. PUBLIC SECTION. METHODS: constructor IMPORTING is_item TYPE ty_item iv_language TYPE spras. CONSTANTS: c_user_unknown TYPE xubname VALUE 'UNKNOWN'. PROTECTED SECTION. DATA: ms_item TYPE ty_item, mv_language TYPE spras. METHODS: get_metadata RETURNING VALUE(rs_metadata) TYPE ty_metadata, corr_insert IMPORTING iv_package TYPE devclass RAISING lcx_exception, jump_se11 IMPORTING iv_radio TYPE string iv_field TYPE string RAISING lcx_exception. ENDCLASS. ""lcl_objects_super DEFINITION ********************************************************************** * Enable plugins CLASS lcl_objects_bridge DEFINITION INHERITING FROM lcl_objects_super FINAL. PUBLIC SECTION. CLASS-METHODS class_constructor. METHODS constructor IMPORTING is_item TYPE ty_item RAISING cx_sy_create_object_error. INTERFACES lif_object. ALIASES mo_files FOR lif_object~mo_files. PRIVATE SECTION. DATA: mo_plugin TYPE REF TO object. TYPES: BEGIN OF ty_s_objtype_map, obj_typ TYPE trobjtype, plugin_class TYPE seoclsname, END OF ty_s_objtype_map, ty_t_objtype_map TYPE SORTED TABLE OF ty_s_objtype_map WITH UNIQUE KEY obj_typ. CLASS-DATA gt_objtype_map TYPE ty_t_objtype_map. ENDCLASS. ""lcl_objects_bridge DEFINITION *----------------------------------------------------------------------* * CLASS lcl_objects_bridge IMPLEMENTATION *----------------------------------------------------------------------* * *----------------------------------------------------------------------* CLASS lcl_objects_bridge IMPLEMENTATION. METHOD lif_object~has_changed_since. rv_changed = abap_true. ENDMETHOD. ""lif_object~has_changed_since METHOD lif_object~get_metadata. CALL METHOD mo_plugin->('ZIF_ABAPGIT_PLUGIN~GET_METADATA') RECEIVING rs_metadata = rs_metadata. ENDMETHOD. ""lif_object~get_metadata METHOD lif_object~changed_by. rv_user = c_user_unknown. "" todo ENDMETHOD. METHOD constructor. DATA ls_objtype_map LIKE LINE OF gt_objtype_map. super->constructor( is_item = is_item iv_language = gc_english ). * determine the responsible plugin READ TABLE gt_objtype_map INTO ls_objtype_map WITH TABLE KEY obj_typ = is_item-obj_type. IF sy-subrc = 0. CREATE OBJECT mo_plugin TYPE (ls_objtype_map-plugin_class). CALL METHOD mo_plugin->('SET_ITEM') EXPORTING iv_obj_type = is_item-obj_type iv_obj_name = is_item-obj_name. ELSE. RAISE EXCEPTION TYPE cx_sy_create_object_error EXPORTING classname = 'LCL_OBJECTS_BRIDGE'. ENDIF. ENDMETHOD. ""constructor METHOD lif_object~serialize. CALL METHOD mo_plugin->('WRAP_SERIALIZE') EXPORTING io_xml = io_xml. ENDMETHOD. ""lif_object~serialize METHOD lif_object~deserialize. DATA: lx_plugin TYPE REF TO cx_static_check. TRY. CALL METHOD mo_plugin->('WRAP_DESERIALIZE') EXPORTING iv_package = iv_package io_xml = io_xml. CATCH cx_static_check INTO lx_plugin. RAISE EXCEPTION TYPE lcx_exception EXPORTING ix_previous = lx_plugin iv_text = lx_plugin->get_text( ). ENDTRY. ENDMETHOD. ""lif_object~deserialize METHOD lif_object~delete. DATA lx_plugin TYPE REF TO cx_static_check. TRY. CALL METHOD mo_plugin->('ZIF_ABAPGIT_PLUGIN~DELETE'). CATCH cx_static_check INTO lx_plugin. RAISE EXCEPTION TYPE lcx_exception EXPORTING ix_previous = lx_plugin iv_text = lx_plugin->get_text( ). ENDTRY. ENDMETHOD. ""lif_object~delete METHOD lif_object~exists. CALL METHOD mo_plugin->('ZIF_ABAPGIT_PLUGIN~EXISTS') RECEIVING rv_bool = rv_bool. ENDMETHOD. ""lif_object~exists METHOD lif_object~jump. CALL METHOD mo_plugin->('ZIF_ABAPGIT_PLUGIN~JUMP'). ENDMETHOD. ""lif_object~jump METHOD class_constructor. DATA lt_plugin_class TYPE STANDARD TABLE OF seoclsname WITH DEFAULT KEY. DATA lv_plugin_class LIKE LINE OF lt_plugin_class. DATA lo_plugin TYPE REF TO object. DATA lt_plugin_obj_type TYPE objtyptable. DATA ls_objtype_map LIKE LINE OF gt_objtype_map. SELECT ext~clsname FROM vseoextend AS ext INTO TABLE lt_plugin_class WHERE ext~refclsname LIKE 'ZCL_ABAPGIT_OBJECT%' AND ext~version = '1'. ""#EC CI_SUBRC CLEAR gt_objtype_map. LOOP AT lt_plugin_class INTO lv_plugin_class WHERE table_line <> 'ZCL_ABAPGIT_OBJECT_BY_SOBJ'. * have the generic plugin only as fallback TRY. CREATE OBJECT lo_plugin TYPE (lv_plugin_class). CATCH cx_sy_create_object_error. CONTINUE. "">>>>>>>>>>>>>> ENDTRY. CALL METHOD lo_plugin->('GET_SUPPORTED_OBJ_TYPES') IMPORTING rt_obj_type = lt_plugin_obj_type. ls_objtype_map-plugin_class = lv_plugin_class. LOOP AT lt_plugin_obj_type INTO ls_objtype_map-obj_typ. INSERT ls_objtype_map INTO TABLE gt_objtype_map. IF sy-subrc <> 0. * No exception in class-contructor possible. * Anyway, a shortdump is more appropriate in this case ASSERT 'There must not be' = |multiple abapGit-Plugins for the same object type { ls_objtype_map-obj_typ }|. ENDIF. ENDLOOP. ENDLOOP. ""at plugins * and the same for the generic plugin if exists * have the generic plugin only as fallback LOOP AT lt_plugin_class INTO lv_plugin_class WHERE table_line = 'ZCL_ABAPGIT_OBJECT_BY_SOBJ'. CREATE OBJECT lo_plugin TYPE (lv_plugin_class). CALL METHOD lo_plugin->('GET_SUPPORTED_OBJ_TYPES') RECEIVING rt_obj_type = lt_plugin_obj_type. ls_objtype_map-plugin_class = lv_plugin_class. LOOP AT lt_plugin_obj_type INTO ls_objtype_map-obj_typ. INSERT ls_objtype_map INTO TABLE gt_objtype_map. ""knowingly ignore the subrc ENDLOOP. ENDLOOP. ""at plugins ENDMETHOD. ""class_constructor METHOD lif_object~compare_to_remote_version. CREATE OBJECT ro_comparison_result TYPE lcl_null_comparison_result. ENDMETHOD. ENDCLASS. ""lcl_objects_bridge IMPLEMENTATION ********************************************************************** CLASS lcl_objects_program DEFINITION INHERITING FROM lcl_objects_super. PUBLIC SECTION. TYPES: BEGIN OF ty_progdir, name TYPE progdir-name, state TYPE progdir-state, sqlx TYPE progdir-sqlx, edtx TYPE progdir-edtx, varcl TYPE progdir-varcl, dbapl TYPE progdir-dbapl, dbna TYPE progdir-dbna, clas TYPE progdir-clas, type TYPE progdir-type, occurs TYPE progdir-occurs, subc TYPE progdir-subc, appl TYPE progdir-appl, secu TYPE progdir-secu, cnam TYPE progdir-cnam, cdat TYPE progdir-cdat, unam TYPE progdir-unam, udat TYPE progdir-udat, vern TYPE progdir-vern, levl TYPE progdir-levl, rstat TYPE progdir-rstat, rmand TYPE progdir-rmand, rload TYPE progdir-rload, fixpt TYPE progdir-fixpt, sset TYPE progdir-sset, sdate TYPE progdir-sdate, stime TYPE progdir-stime, idate TYPE progdir-idate, itime TYPE progdir-itime, ldbname TYPE progdir-ldbname, uccheck TYPE progdir-uccheck, END OF ty_progdir. METHODS serialize_program IMPORTING io_xml TYPE REF TO lcl_xml_output OPTIONAL is_item TYPE ty_item io_files TYPE REF TO lcl_objects_files iv_program TYPE programm OPTIONAL iv_extra TYPE clike OPTIONAL RAISING lcx_exception. METHODS read_progdir IMPORTING iv_program TYPE programm RETURNING VALUE(rs_progdir) TYPE ty_progdir. METHODS deserialize_program IMPORTING is_progdir TYPE ty_progdir it_source TYPE abaptxt255_tab it_tpool TYPE textpool_table iv_package TYPE devclass RAISING lcx_exception. PROTECTED SECTION. TYPES: ty_spaces_tt TYPE STANDARD TABLE OF i WITH DEFAULT KEY. TYPES: BEGIN OF ty_dynpro, header TYPE rpy_dyhead, containers TYPE dycatt_tab, fields TYPE dyfatc_tab, flow_logic TYPE swydyflow, spaces TYPE ty_spaces_tt, END OF ty_dynpro. TYPES: ty_dynpro_tt TYPE STANDARD TABLE OF ty_dynpro WITH DEFAULT KEY. TYPES: BEGIN OF ty_cua, adm TYPE rsmpe_adm, sta TYPE STANDARD TABLE OF rsmpe_stat WITH DEFAULT KEY, fun TYPE STANDARD TABLE OF rsmpe_funt WITH DEFAULT KEY, men TYPE STANDARD TABLE OF rsmpe_men WITH DEFAULT KEY, mtx TYPE STANDARD TABLE OF rsmpe_mnlt WITH DEFAULT KEY, act TYPE STANDARD TABLE OF rsmpe_act WITH DEFAULT KEY, but TYPE STANDARD TABLE OF rsmpe_but WITH DEFAULT KEY, pfk TYPE STANDARD TABLE OF rsmpe_pfk WITH DEFAULT KEY, set TYPE STANDARD TABLE OF rsmpe_staf WITH DEFAULT KEY, doc TYPE STANDARD TABLE OF rsmpe_atrt WITH DEFAULT KEY, tit TYPE STANDARD TABLE OF rsmpe_titt WITH DEFAULT KEY, biv TYPE STANDARD TABLE OF rsmpe_buts WITH DEFAULT KEY, END OF ty_cua. METHODS serialize_dynpros IMPORTING iv_program_name TYPE programm RETURNING VALUE(rt_dynpro) TYPE ty_dynpro_tt RAISING lcx_exception. METHODS serialize_cua IMPORTING iv_program_name TYPE programm RETURNING VALUE(rs_cua) TYPE ty_cua RAISING lcx_exception. METHODS deserialize_dynpros IMPORTING it_dynpros TYPE ty_dynpro_tt RAISING lcx_exception. METHODS deserialize_textpool IMPORTING iv_program TYPE programm it_tpool TYPE textpool_table RAISING lcx_exception. METHODS deserialize_cua IMPORTING iv_program_name TYPE programm is_cua TYPE ty_cua RAISING lcx_exception. METHODS check_prog_changed_since IMPORTING iv_program TYPE programm iv_timestamp TYPE timestamp iv_skip_gui TYPE abap_bool DEFAULT abap_false RETURNING VALUE(rv_changed) TYPE abap_bool. CLASS-METHODS: add_tpool IMPORTING it_tpool TYPE textpool_table RETURNING VALUE(rt_tpool) TYPE ty_tpool_tt, read_tpool IMPORTING it_tpool TYPE ty_tpool_tt RETURNING VALUE(rt_tpool) TYPE ty_tpool_tt. PRIVATE SECTION. METHODS: condense_flow EXPORTING et_spaces TYPE ty_spaces_tt CHANGING ct_flow TYPE swydyflow, uncondense_flow IMPORTING it_flow TYPE swydyflow it_spaces TYPE ty_spaces_tt RETURNING VALUE(rt_flow) TYPE swydyflow. ENDCLASS. ""lcl_objects_program DEFINITION *----------------------------------------------------------------------* * CLASS lcl_objects_program IMPLEMENTATION *----------------------------------------------------------------------* * *----------------------------------------------------------------------* CLASS lcl_objects_program IMPLEMENTATION. METHOD condense_flow. DATA: lv_spaces LIKE LINE OF et_spaces. FIELD-SYMBOLS: LIKE LINE OF ct_flow. CLEAR et_spaces. LOOP AT ct_flow ASSIGNING . lv_spaces = 0. WHILE NOT -line IS INITIAL AND -line(1) = space. lv_spaces = lv_spaces + 1. -line = -line+1. ENDWHILE. APPEND lv_spaces TO et_spaces. ENDLOOP. ENDMETHOD. METHOD uncondense_flow. DATA: lv_spaces LIKE LINE OF it_spaces. FIELD-SYMBOLS: LIKE LINE OF it_flow, LIKE LINE OF rt_flow. LOOP AT it_flow ASSIGNING . APPEND INITIAL LINE TO rt_flow ASSIGNING . -line = -line. READ TABLE it_spaces INDEX sy-tabix INTO lv_spaces. IF sy-subrc = 0. SHIFT -line RIGHT BY lv_spaces PLACES IN CHARACTER MODE. ENDIF. ENDLOOP. ENDMETHOD. METHOD serialize_program. DATA: ls_progdir TYPE ty_progdir, lv_program_name TYPE programm, lt_dynpros TYPE ty_dynpro_tt, ls_cua TYPE ty_cua, lt_source TYPE TABLE OF abaptxt255, lt_tpool TYPE textpool_table, ls_tpool LIKE LINE OF lt_tpool, lo_xml TYPE REF TO lcl_xml_output. IF iv_program IS INITIAL. lv_program_name = is_item-obj_name. ELSE. lv_program_name = iv_program. ENDIF. CALL FUNCTION 'RPY_PROGRAM_READ' EXPORTING program_name = lv_program_name with_lowercase = abap_true TABLES source_extended = lt_source textelements = lt_tpool EXCEPTIONS cancelled = 1 not_found = 2 permission_error = 3 OTHERS = 4. IF sy-subrc = 2. RETURN. ELSEIF sy-subrc <> 0. lcx_exception=>raise( 'Error reading program' ). ENDIF. ls_progdir = read_progdir( lv_program_name ). IF io_xml IS BOUND. lo_xml = io_xml. ELSE. CREATE OBJECT lo_xml. ENDIF. lo_xml->add( iv_name = 'PROGDIR' ig_data = ls_progdir ). IF ls_progdir-subc = '1'. lt_dynpros = serialize_dynpros( lv_program_name ). lo_xml->add( iv_name = 'DYNPROS' ig_data = lt_dynpros ). ls_cua = serialize_cua( lv_program_name ). IF NOT ls_cua IS INITIAL. lo_xml->add( iv_name = 'CUA' ig_data = ls_cua ). ENDIF. ENDIF. READ TABLE lt_tpool WITH KEY id = 'R' INTO ls_tpool. IF sy-subrc = 0 AND ls_tpool-key = '' AND ls_tpool-length = 0. DELETE lt_tpool INDEX sy-tabix. ENDIF. lo_xml->add( iv_name = 'TPOOL' ig_data = add_tpool( lt_tpool ) ). IF NOT io_xml IS BOUND. io_files->add_xml( iv_extra = iv_extra io_xml = lo_xml ). ENDIF. io_files->add_abap( iv_extra = iv_extra it_abap = lt_source ). ENDMETHOD. ""serialize_program METHOD deserialize_program. DATA: lv_exists TYPE sap_bool, lv_progname TYPE reposrc-progname, ls_tpool LIKE LINE OF it_tpool, lv_title TYPE rglif-title, ls_progdir_new TYPE progdir. FIELD-SYMBOLS: TYPE any. CALL FUNCTION 'RS_CORR_INSERT' EXPORTING object = is_progdir-name object_class = 'ABAP' devclass = iv_package master_language = mv_language mode = 'INSERT' EXCEPTIONS cancelled = 1 permission_failure = 2 unknown_objectclass = 3 OTHERS = 4. IF sy-subrc = 1. lcx_exception=>raise( 'Cancelled' ). ELSEIF sy-subrc <> 0. lcx_exception=>raise( 'error from RS_CORR_INSERT' ). ENDIF. READ TABLE it_tpool INTO ls_tpool WITH KEY id = 'R'. ""#EC CI_SUBRC IF sy-subrc = 0. * there is a bug in RPY_PROGRAM_UPDATE, the header line of TTAB is not * cleared, so the title length might be inherited from a different program. ASSIGN ('(SAPLSIFP)TTAB') TO . IF sy-subrc = 0. CLEAR . ENDIF. lv_title = ls_tpool-entry. ENDIF. SELECT SINGLE progname FROM reposrc INTO lv_progname WHERE progname = is_progdir-name AND r3state = 'A'. IF sy-subrc = 0. lv_exists = abap_true. ELSE. lv_exists = abap_false. ENDIF. IF lv_exists = abap_true. CALL FUNCTION 'RPY_PROGRAM_UPDATE' EXPORTING program_name = is_progdir-name title_string = lv_title save_inactive = 'I' TABLES source_extended = it_source EXCEPTIONS cancelled = 1 permission_error = 2 not_found = 3 OTHERS = 4. IF sy-subrc <> 0. IF sy-msgid = 'EU' AND sy-msgno = '510'. lcx_exception=>raise( 'User is currently editing program' ). ELSE. lcx_exception=>raise( 'PROG, error updating' ). ENDIF. ENDIF. ELSE. * function module RPY_PROGRAM_INSERT cannot handle function group includes IF strlen( is_progdir-name ) > 30. "" special treatment for extenstions "" if the program name exceeds 30 characters it is not a usual "" ABAP program but might be some extension, which requires the internal "" addition EXTENSION TYPE, see "" http://help.sap.com/abapdocu_751/en/abapinsert_report_internal.htm#!ABAP_ADDITION_1@1@ "" This e.g. occurs in case of transportable Code Inspector variants (ending with ===VC) INSERT REPORT is_progdir-name FROM it_source STATE 'I' EXTENSION TYPE is_progdir-name+30. IF sy-subrc <> 0. lcx_exception=>raise( 'error from INSERT REPORT .. EXTENSION TYPE' ). ENDIF. ELSE. INSERT REPORT is_progdir-name FROM it_source STATE 'I' PROGRAM TYPE is_progdir-subc. IF sy-subrc <> 0. lcx_exception=>raise( 'error from INSERT REPORT' ). ENDIF. ENDIF. IF NOT it_tpool[] IS INITIAL. INSERT TEXTPOOL is_progdir-name FROM it_tpool LANGUAGE mv_language STATE 'I'. IF sy-subrc <> 0. lcx_exception=>raise( 'error from INSERT TEXTPOOL' ). ENDIF. ENDIF. ENDIF. CALL FUNCTION 'READ_PROGDIR' EXPORTING i_progname = is_progdir-name i_state = 'I' IMPORTING e_progdir = ls_progdir_new EXCEPTIONS not_exists = 1 OTHERS = 2. IF sy-subrc <> 0. lcx_exception=>raise( 'not found in PROGDIR' ). ENDIF. * todo, package? ls_progdir_new-ldbname = is_progdir-ldbname. ls_progdir_new-dbna = is_progdir-dbna. ls_progdir_new-dbapl = is_progdir-dbapl. ls_progdir_new-rload = is_progdir-rload. ls_progdir_new-fixpt = is_progdir-fixpt. ls_progdir_new-varcl = is_progdir-varcl. ls_progdir_new-appl = is_progdir-appl. ls_progdir_new-rstat = is_progdir-rstat. CALL FUNCTION 'UPDATE_PROGDIR' EXPORTING i_progdir = ls_progdir_new i_progname = ls_progdir_new-name i_state = ls_progdir_new-state EXCEPTIONS not_executed = 1 OTHERS = 2. IF sy-subrc <> 0. lcx_exception=>raise( 'PROG, error inserting' ). ENDIF. SELECT SINGLE * FROM progdir INTO ls_progdir_new WHERE name = ls_progdir_new-name AND state = ls_progdir_new-state. IF sy-subrc = 0 AND is_progdir-varcl = space AND ls_progdir_new-varcl = abap_true. * function module UPDATE_PROGDIR does not update VARCL UPDATE progdir SET varcl = is_progdir-varcl WHERE name = ls_progdir_new-name AND state = ls_progdir_new-state. ENDIF. lcl_objects_activation=>add( iv_type = 'REPS' iv_name = is_progdir-name ). ENDMETHOD. ""deserialize_program METHOD read_progdir. DATA: ls_sapdir TYPE progdir. CALL FUNCTION 'READ_PROGDIR' EXPORTING i_progname = iv_program i_state = 'A' IMPORTING e_progdir = ls_sapdir. MOVE-CORRESPONDING ls_sapdir TO rs_progdir. CLEAR: rs_progdir-edtx, rs_progdir-cnam, rs_progdir-cdat, rs_progdir-unam, rs_progdir-udat, rs_progdir-levl, rs_progdir-vern, rs_progdir-rmand, rs_progdir-sdate, rs_progdir-stime, rs_progdir-idate, rs_progdir-itime. ENDMETHOD. ""read_progdir METHOD serialize_cua. CALL FUNCTION 'RS_CUA_INTERNAL_FETCH' EXPORTING program = iv_program_name language = mv_language state = 'A' IMPORTING adm = rs_cua-adm TABLES sta = rs_cua-sta fun = rs_cua-fun men = rs_cua-men mtx = rs_cua-mtx act = rs_cua-act but = rs_cua-but pfk = rs_cua-pfk set = rs_cua-set doc = rs_cua-doc tit = rs_cua-tit biv = rs_cua-biv EXCEPTIONS not_found = 1 unknown_version = 2 OTHERS = 3. IF sy-subrc <> 0. lcx_exception=>raise( 'error from RS_CUA_INTERNAL_FETCH' ). ENDIF. ENDMETHOD. ""serialize_cua METHOD serialize_dynpros. DATA: ls_header TYPE rpy_dyhead, lt_containers TYPE dycatt_tab, lt_fields_to_containers TYPE dyfatc_tab, lt_flow_logic TYPE swydyflow, lt_d020s TYPE TABLE OF d020s. FIELD-SYMBOLS: LIKE LINE OF lt_d020s, TYPE scrpostyle, LIKE LINE OF lt_fields_to_containers, LIKE LINE OF rt_dynpro. CALL FUNCTION 'RS_SCREEN_LIST' EXPORTING dynnr = '' progname = iv_program_name TABLES dynpros = lt_d020s EXCEPTIONS not_found = 1 OTHERS = 2. IF sy-subrc = 2. lcx_exception=>raise( 'error from screen_list' ). ENDIF. * loop dynpros and skip generated selection screens LOOP AT lt_d020s ASSIGNING WHERE type <> 'S'. CALL FUNCTION 'RPY_DYNPRO_READ' EXPORTING progname = iv_program_name dynnr = -dnum IMPORTING header = ls_header TABLES containers = lt_containers fields_to_containers = lt_fields_to_containers flow_logic = lt_flow_logic EXCEPTIONS cancelled = 1 not_found = 2 permission_error = 3 OTHERS = 4. IF sy-subrc <> 0. lcx_exception=>raise( 'Error while reading dynpro' ). ENDIF. LOOP AT lt_fields_to_containers ASSIGNING . * output style is a NUMC field, the XML conversion will fail if it contains invalid value * field does not exist in all versions ASSIGN COMPONENT 'OUTPUTSTYLE' OF STRUCTURE TO . IF sy-subrc = 0 AND = ' '. CLEAR . ENDIF. ENDLOOP. APPEND INITIAL LINE TO rt_dynpro ASSIGNING . -header = ls_header. -containers = lt_containers. -fields = lt_fields_to_containers. condense_flow( IMPORTING et_spaces = -spaces CHANGING ct_flow = lt_flow_logic ). -flow_logic = lt_flow_logic. ENDLOOP. ENDMETHOD. ""serialize_dynpros METHOD deserialize_dynpros. DATA: lv_name TYPE dwinactiv-obj_name, ls_dynpro LIKE LINE OF it_dynpros. * ls_dynpro is changed by the function module, a field-symbol will cause * the program to dump since it_dynpros cannot be changed LOOP AT it_dynpros INTO ls_dynpro. ls_dynpro-flow_logic = uncondense_flow( it_flow = ls_dynpro-flow_logic it_spaces = ls_dynpro-spaces ). CALL FUNCTION 'RPY_DYNPRO_INSERT' EXPORTING header = ls_dynpro-header suppress_exist_checks = abap_true TABLES containers = ls_dynpro-containers fields_to_containers = ls_dynpro-fields flow_logic = ls_dynpro-flow_logic EXCEPTIONS cancelled = 1 already_exists = 2 program_not_exists = 3 not_executed = 4 missing_required_field = 5 illegal_field_value = 6 field_not_allowed = 7 not_generated = 8 illegal_field_position = 9 OTHERS = 10. IF sy-subrc <> 2 AND sy-subrc <> 0. lcx_exception=>raise( 'error from RPY_DYNPRO_INSERT' ). ENDIF. * todo, RPY_DYNPRO_UPDATE? CONCATENATE ls_dynpro-header-program ls_dynpro-header-screen INTO lv_name RESPECTING BLANKS. ASSERT NOT lv_name IS INITIAL. lcl_objects_activation=>add( iv_type = 'DYNP' iv_name = lv_name ). ENDLOOP. ENDMETHOD. ""deserialize_dynpros METHOD add_tpool. FIELD-SYMBOLS: LIKE LINE OF it_tpool, LIKE LINE OF rt_tpool. LOOP AT it_tpool ASSIGNING . APPEND INITIAL LINE TO rt_tpool ASSIGNING . MOVE-CORRESPONDING TO . IF -id = 'S'. -split = -entry. -entry = -entry+8. ENDIF. ENDLOOP. ENDMETHOD. ""add_tpool METHOD read_tpool. FIELD-SYMBOLS: LIKE LINE OF it_tpool, LIKE LINE OF rt_tpool. LOOP AT it_tpool ASSIGNING . APPEND INITIAL LINE TO rt_tpool ASSIGNING . MOVE-CORRESPONDING TO . IF -id = 'S'. CONCATENATE -split -entry INTO -entry RESPECTING BLANKS. ENDIF. ENDLOOP. ENDMETHOD. ""read_tpool METHOD deserialize_textpool. READ TABLE it_tpool WITH KEY id = 'R' TRANSPORTING NO FIELDS. IF ( sy-subrc = 0 AND lines( it_tpool ) = 1 ) OR lines( it_tpool ) = 0. RETURN. "" no action for includes ENDIF. INSERT TEXTPOOL iv_program FROM it_tpool LANGUAGE mv_language STATE 'I'. IF sy-subrc <> 0. lcx_exception=>raise( 'error from INSERT TEXTPOOL' ). ENDIF. lcl_objects_activation=>add( iv_type = 'REPT' iv_name = iv_program ). ENDMETHOD. ""deserialize_textpool METHOD deserialize_cua. DATA: ls_tr_key TYPE trkey. IF lines( is_cua-sta ) = 0 AND lines( is_cua-fun ) = 0 AND lines( is_cua-men ) = 0 AND lines( is_cua-mtx ) = 0 AND lines( is_cua-act ) = 0 AND lines( is_cua-but ) = 0 AND lines( is_cua-pfk ) = 0 AND lines( is_cua-set ) = 0 AND lines( is_cua-doc ) = 0 AND lines( is_cua-tit ) = 0 AND lines( is_cua-biv ) = 0. RETURN. ENDIF. SELECT SINGLE devclass INTO ls_tr_key-devclass FROM tadir WHERE pgmid = 'R3TR' AND object = ms_item-obj_type AND obj_name = ms_item-obj_name. ""#EC CI_GENBUFF IF sy-subrc <> 0. lcx_exception=>raise( 'not found in tadir' ). ENDIF. ls_tr_key-obj_type = ms_item-obj_type. ls_tr_key-obj_name = ms_item-obj_name. ls_tr_key-sub_type = 'CUAD'. ls_tr_key-sub_name = iv_program_name. sy-tcode = 'SE41' ##write_ok. "" evil hack, workaround to handle fixes in note 2159455 CALL FUNCTION 'RS_CUA_INTERNAL_WRITE' EXPORTING program = iv_program_name language = mv_language tr_key = ls_tr_key adm = is_cua-adm state = 'I' TABLES sta = is_cua-sta fun = is_cua-fun men = is_cua-men mtx = is_cua-mtx act = is_cua-act but = is_cua-but pfk = is_cua-pfk set = is_cua-set doc = is_cua-doc tit = is_cua-tit biv = is_cua-biv EXCEPTIONS not_found = 1 OTHERS = 2. IF sy-subrc <> 0. lcx_exception=>raise( 'error from RS_CUA_INTERNAL_WRITE' ). ENDIF. lcl_objects_activation=>add( iv_type = 'CUAD' iv_name = iv_program_name ). ENDMETHOD. ""deserialize_cua METHOD check_prog_changed_since. DATA: lv_date TYPE dats, lv_time TYPE tims, lv_ts TYPE timestamp, lt_screens TYPE STANDARD TABLE OF d020s, lt_eudb TYPE STANDARD TABLE OF eudb. FIELD-SYMBOLS: LIKE LINE OF lt_screens, LIKE LINE OF lt_eudb. SELECT SINGLE udat utime FROM reposrc "" Program INTO (lv_date, lv_time) WHERE progname = iv_program AND r3state = 'A'. _object_check_timestamp lv_date lv_time. SELECT SINGLE udat utime FROM repotext "" Program text pool INTO (lv_date, lv_time) WHERE progname = iv_program AND r3state = 'A'. IF sy-subrc = 0. "" Text not found ? Assuming no changes, see #404 _object_check_timestamp lv_date lv_time. ENDIF. IF iv_skip_gui = abap_true. RETURN. ENDIF. SELECT dgen tgen FROM d020s "" Screens INTO CORRESPONDING FIELDS OF TABLE lt_screens WHERE prog = iv_program ##TOO_MANY_ITAB_FIELDS. LOOP AT lt_screens ASSIGNING . _object_check_timestamp -dgen -tgen. ENDLOOP. SELECT vdatum vzeit FROM eudb "" GUI INTO CORRESPONDING FIELDS OF TABLE lt_eudb WHERE relid = 'CU' AND name = iv_program AND srtf2 = 0 ##TOO_MANY_ITAB_FIELDS. LOOP AT lt_eudb ASSIGNING . _object_check_timestamp -vdatum -vzeit. ENDLOOP. ENDMETHOD. ""check_prog_changed_since ENDCLASS. ""lcl_objects_program IMPLEMENTATION *----------------------------------------------------------------------* * CLASS lcl_objects_super IMPLEMENTATION *----------------------------------------------------------------------* * *----------------------------------------------------------------------* CLASS lcl_objects_super IMPLEMENTATION. METHOD constructor. ms_item = is_item. ASSERT NOT ms_item IS INITIAL. mv_language = iv_language. ASSERT NOT mv_language IS INITIAL. ENDMETHOD. ""constructor METHOD jump_se11. DATA: lt_bdcdata TYPE TABLE OF bdcdata. FIELD-SYMBOLS: LIKE LINE OF lt_bdcdata. APPEND INITIAL LINE TO lt_bdcdata ASSIGNING . -program = 'SAPLSD_ENTRY'. -dynpro = '1000'. -dynbegin = abap_true. APPEND INITIAL LINE TO lt_bdcdata ASSIGNING . -fnam = 'BDC_OKCODE'. -fval = '=WB_DISPLAY'. APPEND INITIAL LINE TO lt_bdcdata ASSIGNING . -fnam = iv_radio. -fval = abap_true. APPEND INITIAL LINE TO lt_bdcdata ASSIGNING . -fnam = iv_field. -fval = ms_item-obj_name. CALL FUNCTION 'ABAP4_CALL_TRANSACTION' STARTING NEW TASK 'GIT' EXPORTING tcode = 'SE11' mode_val = 'E' TABLES using_tab = lt_bdcdata EXCEPTIONS system_failure = 1 communication_failure = 2 resource_failure = 3 OTHERS = 4 ##fm_subrc_ok. ""#EC CI_SUBRC ENDMETHOD. ""jump_se11 METHOD get_metadata. rs_metadata-class = cl_abap_classdescr=>describe_by_object_ref( me )->get_relative_name( ). rs_metadata-version = 'v1.0.0' ##no_text. ENDMETHOD. ""get_metadata METHOD corr_insert. DATA: ls_object TYPE ddenqs. ls_object-objtype = ms_item-obj_type. ls_object-objname = ms_item-obj_name. CALL FUNCTION 'RS_CORR_INSERT' EXPORTING object = ls_object object_class = 'DICT' devclass = iv_package master_language = mv_language mode = 'INSERT' EXCEPTIONS cancelled = 1 permission_failure = 2 unknown_objectclass = 3 OTHERS = 4. IF sy-subrc = 1. lcx_exception=>raise( 'Cancelled' ). ELSEIF sy-subrc <> 0. lcx_exception=>raise( 'error from RS_CORR_INSERT' ). ENDIF. ENDMETHOD. ""corr_insert ENDCLASS. ""lcl_objects_super IMPLEMENTATION *----------------------------------------------------------------------* * CLASS lcl_object DEFINITION *----------------------------------------------------------------------* * *----------------------------------------------------------------------* CLASS lcl_objects DEFINITION FINAL. PUBLIC SECTION. TYPES: ty_types_tt TYPE STANDARD TABLE OF tadir-object WITH DEFAULT KEY. TYPES: BEGIN OF ty_deserialization, obj TYPE REF TO lif_object, xml TYPE REF TO lcl_xml_input, package TYPE devclass, item TYPE ty_item, END OF ty_deserialization. TYPES: ty_deserialization_tt TYPE STANDARD TABLE OF ty_deserialization WITH DEFAULT KEY. CLASS-METHODS serialize IMPORTING is_item TYPE ty_item iv_language TYPE spras io_log TYPE REF TO lcl_log OPTIONAL RETURNING VALUE(rt_files) TYPE ty_files_tt RAISING lcx_exception. CLASS-METHODS deserialize IMPORTING io_repo TYPE REF TO lcl_repo RETURNING VALUE(rt_accessed_files) TYPE ty_file_signatures_tt RAISING lcx_exception. CLASS-METHODS delete IMPORTING it_tadir TYPE ty_tadir_tt RAISING lcx_exception. CLASS-METHODS jump IMPORTING is_item TYPE ty_item RAISING lcx_exception. CLASS-METHODS changed_by IMPORTING is_item TYPE ty_item RETURNING VALUE(rv_user) TYPE xubname RAISING lcx_exception. CLASS-METHODS has_changed_since IMPORTING is_item TYPE ty_item iv_timestamp TYPE timestamp RETURNING VALUE(rv_changed) TYPE abap_bool RAISING lcx_exception. CLASS-METHODS is_supported IMPORTING is_item TYPE ty_item iv_native_only TYPE abap_bool DEFAULT abap_false RETURNING VALUE(rv_bool) TYPE abap_bool. CLASS-METHODS exists IMPORTING is_item TYPE ty_item RETURNING VALUE(rv_bool) TYPE abap_bool. CLASS-METHODS supported_list RETURNING VALUE(rt_types) TYPE ty_types_tt. PRIVATE SECTION. CLASS-DATA: mv_langs_installed TYPE scplangs. CLASS-METHODS check_duplicates IMPORTING it_files TYPE ty_files_tt RAISING lcx_exception. CLASS-METHODS create_object IMPORTING is_item TYPE ty_item iv_language TYPE spras is_metadata TYPE ty_metadata OPTIONAL iv_native_only TYPE abap_bool DEFAULT abap_false RETURNING VALUE(ri_obj) TYPE REF TO lif_object RAISING lcx_exception. CLASS-METHODS prioritize_deser IMPORTING it_results TYPE ty_results_tt RETURNING VALUE(rt_results) TYPE ty_results_tt. CLASS-METHODS path_to_package IMPORTING iv_top TYPE devclass iv_start TYPE string iv_path TYPE string RETURNING VALUE(rv_package) TYPE devclass RAISING lcx_exception. CLASS-METHODS class_name IMPORTING is_item TYPE ty_item RETURNING VALUE(rv_class_name) TYPE string. CLASS-METHODS resolve_ddic CHANGING ct_tadir TYPE ty_tadir_tt RAISING lcx_exception. CLASS-METHODS warning_overwrite CHANGING ct_results TYPE ty_results_tt RAISING lcx_exception. CLASS-METHODS warning_package IMPORTING is_item TYPE ty_item iv_package TYPE devclass RETURNING VALUE(rv_cancel) TYPE abap_bool RAISING lcx_exception. CLASS-METHODS update_package_tree IMPORTING iv_package TYPE devclass. CLASS-METHODS delete_obj IMPORTING is_item TYPE ty_item RAISING lcx_exception. CLASS-METHODS compare_remote_to_local IMPORTING io_object TYPE REF TO lif_object it_remote TYPE ty_files_tt is_result TYPE ty_result RAISING lcx_exception. CLASS-METHODS deserialize_objects IMPORTING it_objects TYPE ty_deserialization_tt iv_ddic TYPE abap_bool DEFAULT abap_false iv_descr TYPE string CHANGING ct_files TYPE ty_file_signatures_tt RAISING lcx_exception. ENDCLASS. ""lcl_object DEFINITION ",13075,True,2681.299696258347,median "// tag::HeaderFullDisplayName[] = repo_sys.RepoObjectReferenced - V // end::HeaderFullDisplayName[] == existing_properties // tag::existing_properties[] :ExistsProperty--antorareferencedlist: :ExistsProperty--antorareferencinglist: :ExistsProperty--has_execution_plan_issue: :ExistsProperty--is_repo_managed: :ExistsProperty--is_ssas: :ExistsProperty--referencedobjectlist: :ExistsProperty--sql_modules_definition: :ExistsProperty--FK: :ExistsProperty--AntoraIndexList: :ExistsProperty--Columns: // end::existing_properties[] == RepoObject_guid // tag::RepoObject_guid[] 0990291C-9D61-EB11-84DC-A81E8446D5B0 // end::RepoObject_guid[] == RepoObject_FullDisplayName2 // tag::RepoObject_FullDisplayName2[] repo_sys.RepoObjectReferenced // 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[] 1992394167 // end::SysObject_id[] == SysObject_modify_date // tag::SysObject_modify_date[] 2021-08-17 20:02:13 // end::SysObject_modify_date[] == AntoraColumnDetails // tag::AntoraColumnDetails[] [discrete] == _ [#column-hasunderlinedifferentunderlinesysunderlinenames] === has_different_sys_names [cols=""d,8a,m,m,m""] |=== | |has_different_sys_names |bit |NULL | |=== .Description -- (CONVERT([bit],case when [RepoObject_schema_name]<>[SysObject_schema_name] OR [RepoObject_name]<>[SysObject_name] OR [RepoObject_type]<>[SysObject_type] then (1) else (0) end)) -- {empty} + .Referenced Columns -- * xref:repo.repoobject.adoc#column-hasunderlinedifferentunderlinesysunderlinenames[+repo.RepoObject.has_different_sys_names+] -- [#column-isunderlineallunderlinecolumnsunderlinefound] === is_all_columns_found [cols=""d,8a,m,m,m""] |=== | |is_all_columns_found |bit |NOT NULL | |=== [#column-isunderlineambiguous] === is_ambiguous [cols=""d,8a,m,m,m""] |=== | |is_ambiguous |bit |NOT NULL | |=== [#column-isunderlinecallerunderlinedependent] === is_caller_dependent [cols=""d,8a,m,m,m""] |=== | |is_caller_dependent |bit |NOT NULL | |=== [#column-isunderlineincomplete] === is_incomplete [cols=""d,8a,m,m,m""] |=== | |is_incomplete |bit |NOT NULL | |=== [#column-isunderlineinsertunderlineall] === is_insert_all [cols=""d,8a,m,m,m""] |=== | |is_insert_all |bit |NOT NULL | |=== [#column-isunderlinerepounderlinemanaged] === is_repo_managed [cols=""d,8a,m,m,m""] |=== | |is_repo_managed |bit |NULL | |=== .Referenced Columns -- * xref:repo.repoobject.adoc#column-isunderlinerepounderlinemanaged[+repo.RepoObject.is_repo_managed+] -- [#column-isunderlineselectunderlineall] === is_select_all [cols=""d,8a,m,m,m""] |=== | |is_select_all |bit |NOT NULL | |=== [#column-isunderlineselected] === is_selected [cols=""d,8a,m,m,m""] |=== | |is_selected |bit |NOT NULL | |=== [#column-isunderlineupdated] === is_updated [cols=""d,8a,m,m,m""] |=== | |is_updated |bit |NOT NULL | |=== [#column-referencedunderlineclass] === referenced_class [cols=""d,8a,m,m,m""] |=== | |referenced_class |tinyint |NULL | |=== [#column-referencedunderlineclassunderlinedesc] === referenced_class_desc [cols=""d,8a,m,m,m""] |=== | |referenced_class_desc |nvarchar(60) |NULL | |=== [#column-referencedunderlinedatabaseunderlinename] === referenced_database_name [cols=""d,8a,m,m,m""] |=== | |referenced_database_name |nvarchar(128) |NULL | |=== [#column-referencedunderlineentityunderlinename] === referenced_entity_name [cols=""d,8a,m,m,m""] |=== | |referenced_entity_name |nvarchar(128) |NULL | |=== [#column-referencedunderlineid] === referenced_id [cols=""d,8a,m,m,m""] |=== | |referenced_id |int |NULL | |=== [#column-referencedunderlineminorunderlineid] === referenced_minor_id [cols=""d,8a,m,m,m""] |=== | |referenced_minor_id |int |NULL | |=== [#column-referencedunderlineminorunderlinename] === referenced_minor_name [cols=""d,8a,m,m,m""] |=== | |referenced_minor_name |nvarchar(128) |NULL | |=== [#column-referencedunderlineschemaunderlinename] === referenced_schema_name [cols=""d,8a,m,m,m""] |=== | |referenced_schema_name |nvarchar(128) |NULL | |=== [#column-referencedunderlineserverunderlinename] === referenced_server_name [cols=""d,8a,m,m,m""] |=== | |referenced_server_name |nvarchar(128) |NULL | |=== [#column-referencingunderlineminorunderlineid] === referencing_minor_id [cols=""d,8a,m,m,m""] |=== | |referencing_minor_id |int |NULL | |=== [#column-repoobjectunderlinefullname] === RepoObject_fullname [cols=""d,8a,m,m,m""] |=== | |RepoObject_fullname |nvarchar(261) |NOT NULL | |=== .Description -- (concat('[',[RepoObject_schema_name],'].[',[RepoObject_name],']')) -- {empty} + .Referenced Columns -- * xref:repo.repoobject.adoc#column-repoobjectunderlinefullname[+repo.RepoObject.RepoObject_fullname+] -- [#column-repoobjectunderlineguid] === RepoObject_guid [cols=""d,8a,m,m,m""] |=== | |RepoObject_guid |uniqueidentifier |NOT NULL | |=== .Referenced Columns -- * xref:repo.repoobject.adoc#column-repoobjectunderlineguid[+repo.RepoObject.RepoObject_guid+] -- [#column-sysobjectunderlinefullname] === SysObject_fullname [cols=""d,8a,m,m,m""] |=== | |SysObject_fullname |nvarchar(261) |NOT NULL | |=== .Description -- (concat('[',[SysObject_schema_name],'].[',[SysObject_name],']')) -- {empty} + .Referenced Columns -- * xref:repo.repoobject.adoc#column-sysobjectunderlinefullname[+repo.RepoObject.SysObject_fullname+] -- [#column-sysobjectunderlineid] === SysObject_id [cols=""d,8a,m,m,m""] |=== | |SysObject_id |int |NULL | |=== .Referenced Columns -- * xref:repo.repoobject.adoc#column-sysobjectunderlineid[+repo.RepoObject.SysObject_id+] -- [#column-sysobjectunderlinemodifyunderlinedate] === SysObject_modify_date [cols=""d,8a,m,m,m""] |=== | |SysObject_modify_date |datetime |NULL | |=== .Referenced Columns -- * xref:repo.repoobject.adoc#column-sysobjectunderlinemodifyunderlinedate[+repo.RepoObject.SysObject_modify_date+] -- [#column-sysobjectunderlinetype] === SysObject_type [cols=""d,8a,m,m,m""] |=== | |SysObject_type |char(2) |NULL | |=== .Referenced Columns -- * xref:repo.repoobject.adoc#column-sysobjectunderlinetype[+repo.RepoObject.SysObject_type+] -- // end::AntoraColumnDetails[] == AntoraPkColumnTableRows // tag::AntoraPkColumnTableRows[] // end::AntoraPkColumnTableRows[] == AntoraNonPkColumnTableRows // tag::AntoraNonPkColumnTableRows[] | |<> |bit |NULL | | |<> |bit |NOT NULL | | |<> |bit |NOT NULL | | |<> |bit |NOT NULL | | |<> |bit |NOT NULL | | |<> |bit |NOT NULL | | |<> |bit |NULL | | |<> |bit |NOT NULL | | |<> |bit |NOT NULL | | |<> |bit |NOT NULL | | |<> |tinyint |NULL | | |<> |nvarchar(60) |NULL | | |<> |nvarchar(128) |NULL | | |<> |nvarchar(128) |NULL | | |<> |int |NULL | | |<> |int |NULL | | |<> |nvarchar(128) |NULL | | |<> |nvarchar(128) |NULL | | |<> |nvarchar(128) |NULL | | |<> |int |NULL | | |<> |nvarchar(261) |NOT NULL | | |<> |uniqueidentifier |NOT NULL | | |<> |nvarchar(261) |NOT NULL | | |<> |int |NULL | | |<> |datetime |NULL | | |<> |char(2) |NULL | // end::AntoraNonPkColumnTableRows[] == AntoraIndexList // tag::AntoraIndexList[] [#index-idxunderlinerepoobjectreferencedunderlineunderline1] === idx_RepoObjectReferenced++__++1 * 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:repo_sys.repoobjectreferenced.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:repo.repoobject.adoc[] * xref:dhw:sqldb:sys_dwh.dm_sql_referenced_entities.adoc[] // end::antorareferencedlist[] === AntoraReferencingList // tag::antorareferencinglist[] * xref:dhw:sqldb:reference.usp_update_referencing_count.adoc[] * xref:dhw:sqldb:repo.usp_update_referencing_count.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[] 1 // 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[] * [repo].[RepoObject] * [sys_dwh].[dm_sql_referenced_entities] // 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[] :has_execution_plan_issue: // 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:repo_sys.repoobjectreferenced.adoc[]"" as repo_sys.RepoObjectReferenced << V >> { has_different_sys_names : (bit) - is_all_columns_found : (bit) - is_ambiguous : (bit) - is_caller_dependent : (bit) - is_incomplete : (bit) - is_insert_all : (bit) is_repo_managed : (bit) - is_select_all : (bit) - is_selected : (bit) - is_updated : (bit) referenced_class : (tinyint) referenced_class_desc : (nvarchar(60)) referenced_database_name : (nvarchar(128)) referenced_entity_name : (nvarchar(128)) referenced_id : (int) referenced_minor_id : (int) referenced_minor_name : (nvarchar(128)) referenced_schema_name : (nvarchar(128)) referenced_server_name : (nvarchar(128)) referencing_minor_id : (int) - RepoObject_fullname : (nvarchar(261)) - RepoObject_guid : (uniqueidentifier) - SysObject_fullname : (nvarchar(261)) SysObject_id : (int) SysObject_modify_date : (datetime) SysObject_type : (char(2)) -- } .... // 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:repo_sys.repoobjectreferenced.adoc[]"" as repo_sys.RepoObjectReferenced << V >> { - idx_RepoObjectReferenced__1 .. 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:reference.usp_update_referencing_count.adoc[]"" as reference.usp_update_Referencing_Count << P >> { -- } entity ""puml-link:dhw:sqldb:repo.repoobject.adoc[]"" as repo.RepoObject << U >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.usp_update_referencing_count.adoc[]"" as repo.usp_update_Referencing_Count << P >> { -- } entity ""puml-link:dhw:sqldb:repo_sys.repoobjectreferenced.adoc[]"" as repo_sys.RepoObjectReferenced << V >> { -- } entity ""puml-link:dhw:sqldb:sys_dwh.dm_sql_referenced_entities.adoc[]"" as sys_dwh.dm_sql_referenced_entities << SN >> { -- } repo.RepoObject <.. repo_sys.RepoObjectReferenced repo_sys.RepoObjectReferenced <.. reference.usp_update_Referencing_Count repo_sys.RepoObjectReferenced <.. repo.usp_update_Referencing_Count sys_dwh.dm_sql_referenced_entities <.. repo_sys.RepoObjectReferenced 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:repo_sys.repoobjectreferenced.adoc[]"" as repo_sys.RepoObjectReferenced << V >> { -- } 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)) -- } entity ""puml-link:dhw:sqldb:sys_dwh.dm_sql_referenced_entities.adoc[]"" as sys_dwh.dm_sql_referenced_entities << SN >> { -- } config.ftv_get_parameter_value <.. repo.RepoObject_external_src config.ftv_get_parameter_value <.. ssas.additional_Reference_step1 config.ftv_get_parameter_value <.. reference.additional_Reference_is_external config.Parameter <.. property.PropertyName_RepoObject config.Parameter <.. config.ftv_get_parameter_value configT.Parameter_default <.. config.Parameter property.external_RepoObjectProperty <.. property.RepoObjectProperty_external_src property.PropertyName_RepoObject <.. property.PropertyName_RepoObject_T property.PropertyName_RepoObject_T <.. property.RepoObjectProperty_external_tgt property.RepoObjectProperty <.. property.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 <.. property.RepoObjectProperty_external_tgt repo.RepoObject <.. repo.RepoObject_external_src repo.RepoObject <.. repo_sys.RepoObjectReferenced 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 ssas.additional_Reference_step1 <.. reference.additional_Reference_from_ssas_src ssas.model_json <.. ssas.model_json_10 ssas.model_json_10 <.. ssas.model_json_20 ssas.model_json_20 <.. repo.RepoSchema_ssas_src ssas.model_json_20 <.. ssas.model_json_201_descriptions_multiline ssas.model_json_20 <.. ssas.model_json_33_dataSources ssas.model_json_20 <.. ssas.model_json_31_tables ssas.model_json_201_descriptions_multiline <.. ssas.model_json_2011_descriptions_StrAgg ssas.model_json_2011_descriptions_StrAgg <.. repo.RepoSchema_ssas_src ssas.model_json_31_tables <.. ssas.model_json_31_tables_T ssas.model_json_31_tables_T <.. ssas.model_json_311_tables_columns ssas.model_json_31_tables_T <.. repo.RepoObject_SSAS_src ssas.model_json_31_tables_T <.. ssas.model_json_313_tables_partitions ssas.model_json_311_tables_columns <.. ssas.model_json_311_tables_columns_T ssas.model_json_311_tables_columns_T <.. ssas.additional_Reference_step1 ssas.model_json_313_tables_partitions <.. ssas.model_json_3131_tables_partitions_source ssas.model_json_3131_tables_partitions_source <.. ssas.model_json_31311_tables_partitions_source_PosFrom ssas.model_json_31311_tables_partitions_source_PosFrom <.. ssas.model_json_313111_tables_partitions_source_StringFrom ssas.model_json_313111_tables_partitions_source_StringFrom <.. ssas.model_json_3131111_tables_partitions_source_PosDot ssas.model_json_3131111_tables_partitions_source_PosDot <.. ssas.model_json_31311111_tables_partitions_source_Part123 ssas.model_json_31311111_tables_partitions_source_Part123 <.. ssas.additional_Reference_step1 ssas.model_json_33_dataSources <.. ssas.model_json_33_dataSources_T ssas.model_json_33_dataSources_T <.. ssas.additional_Reference_step1 sys_dwh.dm_sql_referenced_entities <.. repo_sys.RepoObjectReferenced 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:reference.usp_update_referencing_count.adoc[]"" as reference.usp_update_Referencing_Count << P >> { -- } entity ""puml-link:dhw:sqldb:repo.usp_main.adoc[]"" as repo.usp_main << P >> { -- } entity ""puml-link:dhw:sqldb:repo.usp_update_referencing_count.adoc[]"" as repo.usp_update_Referencing_Count << P >> { -- } entity ""puml-link:dhw:sqldb:repo_sys.repoobjectreferenced.adoc[]"" as repo_sys.RepoObjectReferenced << V >> { -- } reference.usp_update_Referencing_Count <.. repo.usp_main repo_sys.RepoObjectReferenced <.. reference.usp_update_Referencing_Count repo_sys.RepoObjectReferenced <.. repo.usp_update_Referencing_Count 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:reference.usp_update_referencing_count.adoc[]"" as reference.usp_update_Referencing_Count << P >> { -- } entity ""puml-link:dhw:sqldb:repo.repoobject.adoc[]"" as repo.RepoObject << U >> { - **RepoObject_guid** : (uniqueidentifier) external_AntoraComponent : (nvarchar(128)) external_AntoraModule : (nvarchar(128)) has_execution_plan_issue : (bit) has_get_referenced_issue : (bit) indent_sql_modules_definition : (tinyint) Inheritance_Source_fullname : (nvarchar(261)) Inheritance_StringAggSeparatorSql : (nvarchar(4000)) InheritanceDefinition : (nvarchar(4000)) InheritanceType : (tinyint) - is_DocsExclude : (bit) - is_external : (bit) is_repo_managed : (bit) is_required_ObjectMerge : (bit) - is_ssas : (bit) is_SysObject_missing : (bit) - modify_dt : (datetime) pk_index_guid : (uniqueidentifier) pk_IndexPatternColumnName_new : (nvarchar(4000)) Repo_history_table_guid : (uniqueidentifier) Repo_temporal_type : (tinyint) - RepoObject_name : (nvarchar(128)) RepoObject_Referencing_Count : (int) - RepoObject_schema_name : (nvarchar(128)) - RepoObject_type : (char(2)) SysObject_id : (int) SysObject_modify_date : (datetime) - SysObject_name : (nvarchar(128)) - SysObject_parent_object_id : (int) - SysObject_schema_name : (nvarchar(128)) SysObject_type : (char(2)) ~ has_different_sys_names : (bit) # is_RepoObject_name_uniqueidentifier : (int) # is_SysObject_name_uniqueidentifier : (int) ~ node_id : (bigint) # RepoObject_fullname : (nvarchar(261)) # RepoObject_fullname2 : (nvarchar(257)) # SysObject_fullname : (nvarchar(261)) # SysObject_fullname2 : (nvarchar(257)) ~ SysObject_query_sql : (nvarchar(406)) ~ usp_persistence_fullname : (nvarchar(273)) # usp_persistence_fullname2 : (nvarchar(269)) # usp_persistence_name : (nvarchar(140)) -- } entity ""puml-link:dhw:sqldb:repo.usp_update_referencing_count.adoc[]"" as repo.usp_update_Referencing_Count << P >> { -- } entity ""puml-link:dhw:sqldb:repo_sys.repoobjectreferenced.adoc[]"" as repo_sys.RepoObjectReferenced << V >> { has_different_sys_names : (bit) - is_all_columns_found : (bit) - is_ambiguous : (bit) - is_caller_dependent : (bit) - is_incomplete : (bit) - is_insert_all : (bit) is_repo_managed : (bit) - is_select_all : (bit) - is_selected : (bit) - is_updated : (bit) referenced_class : (tinyint) referenced_class_desc : (nvarchar(60)) referenced_database_name : (nvarchar(128)) referenced_entity_name : (nvarchar(128)) referenced_id : (int) referenced_minor_id : (int) referenced_minor_name : (nvarchar(128)) referenced_schema_name : (nvarchar(128)) referenced_server_name : (nvarchar(128)) referencing_minor_id : (int) - RepoObject_fullname : (nvarchar(261)) - RepoObject_guid : (uniqueidentifier) - SysObject_fullname : (nvarchar(261)) SysObject_id : (int) SysObject_modify_date : (datetime) SysObject_type : (char(2)) -- } entity ""puml-link:dhw:sqldb:sys_dwh.dm_sql_referenced_entities.adoc[]"" as sys_dwh.dm_sql_referenced_entities << SN >> { -- } repo.RepoObject <.. repo_sys.RepoObjectReferenced repo_sys.RepoObjectReferenced <.. reference.usp_update_Referencing_Count repo_sys.RepoObjectReferenced <.. repo.usp_update_Referencing_Count sys_dwh.dm_sql_referenced_entities <.. repo_sys.RepoObjectReferenced ""repo.RepoObject::has_different_sys_names"" <-- ""repo_sys.RepoObjectReferenced::has_different_sys_names"" ""repo.RepoObject::is_repo_managed"" <-- ""repo_sys.RepoObjectReferenced::is_repo_managed"" ""repo.RepoObject::RepoObject_fullname"" <-- ""repo_sys.RepoObjectReferenced::RepoObject_fullname"" ""repo.RepoObject::RepoObject_guid"" <-- ""repo_sys.RepoObjectReferenced::RepoObject_guid"" ""repo.RepoObject::SysObject_fullname"" <-- ""repo_sys.RepoObjectReferenced::SysObject_fullname"" ""repo.RepoObject::SysObject_id"" <-- ""repo_sys.RepoObjectReferenced::SysObject_id"" ""repo.RepoObject::SysObject_modify_date"" <-- ""repo_sys.RepoObjectReferenced::SysObject_modify_date"" ""repo.RepoObject::SysObject_type"" <-- ""repo_sys.RepoObjectReferenced::SysObject_type"" 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] ---- /* this view can be used to check if SysObject renaming is safe or if exists referenced objects and refactoring is required */ CREATE View repo_sys.RepoObjectReferenced As -- Select ro.RepoObject_guid --, [ro].[RepoObject_schema_name] --, [ro].[RepoObject_name] --, [ro].[RepoObject_type] , ro.SysObject_id --, [ro].[SysObject_schema_name] --, [ro].[SysObject_name] , ro.SysObject_type , ro.SysObject_modify_date --, [ro].[has_execution_plan_issue] , ro.is_repo_managed --, [ro].[modify_dt] , ro.has_different_sys_names , ro.RepoObject_fullname , ro.SysObject_fullname , referencing_minor_id = referenced.referencing_minor_id , referenced_server_name = referenced.referenced_server_name Collate Database_Default , referenced_database_name = referenced.referenced_database_name Collate Database_Default , referenced_schema_name = referenced.referenced_schema_name Collate Database_Default , referenced_entity_name = referenced.referenced_entity_name Collate Database_Default , referenced_minor_name = referenced.referenced_minor_name Collate Database_Default , referenced_id = referenced.referenced_id , referenced_minor_id = referenced.referenced_minor_id , referenced_class = referenced.referenced_class , referenced_class_desc = referenced.referenced_class_desc Collate Database_Default , is_caller_dependent = referenced.is_caller_dependent , is_ambiguous = referenced.is_ambiguous , is_selected = referenced.is_selected , is_updated = referenced.is_updated , is_select_all = referenced.is_select_all , is_all_columns_found = referenced.is_all_columns_found , is_insert_all = referenced.is_insert_all , is_incomplete = referenced.is_incomplete From repo.RepoObject As ro Cross Apply sys_dwh.dm_sql_referenced_entities ( ro.SysObject_fullname, 'OBJECT' ) As referenced Where IsNull ( ro.has_get_referenced_issue, 0 ) = 0 ---- ======= // end::sql_modules_definition[] ",12180,False,2364.964317067733,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. */ //// [[upgrading]] = Upgrading :doctype: book :numbered: :toc: left :icons: font :experimental: You cannot skip major versions when upgrading. If you are upgrading from version 0.98.x to 2.x, you must first go from 0.98.x to 1.2.x and then go from 1.2.x to 2.x. Review <>, in particular <>. Familiarize yourself with <>. [[hbase.versioning]] == HBase version number and compatibility [[hbase.versioning.post10]] === Aspirational Semantic Versioning Starting with the 1.0.0 release, HBase is working towards link:http://semver.org/[Semantic Versioning] for its release versioning. In summary: .Given a version number MAJOR.MINOR.PATCH, increment the: * MAJOR version when you make incompatible API changes, * MINOR version when you add functionality in a backwards-compatible manner, and * PATCH version when you make backwards-compatible bug fixes. * Additional labels for pre-release and build metadata are available as extensions to the MAJOR.MINOR.PATCH format. [[hbase.versioning.compat]] .Compatibility Dimensions In addition to the usual API versioning considerations HBase has other compatibility dimensions that we need to consider. .Client-Server wire protocol compatibility * Allows updating client and server out of sync. * We could only allow upgrading the server first. I.e. the server would be backward compatible to an old client, that way new APIs are OK. * Example: A user should be able to use an old client to connect to an upgraded cluster. .Server-Server protocol compatibility * Servers of different versions can co-exist in the same cluster. * The wire protocol between servers is compatible. * Workers for distributed tasks, such as replication and log splitting, can co-exist in the same cluster. * Dependent protocols (such as using ZK for coordination) will also not be changed. * Example: A user can perform a rolling upgrade. .File format compatibility * Support file formats backward and forward compatible * Example: File, ZK encoding, directory layout is upgraded automatically as part of an HBase upgrade. User can downgrade to the older version and everything will continue to work. .Client API compatibility * Allow changing or removing existing client APIs. * An API needs to be deprecated for a whole major version before we will change/remove it. ** An example: An API was deprecated in 2.0.1 and will be marked for deletion in 4.0.0. On the other hand, an API deprecated in 2.0.0 can be removed in 3.0.0. * APIs available in a patch version will be available in all later patch versions. However, new APIs may be added which will not be available in earlier patch versions. * New APIs introduced in a patch version will only be added in a source compatible way footnote:[See 'Source Compatibility' https://blogs.oracle.com/darcy/entry/kinds_of_compatibility]: i.e. code that implements public APIs will continue to compile. ** Example: A user using a newly deprecated API does not need to modify application code with HBase API calls until the next major version. * .Client Binary compatibility * Client code written to APIs available in a given patch release can run unchanged (no recompilation needed) against the new jars of later patch versions. * Client code written to APIs available in a given patch release might not run against the old jars from an earlier patch version. ** Example: Old compiled client code will work unchanged with the new jars. * If a Client implements an HBase Interface, a recompile MAY be required upgrading to a newer minor version (See release notes for warning about incompatible changes). All effort will be made to provide a default implementation so this case should not arise. .Server-Side Limited API compatibility (taken from Hadoop) * Internal APIs are marked as Stable, Evolving, or Unstable * This implies binary compatibility for coprocessors and plugins (pluggable classes, including replication) as long as these are only using marked interfaces/classes. * Example: Old compiled Coprocessor, Filter, or Plugin code will work unchanged with the new jars. .Dependency Compatibility * An upgrade of HBase will not require an incompatible upgrade of a dependent project, except for Apache Hadoop. * An upgrade of HBase will not require an incompatible upgrade of the Java runtime. * Example: Upgrading HBase to a version that supports _Dependency Compatibility_ won't require that you upgrade your Apache ZooKeeper service. * Example: If your current version of HBase supported running on JDK 8, then an upgrade to a version that supports _Dependency Compatibility_ will also run on JDK 8. .Hadoop Versions [TIP] ==== Previously, we tried to maintain dependency compatibility for the underly Hadoop service but over the last few years this has proven untenable. While the HBase project attempts to maintain support for older versions of Hadoop, we drop the ""supported"" designator for minor versions that fail to continue to see releases. Additionally, the Hadoop project has its own set of compatibility guidelines, which means in some cases having to update to a newer supported minor release might break some of our compatibility promises. ==== .Operational Compatibility * Metric changes * Behavioral changes of services * JMX APIs exposed via the `/jmx/` endpoint .Summary * A patch upgrade is a drop-in replacement. Any change that is not Java binary and source compatible would not be allowed.footnote:[See http://docs.oracle.com/javase/specs/jls/se7/html/jls-13.html.] Downgrading versions within patch releases may not be compatible. * A minor upgrade requires no application/client code modification. Ideally it would be a drop-in replacement but client code, coprocessors, filters, etc might have to be recompiled if new jars are used. * A major upgrade allows the HBase community to make breaking changes. .Compatibility Matrix footnote:[Note that this indicates what could break, not that it will break. We will/should add specifics in our release notes.] [cols=""1,1,1,1""] |=== | | Major | Minor | Patch |Client-Server wire Compatibility| N |Y |Y |Server-Server Compatibility |N |Y |Y |File Format Compatibility | N footnote:[comp_matrix_offline_upgrade_note,Running an offline upgrade tool without downgrade might be needed. We will typically only support migrating data from major version X to major version X+1.] | Y |Y |Client API Compatibility | N | Y |Y |Client Binary Compatibility | N | N |Y 4+|Server-Side Limited API Compatibility >| Stable | N | Y | Y >| Evolving | N |N |Y >| Unstable | N |N |N |Dependency Compatibility | N |Y |Y |Operational Compatibility | N |N |Y |=== [[hbase.client.api.surface]] ==== HBase API Surface HBase has a lot of API points, but for the compatibility matrix above, we differentiate between Client API, Limited Private API, and Private API. HBase uses link:https://yetus.apache.org/documentation/0.5.0/interface-classification/[Apache Yetus Audience Annotations] to guide downstream expectations for stability. * InterfaceAudience (link:https://yetus.apache.org/documentation/0.5.0/audience-annotations-apidocs/org/apache/yetus/audience/InterfaceAudience.html[javadocs]): captures the intended audience, possible values include: - Public: safe for end users and external projects - LimitedPrivate: used for internals we expect to be pluggable, such as coprocessors - Private: strictly for use within HBase itself Classes which are defined as `IA.Private` may be used as parameters or return values for interfaces which are declared `IA.LimitedPrivate`. Treat the `IA.Private` object as opaque; do not try to access its methods or fields directly. * InterfaceStability (link:https://yetus.apache.org/documentation/0.5.0/audience-annotations-apidocs/org/apache/yetus/audience/InterfaceStability.html[javadocs]): describes what types of interface changes are permitted. Possible values include: - Stable: the interface is fixed and is not expected to change - Evolving: the interface may change in future minor verisons - Unstable: the interface may change at any time Please keep in mind the following interactions between the `InterfaceAudience` and `InterfaceStability` annotations within the HBase project: * `IA.Public` classes are inherently stable and adhere to our stability guarantees relating to the type of upgrade (major, minor, or patch). * `IA.LimitedPrivate` classes should always be annotated with one of the given `InterfaceStability` values. If they are not, you should presume they are `IS.Unstable`. * `IA.Private` classes should be considered implicitly unstable, with no guarantee of stability between releases. [[hbase.client.api]] HBase Client API:: HBase Client API consists of all the classes or methods that are marked with InterfaceAudience.Public interface. All main classes in hbase-client and dependent modules have either InterfaceAudience.Public, InterfaceAudience.LimitedPrivate, or InterfaceAudience.Private marker. Not all classes in other modules (hbase-server, etc) have the marker. If a class is not annotated with one of these, it is assumed to be a InterfaceAudience.Private class. [[hbase.limitetprivate.api]] HBase LimitedPrivate API:: LimitedPrivate annotation comes with a set of target consumers for the interfaces. Those consumers are coprocessors, phoenix, replication endpoint implementations or similar. At this point, HBase only guarantees source and binary compatibility for these interfaces between patch versions. [[hbase.private.api]] HBase Private API:: All classes annotated with InterfaceAudience.Private or all classes that do not have the annotation are for HBase internal use only. The interfaces and method signatures can change at any point in time. If you are relying on a particular interface that is marked Private, you should open a jira to propose changing the interface to be Public or LimitedPrivate, or an interface exposed for this purpose. [[hbase.binary.compatibility]] .Binary Compatibility When we say two HBase versions are compatible, we mean that the versions are wire and binary compatible. Compatible HBase versions means that clients can talk to compatible but differently versioned servers. It means too that you can just swap out the jars of one version and replace them with the jars of another, compatible version and all will just work. Unless otherwise specified, HBase point versions are (mostly) binary compatible. You can safely do rolling upgrades between binary compatible versions; i.e. across maintenance releases: e.g. from 1.2.4 to 1.2.6. See link:[Does compatibility between versions also mean binary compatibility?] discussion on the HBase dev mailing list. [[hbase.rolling.upgrade]] === Rolling Upgrades A rolling upgrade is the process by which you update the servers in your cluster a server at a time. You can rolling upgrade across HBase versions if they are binary or wire compatible. See <> for more on what this means. Coarsely, a rolling upgrade is a graceful stop each server, update the software, and then restart. You do this for each server in the cluster. Usually you upgrade the Master first and then the RegionServers. See <> for tools that can help use the rolling upgrade process. For example, in the below, HBase was symlinked to the actual HBase install. On upgrade, before running a rolling restart over the cluster, we changed the symlink to point at the new HBase software version and then ran [source,bash] ---- $ HADOOP_HOME=~/hadoop-2.6.0-CRC-SNAPSHOT ~/hbase/bin/rolling-restart.sh --config ~/conf_hbase ---- The rolling-restart script will first gracefully stop and restart the master, and then each of the RegionServers in turn. Because the symlink was changed, on restart the server will come up using the new HBase version. Check logs for errors as the rolling upgrade proceeds. [[hbase.rolling.restart]] .Rolling Upgrade Between Versions that are Binary/Wire Compatible Unless otherwise specified, HBase minor versions are binary compatible. You can do a <> between HBase point versions. For example, you can go to 1.2.4 from 1.2.6 by doing a rolling upgrade across the cluster replacing the 1.2.4 binary with a 1.2.6 binary. In the minor version-particular sections below, we call out where the versions are wire/protocol compatible and in this case, it is also possible to do a <>. == Rollback Sometimes things don't go as planned when attempting an upgrade. This section explains how to perform a _rollback_ to an earlier HBase release. Note that this should only be needed between Major and some Minor releases. You should always be able to _downgrade_ between HBase Patch releases within the same Minor version. These instructions may require you to take steps before you start the upgrade process, so be sure to read through this section beforehand. === Caveats .Rollback vs Downgrade This section describes how to perform a _rollback_ on an upgrade between HBase minor and major versions. In this document, rollback refers to the process of taking an upgraded cluster and restoring it to the old version _while losing all changes that have occurred since upgrade_. By contrast, a cluster _downgrade_ would restore an upgraded cluster to the old version while maintaining any data written since the upgrade. We currently only offer instructions to rollback HBase clusters. Further, rollback only works when these instructions are followed prior to performing the upgrade. When these instructions talk about rollback vs downgrade of prerequisite cluster services (i.e. HDFS), you should treat leaving the service version the same as a degenerate case of downgrade. .Replication Unless you are doing an all-service rollback, the HBase cluster will lose any configured peers for HBase replication. If your cluster is configured for HBase replication, then prior to following these instructions you should document all replication peers. After performing the rollback you should then add each documented peer back to the cluster. For more information on enabling HBase replication, listing peers, and adding a peer see <>. Note also that data written to the cluster since the upgrade may or may not have already been replicated to any peers. Determining which, if any, peers have seen replication data as well as rolling back the data in those peers is out of the scope of this guide. .Data Locality Unless you are doing an all-service rollback, going through a rollback procedure will likely destroy all locality for Region Servers. You should expect degraded performance until after the cluster has had time to go through compactions to restore data locality. Optionally, you can force a compaction to speed this process up at the cost of generating cluster load. .Configurable Locations The instructions below assume default locations for the HBase data directory and the HBase znode. Both of these locations are configurable and you should verify the value used in your cluster before proceeding. In the event that you have a different value, just replace the default with the one found in your configuration * HBase data directory is configured via the key 'hbase.rootdir' and has a default value of '/hbase'. * HBase znode is configured via the key 'zookeeper.znode.parent' and has a default value of '/hbase'. === All service rollback If you will be performing a rollback of both the HDFS and ZooKeeper services, then HBase's data will be rolled back in the process. .Requirements * Ability to rollback HDFS and ZooKeeper .Before upgrade No additional steps are needed pre-upgrade. As an extra precautionary measure, you may wish to use distcp to back up the HBase data off of the cluster to be upgraded. To do so, follow the steps in the 'Before upgrade' section of 'Rollback after HDFS downgrade' but copy to another HDFS instance instead of within the same instance. .Performing a rollback . Stop HBase . Perform a rollback for HDFS and ZooKeeper (HBase should remain stopped) . Change the installed version of HBase to the previous version . Start HBase . Verify HBase contents—use the HBase shell to list tables and scan some known values. === Rollback after HDFS rollback and ZooKeeper downgrade If you will be rolling back HDFS but going through a ZooKeeper downgrade, then HBase will be in an inconsistent state. You must ensure the cluster is not started until you complete this process. .Requirements * Ability to rollback HDFS * Ability to downgrade ZooKeeper .Before upgrade No additional steps are needed pre-upgrade. As an extra precautionary measure, you may wish to use distcp to back up the HBase data off of the cluster to be upgraded. To do so, follow the steps in the 'Before upgrade' section of 'Rollback after HDFS downgrade' but copy to another HDFS instance instead of within the same instance. .Performing a rollback . Stop HBase . Perform a rollback for HDFS and a downgrade for ZooKeeper (HBase should remain stopped) . Change the installed version of HBase to the previous version . Clean out ZooKeeper information related to HBase. WARNING: This step will permanently destroy all replication peers. Please see the section on HBase Replication under Caveats for more information. + .Clean HBase information out of ZooKeeper [source,bash] ---- [hpnewton@gateway_node.example.com ~]$ zookeeper-client -server zookeeper1.example.com:2181,zookeeper2.example.com:2181,zookeeper3.example.com:2181 Welcome to ZooKeeper! JLine support is disabled rmr /hbase quit Quitting... ---- . Start HBase . Verify HBase contents—use the HBase shell to list tables and scan some known values. === Rollback after HDFS downgrade If you will be performing an HDFS downgrade, then you'll need to follow these instructions regardless of whether ZooKeeper goes through rollback, downgrade, or reinstallation. .Requirements * Ability to downgrade HDFS * Pre-upgrade cluster must be able to run MapReduce jobs * HDFS super user access * Sufficient space in HDFS for at least two copies of the HBase data directory .Before upgrade Before beginning the upgrade process, you must take a complete backup of HBase's backing data. The following instructions cover backing up the data within the current HDFS instance. Alternatively, you can use the distcp command to copy the data to another HDFS cluster. . Stop the HBase cluster . Copy the HBase data directory to a backup location using the https://hadoop.apache.org/docs/current/hadoop-distcp/DistCp.html[distcp command] as the HDFS super user (shown below on a security enabled cluster) + .Using distcp to backup the HBase data directory [source,bash] ---- [hpnewton@gateway_node.example.com ~]$ kinit -k -t hdfs.keytab hdfs@EXAMPLE.COM [hpnewton@gateway_node.example.com ~]$ hadoop distcp /hbase /hbase-pre-upgrade-backup ---- . Distcp will launch a mapreduce job to handle copying the files in a distributed fashion. Check the output of the distcp command to ensure this job completed successfully. .Performing a rollback . Stop HBase . Perform a downgrade for HDFS and a downgrade/rollback for ZooKeeper (HBase should remain stopped) . Change the installed version of HBase to the previous version . Restore the HBase data directory from prior to the upgrade as the HDFS super user (shown below on a security enabled cluster). If you backed up your data on another HDFS cluster instead of locally, you will need to use the distcp command to copy it back to the current HDFS cluster. + .Restore the HBase data directory [source,bash] ---- [hpnewton@gateway_node.example.com ~]$ kinit -k -t hdfs.keytab hdfs@EXAMPLE.COM [hpnewton@gateway_node.example.com ~]$ hdfs dfs -mv /hbase /hbase-upgrade-rollback [hpnewton@gateway_node.example.com ~]$ hdfs dfs -mv /hbase-pre-upgrade-backup /hbase ---- . Clean out ZooKeeper information related to HBase. WARNING: This step will permanently destroy all replication peers. Please see the section on HBase Replication under Caveats for more information. + .Clean HBase information out of ZooKeeper [source,bash] ---- [hpnewton@gateway_node.example.com ~]$ zookeeper-client -server zookeeper1.example.com:2181,zookeeper2.example.com:2181,zookeeper3.example.com:2181 Welcome to ZooKeeper! JLine support is disabled rmr /hbase quit Quitting... ---- . Start HBase . Verify HBase contents–use the HBase shell to list tables and scan some known values. == Upgrade Paths [[upgrade2.2]] === Upgrade from 2.0 or 2.1 to 2.2+ HBase 2.2+ uses a new Procedure form assiging/unassigning/moving Regions. It does not process HBase 2.1 and 2.0's Unassign/Assign Procedure types. Upgrade requires that we first drain the Master Procedure Store of old style Procedures before starting the new 2.2 Master. So you need to make sure that before you kill the old version (2.0 or 2.1) Master, there is no region in transition. And once the new version (2.2+) Master is up, you can rolling upgrade RegionServers one by one. And there is a more safer way if you are running 2.1.1+ or 2.0.3+ cluster. It need four steps to upgrade Master. . Shutdown both active and standby Masters (Your cluster will continue to server reads and writes without interruption). . Set the property hbase.procedure.upgrade-to-2-2 to true in hbase-site.xml for the Master, and start only one Master, still using the 2.1.1+ (or 2.0.3+) version. . Wait until the Master quits. Confirm that there is a 'READY TO ROLLING UPGRADE' message in the Master log as the cause of the shutdown. The Procedure Store is now empty. . Start new Masters with the new 2.2+ version. Then you can rolling upgrade RegionServers one by one. See link:https://issues.apache.org/jira/browse/HBASE-21075[HBASE-21075] for more details. [[upgrade2.0]] === Upgrading from 1.x to 2.x In this section we will first call out significant changes compared to the prior stable HBase release and then go over the upgrade process. Be sure to read the former with care so you avoid suprises. ==== Changes of Note! First we'll cover deployment / operational changes that you might hit when upgrading to HBase 2.0+. After that we'll call out changes for downstream applications. Please note that Coprocessors are covered in the operational section. Also note that this section is not meant to convey information about new features that may be of interest to you. For a complete summary of changes, please see the CHANGES.txt file in the source release artifact for the version you are planning to upgrade to. [[upgrade2.0.basic.requirements]] .Update to basic prerequisite minimums in HBase 2.0+ As noted in the section <>, HBase 2.0+ requires a minimum of Java 8 and Hadoop 2.6. The HBase community recommends ensuring you have already completed any needed upgrades in prerequisites prior to upgrading your HBase version. [[upgrade2.0.hbck]] .HBCK must match HBase server version You *must not* use an HBase 1.x version of HBCK against an HBase 2.0+ cluster. HBCK is strongly tied to the HBase server version. Using the HBCK tool from an earlier release against an HBase 2.0+ cluster will destructively alter said cluster in unrecoverable ways. As of HBase 2.0, HBCK (A.K.A _HBCK1_ or _hbck1_) is a read-only tool that can report the status of some non-public system internals. You should not rely on the format nor content of these internals to remain consistent across HBase releases. To read about HBCK's replacement, see <> in <>. //// Link to a ref guide section on HBCK in 2.0 that explains use and calls out the inability of clients and server sides to detect version of each other. //// [[upgrade2.0.removed.configs]] .Configuration settings no longer in HBase 2.0+ The following configuration settings are no longer applicable or available. For details, please see the detailed release notes. * hbase.config.read.zookeeper.config (see <> for migration details) * hbase.zookeeper.useMulti (HBase now always uses ZK's multi functionality) * hbase.rpc.client.threads.max * hbase.rpc.client.nativetransport * hbase.fs.tmp.dir // These next two seem worth a call out section? * hbase.bucketcache.combinedcache.enabled * hbase.bucketcache.ioengine no longer supports the 'heap' value. * hbase.bulkload.staging.dir * hbase.balancer.tablesOnMaster wasn't removed, strictly speaking, but its meaning has fundamentally changed and users should not set it. See the section <> for details. * hbase.master.distributed.log.replay See the section <> for details * hbase.regionserver.disallow.writes.when.recovering See the section <> for details * hbase.regionserver.wal.logreplay.batch.size See the section <> for details * hbase.master.catalog.timeout * hbase.regionserver.catalog.timeout * hbase.metrics.exposeOperationTimes * hbase.metrics.showTableName * hbase.online.schema.update.enable (HBase now always supports this) * hbase.thrift.htablepool.size.max [[upgrade2.0.renamed.configs]] .Configuration properties that were renamed in HBase 2.0+ The following properties have been renamed. Attempts to set the old property will be ignored at run time. .Renamed properties [options=""header""] |============================================================================================================ |Old name |New name |hbase.rpc.server.nativetransport |hbase.netty.nativetransport |hbase.netty.rpc.server.worker.count |hbase.netty.worker.count |hbase.hfile.compactions.discharger.interval |hbase.hfile.compaction.discharger.interval |hbase.hregion.percolumnfamilyflush.size.lower.bound |hbase.hregion.percolumnfamilyflush.size.lower.bound.min |============================================================================================================ [[upgrade2.0.changed.defaults]] .Configuration settings with different defaults in HBase 2.0+ The following configuration settings changed their default value. Where applicable, the value to set to restore the behavior of HBase 1.2 is given. * hbase.security.authorization now defaults to false. set to true to restore same behavior as previous default. * hbase.client.retries.number is now set to 10. Previously it was 35. Downstream users are advised to use client timeouts as described in section <> instead. * hbase.client.serverside.retries.multiplier is now set to 3. Previously it was 10. Downstream users are advised to use client timesout as describe in section <> instead. * hbase.master.fileSplitTimeout is now set to 10 minutes. Previously it was 30 seconds. * hbase.regionserver.logroll.multiplier is now set to 0.5. Previously it was 0.95. This change is tied with the following doubling of block size. Combined, these two configuration changes should make for WALs of about the same size as those in hbase-1.x but there should be less incidence of small blocks because we fail to roll the WAL before we hit the blocksize threshold. See link:https://issues.apache.org/jira/browse/HBASE-19148[HBASE-19148] for discussion. * hbase.regionserver.hlog.blocksize defaults to 2x the HDFS default block size for the WAL dir. Previously it was equal to the HDFS default block size for the WAL dir. * hbase.client.start.log.errors.counter changed to 5. Previously it was 9. * hbase.ipc.server.callqueue.type changed to 'fifo'. In HBase versions 1.0 - 1.2 it was 'deadline'. In prior and later 1.x versions it already defaults to 'fifo'. * hbase.hregion.memstore.chunkpool.maxsize is 1.0 by default. Previously it was 0.0. Effectively, this means previously we would not use a chunk pool when our memstore is onheap and now we will. See the section <> for more infromation about the MSLAB chunk pool. * hbase.master.cleaner.interval is now set to 10 minutes. Previously it was 1 minute. * hbase.master.procedure.threads will now default to 1/4 of the number of available CPUs, but not less than 16 threads. Previously it would be number of threads equal to number of CPUs. * hbase.hstore.blockingStoreFiles is now 16. Previously it was 10. * hbase.http.max.threads is now 16. Previously it was 10. * hbase.client.max.perserver.tasks is now 2. Previously it was 5. * hbase.normalizer.period is now 5 minutes. Previously it was 30 minutes. * hbase.regionserver.region.split.policy is now SteppingSplitPolicy. Previously it was IncreasingToUpperBoundRegionSplitPolicy. * replication.source.ratio is now 0.5. Previously it was 0.1. [[upgrade2.0.regions.on.master]] .""Master hosting regions"" feature broken and unsupported The feature ""Master acts as region server"" and associated follow-on work available in HBase 1.y is non-functional in HBase 2.y and should not be used in a production setting due to deadlock on Master initialization. Downstream users are advised to treat related configuration settings as experimental and the feature as inappropriate for production settings. A brief summary of related changes: * Master no longer carries regions by default * hbase.balancer.tablesOnMaster is a boolean, default false (if it holds an HBase 1.x list of tables, will default to false) * hbase.balancer.tablesOnMaster.systemTablesOnly is boolean to keep user tables off master. default false * those wishing to replicate old list-of-servers config should deploy a stand-alone RegionServer process and then rely on Region Server Groups [[upgrade2.0.distributed.log.replay]] .""Distributed Log Replay"" feature broken and removed The Distributed Log Replay feature was broken and has been removed from HBase 2.y+. As a consequence all related configs, metrics, RPC fields, and logging have also been removed. Note that this feature was found to be unreliable in the run up to HBase 1.0, defaulted to being unused, and was effectively removed in HBase 1.2.0 when we started ignoring the config that turns it on (link:https://issues.apache.org/jira/browse/HBASE-14465[HBASE-14465]). If you are currently using the feature, be sure to perform a clean shutdown, ensure all DLR work is complete, and disable the feature prior to upgrading. [[upgrade2.0.prefix-tree.removed]] ._prefix-tree_ encoding removed The prefix-tree encoding was removed from HBase 2.0.0 (link:https://issues.apache.org/jira/browse/HBASE-19179[HBASE-19179]). It was (late!) deprecated in hbase-1.2.7, hbase-1.4.0, and hbase-1.3.2. This feature was removed because it as not being actively maintained. If interested in reviving this sweet facility which improved random read latencies at the expensive of slowed writes, write the HBase developers list at _dev at hbase dot apache dot org_. The prefix-tree encoding needs to be removed from all tables before upgrading to HBase 2.0+. To do that first you need to change the encoding from PREFIX_TREE to something else that is supported in HBase 2.0. After that you have to major compact the tables that were using PREFIX_TREE encoding before. To check which column families are using incompatible data block encoding you can use <>. [[upgrade2.0.metrics]] .Changed metrics The following metrics have changed names: * Metrics previously published under the name ""AssignmentManger"" [sic] are now published under the name ""AssignmentManager"" The following metrics have changed their meaning: * The metric 'blockCacheEvictionCount' published on a per-region server basis no longer includes blocks removed from the cache due to the invalidation of the hfiles they are from (e.g. via compaction). * The metric 'totalRequestCount' increments once per request; previously it incremented by the number of `Actions` carried in the request; e.g. if a request was a `multi` made of four Gets and two Puts, we'd increment 'totalRequestCount' by six; now we increment by one regardless. Expect to see lower values for this metric in hbase-2.0.0. * The 'readRequestCount' now counts reads that return a non-empty row where in older hbases, we'd increment 'readRequestCount' whether a Result or not. This change will flatten the profile of the read-requests graphs if requests for non-existent rows. A YCSB read-heavy workload can do this dependent on how the database was loaded. The following metrics have been removed: * Metrics related to the Distributed Log Replay feature are no longer present. They were previsouly found in the region server context under the name 'replay'. See the section <> for details. The following metrics have been added: * 'totalRowActionRequestCount' is a count of region row actions summing reads and writes. [[upgrade2.0.logging]] .Changed logging HBase-2.0.0 now uses link:https://www.slf4j.org/[slf4j] as its logging frontend. Prevously, we used link:http://logging.apache.org/log4j/1.2/[log4j (1.2)]. For most the transition should be seamless; slf4j does a good job interpreting _log4j.properties_ logging configuration files such that you should not notice any difference in your log system emissions. That said, your _log4j.properties_ may need freshening. See link:https://issues.apache.org/jira/browse/HBASE-20351[HBASE-20351] for example, where a stale log configuration file manifest as netty configuration being dumped at DEBUG level as preamble on every shell command invocation. [[upgrade2.0.zkconfig]] .ZooKeeper configs no longer read from zoo.cfg HBase no longer optionally reads the 'zoo.cfg' file for ZooKeeper related configuration settings. If you previously relied on the 'hbase.config.read.zookeeper.config' config for this functionality, you should migrate any needed settings to the hbase-site.xml file while adding the prefix 'hbase.zookeeper.property.' to each property name. [[upgrade2.0.permissions]] .Changes in permissions The following permission related changes either altered semantics or defaults: * Permissions granted to a user now merge with existing permissions for that user, rather than over-writing them. (see link:https://issues.apache.org/jira/browse/HBASE-17472[the release note on HBASE-17472] for details) * Region Server Group commands (added in 1.4.0) now require admin privileges. [[upgrade2.0.admin.commands]] .Most Admin APIs don't work against an HBase 2.0+ cluster from pre-HBase 2.0 clients A number of admin commands are known to not work when used from a pre-HBase 2.0 client. This includes an HBase Shell that has the library jars from pre-HBase 2.0. You will need to plan for an outage of use of admin APIs and commands until you can also update to the needed client version. The following client operations do not work against HBase 2.0+ cluster when executed from a pre-HBase 2.0 client: * list_procedures * split * merge_region * list_quotas * enable_table_replication * disable_table_replication * Snapshot related commands .Deprecated in 1.0 admin commands have been removed. The following commands that were deprecated in 1.0 have been removed. Where applicable the replacement command is listed. * The 'hlog' command has been removed. Downstream users should rely on the 'wal' command instead. [[upgrade2.0.memory]] .Region Server memory consumption changes. Users upgrading from versions prior to HBase 1.4 should read the instructions in section <>. Additionally, HBase 2.0 has changed how memstore memory is tracked for flushing decisions. Previously, both the data size and overhead for storage were used to calculate utilization against the flush threashold. Now, only data size is used to make these per-region decisions. Globally the addition of the storage overhead is used to make decisions about forced flushes. [[upgrade2.0.ui.splitmerge.by.row]] .Web UI for splitting and merging operate on row prefixes Previously, the Web UI included functionality on table status pages to merge or split based on an encoded region name. In HBase 2.0, instead this functionality works by taking a row prefix. [[upgrade2.0.replication]] .Special upgrading for Replication users from pre-HBase 1.4 User running versions of HBase prior to the 1.4.0 release that make use of replication should be sure to read the instructions in the section <>. [[upgrade2.0.shell]] .HBase shell changes The HBase shell command relies on a bundled JRuby instance. This bundled JRuby been updated from version 1.6.8 to version 9.1.10.0. The represents a change from Ruby 1.8 to Ruby 2.3.3, which introduces non-compatible language changes for user scripts. The HBase shell command now ignores the '--return-values' flag that was present in early HBase 1.4 releases. Instead the shell always behaves as though that flag were passed. If you wish to avoid having expression results printed in the console you should alter your IRB configuration as noted in the section <>. [[upgrade2.0.coprocessors]] .Coprocessor APIs have changed in HBase 2.0+ All Coprocessor APIs have been refactored to improve supportability around binary API compatibility for future versions of HBase. If you or applications you rely on have custom HBase coprocessors, you should read link:https://issues.apache.org/jira/browse/HBASE-18169[the release notes for HBASE-18169] for details of changes you will need to make prior to upgrading to HBase 2.0+. For example, if you had a BaseRegionObserver in HBase 1.2 then at a minimum you will need to update it to implement both RegionObserver and RegionCoprocessor and add the method [source,java] ---- ... @Override public Optional getRegionObserver() { return Optional.of(this); } ... ---- //// This would be a good place to link to a coprocessor migration guide //// [[upgrade2.0.hfile3.only]] .HBase 2.0+ can no longer write HFile v2 files. HBase has simplified our internal HFile handling. As a result, we can no longer write HFile versions earlier than the default of version 3. Upgrading users should ensure that hfile.format.version is not set to 2 in hbase-site.xml before upgrading. Failing to do so will cause Region Server failure. HBase can still read HFiles written in the older version 2 format. [[upgrade2.0.pb.wal.only]] .HBase 2.0+ can no longer read Sequence File based WAL file. HBase can no longer read the deprecated WAL files written in the Apache Hadoop Sequence File format. The hbase.regionserver.hlog.reader.impl and hbase.regionserver.hlog.reader.impl configuration entries should be set to use the Protobuf based WAL reader / writer classes. This implementation has been the default since HBase 0.96, so legacy WAL files should not be a concern for most downstream users. A clean cluster shutdown should ensure there are no WAL files. If you are unsure of a given WAL file's format you can use the `hbase wal` command to parse files while the HBase cluster is offline. In HBase 2.0+, this command will not be able to read a Sequence File based WAL. For more information on the tool see the section <>. [[upgrade2.0.filters]] .Change in behavior for filters The Filter ReturnCode NEXT_ROW has been redefined as skipping to next row in current family, not to next row in all family. it’s more reasonable, because ReturnCode is a concept in store level, not in region level. [[upgrade2.0.shaded.client.preferred]] .Downstream HBase 2.0+ users should use the shaded client Downstream users are strongly urged to rely on the Maven coordinates org.apache.hbase:hbase-shaded-client for their runtime use. This artifact contains all the needed implementation details for talking to an HBase cluster while minimizing the number of third party dependencies exposed. Note that this artifact exposes some classes in the org.apache.hadoop package space (e.g. o.a.h.configuration.Configuration) so that we can maintain source compatibility with our public API. Those classes are included so that they can be altered to use the same relocated third party dependencies as the rest of the HBase client code. In the event that you need to *also* use Hadoop in your code, you should ensure all Hadoop related jars precede the HBase client jar in your classpath. [[upgrade2.0.mapreduce.module]] .Downstream HBase 2.0+ users of MapReduce must switch to new artifact Downstream users of HBase's integration for Apache Hadoop MapReduce must switch to relying on the org.apache.hbase:hbase-shaded-mapreduce module for their runtime use. Historically, downstream users relied on either the org.apache.hbase:hbase-server or org.apache.hbase:hbase-shaded-server artifacts for these classes. Both uses are no longer supported and in the vast majority of cases will fail at runtime. Note that this artifact exposes some classes in the org.apache.hadoop package space (e.g. o.a.h.configuration.Configuration) so that we can maintain source compatibility with our public API. Those classes are included so that they can be altered to use the same relocated third party dependencies as the rest of the HBase client code. In the event that you need to *also* use Hadoop in your code, you should ensure all Hadoop related jars precede the HBase client jar in your classpath. [[upgrade2.0.dependencies]] .Significant changes to runtime classpath A number of internal dependencies for HBase were updated or removed from the runtime classpath. Downstream client users who do not follow the guidance in <> will have to examine the set of dependencies Maven pulls in for impact. Downstream users of LimitedPrivate Coprocessor APIs will need to examine the runtime environment for impact. For details on our new handling of third party libraries that have historically been a problem with respect to harmonizing compatible runtime versions, see the reference guide section <>. [[upgrade2.0.public.api]] .Multiple breaking changes to source and binary compatibility for client API The Java client API for HBase has a number of changes that break both source and binary compatibility for details see the Compatibility Check Report for the release you'll be upgrading to. [[upgrade2.0.tracing]] .Tracing implementation changes The backing implementation of HBase's tracing features was updated from Apache HTrace 3 to HTrace 4, which includes several breaking changes. While HTrace 3 and 4 can coexist in the same runtime, they will not integrate with each other, leading to disjoint trace information. The internal changes to HBase during this upgrade were sufficient for compilation, but it has not been confirmed that there are no regressions in tracing functionality. Please consider this feature expiremental for the immediate future. If you previously relied on client side tracing integrated with HBase operations, it is recommended that you upgrade your usage to HTrace 4 as well. [[upgrade2.0.hfile.compatability]] .HFile lose forward compatability HFiles generated by 2.0.0, 2.0.1, 2.1.0 are not forward compatible to 1.4.6-, 1.3.2.1-, 1.2.6.1-, and other inactive releases. Why HFile lose compatability is hbase in new versions (2.0.0, 2.0.1, 2.1.0) use protobuf to serialize/deserialize TimeRangeTracker (TRT) while old versions use DataInput/DataOutput. To solve this, We have to put link:https://jira.apache.org/jira/browse/HBASE-21012[HBASE-21012] to 2.x and put link:https://jira.apache.org/jira/browse/HBASE-21013[HBASE-21013] in 1.x. For more information, please check link:https://jira.apache.org/jira/browse/HBASE-21008[HBASE-21008]. [[upgrade2.0.perf]] .Performance You will likely see a change in the performance profile on upgrade to hbase-2.0.0 given read and write paths have undergone significant change. On release, writes may be slower with reads about the same or much better, dependent on context. Be prepared to spend time re-tuning (See <>). Performance is also an area that is now under active review so look forward to improvement in coming releases (See link:https://issues.apache.org/jira/browse/HBASE-20188[HBASE-20188 TESTING Performance]). [[upgrade2.0.it.kerberos]] .Integration Tests and Kerberos Integration Tests (`IntegrationTests*`) used to rely on the Kerberos credential cache for authentication against secured clusters. This used to lead to tests failing due to authentication failures when the tickets in the credential cache expired. As of hbase-2.0.0 (and hbase-1.3.0+), the integration test clients will make use of the configuration properties `hbase.client.keytab.file` and `hbase.client.kerberos.principal`. They are required. The clients will perform a login from the configured keytab file and automatically refresh the credentials in the background for the process lifetime (See link:https://issues.apache.org/jira/browse/HBASE-16231[HBASE-16231]). //// This would be a good place to link to an appendix on migrating applications //// [[upgrade2.0.coprocessors]] ==== Upgrading Coprocessors to 2.0 Coprocessors have changed substantially in 2.0 ranging from top level design changes in class hierarchies to changed/removed methods, interfaces, etc. (Parent jira: link:https://issues.apache.org/jira/browse/HBASE-18169[HBASE-18169 Coprocessor fix and cleanup before 2.0.0 release]). Some of the reasons for such widespread changes: . Pass Interfaces instead of Implementations; e.g. TableDescriptor instead of HTableDescriptor and Region instead of HRegion (link:https://issues.apache.org/jira/browse/HBASE-18241[HBASE-18241] Change client.Table and client.Admin to not use HTableDescriptor). . Design refactor so implementers need to fill out less boilerplate and so we can do more compile-time checking (link:https://issues.apache.org/jira/browse/HBASE-17732[HBASE-17732]) . Purge Protocol Buffers from Coprocessor API (link:https://issues.apache.org/jira/browse/HBASE-18859[HBASE-18859], link:https://issues.apache.org/jira/browse/HBASE-16769[HBASE-16769], etc) . Cut back on what we expose to Coprocessors removing hooks on internals that were too private to expose (for eg. link:https://issues.apache.org/jira/browse/HBASE-18453[HBASE-18453] CompactionRequest should not be exposed to user directly; link:https://issues.apache.org/jira/browse/HBASE-18298[HBASE-18298] RegionServerServices Interface cleanup for CP expose; etc) To use coprocessors in 2.0, they should be rebuilt against new API otherwise they will fail to load and HBase processes will die. Suggested order of changes to upgrade the coprocessors: . Directly implement observer interfaces instead of extending Base*Observer classes. Change `Foo extends BaseXXXObserver` to `Foo implements XXXObserver`. (link:https://issues.apache.org/jira/browse/HBASE-17312[HBASE-17312]). . Adapt to design change from Inheritence to Composition (link:https://issues.apache.org/jira/browse/HBASE-17732[HBASE-17732]) by following link:https://github.com/apache/hbase/blob/master/dev-support/design-docs/Coprocessor_Design_Improvements-Use_composition_instead_of_inheritance-HBASE-17732.adoc#migrating-existing-cps-to-new-design[this example]. . getTable() has been removed from the CoprocessorEnvrionment, coprocessors should self-manage Table instances. Some examples of writing coprocessors with new API can be found in hbase-example module link:https://github.com/apache/hbase/tree/branch-2.0/hbase-examples/src/main/java/org/apache/hadoop/hbase/coprocessor/example[here] . Lastly, if an api has been changed/removed that breaks you in an irreparable way, and if there's a good justification to add it back, bring it our notice (dev@hbase.apache.org). [[upgrade2.0.rolling.upgrades]] ==== Rolling Upgrade from 1.x to 2.x Rolling upgrades are currently an experimental feature. They have had limited testing. There are likely corner cases as yet uncovered in our limited experience so you should be careful if you go this route. The stop/upgrade/start described in the next section, <>, is the safest route. That said, the below is a prescription for a rolling upgrade of a 1.4 cluster. .Pre-Requirements * Upgrade to the latest 1.4.x release. Pre 1.4 releases may also work but are not tested, so please upgrade to 1.4.3+ before upgrading to 2.x, unless you are an expert and familiar with the region assignment and crash processing. See the section <> on how to upgrade to 1.4.x. * Make sure that the zk-less assignment is enabled, i.e, set `hbase.assignment.usezk` to `false`. This is the most important thing. It allows the 1.x master to assign/unassign regions to/from 2.x region servers. See the release note section of link:https://issues.apache.org/jira/browse/HBASE-11059[HBASE-11059] on how to migrate from zk based assignment to zk less assignment. * We have tested rolling upgrading from 1.4.3 to 2.1.0, but it should also work if you want to upgrade to 2.0.x. .Instructions . Unload a region server and upgrade it to 2.1.0. With link:https://issues.apache.org/jira/browse/HBASE-17931[HBASE-17931] in place, the meta region and regions for other system tables will be moved to this region server immediately. If not, please move them manually to the new region server. This is very important because ** The schema of meta region is hard coded, if meta is on an old region server, then the new region servers can not access it as it does not have some families, for example, table state. ** Client with lower version can communicate with server with higher version, but not vice versa. If the meta region is on an old region server, the new region server will use a client with higher version to communicate with a server with lower version, this may introduce strange problems. . Rolling upgrade all other region servers. . Upgrading masters. It is OK that during the rolling upgrading there are region server crashes. The 1.x master can assign regions to both 1.x and 2.x region servers, and link:https://issues.apache.org/jira/browse/HBASE-19166[HBASE-19166] fixed a problem so that 1.x region server can also read the WALs written by 2.x region server and split them. NOTE: please read the <> section carefully before rolling upgrading. Make sure that you do not use the removed features in 2.0, for example, the prefix-tree encoding, the old hfile format, etc. They could both fail the upgrading and leave the cluster in an intermediate state and hard to recover. NOTE: If you have success running this prescription, please notify the dev list with a note on your experience and/or update the above with any deviations you may have taken so others going this route can benefit from your efforts. [[upgrade2.0.process]] ==== Upgrade process from 1.x to 2.x To upgrade an existing HBase 1.x cluster, you should: * Clean shutdown of existing 1.x cluster * Update coprocessors * Upgrade Master roles first * Upgrade RegionServers * (Eventually) Upgrade Clients [[upgrade1.4]] === Upgrading from pre-1.4 to 1.4+ [[upgrade1.4.memory]] ==== Region Server memory consumption changes. Users upgrading from versions prior to HBase 1.4 should be aware that the estimates of heap usage by the memstore objects (KeyValue, object and array header sizes, etc) have been made more accurate for heap sizes up to 32G (using CompressedOops), resulting in them dropping by 10-50% in practice. This also results in less number of flushes and compactions due to ""fatter"" flushes. YMMV. As a result, the actual heap usage of the memstore before being flushed may increase by up to 100%. If configured memory limits for the region server had been tuned based on observed usage, this change could result in worse GC behavior or even OutOfMemory errors. Set the environment property (not hbase-site.xml) ""hbase.memorylayout.use.unsafe"" to false to disable. [[upgrade1.4.replication]] ==== Replication peer's TableCFs config Before 1.4, the table name can't include namespace for replication peer's TableCFs config. It was fixed by add TableCFs to ReplicationPeerConfig which was stored on Zookeeper. So when upgrade to 1.4, you have to update the original ReplicationPeerConfig data on Zookeeper firstly. There are four steps to upgrade when your cluster have a replication peer with TableCFs config. * Disable the replication peer. * If master has permission to write replication peer znode, then rolling update master directly. If not, use TableCFsUpdater tool to update the replication peer's config. [source,bash] ---- $ bin/hbase org.apache.hadoop.hbase.replication.master.TableCFsUpdater update ---- * Rolling update regionservers. * Enable the replication peer. Notes: * Can't use the old client(before 1.4) to change the replication peer's config. Because the client will write config to Zookeeper directly, the old client will miss TableCFs config. And the old client write TableCFs config to the old tablecfs znode, it will not work for new version regionserver. [[upgrade1.4.rawscan]] ==== Raw scan now ignores TTL Doing a raw scan will now return results that have expired according to TTL settings. [[upgrade1.3]] === Upgrading from pre-1.3 to 1.3+ If running Integration Tests under Kerberos, see <>. [[upgrade1.0]] === Upgrading to 1.x Please consult the documentation published specifically for the version of HBase that you are upgrading to for details on the upgrade process. ",12541,False,2183.1661479571126,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. // = Использование поддержки Subversion в IDE NetBeans :jbake-type: tutorial :jbake-tags: tutorials :jbake-status: published :icons: font :syntax: true :source-highlighter: pygments :toc: left :toc-title: :description: Использование поддержки Subversion в IDE NetBeans - Apache NetBeans :keywords: Apache NetBeans, Tutorials, Использование поддержки Subversion в IDE NetBeans IDE NetBeans обеспечивает соответствующий уровень интеграции с клиентами Subversion версий 1.6.x и более поздними версиями. Поддержка Subversion в IDE предназначена для упрощения процесса разработки у групп, работающих с общим репозиторием, и позволяет выполнять задачи контроля версий прямо с системы проекта из среды IDE. В этом документе демонстрируется выполнение основных задач контроля версий в среде IDE путем рассмотрения стандартной последовательности действий при использовании программного обеспечения контроля версий. Заметим, что поддержка Subversion в NetBeans _не_ работает при использовании из Cygwin. link:http://subversion.tigris.org/[+Subversion +] — это популярная система контроля версий с открытым кодом, которая стала заменой CVS из следующего поколения программ. Она обладает улучшенными возможностями, например: * предоставляется полный журнал версий для переименованных, перемещенных или удаленных файлов. * операции фиксирования неделимы (атомарны), это означает, что набор изменений проекта либо полностью попадает в репозиторий, либо, в случае ошибки подключения, не попадает совсем. * поддерживается контроль версий метаданных. image::images/netbeans-stamp-80-74-73.png[title=""Содержимое этой страницы применимо к IDE NetBeans 6.9 или более поздней версии""] *Для работы с этим учебным курсом требуются программное обеспечение и ресурсы, перечисленные ниже.* |=== |Программное обеспечение или материал |Требуемая версия |link:https://netbeans.org/downloads/index.html[+IDE NetBeans+] |версия 6.9, 7.0, 7.1, 7.2, 7.3, 7.4 или 8.0 |link:http://java.sun.com/javase/downloads/index.jsp[+Комплект для разработчика на языке Java (JDK)+] |версия 6, 7 или 8 |link:http://www.open.collab.net/downloads/netbeans/[+Клиентское программное обеспечение Subversion+] |1.6.x или более поздняя |=== NOTE: Входящий в комплект клиент Subversion можно установить как подключаемый модуль IDE NetBeans. Выберите 'Сервис' > 'Подключаемые модули', откройте вкладку 'Доступные подключаемые модули' и установите Bundled Subversion Client для Windows. == Настройка Subversion Прежде чем использовать все преимущества поддержки Subversion в среде IDE, необходимо установить клиентское программное обеспечение Subversion. Поддержка Subversion в среде IDE работает путем взаимодействия с клиентом ПО Subversion для выполнения команд контроля версий. В зависимости от системы и пути установки клиентского ПО Subversion, отличающегося от пути по умолчанию, может понадобиться зарегистрировать в среде IDE путь к исполнимому файлу Subversion. Наконец, необходимо убедиться в наличии репозитория Subversion, к которому будет производиться подключение. * <> * <> * <> === Получение программного обеспечения Необходимо убедиться, что на компьютере установлено следующее программное обеспечение: * IDE NetBeans (link:https://netbeans.org/downloads/index.html[+загрузка+]) * Java SE Development Kit (link:http://www.oracle.com/technetwork/java/javase/downloads/index.html[+загрузить+]) * Клиентское программное обеспечение Subversion (link:http://www.open.collab.net/downloads/netbeans/[+загрузить+]) === Укажите путь к исполнимому файлу Subversion. IDE NetBeans автоматически выполняет попытку определить местоположение исполняемого файла Subversion с помощью системной переменной `$PATH` на компьютере пользователя. Однако, в зависимости от платформы и пути установки клиентского ПО Subversion, отличающегося от пути по умолчанию, может понадобиться указать путь к исполнимому файлу Subversion явным образом. По умолчанию исполняемый файл Subversion установлен в папке `/usr/bin` или `/usr/local/bin/` на UNIX и OS X компьютера, а также в папке `C:\\Program Files\\Subversion\\bin\\` (или `C:\\Program Files\\CollabNet Subversion\\bin\\`) в Windows. На компьютерах под управлением *nix местоположение исполнимого файла Subversion можно определить, введя строку `which svn` в окно терминала. На компьютерах под управлением Windows можно запустить поиск файла `svn.exe` по всей системе. Чтобы указать путь к исполнимому файлу в среде IDE, выполните следующие действия: 1. Выберите 'Сервис' > 'Параметры' ('NetBeans'> 'Предпочтения' в OS X) в главном меню. Откроется диалоговое окно Options (""Параметры""). 2. Выберите значок Miscellaneous (""Разное"") наверху диалогового окна, затем щелкните вкладку Versioning (""Управление версии""). В левой панели под заголовком Versioning Systems (""Системы контроля версий"") выберите Subversion. Параметры пользователя Subversion отображаются в главном окне диалога: [.feature] -- image::images/svn-options-small.png[role=""left"", link=""images/svn-options.png""] -- [start=3] . В текстовом поле Specify the SVN Home Folder (""Указать домашний каталог SVN"") следует либо ввести путь к исполнимому файлу, либо нажать кнопку ""Обзор"" и найти этот путь в системе. Заметим, что нет нужды _включать_ в строку пути исполнимый файл Subversion. [start=4] . Нажмите кнопку ""ОК"" и перезапустите среду IDE, чтобы изменения вступили в силу. === Проверка наличия репозитория для подключения Прежде чем запускать Subversion из среды IDE, необходимо проверить наличие доступа к репозиторию Subversion. Среда IDE _не_ предоставляет средства создания репозиториев Subversion, поскольку эта функция редко используется (в производственной среде репозиторий создается только раз, после того как определится проект размещения репозитория). более того, в этой функции необходимы команды администрирования. Чтобы поэкспериментировать с поддержкой IDE, используя локальный репозиторий, можно его создать, используя средство link:http://svnbook.red-bean.com/en/1.1/ch09s02.html[+svnadmin+], которое включено в клиентское программное обеспечение Subversion. Чтобы создать репозиторий Subversion, используется команда `svnadmin create`. В командной строке введите следующее: [source,java] ---- svnadmin create /path/to/your/repository ---- Дополнительную информацию можно получить в главе link:http://svnbook.red-bean.com/en/1.1/ch05s02.html[+http://svnbook.red-bean.com/en/1.1/ch05s02.html+]. <> == Синхронизация локальных файлов с репозиторием При использовании системы контроля версий выполняется синхронизация локальных файлов с репозиторием, вносятся изменения в локальную копию, затем они фиксируются в репозитории. В следующем списке описываются различные способы синхронизации проекта в IDE NetBeans, в зависимости от определенной ситуации: * <> * <> * <> === Открытие проекта Subversion в среде IDE Если под контролем Subversion уже имеется проект, с которым ведется работа вне среды IDE, можно открыть его в IDE, и функции контроля версий станут для него доступны автоматически. Среда IDE проверяет открытые проекты на наличие каталогов `.svn`, и для версий проектов в Subversion состояния файлов и контекстно-зависимая поддержка автоматически становятся активными. === Получение файлов из репозитория Если необходимо подключиться к удаленному репозиторию из среды IDE, получить файлы и начать работу с ними, выполните следующее. 1. В IDE NetBeans в главном меню выберите 'Группа' > 'Subversion' > 'Извлечь'. Откроется мастер взятия для изменения. NOTE: Раскрывающееся меню IDE являются контекстно-зависимыми, то есть доступные параметры зависят от текущего выбранного элемента. Таким образом, во время работы с проектом в Subversion можно выбрать элемент Versioning (""Контроль версий"") > Checkout (""Извлечь"") в главном меню. [start=2] . На первой панели мастера введите URL-адрес, который содержит протокол подключения и путь к репозиторию, к которому необходимо подключиться. В среде IDE поддерживаются следующие типы протоколов: |=== |Протокол |Метод доступа |Пример |*файл* |Прямой доступ к репозиторию (на локальном диске) |`file:///путь_к_репозиторию` |*http* |Доступ к серверу с поддержкой Subversion через протокол WebDAV. |`http://имя_узла/путь_к_репозиторию` |*https* |Доступ через протокол HTTP с поддержкой шифрования SSL |`https://имя_узла/путь_к_репозиторию` |*svn* |Доступ через особый протокол к серверу `svnserve`. |`svn://имя_узла/путь_к_репозиторию` |*svn+ssh* |Доступ через протокол SVN с использованием внешнего туннеля SSH |`svn+ssh://имя_узла/путь_к_репозиторию` |=== В зависимости от используемого протокола может понадобиться ввести информацию, как, например, имя пользователя или пароль (для `http://`, `https://` или `svn://`), а в случае `svn+ssh://` необходимо указать команду для установления внешнего туннеля. NOTE: Если выполняется попытка реализации сертифицированной аутентификации с помощью `https`, см: раздел link:http://wiki.netbeans.org/wiki/view/FaqSslUserCert[+Подключение к репозиторию Subversion с помощью аутентификации, сертифицированной пользователем+] Дополнительные сведения с `svn+ssh` см. в разделе link:http://wiki.netbeans.org/wiki/view/FaqSubversionSSH[+Настройка SSH с использованием Subversion?+] . При использовании прокси необходимо нажать кнопку Proxy Configuration (""Настройка прокси-сервера"") и ввести всю необходимую информацию. Если вы не уверены в правильности параметров подключения к репозиторию, нажмите кнопку ""Далее"". . В поле Repository Folder(s) (""Каталог (-и) репозитория"") панели Folders to Checkout (""Каталоги для извлечения"") мастера настройте каталог, который необходимо взять для изменения. Если имя каталога, который необходимо взять для изменения, неизвестно, нажмите кнопку Browse (""Обзор""), чтобы просмотреть каталоги, которые хранятся в репозитории. В диалоговом окне Browse Repository Folders (""Обзор каталогов репозитория"") выберите любой из перечисленных каталогов и нажмите кнопку ""ОК"". Выбранный каталог потом добавляется в поле Repository Folder(s) ('Каталог (-и) репозитория') (каталог 'MyProject&' на снимке экрана ниже). [.feature] -- image::images/checkout-small.png[role=""left"", link=""images/checkout.png""] -- . Введите номер редакции в поле ""Редакция репозитория"" или оставьте его пустым, что приведет к взятию для изменения каталога _HEAD_ или более поздних редакций. . В поле Local Folder (""Локальный каталог"") введите путь к каталогу на компьютере, куда необходимо извлечь файлы. Оставьте установленным флажок ""Поиск проектов Netbeans после выгрузки"", затем нажмите ""Готово"", чтобы инициировать действие взятия. Среда IDE берёт указанные исходные коды для изменения, а в строке состояния IDE отображается ход выполнения загрузки файлов из репозитория в локальный рабочий каталог. Также можно просмотреть файлы и их изъятие в окне 'Выходные данные' (Ctrl-4 в Windows/Cmd-4 в OS X). NOTE: Если изъятые для использования источники содержат проекты NetBeans, отображается диалоговое окно с запросом на открытие их в IDE. Если в исходных файлах отсутствует проект, появится диалоговое окно с запросом на создание нового проекта из исходных файлов и их открытие в среде IDE. Чтобы создать проект из этих файлов, выберите соответствующую категорию проекта (в мастере создания проекта), затем используйте для нее пункт ""С существующими исходными кодами"". === Импорт файлов в репозиторий В качестве альтернативы можно импортировать проект, с котором вы работаете в среде IDE, в удаленный репозиторий, а затем продолжить с ним работу в среде IDE после его синхронизации. NOTE: При непосредственном _экспорте_ файлов из используемой системы термин 'импорт' используется в системах управления версиями для указания того, что файлы _импортируются в_ репозиторий. Чтобы импортировать проект в репозиторий, выполните следующее. 1. В окне 'Проекты' (Ctrl-1 в Windows/Cmd-1 в OS X) выберите проект, для которого не осуществляется управление версиями, и выберите 'Управление версиями' > 'Импорт в репозиторий Subversion' в меню правой кнопки мыши этого узла. Открывается мастер импорта в Subversion. 2. В панели ""Репозиторий Subversion"" мастера импорта укажите <> и путь к репозиторию Subversion, как определено в URL-адресе Subversion. В зависимости от сделанного выбора может понадобиться указать такие параметры, как имя пользователя и пароль для репозитория, или, в случае `svn+ssh://`, команду для установления внешнего туннеля. Дополнительные сведения см. в разделе link:http://wiki.netbeans.org/wiki/view/NetBeansUserFAQ#section-NetBeansUserFAQ-VersionControlSystems[+Часто задаваемые вопросы пользователей по Subversion+]. Нажмите кнопку ""Далее"". 3. В панели ""Каталог репозитория"" укажите каталог репозитория, в котором будет находиться проект. По умолчанию в текстовом поле ""Каталог репозитория"" предлагается каталог с названием, совпадающим с названием проекта. 4. В текстовом поле под заголовком ""Укажите сообщение"" введите описание проекта, который импортируется в репозиторий. 5. Нажмите кнопку ""Завершить"" для запуска импорта или кнопку ""Далее"" для перехода на третью панель, которая позволяет просматривать все файлы, приготовленные для импорта. В этой панели можно исключить из импорта отдельные файлы (как показано ниже) или определить типы MIME файлов перед импортом. [.feature] -- image::images/import-small.png[role=""left"", link=""images/import.png""] -- После нажатия кнопки ""Завершить"" среда IDE выгружает в репозиторий файлы проекта, и открывается окно вывода, в котором отображается ход импорта. <> == Изменение файлов исходного кода Если версия проекта Subversion открыта в среде IDE, можно начать вносить изменения в исходные файлы. Как и в любом проекте, открытом в IDE NetBeans, в редакторе исходного кода можно открывать файлы двойным щелчком на соответствующих узлах по мере их отображения в IDE (например, 'Проекты' (Ctrl-1 в Windows/Cmd-1 в OS X ), 'Файлы'(Ctrl-2 в Windows/Cmd-2 в OS X), 'Избранное' (Ctrl-3 в Windows/Cmd-3 в OS X)). При работе с файлами исходного кода в среде IDE можно пользоваться различными компонентами пользовательского интерфейса, помогающими как в просмотре, так и в работе с командами контроля версий: * <> * <> * <> * <> === Просмотр изменений в редакторе исходного кода При открытии файла с контролем версий в редакторе исходного кода IDE и внесении в него изменений их можно просматривать в реальном времени в сравнении с ранее полученной версией из репозитория. По ходу работы среда IDE использует условные цвета на полях редактора файлов исходного кода для передачи следующей информации: |=== |*Синий* (       ) |Обозначает строки, измененные по сравнению с более ранней версией. |*Зеленый* (       ) |Обозначает строки, добавленные к более ранней версии. |*Красный* (       ) |Обозначает строки, удаленные по сравнению с более ранней версией. |=== В левом поле редактора исходного кода отображаются изменения для каждой отдельной строки. При изменении определенной строки изменения немедленно показываются в левом поле. Можно щелкнуть группирование цвета в поле для вызова команд контроля версий. Например, на снимке экрана ниже показаны элементы оформления, доступные при щелчке красного значка, указывая, что строки были удалены из локальной копии. На правом поле редактора исходного кода предоставлен обзор изменений, внесенных в файл в целом, сверху донизу. Условные цвета применяются сразу после внесения изменений в файл. Обратите внимание, что можно щелкнуть определенную точку внутри поля, чтобы немедленно перенести курсор в строке к этому месту файла. Для просмотра числа затронутых строк наведите мышь на цветные значки в правом поле: |=== |[.feature] -- image::images/left-ui-small.png[role=""left"", link=""images/left-ui.png""] -- *Левое поле* |image:images/right-ui.png[title=""цветовая кодировка управления версиями отображается на правой границе редактора""] *Правое поле* |=== === Просмотр информации о состоянии файла При работе в окнах ""Проекты"" (CTRL+1 в системе Windows/CMD+1 в системе OS X), ""Файлы"" (CTRL+2 в системе Windows/CMD+2 в системе OS X), ""Избранное"" (CTRL+3 в системе Windows/CMD+3 в системе OS X) или окнах управления версиями некоторые функции отображения среды IDE помогают просматривать информацию о состоянии файла. В примере, приведенном ниже, обратите внимание, как метка (например, image:images/blue-badge.png[]), цвет имени файла и смежная метка состояния соответствуют друг другу для предоставления для пользователей простого и эффективного способа отслеживания данных об изменениях версий файлов: image::images/badge-example.png[] Метки, условные цвета, ярлыки состояния файлов и, что, пожалуй, наиболее важно, окно контроля версий вместе дают дополнительные возможности по просмотру и управлению сведениями о версиях в среде IDE. * <> * <> * <> ==== Метки и условные цвета Метки относятся к узлам проектов, папок и пакетов. Они сообщают о состоянии файлов внутри соответствующего узла: Ниже в таблице приведена цветовая схема, используемая для меток. |=== |Элемент пользовательского интерфейса |Описание |*Синяя метка* (image:images/blue-badge.png[]) |Указывает на присутствие файлов, которые были локально изменены, добавлены или удалены. Касательно пакетов, данная метка относится только к самому пакету, но не к его подпакетам. Что касается проектов и папок, метка указывает на изменения как внутри самого элемента, так и внутри любых его подпапок. |*Красная метка* (image:images/red-badge.png[]) |Используется для проектов, папок и пакетов, содержащих _конфликтующие_ файлы (например, локальные версии, конфликтующие с версиями, хранящимися в репозитории). Касательно пакетов, данная метка относится только к самому пакету, но не к его подпакетам. Для проектов и папок метка обозначает конфликты этого элемента и всех содержащихся подпапок. |=== Цветовое обозначение применяется к именам файлов для обозначения их текущего состояния по сравнению с репозиторием: |=== |Цвет |Пример |Описание |*Синий* |image:images/blue-text.png[] |Обозначает локально измененный файл. |*Зеленый* |image:images/green-text.png[] |Обозначает локально добавленный файл. |*Красный* |image:images/red-text.png[] |Обозначает, что файл содержит конфликт между локальной рабочей копией и версией в репозитории. |*Серый* |image:images/gray-text.png[] |Указывает но то, что файл пропущен системой Subversion и не будет обработан командами контроля версий (такими как ""Update"" (Обновить) и ""Commit"" (Зафиксировать)). Файлы можно сделать игнорируемыми, только если они еще не добавлены под контроль версий. |*Перечеркивание* |image:images/strike-through-text.png[] |Указывает на то, что файл исключен из операций фиксации. Перечеркнутый текст отображается только в некоторых местах, например, окно ""Контроль версий"" или диалоговое окно ""Фиксация"", при исключении отдельных файлов из действия фиксации. Такие файлы всё еще могут быть затронуты командами Subversion, такими как ""Update"" (Обновить). |=== ==== Ярлыки состояния файлов Ярлыки состояния файлов предоставляют в окнах среды IDE текстовое указание на состояние файлов, включенных в управление версиями. По умолчанию в окнах среды IDE состояние (новый, измененный, игнорируется и т.п.) и информация о папке отображаются в сером цвете справа от файлов, представленных в виде списка. Однако этот формат можно изменить под свои потребности. Например, для добавления номеров редакций к ярлыкам состояния выполните следующее. 1. Выберите 'Сервис' > 'Параметры' ('NetBeans'> 'Предпочтения' на OS X) в главном меню. Откроется окно ""Options"". 2. Выберите кнопку Miscellaneous (""Разное"") наверху диалогового окна, затем щелкните вкладку Versioning (""Контроль версий"") под ним. Убедитесь, что в левой панели под системами управления версиями выбрана система Subversion. (Для справки см. <> выше). 3. Нажмите кнопку Add Variable (""Добавить переменную"") справа от текстового поля строки состояния Format (""Формат""). В открывшемся диалоговом окне"" Добавление переменной"" выберите переменную`{revision}` и нажмите ""ОК"". Переменная revision добавляется в текстовое поле ""Формат ярлыка состояния"". 4. Переформатировать метки состояний так, чтобы справа от файлов отображались только их состояние и редакция, можно, изменив порядок следования содержимое текстового поля ""Формат меток состояний"" на следующий: [source,java] ---- [{status}; {revision}] ---- Нажмите кнопку ""ОК"". Ярлыки состояния теперь показывают состояние файла и номер редакции (где это применимо). Ярлыки состояния файлов можно включать и отключать. Для этого в главном меню выберите ""Вид"" > ""Показать ярлыки контроля версий"". image::images/file-labels.png[] Ярлыки состояния файлов можно включать и отключать. Для этого в главном меню выберите ""Вид"" > ""Показать ярлыки контроля версий"". ==== Окно контроля версий Окно контроля версий в Subversion предоставляет в реальном времени список всех изменений, произведенных с файлами локальной рабочей копии выбранной папки. По умолчанию оно открывается в нижней панели среды IDE, и в нем перечислены добавленные, удаленные и измененные файлы. Чтобы открыть окно контроля версий, выберите версию файла или каталога (например, из окна ""Проекты"", ""Файлы"" или ""Избранное"") и либо выберите ""Subversion"" > ""Показать изменения"" из контекстного меню, либо ""Группа"" > ""Показать изменения"" из главного меню. В нижней панели среды IDE откроется следующее окно: [.feature] -- image::images/versioning-window-small.png[role=""left"", link=""images/versioning-window.png""] -- По умолчанию в окне контроля версий отображается список измененных файлов в выбранном пакете или папке. Кнопки на панели инструментов используются для выбора отображения всех изменений или ограничения списка отображаемых файлов локальными или удаленными измененными файлами. Также можно щелкнуть заголовки столбцов над перечисленными файлами, чтобы отсортировать их по имени, состоянию или местоположению. *Примечания* * Для получения уведомления об изменении исходного файла в одном из открытых проектов выберите 'Группа' > 'Показать изменения' в главном меню. Либо если открыто окно 'Управление версиями', можно нажать кнопку 'Обновить состояние'. * Операции в окне 'Проекты' выполняются только над проектами и не являются рекурсивными. Для отображения изменений вложенных/дочерних проектов можно использовать окно 'Файлы' или 'Избранное'. На панели инструментов окна контроля версий имеются кнопки, которые позволяют назначать самые распространенные задачи Subversion любому файлу из списка. В приведенной ниже таблице дан список команд Subversion, которые доступны из панели инструментов окна контроля версий. |=== |Значок |Имя |Функция |image:images/refresh.png[] |*Refresh Status (""Обновить состояние"")* |Обновление состояния всех выбранных файлов и папок. Файлы, отображаемые в окне контроля версий, можно обновить для отражения любых изменений, внесенных извне. |image:images/diff.png[] |*Diff All (""Сравнить все"")* |Открытие представления различий, предоставляющее параллельное сравнение локальных копий и версий в репозитории. |image:images/update.png[] |*Update All (""Обновить все"")* |Обновление всех выбранных файлов в репозитории. |image:images/commit.png[] |*Фиксировать все* |Позволяет фиксировать локальные изменения в репозитории. |=== Для доступа к другим командам Subversion в окне контроля версий необходимо выбрать строку таблицы, соответствующую измененному файлу, а затем выбрать команду в контекстом меню: image::images/versioning-right-click.png[] Для примера, с файлом можно выполнить следующие действия: |=== |* *Показать аннотации*: Сведения об авторе и номере редакции в левом поле файлов, открытых в редакторе исходных файлов. |image:images/annotations.png[] |* *Поиск в журнале*: Позволяет искать и сравнивать ранние редакции выбранного файла в окне просмотра журнала в среде IDE. Из окна просмотра журнала можно вызвать команду <> или вернуть текущую локальную копию в состояние выбранной редакции. |[.feature] -- image::images/history-viewer-small.png[role=""left"", link=""images/history-viewer.png""] -- |* *Исключить из фиксации*: Позволяет исключить файл из процесса фиксации. |[.feature] -- image::images/exclude-from-commit-small.png[role=""left"", link=""images/exclude-from-commit.png""] -- |* *Откатить удаление* Открывает диалоговое окно ""Откатить изменения"", при помощи которого можно откатывать любые действия по удалению локальных копий файлов. Указанные файлы извлекаются из локального архива журнала и восстанавливаются в локальную рабочую копию. |[.feature] -- image::images/revert-mods-small.png[role=""left"", link=""images/revert-mods.png""] -- |* *Откатить изменения*: Открывает диалоговое окно ""Откатить изменения"", при помощи которого можно указать параметры отката любых локальных изменений для редакций, которые хранятся в репозитории. При указании редакций можно нажать кнопку ""Поиск"", чтобы открыть диалоговое окно ""Поиск редакции"". Произойдет поиск по репозиторию и вывод редакций в зависимости от введенной даты. |[.feature] -- image::images/search-rev-small.png[role=""left"", link=""images/search-rev.png""] -- |=== === Сравнение редакций файлов Сравнение редакций файлов — это распространенная задача при работу с проектами с контролем версий. Среда IDE позволяет сравнивать редакции, используя команду Diff, доступную в контекстном меню выбранного элемента (Subversion > Diff), а также в окне контроля версий. В окне 'Управление версиями', вы можете выполнить сравнение либо двойным щелчком указанного файла, либо щелкнув значок 'Сравнить все' (image:images/diff.png[]), расположенный на панели инструментов в верхней части. При выполнении сравнения откроется средство просмотра различий для выбранного файла(-в) и редакций в главном окне IDE. В средстве просмотра различий отображаются две копии на параллельных панелях. Текущая копия отображается в правой части, поэтому при сравнении копии в репозитории с рабочей копией последняя отображается на правой панели: [.feature] -- image::images/diff-viewer-small.png[role=""left"", link=""images/diff-viewer.png""] -- В просмотре различий используются те же <>, что используются и в других местах для показа изменений под контролем версий. На снимке экрана выше зеленый блок обозначает содержание, добавленное к последней редакции. Красный блок указывает, что содержание из ранней редакции было позднее удалено. Синий указывает, что в выделенных строках произошли изменения. Также при выполнении сравнения в группе файлов, таких, как проект, пакет или папка, или при щелчке 'Сравнить все' (image:images/diff.png[]), вы можете переключаться между различиями с помощью щелчков файлов, перечисленных в верхней области 'Средства просмотра различий'. Средство просмотра различий также предоставляет следующие функции: * <> * <> * <> ==== Внесение изменений в локальную рабочую копию При выполнении различия с локальной рабочей копией среда IDE позволяет вносить изменения непосредственно в средстве просмотра различий. Чтобы сделать это, поместите свой курсор внутри правой панели просмотра различий и измените свой файл соответственно, либо используйте значки, отображающиеся в строке рядом с каждым выделенным изменением: |=== |*Заменить* (image:images/insert.png[]): |Вставка выделенного текста из предыдущей редакции в текущую редакцию |*Переместить все* (image:images/arrow.png[]): |Откат текущей редакции файла к состоянию предыдущей выбранной редакции |*Удалить * (image:images/remove.png[]): |Удаление выделенного текста из текущей редакции для зеркального соответствия предыдущей редакции |=== ==== Переходы между различиями в сравниваемых файлах Если сравнение содержит несколько изменений, между ними можно переходить, используя значки стрелок, отображающиеся на панели инструментов. Значки стрелок позволяют просматривать появляющиеся различия сверху донизу: |=== |*Предыдущий* (image:images/diff-prev.png[]): |переход к предыдущему различию, отображенному в сравнении. |*Далее* (image:images/diff-next.png[]): |переход к следующему различию, отображенному в сравнении. |=== ==== Изменение критериев просмотра Можно выбрать просмотр файлов, содержащих изменения, из локальной рабочей копии, репозитория, или одновременно просмотреть оба файла одновременно: |=== |*Локальный* ( image:images/locally-mod.png[] ): |Отображение только локально измененных файлов |*Удаленный* ( image:images/remotely-mod.png[] ): |Отображение только удаленно измененных файлов |*Оба* ( image:images/both-mod.png[] ): |Отображение локально и удаленно измененных файлов |=== NOTE: Цветовая схема, описанная в разделе <> не применяется для приведенных выше значков. === Слияние редакций файлов IDE NetBeans обеспечивает возможность слияния изменений между версиями репозитория и локальной рабочей копии. Можно указать диапазон редакций для слияния. Можно даже объединять диапазон редакций из двух разных каталогов репозитория. Обычно используется следующая схема работы: имеется взятая из головной ветви версия, сохраненная в папке под именем `JavaApp`, и требуется произвести слияние этой копии с ветвью. В целях демонстрации репозиторий содержит каталог `branches`, в котором находятся все ответвленные файлы: 1. В окне 'Проекты', 'Файлы' или 'Избранное' правой кнопкой мыши щелкните файлы или папки, для которых необходимо выполнить операцию слияния, и выберите 'Subversion' > 'Объединить изменения'. Появляется диалоговое окно Merge (""Слияние""). 2. В раскрывающемся списке Merge From (""Слить из"") выберите One Repository Folder Since Its Origin (""Одна папка репозитория после создания""). Переносятся все изменения, которые были сделаны в отдельном файле после его создания. 3. В текстовом поле папки репозитория введите путь к папке, из которой необходимо перенести изменения (`branches/JavaApp`). Оставьте поле ""Конечная редакция"" пустым, чтобы включить все редакции от первой до _HEAD_ (то есть текущего состояния). [.feature] -- image::images/svn-merge-small.png[role=""left"", link=""images/svn-merge.png""] -- . Щелкните ""Слить"". Среда IDE объединит все различия, которые будут найдены между редакциями ветви и локальной копией файла. При возникновении конфликтов слияния устанавливается состояние файла <> для указания на это. NOTE: После слияния изменений с локальной рабочей копией, все равно необходимо зафиксировать изменения, используя команду Commit для того, чтобы они были добавлены в репозиторий. <> == Фиксация исходных файлов в репозитории После внесения изменений в исходные файла необходимо выполнить их фиксацию в репозитории. Как правило, рекомендуется обновить все копии в соответствии с репозиторием до выполнения фиксации, чтобы обеспечить отсутствие конфликтов. Однако конфликты все равно могут возникать и должны считаться обычным явлением при одновременной работе с проектом множества разработчиков. Среда IDE предоставляет гибкую поддержку, позволяющую выполнять все эти функции. Она также предоставляет компонент разрешения конфликтов, позволяющий корректно устранять конфликты при их возникновении. * <> * <> * <> === Обновление локальных копий Обновление выполняются путем выбора 'Subversion' > 'Обновить' из контекстного меню любого элемента, для которого осуществляется управление версиями, в окнах 'Проекты', 'Файлы' или 'Избранное'. При работе напрямую из окна 'Управление версиями' нужно просто щелкнуть правой кнопкой мыши указанный файл и выбрать 'Обновить'. Чтобы выполнить обновление всех исходных файлов, можно нажать кнопку 'Обновить все' (image:images/update.png[]) на панели инструментов, расположенной в верхней части окон <> и <>. Все изменения, которые могли быть внесены в репозитории, отображаются в окне ""Вывод версий"". === Разрешение конфликтов При обновлении или фиксировании файлов средства поддержки Subversion сравнивают файлы с исходными файлами из репозитория, чтобы убедиться, что те же файлы уже не изменены ранее. Если извлеченная (или обновленная) редакция больше не совпадает с _HEAD_ репозитория (т.е. с текущей версией), _и_ области кода, которые изменялись в локальной копии, совпадают с областями в HEAD, которые также изменены, обновление или фиксирование приводят к _конфликтам_. Как указано в <>, конфликты выделяются в среде IDE красным текстом и рядом с ними отображается красный значок (image:images/red-badge.png[]) при просмотре в окнах 'Проекты', 'Файлы', или 'Избранное'. В окне ""Контроль версий"" конфликты отмечены состоянием файлов. image::images/conflict-versioning-win.png[] Любой возникший конфликт необходимо разрешить, прежде чем выполнять фиксацию в репозиторий. В среде IDE конфликты можно разрешить с помощью средства разрешения конфликтов слияния. Средство разрешения конфликтов слияния предлагает интуитивно понятный интерфейс, помогающий последовательно разрешать отдельные конфликты во время просмотра результатов слияния. Для получения доступа к средству разрешения конфликтов слияния в конфликтующем файле щелкните правой кнопкой мыши этот файл и выберите 'Subversion' > 'Разрещить конфликты'. Средство разрешения конфликтов слияния отображает две конфликтующие копии рядом на верхней панели, выделяя при этом конфликтующие области. На нижней панели изображен файл так, как он отображается во время слияния для отдельных конфликтов между двумя редакциями: [.feature] -- image::images/conflict-resolver-small.png[role=""left"", link=""images/conflict-resolver.png""] -- Для разрешения конфликта примите одну из двух редакций, которые отображаются на верхней панели. В редакции, которую необходимо принять нажмите кнопку ""Принять"". Среда IDE сливает принятую редакцию с исходным файлом, и результаты слияния мгновенно отображаются на нижней панели разрешителя конфликтов слияния. Когда все конфликты будут разрешены, нажмите ""ОК"" для выхода из средства разрешения конфликтов слияния и сохранения измененного файла. Метка конфликта будет удалена, и файл можно будет фиксировать в репозитории. === Выполнение фиксации После редактирования исходных файлов, выполнения обновления и устранения конфликтов выполняется фиксация файлов из локальной рабочей копии в репозиторий. Среда IDE позволяет вызывать команду фиксации следующими способами: * В окне 'Проекты', 'Файлы' или 'Избранное' правой кнопкой мыши щелкните новые или измененные элементы и выберите 'Subversion' > 'Фиксация'. * В окне 'Управление версиями' или 'Средства просмотра различий' нажмите кнопку 'Фиксировать все' (image:images/commit.png[]) на панели инструментов. Откроется диалоговое окно ""Фиксация"", в котором отображаются файлы для фиксации в репозитории: [.feature] -- image::images/commit-dialog-small.png[role=""left"", link=""images/commit-dialog.png""] -- В диалоговом окне ""Фиксация"" перечислено следующее: * все локально измененные файлы; * все файлы, которые были локально удалены; * все новые файлы (то есть, файлы, которых пока нет в репозитории); * все файлы, которые были переименованы. Для хранения переименованных файлов в Subversion удаляются исходные файлы и создаются дубликаты с новым именем. В диалоговом окне ""Фиксация"" можно указать исключение отдельных файлов из фиксации. Для этого щелкните столбец ""Действие фиксации"" для выбранного файла и выберите пункт ""Исключить из фиксации"" в раскрывающемся списке. Аналогично, при включении новых файлов можно указать тип MIME, выбрав ""Добавить как исходный файл"" или ""Добавить как текст"" в раскрывающемся списке. Для фиксации выполните следующее. 1. Введите сообщение о фиксации в текстовой области ""Сообщение о фиксации"". В качестве альтернативы щелкните значок 'Последние сообщения' ( image:images/recent-msgs.png[] ), расположенный в правом верхнем углу, чтобы просмотреть и выбрать необходимое из ранее использованного списка сообщений. 2. После указания действий для отдельных файлов щелкните ""Фиксация"". Среда IDE выполнит фиксацию и отправит локальные изменения в репозиторий. В строке состояния IDE, расположенной в правой нижней части интерфейса, отображается выполнение действия фиксации. При успешной фиксации метки контроля версий перестают отображаться в окнах ""Проекты"", ""Файлы"" и ""Избранное"", а для цветового обозначения фиксированных файлов используется черный цвет. <> == Заключение На этом завершается обзор возможностей Subversion для IDE NetBeans версии 6.x и более поздних версий. В данном документе описано выполнение основных задач контроля версий в среде IDE на примере стандартного порядка действий при использовании поддержки Subversion в среде IDE. В руководстве показано, как настраивать версию проекта и выполнять основные задачи для файлов под контролем версий с помощью некоторых новых функции Subversion в среде IDE. link:/about/contact_form.html?to=3&subject=Feedback:%20Using%20Subversion%20Support%20in%20NetBeans%20IDE[+Отправить отзыв по этому учебному курсу+] <> == Дополнительные сведения Материалы на связанные темы: * link:http://wiki.netbeans.org/wiki/view/NetBeansUserFAQ#section-NetBeansUserFAQ-VersionControlSystems[+Часто задаваемые вопросы по поддержке Subversion для IDE NetBeans+] * link:http://wiki.netbeans.org/FaqSubversionClients[+Часто задаваемые вопросы о клиентах Subversion+] * link:git.html[+Использование поддержки Git в IDE NetBeans+] * link:mercurial.html[+Использование поддержки Mercurial в IDE NetBeans+] * link:mercurial-queues.html[+Использование поддержки Mercurial Queues в IDE NetBeans+] * link:cvs.html[+Использование поддержки CVS в IDE NetBeans+] * link:clearcase.html[+Использование поддержки ClearCase в IDE NetBeans+] * link:http://www.oracle.com/pls/topic/lookup?ctx=nb8000&id=NBDAG234[+Управление версиями приложений с помощью системы контроля версий+] в _Разработка приложений с помощью IDE NetBeans_. <> ",12452,False,2472.834309947145,median "= Spring for GraphQL Documentation Brian Clozel; Andreas Marek; Rossen Stoyanchev; Mark Paluch include::attributes.adoc[] [[overview]] == Overview Spring for GraphQL provides support for Spring applications built on https://www.graphql-java.com/[GraphQL Java]. It is a joint collaboration between both teams. Our shared philosophy is to be less opinionated and more focused on comprehensive and wide-ranging support. Spring for GraphQL is the successor of the https://github.com/graphql-java/graphql-java-spring[GraphQL Java Spring] project from the GraphQL Java team. It aims to be the foundation for all Spring, GraphQL applications. The project is in a milestone phase towards a 1.0 release, currently, and looking for feedback. Please, use our https://github.com/spring-projects/spring-graphql/issues[issue tracker] to report a problem, discuss a design issue, or request a feature. To get started, check the Spring GraphQL starter on https://start.spring.io and the <> sections. [[requirements]] == Requirements Spring for GraphQL requires the following as a baseline: * JDK8 * Spring Framework 5.3 * GraphQL Java 17 * Spring Data 2021.1.0 or later for QueryDSL or Query by Example [[web-transports]] == Web Transports Spring for GraphQL supports GraphQL requests over HTTP and over WebSocket. [[web-http]] === HTTP `GraphQlHttpHandler` handles GraphQL over HTTP requests and delegates to the <> chain for request execution. There are two variants, one for Spring MVC and one for Spring WebFlux. Both handle requests asynchronously and have equivalent functionality, but rely on blocking vs non-blocking I/O respectively for writing the HTTP response. Requests must use HTTP POST with GraphQL request details included as JSON in the request body, as defined in the proposed https://github.com/graphql/graphql-over-http/blob/main/spec/GraphQLOverHTTP.md[GraphQL over HTTP] specification. Once the JSON body has been successfully decoded, the HTTP response status is always 200 (OK), and any errors from GraphQL request execution appear in the ""errors"" section of the GraphQL response. `GraphQlHttpHandler` can be exposed as an HTTP endpoint by declaring a `RouterFunction` bean and using the `RouterFunctions` from Spring MVC or WebFlux to create the route. The Boot starter does this, see the {spring-boot-ref-docs}/web.html#web.graphql.web-endpoints[Web Endpoints] section for details, or check `GraphQlWebMvcAutoConfiguration` or `GraphQlWebFluxAutoConfiguration` it contains, for the actual config. The Spring for GraphQL repository contains a Spring MVC {github-main-branch}/samples/webmvc-http[HTTP sample] application. [[web-websocket]] === WebSocket `GraphQlWebSocketHandler` handles GraphQL over WebSocket requests based on the https://github.com/enisdenjo/graphql-ws/blob/master/PROTOCOL.md[protocol] defined in the https://github.com/enisdenjo/graphql-ws[graphql-ws] library. The main reason to use GraphQL over WebSocket is subscriptions which allow sending a stream of GraphQL responses, but it can also be used for regular queries with a single response. The handler delegates every request to the <> chain for further request execution. [TIP] .GraphQL Over WebSocket Protocols ==== There are two such protocols, one in the https://github.com/apollographql/subscriptions-transport-ws[subscriptions-transport-ws] library and another in the https://github.com/enisdenjo/graphql-ws[graphql-ws] library. The former is not active and succeeded by the latter. Read this https://the-guild.dev/blog/graphql-over-websockets[blog post] for the history. ==== There are two variants of `GraphQlWebSocketHandler`, one for Spring MVC and one for Spring WebFlux. Both handle requests asynchronously and have equivalent functionality. The WebFlux handler also uses non-blocking I/O and back pressure to stream messages, which works well since in GraphQL Java a subscription response is a Reactive Streams `Publisher`. The `graphql-ws` project lists a number of https://github.com/enisdenjo/graphql-ws#recipes[recipes] for client use. `GraphQlWebSocketHandler` can be exposed as a WebSocket endpoint by declaring a `SimpleUrlHandlerMapping` bean and using it to map the handler to a URL path. The Boot starter has options to enable this, see the {spring-boot-ref-docs}/web.html#web.graphql.web-endpoints[Web Endpoints] section for details, or check `GraphQlWebMvcAutoConfiguration` or `GraphQlWebFluxAutoConfiguration` it contains, for the actual config. The Spring for GraphQL repository contains a WebFlux {github-main-branch}/samples/webflux-websocket[WebSocket sample] application. [[web-interception]] === Web Interception <> and <> transport handlers delegate to a common Web interception chain for request execution. The chain consists of a sequence of `WebGraphQlHandlerInterceptor` components, followed by a `ExecutionGraphQlService` that invokes GraphQL Java. `WebGraphQlHandlerInterceptor` is as a common contract to use in both Spring MVC and WebFlux applications. Use it to intercept requests, inspect HTTP request headers, or to register a transformation of the `graphql.ExecutionInput`: [source,java,indent=0,subs=""verbatim,quotes""] ---- class MyInterceptor implements WebGraphQlHandlerInterceptor { @Override public Mono intercept(WebGraphQlRequest request, Chain chain) { request.configureExecutionInput((executionInput, builder) -> { Map map = ... ; return builder.extensions(map).build(); }); return chain.next(request); } } ---- Use `WebGraphQlHandlerInterceptor` also to intercept responses, add HTTP response headers, or transform the `graphql.ExecutionResult`: [source,java,indent=0,subs=""verbatim,quotes""] ---- class MyInterceptor implements WebGraphQlHandlerInterceptor { @Override public Mono intercept(WebGraphQlRequest request, Chain chain) { return chain.next(request) .map(response -> { Object data = response.getData(); Object updatedData = ... ; return response.transform(builder -> builder.data(updatedData)); }); } } ---- `WebGraphQlHandler` provides a builder to initialize the Web interception chain. After you build the chain, you can use the resulting `WebGraphQlHandler` to initialize the HTTP or WebSocket transport handlers. The Boot starter configures all this, see the {spring-boot-ref-docs}/web.html#web.graphql.web-endpoints[Web Endpoints] section for details, or check `GraphQlWebMvcAutoConfiguration` or `GraphQlWebFluxAutoConfiguration` it contains, for the actual config. [[execution]] == Request Execution `ExecutionGraphQlService` is the main Spring abstraction to call GraphQL Java to execute requests. Underlying transports, such as the <>, delegate to `ExecutionGraphQlService` to handle requests. The main implementation, `DefaultExecutionGraphQlService`, is configured with a `GraphQlSource` for access to the `graphql.GraphQL` instance to invoke. [[execution-graphqlsource]] === `GraphQLSource` `GraphQlSource` is a core Spring abstraction for access to the `graphql.GraphQL` instance to use for request execution. It provides a builder API to initialize GraphQL Java and build a `GraphQlSource`. The default `GraphQlSource` builder, accessible via `GraphQlSource.builder()`, enables support for <>, <>, and <>. The Spring Boot {spring-boot-ref-docs}/web.html#web.graphql[starter] initializes a `GraphQlSource` instance through the default `GraphQlSource.Builder` and also enables the following: - Load <> from a configurable location. - Expose {spring-boot-ref-docs}/application-properties.html#appendix.application-properties.web[properties] that apply to `GraphQlSource.Builder`. - Detect <> beans. - Detect https://www.graphql-java.com/documentation/instrumentation[Instrumentation] beans for {spring-boot-ref-docs}/actuator.html#actuator.metrics.supported.spring-graphql[GraphQL metrics]. - Detect `DataFetcherExceptionResolver` beans for <>. For further customizations, you can declare your own `GraphQlSourceBuilderCustomizer` beans; for example, for configuring your own `ExecutionIdProvider`: [source,java,indent=0,subs=""verbatim,quotes""] ---- @Configuration(proxyBeanMethods = false) class GraphQlConfig { @Bean public GraphQlSourceBuilderCustomizer sourceBuilderCustomizer() { return (builder) -> { builder.configureGraphQl(graphQlBuilder -> graphQlBuilder.executionIdProvider(new CustomExecutionIdProvider())); }; } } ---- [[execution-graphqlsource-schema-resources]] ==== Schema Resources `GraphQlSource.Builder` can be configured with one or more `Resource` instances to be parsed and merged together. That means schema files can be loaded from just about any location. By default, the Spring Boot starter {spring-boot-ref-docs}/web.html#web.graphql.schema[finds schema files] from a well-known classpath location, but you can change that to a location on the file system via `FileSystemResource`, to byte content via `ByteArrayResource`, or implement a custom `Resource` that loads schema files from a remote location or storage. [[execution-graphqlsource-schema-creation]] ==== Schema Creation By default, `GraphQlSource.Builder` uses the GraphQL Java `GraphQLSchemaGenerator` to create the `graphql.schema.GraphQLSchema`. This works for most applications, but if necessary, you can hook into the schema creation through the builder: [source,java,indent=0,subs=""verbatim,quotes""] ---- GraphQlSource.Builder builder = ... builder.schemaResources(..) .configureRuntimeWiring(..) .schemaFactory((typeDefinitionRegistry, runtimeWiring) -> { // create GraphQLSchema }) ---- The primary reason for this is to create the schema through a federation library. The <> explains how to configure that with Spring Boot. [[execution-graphqlsource-runtimewiring-configurer]] ==== `RuntimeWiringConfigurer` You can use `RuntimeWiringConfigurer` to register: - Custom scalar types. - Directives handling code. - `TypeResolver`, if you need to override the <> for a type. - `DataFetcher` for a field, although most applications will simply configure `AnnotatedControllerConfigurer`, which detects annotated, `DataFetcher` handler methods. The Spring Boot starter adds the `AnnotatedControllerConfigurer` by default. NOTE: Unlike web frameworks, GraphQL does not use Jackson annotations to drive JSON serialization/deserialization. Custom data types and their serialization https://www.graphql-java.com/documentation/scalars/[must be described as Scalars]. The Spring Boot starter detects beans of type `RuntimeWiringConfigurer` and registers them in the `GraphQlSource.Builder`. That means in most cases, you'll' have something like the following in your configuration: [source,java,indent=0,subs=""verbatim,quotes""] ---- @Configuration public class GraphQlConfig { @Bean public RuntimeWiringConfigurer runtimeWiringConfigurer(BookRepository repository) { GraphQLScalarType scalarType = ... ; SchemaDirectiveWiring directiveWiring = ... ; DataFetcher dataFetcher = QuerydslDataFetcher.builder(repository).single(); return wiringBuilder -> wiringBuilder .scalar(scalarType) .directiveWiring(directiveWiring) .type(""Query"", builder -> builder.dataFetcher(""book"", dataFetcher)); } } ---- If you need to add a `WiringFactory`, e.g. to make registrations that take into account schema definitions, implement the alternative `configure` method that accepts both the `RuntimeWiring.Builder` and an output `List`. This allows you to add any number of factories that are then invoked in sequence. [[execution-graphqlsource-default-type-resolver]] ==== Default `TypeResolver` `GraphQlSource.Builder` registers `ClassNameTypeResolver` as the default `TypeResolver` to use for GraphQL Interfaces and Unions that don't already have such a registration through a <>. The purpose of a `TypeResolver` in GraphQL Java is to determine the GraphQL Object type for values returned from the `DataFetcher` for a GraphQL Interface or Union field. `ClassNameTypeResolver` tries to match the simple class name of the value to a GraphQL Object Type and if it is not successful, it also navigates its super types including base classes and interfaces, looking for a match. `ClassNameTypeResolver` provides an option to configure a name extracting function along with `Class` to GraphQL Object type name mappings that should help to cover more corner cases: [source,java,indent=0,subs=""verbatim,quotes""] ---- GraphQlSource.Builder builder = ... ClassNameTypeResolver classNameTypeResolver = new ClassNameTypeResolver(); classNameTypeResolver.setClassNameExtractor((klass) -> { // Implement Custom ClassName Extractor here }); builder.defaultTypeResolver(classNameTypeResolver); ---- The <> explains how to configure that with Spring Boot. [[execution-graphqlsource-operation-caching]] ==== Operation Caching GraphQL Java must _parse_ and _validate_ an operation before executing it. This may impact performance significantly. To avoid the need to re-parse and validate, an application may configure a `PreparsedDocumentProvider` that caches and reuses Document instances. The {graphql-java-docs}/execution/#query-caching[GraphQL Java docs] provide more details on query caching through a `PreparsedDocumentProvider`. In Spring GraphQL you can register a `PreparsedDocumentProvider` through `GraphQlSource.Builder#configureGraphQl`: . [source,java,indent=0,subs=""verbatim,quotes""] ---- // Typically, accessed through Spring Boot's GraphQlSourceBuilderCustomizer GraphQlSource.Builder builder = ... // Create provider PreparsedDocumentProvider provider = ... builder.schemaResources(..) .configureRuntimeWiring(..) .configureGraphQl(graphQLBuilder -> graphQLBuilder.preparsedDocumentProvider(provider)) ---- The <> explains how to configure that with Spring Boot. [[execution-graphqlsource-directives]] ==== Directives The GraphQL language supports directives that ""describe alternate runtime execution and type validation behavior in a GraphQL document"". Directives are similar to annotations in Java but declared on types, fields, fragments and operations in a GraphQL document. GraphQL Java provides the `SchemaDirectiveWiring` contract to help applications detect and handle directives. For more details, see {graphql-java-docs}/sdl-directives/[Schema Directives] in the GraphQL Java documentation. In Spring GraphQL you can register a `SchemaDirectiveWiring` through a <>. The Spring Boot starter detects such beans, so you might have something like: [source,java,indent=0,subs=""verbatim,quotes""] ---- @Configuration public class GraphQlConfig { @Bean public RuntimeWiringConfigurer runtimeWiringConfigurer() { return builder -> builder.directiveWiring(new MySchemaDirectiveWiring()); } } ---- TIP: For an example of directives support check out the https://github.com/graphql-java/graphql-java-extended-validation[Extended Validation for Graphql Java] library. [[execution-reactive-datafetcher]] === Reactive `DataFetcher` The default `GraphQlSource` builder enables support for a `DataFetcher` to return `Mono` or `Flux` which adapts those to a `CompletableFuture` where `Flux` values are aggregated and turned into a List, unless the request is a GraphQL subscription request, in which case the return value remains a Reactive Streams `Publisher` for streaming GraphQL responses. A reactive `DataFetcher` can rely on access to Reactor context propagated from the transport layer, such as from a WebFlux request handling, see <>. [[execution-context]] === Context Propagation Spring for GraphQL provides support to transparently propagate context from the <>, through GraphQL Java, and to `DataFetcher` and other components it invokes. This includes both `ThreadLocal` context from the Spring MVC request handling thread and Reactor `Context` from the WebFlux processing pipeline. [[execution-context-webmvc]] ==== WebMvc A `DataFetcher` and other components invoked by GraphQL Java may not always execute on the same thread as the Spring MVC handler, for example if an asynchronous <> or `DataFetcher` switches to a different thread. Spring for GraphQL supports propagating `ThreadLocal` values from the Servlet container thread to the thread a `DataFetcher` and other components invoked by GraphQL Java to execute on. To do this, an application needs to create a `ThreadLocalAccessor` to extract `ThreadLocal` values of interest: [source,java,indent=0,subs=""verbatim,quotes""] ---- public class RequestAttributesAccessor implements ThreadLocalAccessor { private static final String KEY = RequestAttributesAccessor.class.getName(); @Override public void extractValues(Map container) { container.put(KEY, RequestContextHolder.getRequestAttributes()); } @Override public void restoreValues(Map values) { if (values.containsKey(KEY)) { RequestContextHolder.setRequestAttributes((RequestAttributes) values.get(KEY)); } } @Override public void resetValues(Map values) { RequestContextHolder.resetRequestAttributes(); } } ---- A `ThreadLocalAccessor` can be registered in the <> builder. The Boot starter detects beans of this type and automatically registers them for Spring MVC application, see the {spring-boot-ref-docs}/web.html#web.graphql.web-endpoints[Web Endpoints] section. [[execution-context-webflux]] ==== WebFlux A <> can rely on access to Reactor context that originates from the WebFlux request handling chain. This includes Reactor context added by <> components. [[execution-exceptions]] === Exception Resolution GraphQL Java applications can register a `DataFetcherExceptionHandler` to decide how to represent exceptions from the data layer in the ""errors"" section of the GraphQL response. Spring for GraphQL has a built-in `DataFetcherExceptionHandler` that is configured for use by the <> builder. It enables applications to register one or more Spring `DataFetcherExceptionResolver` components that are invoked sequentially until one resolves the `Exception` to a list of `graphql.GraphQLError` objects. `DataFetcherExceptionResolver` is an asynchronous contract. For most implementations, it would be sufficient to extend `DataFetcherExceptionResolverAdapter` and override one of its `resolveToSingleError` or `resolveToMultipleErrors` methods that resolve exceptions synchronously. A `GraphQLError` can be assigned an `graphql.ErrorClassification`. Spring for GraphQL defines an `ErrorType` enum with common, error classification categories: - `BAD_REQUEST` - `UNAUTHORIZED` - `FORBIDDEN` - `NOT_FOUND` - `INTERNAL_ERROR` Applications can use this to classify errors. If an error remains unresolved, by default it is marked as `INTERNAL_ERROR`. [[execution-batching]] === Batch Loading Given a `Book` and its `Author`, we can create one `DataFetcher` for a book and another for its author. This allows selecting books with or without authors, but it means books and authors aren't loaded together, which is especially inefficient when querying multiple books as the author for each book is loaded individually. This is known as the N+1 select problem. [[execution-batching-dataloader]] ==== `DataLoader` GraphQL Java provides a `DataLoader` mechanism for batch loading of related entities. You can find the full details in the {graphql-java-docs}/batching/[GraphQL Java docs]. Below is a summary of how it works: 1. Register ``DataLoader``'s in the `DataLoaderRegistry` that can load entities, given unique keys. 2. ``DataFetcher``'s can access ``DataLoader``'s and use them to load entities by id. 3. A `DataLoader` defers loading by returning a future so it can be done in a batch. 4. ``DataLoader``'s maintain a per request cache of loaded entities that can further improve efficiency. [[execution-batching-batch-loader-registry]] ==== `BatchLoaderRegistry` The complete batching loading mechanism in GraphQL Java requires implementing one of several `BatchLoader` interface, then wrapping and registering those as ``DataLoader``s with a name in the `DataLoaderRegistry`. The API in Spring GraphQL is slightly different. For registration, there is only one, central `BatchLoaderRegistry` exposing factory methods and a builder to create and register any number of batch loading functions: [source,java,indent=0,subs=""verbatim,quotes""] ---- @Configuration public class MyConfig { public MyConfig(BatchLoaderRegistry registry) { registry.forTypePair(Long.class, Author.class).registerMappedBatchLoader((authorIds, env) -> { // return Mono }); // more registrations ... } } ---- The Spring Boot starter declares a `BatchLoaderRegistry` bean that you can inject into your configuration, as shown above, or into any component such as a controller in order register batch loading functions. In turn the `BatchLoaderRegistry` is injected into `DefaultExecutionGraphQlService` where it ensures `DataLoader` registrations per request. By default, the `DataLoader` name is based on the class name of the target entity. This allows an `@SchemaMapping` method to declare a <> with a generic type, and without the need for specifying a name. The name, however, can be customized through the `BatchLoaderRegistry` builder, if necessary, along with other `DataLoader` options. For many cases, when loading related entities, you can use <> controller methods, which are a shortcut for and replace the need to use `BatchLoaderRegistry` and `DataLoader` directly. s `BatchLoaderRegistry` provides other important benefits too. It supports access to the same `GraphQLContext` from batch loading functions and from `@BatchMapping` methods, as well as ensures <> to them. This is why applications are expected to use it. It is possible to perform your own `DataLoader` registrations directly but such registrations would forgo the above benefits. [[execution-batching-testing]] ==== Testing Batch Loading Start by having `BatchLoaderRegistry` perform registrations on a `DataLoaderRegistry`: [source,java,indent=0,subs=""verbatim,quotes""] ---- BatchLoaderRegistry batchLoaderRegistry = new DefaultBatchLoaderRegistry(); // perform registrations... DataLoaderRegistry dataLoaderRegistry = DataLoaderRegistry.newRegistry().build(); batchLoaderRegistry.registerDataLoaders(dataLoaderRegistry, graphQLContext); ---- Now you can access and test individual ``DataLoader``'s as follows: [source,java,indent=0,subs=""verbatim,quotes""] ---- DataLoader loader = dataLoaderRegistry.getDataLoader(Book.class.getName()); loader.load(1L); loader.loadMany(Arrays.asList(2L, 3L)); List books = loader.dispatchAndJoin(); // actual loading assertThat(books).hasSize(3); assertThat(books.get(0).getName()).isEqualTo(""...""); // ... ---- [[data]] == Data Integration Spring for GraphQL lets you leverage existing Spring technology, following common programming models to expose underlying data sources through GraphQL. This section discusses an integration layer for Spring Data that provides an easy way to adapt a Querydsl or a Query by Example repository to a `DataFetcher`, including the option for automated detection and GraphQL Query registration for repositories marked with `@GraphQlRepository`. [[data-querydsl]] === Querydsl Spring for GraphQL supports use of http://www.querydsl.com/[Querydsl] to fetch data through the Spring Data https://docs.spring.io/spring-data/commons/docs/current/reference/html/#core.extensions[Querydsl extension]. Querydsl provides a flexible yet typesafe approach to express query predicates by generating a meta-model using annotation processors. For example, declare a repository as `QuerydslPredicateExecutor`: [source,java,indent=0,subs=""verbatim,quotes""] ---- public interface AccountRepository extends Repository, QuerydslPredicateExecutor { } ---- Then use it to create a `DataFetcher`: [source,java,indent=0,subs=""verbatim,quotes""] ---- // For single result queries DataFetcher dataFetcher = QuerydslDataFetcher.builder(repository).single(); // For multi-result queries DataFetcher> dataFetcher = QuerydslDataFetcher.builder(repository).many(); ---- You can now register the above `DataFetcher` through a <>. The `DataFetcher` builds a Querydsl `Predicate` from GraphQL request parameters, and uses it to fetch data. Spring Data supports `QuerydslPredicateExecutor` for JPA, MongoDB, and LDAP. If the repository is `ReactiveQuerydslPredicateExecutor`, the builder returns `DataFetcher>` or `DataFetcher>`. Spring Data supports this variant for MongoDB. [[data-querydsl-build]] ==== Build Setup To configure Querydsl in your build, follow the https://querydsl.com/static/querydsl/latest/reference/html/ch02.html[official reference documentation]: For example: [source,groovy,indent=0,subs=""verbatim,quotes,attributes"",role=""primary""] .Gradle ---- dependencies { //... annotationProcessor ""com.querydsl:querydsl-apt:$querydslVersion:jpa"", 'org.hibernate.javax.persistence:hibernate-jpa-2.1-api:1.0.2.Final', 'javax.annotation:javax.annotation-api:1.3.2' } compileJava { options.annotationProcessorPath = configurations.annotationProcessor } ---- [source,xml,indent=0,subs=""verbatim,quotes,attributes"",role=""secondary""] .Maven ---- com.querydsl querydsl-apt ${querydsl.version} jpa provided org.hibernate.javax.persistence hibernate-jpa-2.1-api 1.0.2.Final javax.annotation javax.annotation-api 1.3.2 com.mysema.maven apt-maven-plugin ${apt-maven-plugin.version} process target/generated-sources/java com.querydsl.apt.jpa.JPAAnnotationProcessor ---- The {github-main-branch}/samples/webmvc-http[webmvc-http] sample uses Querydsl for `artifactRepositories`. [[data-querydsl-customizations]] ==== Customizations `QuerydslDataFetcher` supports customizing how GraphQL arguments are bound onto properties to create a Querydsl `Predicate`. By default, arguments are bound as ""is equal to"" for each available property. To customize that, you can use `QuerydslDataFetcher` builder methods to provide a `QuerydslBinderCustomizer`. A repository may itself be an instance of `QuerydslBinderCustomizer`. This is auto-detected and transparently applied during <>. However, when manually building a `QuerydslDataFetcher` you will need to use builder methods to apply it. `QuerydslDataFetcher` supports interface and DTO projections to transform query results before returning these for further GraphQL processing. TIP: To learn what projections are, please refer to the https://docs.spring.io/spring-data/commons/docs/current/reference/html/#projections[Spring Data docs]. To understand how to use projections in GraphQL, please see <>. To use Spring Data projections with Querydsl repositories, create either a projection interface or a target DTO class and configure it through the `projectAs` method to obtain a `DataFetcher` producing the target type: [source,java,indent=0,subs=""verbatim,quotes""] ---- class Account { String name, identifier, description; Person owner; } interface AccountProjection { String getName(); String getIdentifier(); } // For single result queries DataFetcher dataFetcher = QuerydslDataFetcher.builder(repository).projectAs(AccountProjection.class).single(); // For multi-result queries DataFetcher> dataFetcher = QuerydslDataFetcher.builder(repository).projectAs(AccountProjection.class).many(); ---- [[data-querydsl-registration]] ==== Auto-Registration If a repository is annotated with `@GraphQlRepository`, it is automatically registered for queries that do not already have a registered `DataFetcher` and whose return type matches that of the repository domain type. This includes both single value and multi-value queries. By default, the name of the GraphQL type returned by the query must match the simple name of the repository domain type. If needed, you can use the `typeName` attribute of `@GraphQlRepository` to specify the target GraphQL type name. Auto-registration detects if a given repository implements `QuerydslBinderCustomizer` and transparently applies that through `QuerydslDataFetcher` builder methods. Auto-registration is performed through a built-in `RuntimeWiringConfigurer` that can be obtained from `QuerydslDataFetcher`. The {spring-boot-ref-docs}/web.html#web.graphql.data-query[Boot starter] automatically detects `@GraphQlRepository` beans and uses them to initialize the `RuntimeWiringConfigurer` with. Auto-registration does not support <>. If you need that, you'll need to use `QueryByExampleDataFetcher` to build and register the `DataFetcher` manually through a <>. [[data-querybyexample]] === Query by Example Spring Data supports the use of https://docs.spring.io/spring-data/commons/docs/current/reference/html/#query-by-example[Query by Example] to fetch data. Query by Example (QBE) is a simple querying technique that does not require you to write queries through store-specific query languages. Start by declaring a repository that is `QueryByExampleExecutor`: [source,java,indent=0,subs=""verbatim,quotes""] ---- public interface AccountRepository extends Repository, QueryByExampleExecutor { } ---- Use `QueryByExampleDataFetcher` to turn the repository into a `DataFecher`: [source,java,indent=0,subs=""verbatim,quotes""] ---- // For single result queries DataFetcher dataFetcher = QueryByExampleDataFetcher.builder(repository).single(); // For multi-result queries DataFetcher> dataFetcher = QueryByExampleDataFetcher.builder(repository).many(); ---- You can now register the above `DataFetcher` through a <>. The `DataFetcher` uses the GraphQL arguments map to create the domain type of the repository and use that as the example object to fetch data with. Spring Data supports `QueryByExampleDataFetcher` for JPA, MongoDB, Neo4j, and Redis. If the repository is `ReactiveQueryByExampleExecutor`, the builder returns `DataFetcher>` or `DataFetcher>`. Spring Data supports this variant for MongoDB, Neo4j, Redis, and R2dbc. [[data-querybyexample-build]] ==== Build Setup Query by Example is already included in the Spring Data modules for the data stores where it is supported, so no extra setup is required to enable it. [[data-querybyexample-customizations]] ==== Customizations `QueryByExampleDataFetcher` supports interface and DTO projections to transform query results before returning these for further GraphQL processing. TIP: To learn what projections are, please refer to the https://docs.spring.io/spring-data/commons/docs/current/reference/html/#projections[Spring Data documentation]. To understand the role of projections in GraphQL, please see <>. To use Spring Data projections with Query by Example repositories, create either a projection interface or a target DTO class and configure it through the `projectAs` method to obtain a `DataFetcher` producing the target type: [source,java,indent=0,subs=""verbatim,quotes""] ---- class Account { String name, identifier, description; Person owner; } interface AccountProjection { String getName(); String getIdentifier(); } // For single result queries DataFetcher dataFetcher = QueryByExampleDataFetcher.builder(repository).projectAs(AccountProjection.class).single(); // For multi-result queries DataFetcher> dataFetcher = QueryByExampleDataFetcher.builder(repository).projectAs(AccountProjection.class).many(); ---- [[data-querybyexample-registration]] ==== Auto-Registration If a repository is annotated with `@GraphQlRepository`, it is automatically registered for queries that do not already have a registered `DataFetcher` and whose return type matches that of the repository domain type. This includes both single value and multi-value queries. By default, the name of the GraphQL type returned by the query must match the simple name of the repository domain type. If needed, you can use the `typeName` attribute of `@GraphQlRepository` to specify the target GraphQL type name. Auto-registration is performed through a built-in `RuntimeWiringConfigurer` that can be obtained from `QueryByExampleDataFetcher`. The {spring-boot-ref-docs}/web.html#web.graphql.data-query[Boot starter] automatically detects `@GraphQlRepository` beans and uses them to initialize the `RuntimeWiringConfigurer` with. Auto-registration does not support <>. If you need that, you'll need to use `QueryByExampleDataFetcher` to build and register the `DataFetcher` manually through a <>. [[data-projections]] === Selection Set vs Projections A common question that arises is, how GraphQL selection sets compare to https://docs.spring.io/spring-data/commons/docs/current/reference/html/#projections[Spring Data projections] and what role does each play? The short answer is that Spring for GraphQL is not a data gateway that translates GraphQL queries directly into SQL or JSON queries. Instead, it lets you leverage existing Spring technology and does not assume a one for one mapping between the GraphQL schema and the underlying data model. That is why client-driven selection and server-side transformation of the data model can play complementary roles. To better understand, consider that Spring Data promotes domain-driven (DDD) design as the recommended approach to manage complexity in the data layer. In DDD, it is important to adhere to the constraints of an aggregate. By definition an aggregate is valid only if loaded in its entirety, since a partially loaded aggregate may impose limitations on aggregate functionality. In Spring Data you can choose whether you want your aggregate be exposed as is, or whether to apply transformations to the data model before returning it as a GraphQL result. Sometimes it's enough to do the former, and by default the <> and the <> integrations turn the GraphQL selection set into property path hints that the underlying Spring Data module uses to limit the selection. In other cases, it's useful to reduce or even transform the underlying data model in order to adapt to the GraphQL schema. Spring Data supports this through Interface and DTO Projections. Interface projections define a fixed set of properties to expose where properties may or may not be `null`, depending on the data store query result. There are two kinds of interface projections both of which determine what properties to load from the underlying data source: - https://docs.spring.io/spring-data/commons/docs/current/reference/html/#projections.interfaces.closed[Closed interface projections] are helpful if you cannot partially materialize the aggregate object, but you still want to expose a subset of properties. - https://docs.spring.io/spring-data/commons/docs/current/reference/html/#projections.interfaces.open[Open interface projections] leverage Spring's `@Value` annotation and {spring-framework-ref-docs}/core.html#expressions[SpEL] expressions to apply lightweight data transformations, such as concatenations, computations, or applying static functions to a property. DTO projections offer a higher level of customization as you can place transformation code either in the constructor or in getter methods. DTO projections materialize from a query where the individual properties are determined by the projection itself. DTO projections are commonly used with full-args constructors (e.g. Java records), and therefore they can only be constructed if all required fields (or columns) are part of the database query result. [[controllers]] == Annotated Controllers Spring for GraphQL provides an annotation-based programming model where `@Controller` components use annotations to declare handler methods with flexible method signatures to fetch the data for specific GraphQL fields. For example: [source,java,indent=0,subs=""verbatim,quotes""] ---- @Controller public class GreetingController { @QueryMapping // <1> public String hello() { // <2> return ""Hello, world!""; } } ---- <1> Bind this method to a query, i.e. a field under the Query type. <2> Determine the query from the method name if not declared on the annotation. Spring for GraphQL uses `RuntimeWiring.Builder` to register the above handler method as a `graphql.schema.DataFetcher` for the query named ""hello"". [[controllers-declaration]] === Declaration You can define `@Controller` beans as standard Spring bean definitions. The `@Controller` stereotype allows for auto-detection, aligned with Spring general support for detecting `@Controller` and `@Component` classes on the classpath and auto-registering bean definitions for them. It also acts as a stereotype for the annotated class, indicating its role as a data fetching component in a GraphQL application. `AnnotatedControllerConfigurer` detects `@Controller` beans and registers their annotated handler methods as ``DataFetcher``s via `RuntimeWiring.Builder`. It is an implementation of `RuntimeWiringConfigurer` which can be added to `GraphQlSource.Builder`. The Spring Boot starter automatically declares `AnnotatedControllerConfigurer` as a bean and adds all `RuntimeWiringConfigurer` beans to `GraphQlSource.Builder` and that enables support for annotated ``DataFetcher``s, see the {spring-boot-ref-docs}/web.html#web.graphql.runtimewiring[GraphQL RuntimeWiring] section in the Boot starter documentation. [[controllers-schema-mapping]] === `@SchemaMapping` The `@SchemaMapping` annotation maps a handler method to a field in the GraphQL schema and declares it to be the `DataFetcher` for that field. The annotation can specify the parent type name, and the field name: [source,java,indent=0,subs=""verbatim,quotes""] ---- @Controller public class BookController { @SchemaMapping(typeName=""Book"", field=""author"") public Author getAuthor(Book book) { // ... } } ---- The `@SchemaMapping` annotation can also leave out those attributes, in which case the field name defaults to the method name, while the type name defaults to the simple class name of the source/parent object injected into the method. For example, the below defaults to type ""Book"" and field ""author"": [source,java,indent=0,subs=""verbatim,quotes""] ---- @Controller public class BookController { @SchemaMapping public Author author(Book book) { // ... } } ---- The `@SchemaMapping` annotation can be declared at the class level to specify a default type name for all handler methods in the class. [source,java,indent=0,subs=""verbatim,quotes""] ---- @Controller @SchemaMapping(typeName=""Book"") public class BookController { // @SchemaMapping methods for fields of the ""Book"" type } ---- `@QueryMapping`, `@MutationMapping`, and `@SubscriptionMapping` are meta annotations that are themselves annotated with `@SchemaMapping` and have the typeName preset to `Query`, `Mutation`, or `Subscription` respectively. Effectively, these are shortcut annotations for fields under the Query, Mutation, and Subscription types respectively. For example: [source,java,indent=0,subs=""verbatim,quotes""] ---- @Controller public class BookController { @QueryMapping public Book bookById(@Argument Long id) { // ... } @MutationMapping public Book addBook(@Argument BookInput bookInput) { // ... } @SubscriptionMapping public Flux newPublications() { // ... } } ---- `@SchemaMapping` handler methods have flexible signatures and can choose from a range of method arguments and return values.. [[controllers-schema-mapping-signature]] ==== Method Signature Schema mapping handler methods can have any of the following method arguments: [cols=""1,2""] |=== | Method Argument | Description | `@Argument` | For access to a named field argument bound to a higher-level, typed Object. See <>. | `@Arguments` | For access to all field arguments bound to a higher-level, typed Object. See <>. | `@ProjectedPayload` Interface | For access to field arguments through a project interface. See <>. | Source | For access to the source (i.e. parent/container) instance of the field. See <>. | `DataLoader` | For access to a `DataLoader` in the `DataLoaderRegistry`. See <>. | `@ContextValue` | For access to a value from the localContext, if it is an instance of `GraphQLContext`, or from the `GraphQLContext` of `DataFetchingEnvironment`. | `GraphQLContext` | For access to the context from the `DataFetchingEnvironment`. | `java.security.Principal` | Obtained from the Spring Security context, if available. | `@AuthenticationPrincipal` | For access to `Authentication#getPrincipal()` from the Spring Security context. | `DataFetchingFieldSelectionSet` | For access to the selection set for the query through the `DataFetchingEnvironment`. | `Locale`, `Optional` | For access to the `Locale` from the `DataFetchingEnvironment`. | `DataFetchingEnvironment` | For direct access to the underlying `DataFetchingEnvironment`. |=== Schema mapping handler methods can return any value, including Reactor `Mono` and `Flux` as described in <>. [[controllers-schema-mapping-argument]] ==== `@Argument` In GraphQL Java, `DataFetchingEnvironment` provides access to a map of field-specific argument values. The values can be simple scalar values (e.g. String, Long), a `Map` of values for more complex input, or a `List` of values. Use the `@Argument` annotation to have an argument bound to a target object and injected into the handler method. Binding is performed by mapping argument values to a primary data constructor of the expected method parameter type, or by using a default constructor to create the object and then map argument values to its properties. This is repeated recursively, using all nested argument values and creating nested target objects accordingly. For example: [source,java,indent=0,subs=""verbatim,quotes""] ---- @Controller public class BookController { @QueryMapping public Book bookById(@Argument Long id) { // ... } @MutationMapping public Book addBook(@Argument BookInput bookInput) { // ... } } ---- By default, if the method parameter name is available (requires the `-parameters` compiler flag with Java 8+ or debugging info from the compiler), it is used to look up the argument. If needed, you can customize the name through the annotation, e.g. `@Argument(""bookInput"")`. TIP: The `@Argument` annotation does not have a ""required"" flag, nor the option to specify a default value. Both of these can be specified at the GraphQL schema level and are enforced by GraphQL Java. If binding fails, a `BindException` is raised with binding issues accumulated as field errors where the `field` of each error is the argument path where the issue occurred. You can use `@Argument` on a `Map` argument, to obtain all argument values. The name attribute on `@Argument` must not be set. [[controllers-schema-mapping-arguments]] ==== `@Arguments` Use the `@Arguments` annotation, if you want to bind the full arguments map onto a single target Object, in contrast to `@Argument`, which binds a specific, named argument. For example, `@Argument BookInput bookInput` uses the value of the argument ""bookInput"" to initialize `BookInput`, while `@Arguments` uses the full arguments map and in that case, top-level arguments are bound to `BookInput` properties. [[controllers-schema-mapping-validation]] ==== `@Argument(s)` Validation If a {spring-framework-ref-docs}/core.html#validation-beanvalidation-overview[Bean Validation] `Validator` (or typically, a `LocalValidatorFactoryBean`) bean is present in the application context, the `AnnotatedControllerConfigurer` will auto-detect it and configure support for validation. Controller arguments annotated with `@Valid` and `@Validated` are then validated before method invocation. Bean Validation lets you declare constraints on types, as the following example shows: [source,java,indent=0,subs=""verbatim,quotes""] ---- public class BookInput { @NotNull private String title; @NotNull @Size(max=13) private String isbn; } ---- We can then mark our argument for validation with `@Valid`: [source,java,indent=0,subs=""verbatim,quotes""] ---- @Controller public class BookController { @MutationMapping public Book addBook(@Argument @Valid BookInput bookInput) { // ... } } ---- If an error occurs during validation, a `ConstraintViolationException` is thrown and can be later <>. [TIP] ==== Unlike Spring MVC, handler method signatures do not support the injection of `BindingResult` for reacting to validation errors: those are globally dealt with as exceptions. ==== [[controllers-schema-mapping-projectedpayload-argument]] ==== `@ProjectedPayload` Interface As an alternative to using complete Objects with <>, you can also use a projection interface to access GraphQL request arguments through a well-defined, minimal interface. Argument projections are provided by https://docs.spring.io/spring-data/commons/docs/current/reference/html/#projections.interfaces[Spring Data's Interface projections] when Spring Data is on the class path. To make use of this, create an interface annotated with `@ProjectedPayload` and declare it as a controller method parameter. If the parameter is annotated with `@Argument`, it applies to an individual argument within the `DataFetchingEnvironment.getArguments()` map. When declared without `@Argument`, the projection works on top-level arguments in the complete arguments map. For example: [source,java,indent=0,subs=""verbatim,quotes""] ---- @Controller public class BookController { @QueryMapping public Book bookById(BookIdProjection bookId) { // ... } @MutationMapping public Book addBook(@Argument BookInputProjection bookInput) { // ... } } @ProjectedPayload interface BookIdProjection { Long getId(); } @ProjectedPayload interface BookInputProjection { String getName(); @Value(""#{target.author + ' ' + target.name}"") String getAuthorAndName(); } ---- [[controllers-schema-mapping-source]] ==== Source In GraphQL Java, the `DataFetchingEnvironment` provides access to the source (i.e. parent/container) instance of the field. To access this, simply declare a method parameter of the expected target type. [source,java,indent=0,subs=""verbatim,quotes""] ---- @Controller public class BookController { @SchemaMapping public Author author(Book book) { // ... } } ---- The source method argument also helps to determine the type name for the mapping. If the simple name of the Java class matches the GraphQL type, then there is no need to explicitly specify the type name in the `@SchemaMapping` annotation. [TIP] ==== A <> handler method can batch load all authors for a query, given a list of source/parent books objects. ==== [[controllers-schema-mapping-data-loader]] ==== `DataLoader` When you register a batch loading function for an entity, as explained in <>, you can access the `DataLoader` for the entity by declaring a method argument of type `DataLoader` and use it to load the entity: [source,java,indent=0,subs=""verbatim,quotes""] ---- @Controller public class BookController { public BookController(BatchLoaderRegistry registry) { registry.forTypePair(Long.class, Author.class).registerMappedBatchLoader((authorIds, env) -> { // return Map }); } @SchemaMapping public CompletableFuture author(Book book, DataLoader loader) { return loader.load(book.getAuthorId()); } } ---- By default, `BatchLoaderRegistry` uses the full class name of the value type (e.g. the class name for `Author`) for the key of the registration, and therefore simply declaring the `DataLoader` method argument with generic types provides enough information to locate it in the `DataLoaderRegistry`. As a fallback, the `DataLoader` method argument resolver will also try the method argument name as the key but typically that should not be necessary. Note that for many cases with loading related entities, where the `@SchemaMapping` simply delegates to a `DataLoader`, you can reduce boilerplate by using a <> method as described in the next section. [[controllers-batch-mapping]] === `@BatchMapping` <> addresses the N+1 select problem through the use of an `org.dataloader.DataLoader` to defer the loading of individual entity instances, so they can be loaded together. For example: [source,java,indent=0,subs=""verbatim,quotes""] ---- @Controller public class BookController { public BookController(BatchLoaderRegistry registry) { registry.forTypePair(Long.class, Author.class).registerMappedBatchLoader((authorIds, env) -> { // return Map }); } @SchemaMapping public CompletableFuture author(Book book, DataLoader loader) { return loader.load(book.getAuthorId()); } } ---- For the straight-forward case of loading an associated entity, shown above, the `@SchemaMapping` method does nothing more than delegate to the `DataLoader`. This is boilerplate that can be avoided with a `@BatchMapping` method. For example: [source,java,indent=0,subs=""verbatim,quotes""] ---- @Controller public class BookController { @BatchMapping public Mono> author(List books) { // ... } } ---- The above becomes a batch loading function in the `BatchLoaderRegistry` where keys are `Book` instances and the loaded values their authors. In addition, a `DataFetcher` is also transparently bound to the `author` field of the type `Book`, which simply delegates to the `DataLoader` for authors, given its source/parent `Book` instance. [TIP] ==== To be used as a unique key, `Book` must implement `hashcode` and `equals`. ==== By default, the field name defaults to the method name, while the type name defaults to the simple class name of the input `List` element type. Both can be customized through annotation attributes. The type name can also be inherited from a class level `@SchemaMapping`. [[controllers-batch-mapping-signature]] ==== Method Signature Batch mapping methods support the following arguments: [cols=""1,2""] |=== | Method Argument | Description | `List` | The source/parent objects. | `java.security.Principal` | Obtained from Spring Security context, if available. | `@ContextValue` | For access to a value from the `GraphQLContext` of `BatchLoaderEnvironment`, which is the same context as the one from the `DataFetchingEnvironment`. | `GraphQLContext` | For access to the context from the `BatchLoaderEnvironment`, which is the same context as the one from the `DataFetchingEnvironment`. | `BatchLoaderEnvironment` | The environment that is available in GraphQL Java to a `org.dataloader.BatchLoaderWithContext`. |=== Batch mapping methods can return: [cols=""1,2""] |=== | Return Type | Description | `Mono>` | A map with parent objects as keys, and batch loaded objects as values. | `Flux` | A sequence of batch loaded objects that must be in the same order as the source/parent objects passed into the method. | `Map`, `List` | Imperative variants, e.g. without remote calls to make. |=== [[security]] == Security The path to a <> GraphQL endpoint can be secured with HTTP URL security to ensure that only authenticated users can access it. This does not, however, differentiate among different GraphQL requests on such a shared endpoint on a single URL. To apply more fine-grained security, add Spring Security annotations such as `@PreAuthorize` or `@Secured` to service methods involved in fetching specific parts of the GraphQL response. This should work due to <> that aims to make Security, and other context, available at the data fetching level. The Spring for GraphQL repository contains samples for {github-main-branch}/samples/webmvc-http-security[Spring MVC] and for {github-main-branch}/samples/webflux-security[WebFlux]. include::client.adoc[leveloffset=+1] include::testing.adoc[leveloffset=+1] [[samples]] == Samples This Spring for GraphQL repository contains {github-main-branch}/samples[sample applications] for various scenarios. You can run those by cloning this repository and running main application classes from your IDE or by typing the following on the command line: [source,bash,indent=0,subs=""verbatim,quotes""] ---- $ ./gradlew :samples:{sample-directory-name}:bootRun ---- ",12231,False,2012.2540292934125,median "class ZCL_ABAK_SHM_AREA definition public inheriting from CL_SHM_AREA final create private global friends CL_SHM_AREA . public section. constants AREA_NAME type SHM_AREA_NAME value 'ZCL_ABAK_SHM_AREA'. ""#EC NOTEXT data ROOT type ref to ZCL_ABAK_SHM_ROOT read-only . class-methods CLASS_CONSTRUCTOR . class-methods GET_GENERATOR_VERSION returning value(GENERATOR_VERSION) type I . class-methods ATTACH_FOR_READ importing !INST_NAME type SHM_INST_NAME default CL_SHM_AREA=>DEFAULT_INSTANCE preferred parameter INST_NAME returning value(HANDLE) type ref to ZCL_ABAK_SHM_AREA raising CX_SHM_INCONSISTENT CX_SHM_NO_ACTIVE_VERSION CX_SHM_READ_LOCK_ACTIVE CX_SHM_EXCLUSIVE_LOCK_ACTIVE CX_SHM_PARAMETER_ERROR CX_SHM_CHANGE_LOCK_ACTIVE . class-methods ATTACH_FOR_WRITE importing !INST_NAME type SHM_INST_NAME default CL_SHM_AREA=>DEFAULT_INSTANCE !ATTACH_MODE type SHM_ATTACH_MODE default CL_SHM_AREA=>ATTACH_MODE_DEFAULT !WAIT_TIME type I default 0 preferred parameter INST_NAME returning value(HANDLE) type ref to ZCL_ABAK_SHM_AREA raising CX_SHM_EXCLUSIVE_LOCK_ACTIVE CX_SHM_VERSION_LIMIT_EXCEEDED CX_SHM_CHANGE_LOCK_ACTIVE CX_SHM_PARAMETER_ERROR CX_SHM_PENDING_LOCK_REMOVED . class-methods ATTACH_FOR_UPDATE importing !INST_NAME type SHM_INST_NAME default CL_SHM_AREA=>DEFAULT_INSTANCE !ATTACH_MODE type SHM_ATTACH_MODE default CL_SHM_AREA=>ATTACH_MODE_DEFAULT !WAIT_TIME type I default 0 preferred parameter INST_NAME returning value(HANDLE) type ref to ZCL_ABAK_SHM_AREA raising CX_SHM_INCONSISTENT CX_SHM_NO_ACTIVE_VERSION CX_SHM_EXCLUSIVE_LOCK_ACTIVE CX_SHM_VERSION_LIMIT_EXCEEDED CX_SHM_CHANGE_LOCK_ACTIVE CX_SHM_PARAMETER_ERROR CX_SHM_PENDING_LOCK_REMOVED . class-methods DETACH_AREA returning value(RC) type SHM_RC . class-methods INVALIDATE_INSTANCE importing !INST_NAME type SHM_INST_NAME default CL_SHM_AREA=>DEFAULT_INSTANCE !TERMINATE_CHANGER type ABAP_BOOL default ABAP_TRUE preferred parameter INST_NAME returning value(RC) type SHM_RC raising CX_SHM_PARAMETER_ERROR . class-methods INVALIDATE_AREA importing !TERMINATE_CHANGER type ABAP_BOOL default ABAP_TRUE returning value(RC) type SHM_RC raising CX_SHM_PARAMETER_ERROR . class-methods FREE_INSTANCE importing !INST_NAME type SHM_INST_NAME default CL_SHM_AREA=>DEFAULT_INSTANCE !TERMINATE_CHANGER type ABAP_BOOL default ABAP_TRUE preferred parameter INST_NAME returning value(RC) type SHM_RC raising CX_SHM_PARAMETER_ERROR . class-methods FREE_AREA importing !TERMINATE_CHANGER type ABAP_BOOL default ABAP_TRUE returning value(RC) type SHM_RC raising CX_SHM_PARAMETER_ERROR . class-methods GET_INSTANCE_INFOS importing !INST_NAME type SHM_INST_NAME optional returning value(INFOS) type SHM_INST_INFOS . class-methods BUILD importing !INST_NAME type SHM_INST_NAME default CL_SHM_AREA=>DEFAULT_INSTANCE raising CX_SHMA_NOT_CONFIGURED CX_SHMA_INCONSISTENT CX_SHM_BUILD_FAILED . methods SET_ROOT importing !ROOT type ref to ZCL_ABAK_SHM_ROOT raising CX_SHM_INITIAL_REFERENCE CX_SHM_WRONG_HANDLE . methods GET_ROOT redefinition . protected section. private section. constants _VERSION_ type I value 21. ""#EC NOTEXT class-data _TRACE_SERVICE type ref to IF_SHM_TRACE . class-data _TRACE_ACTIVE type ABAP_BOOL value ABAP_FALSE. ""#EC NOTEXT constants _TRANSACTIONAL type ABAP_BOOL value ABAP_FALSE. ""#EC NOTEXT constants _CLIENT_DEPENDENT type ABAP_BOOL value ABAP_FALSE. ""#EC NOTEXT constants _LIFE_CONTEXT type SHM_LIFE_CONTEXT value CL_SHM_AREA=>LIFE_CONTEXT_APPSERVER. ""#EC NOTEXT ENDCLASS. CLASS ZCL_ABAK_SHM_AREA IMPLEMENTATION. method ATTACH_FOR_READ. DATA: l_attributes TYPE shma_attributes, l_root TYPE REF TO object, l_cx TYPE REF TO cx_root, l_client TYPE shm_client, l_client_supplied TYPE abap_bool. ""#EC NEEDED * check if tracing should be activated/de-activated IF ( NOT _trace_service IS INITIAL ). TRY. _trace_active = cl_shm_service=>trace_is_variant_active( _trace_service->variant-def_name ). CATCH cx_root. ""#EC NO_HANDLER ""#EC CATCH_ALL ENDTRY. ENDIF. IF _trace_active = abap_false OR _trace_service->variant-attach_for_read = abap_false. * > CREATE OBJECT handle. handle->client = l_client. handle->inst_name = inst_name. * try sneak mode first handle->_attach_read71( EXPORTING area_name = area_name sneak_mode = abap_true life_context = _life_context IMPORTING root = l_root ). IF l_root IS INITIAL. * no root object returned, sneak mode was not successful. * -> read area properties from database and try again. cl_shm_service=>initialize( EXPORTING area_name = handle->area_name client = l_client IMPORTING attributes = l_attributes ). handle->properties = l_attributes-properties. handle->_attach_read71( EXPORTING area_name = area_name sneak_mode = abap_false life_context = _life_context IMPORTING root = l_root ). ENDIF. handle->root ?= l_root. * < ELSE. TRY. * > CREATE OBJECT handle. handle->client = l_client. handle->inst_name = inst_name. handle->_attach_read71( EXPORTING area_name = area_name sneak_mode = abap_true life_context = _life_context IMPORTING root = l_root ). IF l_root IS INITIAL. * no root object returned, sneak mode was not successful. * -> read area properties from database and try again. cl_shm_service=>initialize( EXPORTING area_name = handle->area_name client = l_client IMPORTING attributes = l_attributes ). handle->properties = l_attributes-properties. handle->_attach_read71( EXPORTING area_name = area_name sneak_mode = abap_false life_context = _life_context IMPORTING root = l_root ). ENDIF. handle->root ?= l_root. * < _trace_service->trin_attach_for_read( area_name = area_name inst_name = inst_name client = l_client ). CLEANUP INTO l_cx. _trace_service->trcx_attach_for_read( area_name = area_name inst_name = inst_name client = l_client cx = l_cx ). ENDTRY. ENDIF. handle->inst_trace_service = _trace_service. handle->inst_trace_active = _trace_active. endmethod. method ATTACH_FOR_UPDATE. DATA: l_attributes TYPE shma_attributes, l_root TYPE REF TO object, l_cx TYPE REF TO cx_root, l_client TYPE shm_client, l_client_supplied TYPE abap_bool, ""#EC NEEDED l_wait_time TYPE i, l_wait_time_per_loop TYPE i, l_wait_time_per_loop_sec TYPE f. l_wait_time = wait_time. * check if tracing should be activated/de-activated IF ( NOT _trace_service IS INITIAL ). TRY. _trace_active = cl_shm_service=>trace_is_variant_active( _trace_service->variant-def_name ). CATCH cx_root. ""#EC NO_HANDLER ""#EC CATCH_ALL ENDTRY. ENDIF. IF _trace_active = abap_false OR _trace_service->variant-attach_for_upd = abap_false. * > CREATE OBJECT handle. handle->client = l_client. handle->inst_name = inst_name. cl_shm_service=>initialize( EXPORTING area_name = handle->area_name client = l_client IMPORTING attributes = l_attributes ). handle->properties = l_attributes-properties. handle->_attach_update70( EXPORTING area_name = handle->area_name mode = attach_mode IMPORTING root = l_root CHANGING wait_time = l_wait_time ). IF abap_true = l_attributes-properties-has_versions AND handle->_lock IS NOT INITIAL. * we may need a second try in case of class constructors handle->_attach_update70( EXPORTING area_name = handle->area_name mode = attach_mode IMPORTING root = l_root CHANGING wait_time = l_wait_time ). ENDIF. IF attach_mode = cl_shm_area=>attach_mode_wait AND handle->_lock IS INITIAL. l_wait_time_per_loop = l_wait_time / 10. * wait_time_per_loop should be at least 2 * SHMATTACHWRITE_MAXACTIVEWAIT IF l_wait_time_per_loop < 2000. l_wait_time_per_loop = 2000. ELSEIF l_wait_time_per_loop > 300000. l_wait_time_per_loop = 300000. ENDIF. l_wait_time_per_loop_sec = l_wait_time_per_loop / 1000. WHILE handle->_lock IS INITIAL. IF l_wait_time_per_loop > l_wait_time. l_wait_time_per_loop = l_wait_time. l_wait_time_per_loop_sec = l_wait_time_per_loop / 1000. ENDIF. WAIT UP TO l_wait_time_per_loop_sec SECONDS. l_wait_time = l_wait_time - l_wait_time_per_loop. handle->_attach_update70( EXPORTING area_name = handle->area_name mode = cl_shm_area=>attach_mode_wait_2nd_try IMPORTING root = l_root CHANGING wait_time = l_wait_time ). IF abap_true = l_attributes-properties-has_versions AND handle->_lock IS NOT INITIAL. * we may need a second try in case of class constructors handle->_attach_update70( EXPORTING area_name = handle->area_name mode = cl_shm_area=>attach_mode_wait_2nd_try IMPORTING root = l_root CHANGING wait_time = l_wait_time ). ENDIF. ENDWHILE. ENDIF. handle->root ?= l_root. * < ELSE. TRY. * > CREATE OBJECT handle. handle->client = l_client. handle->inst_name = inst_name. cl_shm_service=>initialize( EXPORTING area_name = handle->area_name client = l_client IMPORTING attributes = l_attributes ). handle->properties = l_attributes-properties. handle->_attach_update70( EXPORTING area_name = handle->area_name mode = attach_mode IMPORTING root = l_root CHANGING wait_time = l_wait_time ). IF abap_true = l_attributes-properties-has_versions AND handle->_lock IS NOT INITIAL. * we may need a second try in case of class constructors handle->_attach_update70( EXPORTING area_name = handle->area_name mode = attach_mode IMPORTING root = l_root CHANGING wait_time = l_wait_time ). ENDIF. IF attach_mode = cl_shm_area=>attach_mode_wait AND handle->_lock IS INITIAL. l_wait_time_per_loop = l_wait_time / 10. * wait_time_per_loop should be at least 2 * SHMATTACHWRITE_MAXACTIVEWAIT IF l_wait_time_per_loop < 2000. l_wait_time_per_loop = 2000. ELSEIF l_wait_time_per_loop > 300000. l_wait_time_per_loop = 300000. ENDIF. l_wait_time_per_loop_sec = l_wait_time_per_loop / 1000. WHILE handle->_lock IS INITIAL. IF l_wait_time_per_loop > l_wait_time. l_wait_time_per_loop = l_wait_time. l_wait_time_per_loop_sec = l_wait_time_per_loop / 1000. ENDIF. WAIT UP TO l_wait_time_per_loop_sec SECONDS. l_wait_time = l_wait_time - l_wait_time_per_loop. handle->_attach_update70( EXPORTING area_name = handle->area_name mode = cl_shm_area=>attach_mode_wait_2nd_try IMPORTING root = l_root CHANGING wait_time = l_wait_time ). IF abap_true = l_attributes-properties-has_versions AND handle->_lock IS NOT INITIAL. * we may need a second try in case of class constructors handle->_attach_update70( EXPORTING area_name = handle->area_name mode = cl_shm_area=>attach_mode_wait_2nd_try IMPORTING root = l_root CHANGING wait_time = l_wait_time ). ENDIF. ENDWHILE. ENDIF. handle->root ?= l_root. * < _trace_service->trin_attach_for_update( area_name = area_name inst_name = inst_name client = l_client mode = attach_mode wait_time = wait_time ). CLEANUP INTO l_cx. _trace_service->trcx_attach_for_update( area_name = area_name inst_name = inst_name client = l_client mode = attach_mode wait_time = wait_time cx = l_cx ). ENDTRY. ENDIF. handle->inst_trace_service = _trace_service. handle->inst_trace_active = _trace_active. endmethod. method ATTACH_FOR_WRITE. DATA: l_attributes TYPE shma_attributes, l_cx TYPE REF TO cx_root, l_client TYPE shm_client, l_client_supplied TYPE abap_bool, ""#EC NEEDED l_wait_time TYPE i, l_wait_time_per_loop TYPE i, l_wait_time_per_loop_sec TYPE f. l_wait_time = wait_time. * check if tracing should be activated/de-activated IF ( NOT _trace_service IS INITIAL ). TRY. _trace_active = cl_shm_service=>trace_is_variant_active( _trace_service->variant-def_name ). CATCH cx_root. ""#EC NO_HANDLER ""#EC CATCH_ALL ENDTRY. ENDIF. IF _trace_active = abap_false OR _trace_service->variant-attach_for_write = abap_false. * > CREATE OBJECT handle. handle->client = l_client. handle->inst_name = inst_name. cl_shm_service=>initialize( EXPORTING area_name = handle->area_name client = l_client IMPORTING attributes = l_attributes ). handle->properties = l_attributes-properties. handle->_attach_write70( EXPORTING area_name = handle->area_name mode = attach_mode CHANGING wait_time = l_wait_time ). IF attach_mode = cl_shm_area=>attach_mode_wait AND handle->_lock IS INITIAL. l_wait_time_per_loop = l_wait_time / 10. * wait_time_per_loop should be at least 2 * SHMATTACHWRITE_MAXACTIVEWAIT IF l_wait_time_per_loop < 2000. l_wait_time_per_loop = 2000. ELSEIF l_wait_time_per_loop > 300000. l_wait_time_per_loop = 300000. ENDIF. l_wait_time_per_loop_sec = l_wait_time_per_loop / 1000. WHILE handle->_lock IS INITIAL. IF l_wait_time_per_loop > l_wait_time. l_wait_time_per_loop = l_wait_time. l_wait_time_per_loop_sec = l_wait_time_per_loop / 1000. ENDIF. WAIT UP TO l_wait_time_per_loop_sec SECONDS. l_wait_time = l_wait_time - l_wait_time_per_loop. handle->_attach_write70( EXPORTING area_name = handle->area_name mode = cl_shm_area=>attach_mode_wait_2nd_try CHANGING wait_time = l_wait_time ). ENDWHILE. ENDIF. * < ELSE. TRY. * > CREATE OBJECT handle. handle->client = l_client. handle->inst_name = inst_name. cl_shm_service=>initialize( EXPORTING area_name = handle->area_name client = l_client IMPORTING attributes = l_attributes ). handle->properties = l_attributes-properties. handle->_attach_write70( EXPORTING area_name = handle->area_name mode = attach_mode CHANGING wait_time = l_wait_time ). IF attach_mode = cl_shm_area=>attach_mode_wait AND handle->_lock IS INITIAL. l_wait_time_per_loop = l_wait_time / 10. * wait_time_per_loop should be at least 2 * SHMATTACHWRITE_MAXACTIVEWAIT IF l_wait_time_per_loop < 2000. l_wait_time_per_loop = 2000. ELSEIF l_wait_time_per_loop > 300000. l_wait_time_per_loop = 300000. ENDIF. l_wait_time_per_loop_sec = l_wait_time_per_loop / 1000. WHILE handle->_lock IS INITIAL. IF l_wait_time_per_loop > l_wait_time. l_wait_time_per_loop = l_wait_time. l_wait_time_per_loop_sec = l_wait_time_per_loop / 1000. ENDIF. WAIT UP TO l_wait_time_per_loop_sec SECONDS. l_wait_time = l_wait_time - l_wait_time_per_loop. handle->_attach_write70( EXPORTING area_name = handle->area_name mode = cl_shm_area=>attach_mode_wait_2nd_try CHANGING wait_time = l_wait_time ). ENDWHILE. ENDIF. * < _trace_service->trin_attach_for_write( area_name = area_name inst_name = inst_name client = l_client mode = attach_mode wait_time = wait_time ). CLEANUP INTO l_cx. _trace_service->trcx_attach_for_write( area_name = area_name inst_name = inst_name client = l_client mode = attach_mode wait_time = wait_time cx = l_cx ). ENDTRY. ENDIF. handle->inst_trace_service = _trace_service. handle->inst_trace_active = _trace_active. endmethod. method BUILD. DATA: l_cls_name TYPE shm_auto_build_class_name, l_cx TYPE REF TO cx_root. IF _trace_active = abap_false OR _trace_service->variant-build = abap_false. * > l_cls_name = cl_shm_service=>get_auto_build_class_name( area_name ). CALL METHOD (l_cls_name)=>if_shm_build_instance~build EXPORTING inst_name = inst_name. * < ELSE. TRY. * > l_cls_name = cl_shm_service=>get_auto_build_class_name( area_name ). CALL METHOD (l_cls_name)=>if_shm_build_instance~build EXPORTING inst_name = inst_name. * < _trace_service->trin_build( area_name = area_name inst_name = inst_name ). CLEANUP INTO l_cx. _trace_service->trcx_build( area_name = area_name inst_name = inst_name cx = l_cx ). ENDTRY. ENDIF. endmethod. method CLASS_CONSTRUCTOR. * TRACE { DO NOT REMOVE THIS LINE ! _trace_active = abap_false. TRY. _trace_service = cl_shm_service=>trace_get_service( area_name ). IF NOT _trace_service IS INITIAL. _trace_active = cl_shm_service=>trace_is_variant_active( _trace_service->variant-def_name ). ENDIF. CATCH cx_root. ""#EC NO_HANDLER ""#EC CATCH_ALL ENDTRY. * TRACE } DO NOT REMOVE THIS LINE ! endmethod. method DETACH_AREA. DATA: l_client TYPE shm_client, l_client_supplied TYPE abap_bool VALUE abap_false. * > rc = _detach_area71( area_name = area_name client = l_client client_supplied = l_client_supplied client_dependent = _client_dependent life_context = _life_context ). * < IF _trace_active = abap_true. IF _trace_service->variant-detach_area = abap_true. _trace_service->trin_detach_area( area_name = area_name client = l_client rc = rc ). ENDIF. ENDIF. endmethod. method FREE_AREA. DATA: l_client TYPE shm_client, l_client_supplied TYPE abap_bool VALUE abap_false. CONSTANTS: affect_server TYPE shm_affect_server VALUE cl_shm_area=>affect_local_server. * > rc = _free_area71( area_name = area_name client = l_client client_supplied = l_client_supplied client_dependent = _client_dependent transactional = _transactional terminate_changer = terminate_changer affect_server = affect_server life_context = _life_context ). * < IF _trace_active = abap_true. IF _trace_service->variant-free_area = abap_true. _trace_service->trin_free_area( area_name = area_name client = l_client terminate_changer = terminate_changer affect_server = affect_server rc = rc ). ENDIF. ENDIF. endmethod. method FREE_INSTANCE. DATA: l_client TYPE shm_client, l_client_supplied TYPE abap_bool VALUE abap_false. CONSTANTS: affect_server TYPE shm_affect_server VALUE cl_shm_area=>affect_local_server. * > rc = _free_instance71( area_name = area_name inst_name = inst_name client = l_client client_supplied = l_client_supplied client_dependent = _client_dependent transactional = _transactional terminate_changer = terminate_changer affect_server = affect_server life_context = _life_context ). * < IF _trace_active = abap_true. IF _trace_service->variant-free_instance = abap_true. _trace_service->trin_free_instance( area_name = area_name inst_name = inst_name client = l_client terminate_changer = terminate_changer affect_server = affect_server rc = rc ). ENDIF. ENDIF. endmethod. method GET_GENERATOR_VERSION. generator_version = _version_. endmethod. method GET_INSTANCE_INFOS. DATA: l_client TYPE shm_client, l_client_supplied TYPE abap_bool VALUE abap_false, l_inst_name_supplied TYPE abap_bool VALUE abap_false. IF inst_name IS SUPPLIED. l_inst_name_supplied = abap_true. ENDIF. * > TRY. CALL METHOD ('_GET_INSTANCE_INFOS804') EXPORTING area_name = area_name client = l_client client_supplied = l_client_supplied client_dependent = _client_dependent life_context = _life_context inst_name = inst_name inst_name_supplied = l_inst_name_supplied RECEIVING infos = infos. CATCH cx_sy_dyn_call_illegal_method. * New kernel and/or new basis SP missing -> use slow fallback infos = _get_instance_infos71( area_name = area_name client = l_client client_supplied = l_client_supplied client_dependent = _client_dependent life_context = _life_context ). IF abap_true = l_inst_name_supplied. DELETE infos WHERE name <> inst_name. ENDIF. ENDTRY. * < IF _trace_active = abap_true. IF _trace_service->variant-get_instance_inf = abap_true. _trace_service->trin_get_instance_infos( area_name = area_name client = l_client infos = infos ). ENDIF. ENDIF. endmethod. method GET_ROOT. DATA: l_cx TYPE REF TO cx_root, l_area_name TYPE string, l_inst_name TYPE string, l_client TYPE string. IF _trace_active = abap_false OR _trace_service->variant-get_root = abap_false. * > IF is_valid( ) = abap_false. l_area_name = me->area_name. l_inst_name = me->inst_name. l_client = me->client. RAISE EXCEPTION TYPE cx_shm_already_detached EXPORTING area_name = l_area_name inst_name = l_inst_name client = l_client. ENDIF. root = me->root. * < ELSE. TRY. * > IF is_valid( ) = abap_false. l_area_name = me->area_name. l_inst_name = me->inst_name. l_client = me->client. RAISE EXCEPTION TYPE cx_shm_already_detached EXPORTING area_name = l_area_name inst_name = l_inst_name client = l_client. ENDIF. root = me->root. * < _trace_service->trin_get_root( area_name = area_name ). CLEANUP INTO l_cx. _trace_service->trcx_get_root( area_name = area_name cx = l_cx ). ENDTRY. ENDIF. endmethod. method INVALIDATE_AREA. DATA: l_client TYPE shm_client, l_client_supplied TYPE abap_bool VALUE abap_false. CONSTANTS: affect_server TYPE shm_affect_server VALUE cl_shm_area=>affect_local_server. * > rc = _invalidate_area71( area_name = area_name client = l_client client_supplied = l_client_supplied client_dependent = _client_dependent transactional = _transactional terminate_changer = terminate_changer affect_server = affect_server life_context = _life_context ). * < IF _trace_active = abap_true. IF _trace_service->variant-invalidate_area = abap_true. _trace_service->trin_invalidate_area( area_name = area_name client = l_client terminate_changer = terminate_changer affect_server = affect_server rc = rc ). ENDIF. ENDIF. endmethod. method INVALIDATE_INSTANCE. DATA: l_client TYPE shm_client, l_client_supplied TYPE abap_bool value abap_false. CONSTANTS: affect_server TYPE shm_affect_server VALUE cl_shm_area=>affect_local_server. * > rc = _invalidate_instance71( area_name = area_name inst_name = inst_name client = l_client client_supplied = l_client_supplied client_dependent = _client_dependent transactional = _transactional terminate_changer = terminate_changer affect_server = affect_server life_context = _life_context ). * < IF _trace_active = abap_true. IF _trace_service->variant-invalidate_inst = abap_true. _trace_service->trin_invalidate_instance( area_name = area_name inst_name = inst_name client = l_client terminate_changer = terminate_changer affect_server = affect_server rc = rc ). ENDIF. ENDIF. endmethod. method SET_ROOT. DATA: l_cx TYPE REF TO cx_root. IF _trace_active = abap_false OR _trace_service->variant-set_root = abap_false. * > _set_root( root ). me->root = root. * < ELSE. TRY. * > _set_root( root ). me->root = root. * < _trace_service->trin_set_root( area_name = area_name inst_name = inst_name root = root ). CLEANUP INTO l_cx. _trace_service->trcx_set_root( area_name = area_name inst_name = inst_name root = root cx = l_cx ). ENDTRY. ENDIF. endmethod. ENDCLASS. ",6808,False,1487.8058836500477,median "open util/ordering [State] as ord pred test25 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Chicken0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State1->Chicken0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Farmer0,Grain0,Fox0 + Chicken0] }}}}}} } run test25 for 4 expect 0 pred test35 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Chicken0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State1->Chicken0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Grain0,Fox0,none,Farmer0 + Grain0] }}}}}} } run test35 for 4 expect 1 pred test27 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Chicken0 + Grain0,Grain0,Chicken0 + Grain0,Farmer0 + Chicken0 + Grain0] }}}}}} } run test27 for 4 expect 1 pred test1 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State1->Chicken0 + State2->Chicken0 + State3->Farmer0 + State3->Chicken0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test1 for 4 expect 1 pred test29 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Grain0,Fox0,none,Farmer0 + Grain0] }}}}}} } run test29 for 4 expect 1 pred test9 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Grain0,Fox0 + Grain0,none,Farmer0] }}}}}} } run test9 for 4 expect 1 pred test16 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Chicken0 + Grain0,Chicken0,none,Farmer0] }}}}}} } run test16 for 4 expect 1 pred test12 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Farmer0,none,Farmer0] }}}}}} } run test12 for 4 expect 0 pred test13 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State1->Chicken0 + State2->Chicken0 + State3->Farmer0 + State3->Chicken0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Farmer0,none,Farmer0] }}}}}} } run test13 for 4 expect 0 pred test41 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Fox0 + Grain0,none,Farmer0 + Chicken0] }}}}}} } run test41 for 4 expect 1 pred test28 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Chicken0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State1->Chicken0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Chicken0,Fox0 + Grain0,Chicken0] }}}}}} } run test28 for 4 expect 0 pred test10 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Grain0,Fox0 + Grain0,none,Farmer0] }}}}}} } run test10 for 4 expect 1 pred test54 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Chicken0 + State2->Grain0 + State3->Fox0 + State3->Chicken0 far = State1->Farmer0 + State2->Fox0 + State2->Chicken0 + State2->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test54 for 4 expect 0 pred test21 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Chicken0 + State2->Farmer0 + State2->Fox0 + State2->Chicken0 + State3->Fox0 far = State1->Farmer0 + State1->Fox0 + State3->Farmer0 + State3->Chicken0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Grain0,Fox0 + Grain0,none,Farmer0] }}}}}} } run test21 for 4 expect 1 pred test53 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State0->Fox0 + State1->Farmer0 + State1->Fox0 + State1->Chicken0 + State2->Chicken0 + State3->Farmer0 + State3->Chicken0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test53 for 4 expect 0 pred test40 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Chicken0,none,Farmer0 + Fox0] }}}}}} } run test40 for 4 expect 1 pred test23 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Chicken0,none,Farmer0 + Fox0] }}}}}} } run test23 for 4 expect 1 pred test6 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Chicken0 + State2->Farmer0 + State2->Chicken0 far = State1->Farmer0 + State1->Fox0 + State2->Fox0 + State3->Farmer0 + State3->Fox0 + State3->Chicken0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test6 for 4 expect 1 pred test50 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State1->Farmer0 + State3->Farmer0 + State3->Fox0 far = State0->Fox0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test50 for 4 expect 0 pred test3 { some disj Farmer0: Farmer {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 no Fox Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Chicken0 + Grain0 eats = Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Chicken0 + State0->Grain0 + State1->Grain0 + State2->Farmer0 + State2->Grain0 + State3->Grain0 far = State1->Farmer0 + State1->Chicken0 + State2->Chicken0 + State3->Farmer0 + State3->Chicken0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}} } run test3 for 4 expect 0 pred test20 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Chicken0 + State2->Farmer0 + State2->Fox0 + State2->Chicken0 + State3->Chicken0 far = State1->Farmer0 + State1->Fox0 + State3->Farmer0 + State3->Fox0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0,Fox0,none,Farmer0] }}}}}} } run test20 for 4 expect 1 pred test56 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Chicken0 + State2->Farmer0 + State2->Chicken0 + State3->Chicken0 far = State1->Farmer0 + State1->Fox0 + State2->Fox0 + State3->Farmer0 + State3->Fox0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test56 for 4 expect 1 pred test14 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Grain0,Fox0 + Grain0,Grain0,Fox0 + Chicken0] }}}}}} } run test14 for 4 expect 0 pred test44 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Chicken0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Chicken0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Grain0,none,none,Farmer0 + Grain0] }}}}}} } run test44 for 4 expect 1 pred test31 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Chicken0 + Grain0,Chicken0,none,Farmer0 + Grain0] }}}}}} } run test31 for 4 expect 1 pred test55 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Farmer0 + State1->Grain0 + State2->Grain0 + State3->Fox0 + State3->Chicken0 far = State1->Fox0 + State1->Chicken0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Chicken0 + State2->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test55 for 4 expect 0 pred test43 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0,Fox0,none,Farmer0 + Chicken0] }}}}}} } run test43 for 4 expect 1 pred test51 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Farmer0 + State1->Fox0 + State1->Chicken0 + State1->Grain0 + State2->Fox0 + State2->Grain0 + State3->Farmer0 + State3->Fox0 + State3->Grain0 far = State2->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test51 for 4 expect 0 ",8100,True,3158.707240313085,median "#include ""il2cpp-config.h"" #ifndef _MSC_VER # include #else # include #endif #include #include #include #include #include #include #include ""class-internals.h"" #include ""codegen/il2cpp-codegen.h"" #include ""System_System_Collections_Specialized_NameObjectCol633582367.h"" #include ""System_System_Collections_Specialized_NameValueCol3047564564.h"" #include ""System_System_ComponentModel_EditorBrowsableAttrib1050682502.h"" #include ""System_System_ComponentModel_EditorBrowsableState373498655.h"" #include ""System_System_ComponentModel_TypeConverter745995970.h"" #include ""System_System_ComponentModel_TypeConverterAttribute252469870.h"" #include ""System_System_Net_Security_AuthenticationLevel2424130044.h"" #include ""System_System_Net_Security_SslPolicyErrors1928581431.h"" #include ""System_System_Net_Sockets_AddressFamily303362630.h"" #include ""System_System_Net_DefaultCertificatePolicy2545332216.h"" #include ""System_System_Net_FileWebRequest1571840111.h"" #include ""System_System_Net_FileWebRequestCreator1109072211.h"" #include ""System_System_Net_FtpRequestCreator3711983251.h"" #include ""System_System_Net_FtpWebRequest3120721823.h"" #include ""System_System_Net_GlobalProxySelection2251180943.h"" #include ""System_System_Net_HttpRequestCreator1416559589.h"" #include ""System_System_Net_HttpVersion1276659706.h"" #include ""System_System_Net_HttpWebRequest1951404513.h"" #include ""System_System_Net_IPAddress1399971723.h"" #include ""System_System_Net_IPv6Address2596635879.h"" #include ""System_System_Net_SecurityProtocolType3099771628.h"" #include ""System_System_Net_ServicePoint2765344313.h"" #include ""System_System_Net_ServicePointManager745663000.h"" #include ""System_System_Net_ServicePointManager_SPKey1552752485.h"" #include ""System_System_Net_WebHeaderCollection3028142837.h"" #include ""System_System_Net_WebProxy1169192840.h"" #include ""System_System_Net_WebRequest1365124353.h"" #include ""System_System_Security_Cryptography_X509Certificat2370524385.h"" #include ""System_System_Security_Cryptography_X509Certificates_P870392.h"" #include ""System_System_Security_Cryptography_X509Certificat1570828128.h"" #include ""System_System_Security_Cryptography_X509Certificat2183514610.h"" #include ""System_System_Security_Cryptography_X509Certificate452415348.h"" #include ""System_System_Security_Cryptography_X509Certificat2005802885.h"" #include ""System_System_Security_Cryptography_X509Certificat1562873317.h"" #include ""System_System_Security_Cryptography_X509Certificat4056456767.h"" #include ""System_System_Security_Cryptography_X509Certificat1108969367.h"" #include ""System_System_Security_Cryptography_X509Certificat2356134957.h"" #include ""System_System_Security_Cryptography_X509Certificat1197680765.h"" #include ""System_System_Security_Cryptography_X509Certificat1208230922.h"" #include ""System_System_Security_Cryptography_X509Certificate777637347.h"" #include ""System_System_Security_Cryptography_X509Certificate528874471.h"" #include ""System_System_Security_Cryptography_X509Certificat2081831987.h"" #include ""System_System_Security_Cryptography_X509Certificat3304975821.h"" #include ""System_System_Security_Cryptography_X509Certificat3452126517.h"" #include ""System_System_Security_Cryptography_X509Certificat4278378721.h"" #include ""System_System_Security_Cryptography_X509Certificate480677120.h"" #include ""System_System_Security_Cryptography_X509Certificat2099881051.h"" #include ""System_System_Security_Cryptography_X509Certificat1320896183.h"" #include ""System_System_Security_Cryptography_X509Certificate650873211.h"" #include ""System_System_Security_Cryptography_X509Certificat3763443773.h"" #include ""System_System_Security_Cryptography_X509Certificat3221716179.h"" #include ""System_System_Security_Cryptography_X509Certificat1038124237.h"" #include ""System_System_Security_Cryptography_X509Certificat2461349531.h"" #include ""System_System_Security_Cryptography_X509Certificat2669466891.h"" #include ""System_System_Security_Cryptography_X509Certificat2166064554.h"" #include ""System_System_Security_Cryptography_X509Certificat2065307963.h"" #include ""System_System_Security_Cryptography_X509Certificat1617430119.h"" #include ""System_System_Security_Cryptography_X509Certificat2508879999.h"" #include ""System_System_Security_Cryptography_X509Certificate110301003.h"" #include ""System_System_Security_Cryptography_X509Certificat2169036324.h"" #include ""System_System_Security_Cryptography_AsnDecodeStatu1962003286.h"" #include ""System_System_Security_Cryptography_AsnEncodedData463456204.h"" #include ""System_System_Security_Cryptography_Oid3221867120.h"" #include ""System_System_Security_Cryptography_OidCollection3790243618.h"" #include ""System_System_Security_Cryptography_OidEnumerator3674631724.h"" #include ""System_System_Text_RegularExpressions_BaseMachine4008011478.h"" #include ""System_System_Text_RegularExpressions_Capture4157900610.h"" #include ""System_System_Text_RegularExpressions_CaptureColle1671345504.h"" #include ""System_System_Text_RegularExpressions_Group3761430853.h"" #include ""System_System_Text_RegularExpressions_GroupCollecti939014605.h"" #include ""System_System_Text_RegularExpressions_Match3164245899.h"" #include ""System_System_Text_RegularExpressions_MatchCollect3718216671.h"" #include ""System_System_Text_RegularExpressions_MatchCollecti501456973.h"" #include ""System_System_Text_RegularExpressions_Regex1803876613.h"" #include ""System_System_Text_RegularExpressions_RegexOptions2418259727.h"" #include ""System_System_Text_RegularExpressions_OpCode586571952.h"" #include ""System_System_Text_RegularExpressions_OpFlags378191910.h"" #include ""System_System_Text_RegularExpressions_Position3781184359.h"" #include ""System_System_Text_RegularExpressions_FactoryCache2051534610.h"" #include ""System_System_Text_RegularExpressions_FactoryCache_655155419.h"" #include ""System_System_Text_RegularExpressions_MRUList33178162.h"" #include ""System_System_Text_RegularExpressions_MRUList_Node1107172180.h"" #include ""System_System_Text_RegularExpressions_Category1984577050.h"" #include ""System_System_Text_RegularExpressions_CategoryUtil3840220623.h"" #include ""System_System_Text_RegularExpressions_LinkRef2090853131.h"" #include ""System_System_Text_RegularExpressions_InterpreterFa556462562.h"" #include ""System_System_Text_RegularExpressions_PatternCompil637049905.h"" #include ""System_System_Text_RegularExpressions_PatternCompi3979537293.h"" #include ""System_System_Text_RegularExpressions_PatternCompi3337276394.h"" #include ""System_System_Text_RegularExpressions_LinkStack954792760.h"" #include ""System_System_Text_RegularExpressions_Mark2724874473.h"" #include ""System_System_Text_RegularExpressions_Interpreter3731288230.h"" #include ""System_System_Text_RegularExpressions_Interpreter_I273560425.h"" #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored ""-Winvalid-offsetof"" #pragma clang diagnostic ignored ""-Wunused-variable"" #endif extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize900 = { sizeof (KeysCollection_t633582367), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable900[1] = { KeysCollection_t633582367::get_offset_of_m_collection_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize901 = { sizeof (NameValueCollection_t3047564564), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable901[2] = { NameValueCollection_t3047564564::get_offset_of_cachedAllKeys_10(), NameValueCollection_t3047564564::get_offset_of_cachedAll_11(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize902 = { sizeof (EditorBrowsableAttribute_t1050682502), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable902[1] = { EditorBrowsableAttribute_t1050682502::get_offset_of_state_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize903 = { sizeof (EditorBrowsableState_t373498655)+ sizeof (Il2CppObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable903[4] = { EditorBrowsableState_t373498655::get_offset_of_value___1() + static_cast(sizeof(Il2CppObject)), 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize904 = { sizeof (TypeConverter_t745995970), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize905 = { sizeof (TypeConverterAttribute_t252469870), -1, sizeof(TypeConverterAttribute_t252469870_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable905[2] = { TypeConverterAttribute_t252469870_StaticFields::get_offset_of_Default_0(), TypeConverterAttribute_t252469870::get_offset_of_converter_type_1(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize906 = { sizeof (AuthenticationLevel_t2424130044)+ sizeof (Il2CppObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable906[4] = { AuthenticationLevel_t2424130044::get_offset_of_value___1() + static_cast(sizeof(Il2CppObject)), 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize907 = { sizeof (SslPolicyErrors_t1928581431)+ sizeof (Il2CppObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable907[5] = { SslPolicyErrors_t1928581431::get_offset_of_value___1() + static_cast(sizeof(Il2CppObject)), 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize908 = { sizeof (AddressFamily_t303362630)+ sizeof (Il2CppObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable908[32] = { AddressFamily_t303362630::get_offset_of_value___1() + static_cast(sizeof(Il2CppObject)), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize909 = { sizeof (DefaultCertificatePolicy_t2545332216), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize910 = { sizeof (FileWebRequest_t1571840111), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable910[9] = { FileWebRequest_t1571840111::get_offset_of_uri_6(), FileWebRequest_t1571840111::get_offset_of_webHeaders_7(), FileWebRequest_t1571840111::get_offset_of_connectionGroup_8(), FileWebRequest_t1571840111::get_offset_of_contentLength_9(), FileWebRequest_t1571840111::get_offset_of_fileAccess_10(), FileWebRequest_t1571840111::get_offset_of_method_11(), FileWebRequest_t1571840111::get_offset_of_proxy_12(), FileWebRequest_t1571840111::get_offset_of_preAuthenticate_13(), FileWebRequest_t1571840111::get_offset_of_timeout_14(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize911 = { sizeof (FileWebRequestCreator_t1109072211), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize912 = { sizeof (FtpRequestCreator_t3711983251), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize913 = { sizeof (FtpWebRequest_t3120721823), -1, sizeof(FtpWebRequest_t3120721823_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable913[11] = { FtpWebRequest_t3120721823::get_offset_of_requestUri_6(), FtpWebRequest_t3120721823::get_offset_of_proxy_7(), FtpWebRequest_t3120721823::get_offset_of_timeout_8(), FtpWebRequest_t3120721823::get_offset_of_rwTimeout_9(), FtpWebRequest_t3120721823::get_offset_of_binary_10(), FtpWebRequest_t3120721823::get_offset_of_usePassive_11(), FtpWebRequest_t3120721823::get_offset_of_method_12(), FtpWebRequest_t3120721823::get_offset_of_locker_13(), FtpWebRequest_t3120721823_StaticFields::get_offset_of_supportedCommands_14(), FtpWebRequest_t3120721823::get_offset_of_callback_15(), FtpWebRequest_t3120721823_StaticFields::get_offset_of_U3CU3Ef__amU24cache1C_16(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize914 = { sizeof (GlobalProxySelection_t2251180943), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize915 = { sizeof (HttpRequestCreator_t1416559589), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize916 = { sizeof (HttpVersion_t1276659706), -1, sizeof(HttpVersion_t1276659706_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable916[2] = { HttpVersion_t1276659706_StaticFields::get_offset_of_Version10_0(), HttpVersion_t1276659706_StaticFields::get_offset_of_Version11_1(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize917 = { sizeof (HttpWebRequest_t1951404513), -1, sizeof(HttpWebRequest_t1951404513_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable917[24] = { HttpWebRequest_t1951404513::get_offset_of_requestUri_6(), HttpWebRequest_t1951404513::get_offset_of_actualUri_7(), HttpWebRequest_t1951404513::get_offset_of_hostChanged_8(), HttpWebRequest_t1951404513::get_offset_of_allowAutoRedirect_9(), HttpWebRequest_t1951404513::get_offset_of_allowBuffering_10(), HttpWebRequest_t1951404513::get_offset_of_certificates_11(), HttpWebRequest_t1951404513::get_offset_of_connectionGroup_12(), HttpWebRequest_t1951404513::get_offset_of_contentLength_13(), HttpWebRequest_t1951404513::get_offset_of_webHeaders_14(), HttpWebRequest_t1951404513::get_offset_of_keepAlive_15(), HttpWebRequest_t1951404513::get_offset_of_maxAutoRedirect_16(), HttpWebRequest_t1951404513::get_offset_of_mediaType_17(), HttpWebRequest_t1951404513::get_offset_of_method_18(), HttpWebRequest_t1951404513::get_offset_of_initialMethod_19(), HttpWebRequest_t1951404513::get_offset_of_pipelined_20(), HttpWebRequest_t1951404513::get_offset_of_version_21(), HttpWebRequest_t1951404513::get_offset_of_proxy_22(), HttpWebRequest_t1951404513::get_offset_of_sendChunked_23(), HttpWebRequest_t1951404513::get_offset_of_servicePoint_24(), HttpWebRequest_t1951404513::get_offset_of_timeout_25(), HttpWebRequest_t1951404513::get_offset_of_redirects_26(), HttpWebRequest_t1951404513::get_offset_of_locker_27(), HttpWebRequest_t1951404513_StaticFields::get_offset_of_defaultMaxResponseHeadersLength_28(), HttpWebRequest_t1951404513::get_offset_of_readWriteTimeout_29(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize918 = { 0, -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize919 = { 0, -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize920 = { sizeof (IPAddress_t1399971723), -1, sizeof(IPAddress_t1399971723_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable920[11] = { IPAddress_t1399971723::get_offset_of_m_Address_0(), IPAddress_t1399971723::get_offset_of_m_Family_1(), IPAddress_t1399971723::get_offset_of_m_Numbers_2(), IPAddress_t1399971723::get_offset_of_m_ScopeId_3(), IPAddress_t1399971723_StaticFields::get_offset_of_Any_4(), IPAddress_t1399971723_StaticFields::get_offset_of_Broadcast_5(), IPAddress_t1399971723_StaticFields::get_offset_of_Loopback_6(), IPAddress_t1399971723_StaticFields::get_offset_of_None_7(), IPAddress_t1399971723_StaticFields::get_offset_of_IPv6Any_8(), IPAddress_t1399971723_StaticFields::get_offset_of_IPv6Loopback_9(), IPAddress_t1399971723_StaticFields::get_offset_of_IPv6None_10(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize921 = { sizeof (IPv6Address_t2596635879), -1, sizeof(IPv6Address_t2596635879_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable921[5] = { IPv6Address_t2596635879::get_offset_of_address_0(), IPv6Address_t2596635879::get_offset_of_prefixLength_1(), IPv6Address_t2596635879::get_offset_of_scopeId_2(), IPv6Address_t2596635879_StaticFields::get_offset_of_Loopback_3(), IPv6Address_t2596635879_StaticFields::get_offset_of_Unspecified_4(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize922 = { 0, -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize923 = { 0, -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize924 = { sizeof (SecurityProtocolType_t3099771628)+ sizeof (Il2CppObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable924[3] = { SecurityProtocolType_t3099771628::get_offset_of_value___1() + static_cast(sizeof(Il2CppObject)), 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize925 = { sizeof (ServicePoint_t2765344313), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable925[11] = { ServicePoint_t2765344313::get_offset_of_uri_0(), ServicePoint_t2765344313::get_offset_of_connectionLimit_1(), ServicePoint_t2765344313::get_offset_of_maxIdleTime_2(), ServicePoint_t2765344313::get_offset_of_currentConnections_3(), ServicePoint_t2765344313::get_offset_of_idleSince_4(), ServicePoint_t2765344313::get_offset_of_usesProxy_5(), ServicePoint_t2765344313::get_offset_of_sendContinue_6(), ServicePoint_t2765344313::get_offset_of_useConnect_7(), ServicePoint_t2765344313::get_offset_of_locker_8(), ServicePoint_t2765344313::get_offset_of_hostE_9(), ServicePoint_t2765344313::get_offset_of_useNagle_10(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize926 = { sizeof (ServicePointManager_t745663000), -1, sizeof(ServicePointManager_t745663000_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable926[10] = { ServicePointManager_t745663000_StaticFields::get_offset_of_servicePoints_0(), ServicePointManager_t745663000_StaticFields::get_offset_of_policy_1(), ServicePointManager_t745663000_StaticFields::get_offset_of_defaultConnectionLimit_2(), ServicePointManager_t745663000_StaticFields::get_offset_of_maxServicePointIdleTime_3(), ServicePointManager_t745663000_StaticFields::get_offset_of_maxServicePoints_4(), ServicePointManager_t745663000_StaticFields::get_offset_of__checkCRL_5(), ServicePointManager_t745663000_StaticFields::get_offset_of__securityProtocol_6(), ServicePointManager_t745663000_StaticFields::get_offset_of_expectContinue_7(), ServicePointManager_t745663000_StaticFields::get_offset_of_useNagle_8(), ServicePointManager_t745663000_StaticFields::get_offset_of_server_cert_cb_9(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize927 = { sizeof (SPKey_t1552752485), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable927[2] = { SPKey_t1552752485::get_offset_of_uri_0(), SPKey_t1552752485::get_offset_of_use_connect_1(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize928 = { sizeof (WebHeaderCollection_t3028142837), -1, sizeof(WebHeaderCollection_t3028142837_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable928[5] = { WebHeaderCollection_t3028142837_StaticFields::get_offset_of_restricted_12(), WebHeaderCollection_t3028142837_StaticFields::get_offset_of_multiValue_13(), WebHeaderCollection_t3028142837_StaticFields::get_offset_of_restricted_response_14(), WebHeaderCollection_t3028142837::get_offset_of_internallyCreated_15(), WebHeaderCollection_t3028142837_StaticFields::get_offset_of_allowed_chars_16(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize929 = { sizeof (WebProxy_t1169192840), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable929[5] = { WebProxy_t1169192840::get_offset_of_address_0(), WebProxy_t1169192840::get_offset_of_bypassOnLocal_1(), WebProxy_t1169192840::get_offset_of_bypassList_2(), WebProxy_t1169192840::get_offset_of_credentials_3(), WebProxy_t1169192840::get_offset_of_useDefaultCredentials_4(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize930 = { sizeof (WebRequest_t1365124353), -1, sizeof(WebRequest_t1365124353_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable930[5] = { WebRequest_t1365124353_StaticFields::get_offset_of_prefixes_1(), WebRequest_t1365124353_StaticFields::get_offset_of_isDefaultWebProxySet_2(), WebRequest_t1365124353_StaticFields::get_offset_of_defaultWebProxy_3(), WebRequest_t1365124353::get_offset_of_authentication_level_4(), WebRequest_t1365124353_StaticFields::get_offset_of_lockobj_5(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize931 = { sizeof (OpenFlags_t2370524385)+ sizeof (Il2CppObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable931[6] = { OpenFlags_t2370524385::get_offset_of_value___1() + static_cast(sizeof(Il2CppObject)), 0, 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize932 = { sizeof (PublicKey_t870392), -1, sizeof(PublicKey_t870392_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable932[5] = { PublicKey_t870392::get_offset_of__key_0(), PublicKey_t870392::get_offset_of__keyValue_1(), PublicKey_t870392::get_offset_of__params_2(), PublicKey_t870392::get_offset_of__oid_3(), PublicKey_t870392_StaticFields::get_offset_of_U3CU3Ef__switchU24map9_4(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize933 = { sizeof (StoreLocation_t1570828128)+ sizeof (Il2CppObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable933[3] = { StoreLocation_t1570828128::get_offset_of_value___1() + static_cast(sizeof(Il2CppObject)), 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize934 = { sizeof (StoreName_t2183514610)+ sizeof (Il2CppObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable934[9] = { StoreName_t2183514610::get_offset_of_value___1() + static_cast(sizeof(Il2CppObject)), 0, 0, 0, 0, 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize935 = { sizeof (X500DistinguishedName_t452415348), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable935[1] = { X500DistinguishedName_t452415348::get_offset_of_name_3(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize936 = { sizeof (X500DistinguishedNameFlags_t2005802885)+ sizeof (Il2CppObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable936[11] = { X500DistinguishedNameFlags_t2005802885::get_offset_of_value___1() + static_cast(sizeof(Il2CppObject)), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize937 = { sizeof (X509BasicConstraintsExtension_t1562873317), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable937[6] = { 0, 0, X509BasicConstraintsExtension_t1562873317::get_offset_of__certificateAuthority_6(), X509BasicConstraintsExtension_t1562873317::get_offset_of__hasPathLengthConstraint_7(), X509BasicConstraintsExtension_t1562873317::get_offset_of__pathLengthConstraint_8(), X509BasicConstraintsExtension_t1562873317::get_offset_of__status_9(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize938 = { sizeof (X509Certificate2_t4056456767), -1, sizeof(X509Certificate2_t4056456767_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable938[13] = { X509Certificate2_t4056456767::get_offset_of__archived_5(), X509Certificate2_t4056456767::get_offset_of__extensions_6(), X509Certificate2_t4056456767::get_offset_of__name_7(), X509Certificate2_t4056456767::get_offset_of__serial_8(), X509Certificate2_t4056456767::get_offset_of__publicKey_9(), X509Certificate2_t4056456767::get_offset_of_issuer_name_10(), X509Certificate2_t4056456767::get_offset_of_subject_name_11(), X509Certificate2_t4056456767::get_offset_of_signature_algorithm_12(), X509Certificate2_t4056456767::get_offset_of__cert_13(), X509Certificate2_t4056456767_StaticFields::get_offset_of_empty_error_14(), X509Certificate2_t4056456767_StaticFields::get_offset_of_commonName_15(), X509Certificate2_t4056456767_StaticFields::get_offset_of_email_16(), X509Certificate2_t4056456767_StaticFields::get_offset_of_signedData_17(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize939 = { sizeof (X509Certificate2Collection_t1108969367), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize940 = { sizeof (X509Certificate2Enumerator_t2356134957), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable940[1] = { X509Certificate2Enumerator_t2356134957::get_offset_of_enumerator_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize941 = { sizeof (X509CertificateCollection_t1197680765), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize942 = { sizeof (X509CertificateEnumerator_t1208230922), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable942[1] = { X509CertificateEnumerator_t1208230922::get_offset_of_enumerator_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize943 = { sizeof (X509Chain_t777637347), -1, sizeof(X509Chain_t777637347_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable943[15] = { X509Chain_t777637347::get_offset_of_location_0(), X509Chain_t777637347::get_offset_of_elements_1(), X509Chain_t777637347::get_offset_of_policy_2(), X509Chain_t777637347::get_offset_of_status_3(), X509Chain_t777637347_StaticFields::get_offset_of_Empty_4(), X509Chain_t777637347::get_offset_of_max_path_length_5(), X509Chain_t777637347::get_offset_of_working_issuer_name_6(), X509Chain_t777637347::get_offset_of_working_public_key_7(), X509Chain_t777637347::get_offset_of_bce_restriction_8(), X509Chain_t777637347::get_offset_of_roots_9(), X509Chain_t777637347::get_offset_of_cas_10(), X509Chain_t777637347::get_offset_of_collection_11(), X509Chain_t777637347_StaticFields::get_offset_of_U3CU3Ef__switchU24mapB_12(), X509Chain_t777637347_StaticFields::get_offset_of_U3CU3Ef__switchU24mapC_13(), X509Chain_t777637347_StaticFields::get_offset_of_U3CU3Ef__switchU24mapD_14(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize944 = { sizeof (X509ChainElement_t528874471), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable944[4] = { X509ChainElement_t528874471::get_offset_of_certificate_0(), X509ChainElement_t528874471::get_offset_of_status_1(), X509ChainElement_t528874471::get_offset_of_info_2(), X509ChainElement_t528874471::get_offset_of_compressed_status_flags_3(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize945 = { sizeof (X509ChainElementCollection_t2081831987), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable945[1] = { X509ChainElementCollection_t2081831987::get_offset_of__list_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize946 = { sizeof (X509ChainElementEnumerator_t3304975821), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable946[1] = { X509ChainElementEnumerator_t3304975821::get_offset_of_enumerator_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize947 = { sizeof (X509ChainPolicy_t3452126517), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable947[8] = { X509ChainPolicy_t3452126517::get_offset_of_apps_0(), X509ChainPolicy_t3452126517::get_offset_of_cert_1(), X509ChainPolicy_t3452126517::get_offset_of_store_2(), X509ChainPolicy_t3452126517::get_offset_of_rflag_3(), X509ChainPolicy_t3452126517::get_offset_of_mode_4(), X509ChainPolicy_t3452126517::get_offset_of_timeout_5(), X509ChainPolicy_t3452126517::get_offset_of_vflags_6(), X509ChainPolicy_t3452126517::get_offset_of_vtime_7(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize948 = { sizeof (X509ChainStatus_t4278378721)+ sizeof (Il2CppObject), sizeof(X509ChainStatus_t4278378721_marshaled_pinvoke), 0, 0 }; extern const int32_t g_FieldOffsetTable948[2] = { X509ChainStatus_t4278378721::get_offset_of_status_0() + static_cast(sizeof(Il2CppObject)), X509ChainStatus_t4278378721::get_offset_of_info_1() + static_cast(sizeof(Il2CppObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize949 = { sizeof (X509ChainStatusFlags_t480677120)+ sizeof (Il2CppObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable949[24] = { X509ChainStatusFlags_t480677120::get_offset_of_value___1() + static_cast(sizeof(Il2CppObject)), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize950 = { sizeof (X509EnhancedKeyUsageExtension_t2099881051), -1, sizeof(X509EnhancedKeyUsageExtension_t2099881051_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable950[3] = { X509EnhancedKeyUsageExtension_t2099881051::get_offset_of__enhKeyUsage_4(), X509EnhancedKeyUsageExtension_t2099881051::get_offset_of__status_5(), X509EnhancedKeyUsageExtension_t2099881051_StaticFields::get_offset_of_U3CU3Ef__switchU24mapE_6(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize951 = { sizeof (X509Extension_t1320896183), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable951[1] = { X509Extension_t1320896183::get_offset_of__critical_3(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize952 = { sizeof (X509ExtensionCollection_t650873211), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable952[1] = { X509ExtensionCollection_t650873211::get_offset_of__list_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize953 = { sizeof (X509ExtensionEnumerator_t3763443773), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable953[1] = { X509ExtensionEnumerator_t3763443773::get_offset_of_enumerator_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize954 = { sizeof (X509FindType_t3221716179)+ sizeof (Il2CppObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable954[16] = { X509FindType_t3221716179::get_offset_of_value___1() + static_cast(sizeof(Il2CppObject)), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize955 = { sizeof (X509KeyUsageExtension_t1038124237), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable955[5] = { 0, 0, 0, X509KeyUsageExtension_t1038124237::get_offset_of__keyUsages_7(), X509KeyUsageExtension_t1038124237::get_offset_of__status_8(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize956 = { sizeof (X509KeyUsageFlags_t2461349531)+ sizeof (Il2CppObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable956[11] = { X509KeyUsageFlags_t2461349531::get_offset_of_value___1() + static_cast(sizeof(Il2CppObject)), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize957 = { sizeof (X509NameType_t2669466891)+ sizeof (Il2CppObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable957[7] = { X509NameType_t2669466891::get_offset_of_value___1() + static_cast(sizeof(Il2CppObject)), 0, 0, 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize958 = { sizeof (X509RevocationFlag_t2166064554)+ sizeof (Il2CppObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable958[4] = { X509RevocationFlag_t2166064554::get_offset_of_value___1() + static_cast(sizeof(Il2CppObject)), 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize959 = { sizeof (X509RevocationMode_t2065307963)+ sizeof (Il2CppObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable959[4] = { X509RevocationMode_t2065307963::get_offset_of_value___1() + static_cast(sizeof(Il2CppObject)), 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize960 = { sizeof (X509Store_t1617430119), -1, sizeof(X509Store_t1617430119_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable960[6] = { X509Store_t1617430119::get_offset_of__name_0(), X509Store_t1617430119::get_offset_of__location_1(), X509Store_t1617430119::get_offset_of_list_2(), X509Store_t1617430119::get_offset_of__flags_3(), X509Store_t1617430119::get_offset_of_store_4(), X509Store_t1617430119_StaticFields::get_offset_of_U3CU3Ef__switchU24mapF_5(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize961 = { sizeof (X509SubjectKeyIdentifierExtension_t2508879999), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable961[5] = { 0, 0, X509SubjectKeyIdentifierExtension_t2508879999::get_offset_of__subjectKeyIdentifier_6(), X509SubjectKeyIdentifierExtension_t2508879999::get_offset_of__ski_7(), X509SubjectKeyIdentifierExtension_t2508879999::get_offset_of__status_8(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize962 = { sizeof (X509SubjectKeyIdentifierHashAlgorithm_t110301003)+ sizeof (Il2CppObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable962[4] = { X509SubjectKeyIdentifierHashAlgorithm_t110301003::get_offset_of_value___1() + static_cast(sizeof(Il2CppObject)), 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize963 = { sizeof (X509VerificationFlags_t2169036324)+ sizeof (Il2CppObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable963[15] = { X509VerificationFlags_t2169036324::get_offset_of_value___1() + static_cast(sizeof(Il2CppObject)), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize964 = { sizeof (AsnDecodeStatus_t1962003286)+ sizeof (Il2CppObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable964[7] = { AsnDecodeStatus_t1962003286::get_offset_of_value___1() + static_cast(sizeof(Il2CppObject)), 0, 0, 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize965 = { sizeof (AsnEncodedData_t463456204), -1, sizeof(AsnEncodedData_t463456204_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable965[3] = { AsnEncodedData_t463456204::get_offset_of__oid_0(), AsnEncodedData_t463456204::get_offset_of__raw_1(), AsnEncodedData_t463456204_StaticFields::get_offset_of_U3CU3Ef__switchU24mapA_2(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize966 = { sizeof (Oid_t3221867120), -1, sizeof(Oid_t3221867120_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable966[3] = { Oid_t3221867120::get_offset_of__value_0(), Oid_t3221867120::get_offset_of__name_1(), Oid_t3221867120_StaticFields::get_offset_of_U3CU3Ef__switchU24map10_2(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize967 = { sizeof (OidCollection_t3790243618), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable967[2] = { OidCollection_t3790243618::get_offset_of__list_0(), OidCollection_t3790243618::get_offset_of__readOnly_1(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize968 = { sizeof (OidEnumerator_t3674631724), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable968[2] = { OidEnumerator_t3674631724::get_offset_of__collection_0(), OidEnumerator_t3674631724::get_offset_of__position_1(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize969 = { sizeof (BaseMachine_t4008011478), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable969[1] = { BaseMachine_t4008011478::get_offset_of_needs_groups_or_captures_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize970 = { sizeof (Capture_t4157900610), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable970[3] = { Capture_t4157900610::get_offset_of_index_0(), Capture_t4157900610::get_offset_of_length_1(), Capture_t4157900610::get_offset_of_text_2(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize971 = { sizeof (CaptureCollection_t1671345504), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable971[1] = { CaptureCollection_t1671345504::get_offset_of_list_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize972 = { sizeof (Group_t3761430853), -1, sizeof(Group_t3761430853_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable972[3] = { Group_t3761430853_StaticFields::get_offset_of_Fail_3(), Group_t3761430853::get_offset_of_success_4(), Group_t3761430853::get_offset_of_captures_5(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize973 = { sizeof (GroupCollection_t939014605), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable973[2] = { GroupCollection_t939014605::get_offset_of_list_0(), GroupCollection_t939014605::get_offset_of_gap_1(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize974 = { sizeof (Match_t3164245899), -1, sizeof(Match_t3164245899_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable974[5] = { Match_t3164245899::get_offset_of_regex_6(), Match_t3164245899::get_offset_of_machine_7(), Match_t3164245899::get_offset_of_text_length_8(), Match_t3164245899::get_offset_of_groups_9(), Match_t3164245899_StaticFields::get_offset_of_empty_10(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize975 = { sizeof (MatchCollection_t3718216671), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable975[2] = { MatchCollection_t3718216671::get_offset_of_current_0(), MatchCollection_t3718216671::get_offset_of_list_1(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize976 = { sizeof (Enumerator_t501456973), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable976[2] = { Enumerator_t501456973::get_offset_of_index_0(), Enumerator_t501456973::get_offset_of_coll_1(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize977 = { sizeof (Regex_t1803876613), -1, sizeof(Regex_t1803876613_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable977[9] = { Regex_t1803876613_StaticFields::get_offset_of_cache_0(), Regex_t1803876613::get_offset_of_machineFactory_1(), Regex_t1803876613::get_offset_of_mapping_2(), Regex_t1803876613::get_offset_of_group_count_3(), Regex_t1803876613::get_offset_of_gap_4(), Regex_t1803876613::get_offset_of_group_names_5(), Regex_t1803876613::get_offset_of_group_numbers_6(), Regex_t1803876613::get_offset_of_pattern_7(), Regex_t1803876613::get_offset_of_roptions_8(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize978 = { sizeof (RegexOptions_t2418259727)+ sizeof (Il2CppObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable978[10] = { RegexOptions_t2418259727::get_offset_of_value___1() + static_cast(sizeof(Il2CppObject)), 0, 0, 0, 0, 0, 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize979 = { sizeof (OpCode_t586571952)+ sizeof (Il2CppObject), sizeof(uint16_t), 0, 0 }; extern const int32_t g_FieldOffsetTable979[26] = { OpCode_t586571952::get_offset_of_value___1() + static_cast(sizeof(Il2CppObject)), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize980 = { sizeof (OpFlags_t378191910)+ sizeof (Il2CppObject), sizeof(uint16_t), 0, 0 }; extern const int32_t g_FieldOffsetTable980[6] = { OpFlags_t378191910::get_offset_of_value___1() + static_cast(sizeof(Il2CppObject)), 0, 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize981 = { sizeof (Position_t3781184359)+ sizeof (Il2CppObject), sizeof(uint16_t), 0, 0 }; extern const int32_t g_FieldOffsetTable981[11] = { Position_t3781184359::get_offset_of_value___1() + static_cast(sizeof(Il2CppObject)), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize982 = { 0, -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize983 = { 0, -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize984 = { sizeof (FactoryCache_t2051534610), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable984[3] = { FactoryCache_t2051534610::get_offset_of_capacity_0(), FactoryCache_t2051534610::get_offset_of_factories_1(), FactoryCache_t2051534610::get_offset_of_mru_list_2(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize985 = { sizeof (Key_t655155419), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable985[2] = { Key_t655155419::get_offset_of_pattern_0(), Key_t655155419::get_offset_of_options_1(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize986 = { sizeof (MRUList_t33178162), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable986[2] = { MRUList_t33178162::get_offset_of_head_0(), MRUList_t33178162::get_offset_of_tail_1(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize987 = { sizeof (Node_t1107172180), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable987[3] = { Node_t1107172180::get_offset_of_value_0(), Node_t1107172180::get_offset_of_previous_1(), Node_t1107172180::get_offset_of_next_2(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize988 = { sizeof (Category_t1984577050)+ sizeof (Il2CppObject), sizeof(uint16_t), 0, 0 }; extern const int32_t g_FieldOffsetTable988[146] = { Category_t1984577050::get_offset_of_value___1() + static_cast(sizeof(Il2CppObject)), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize989 = { sizeof (CategoryUtils_t3840220623), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize990 = { sizeof (LinkRef_t2090853131), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize991 = { 0, -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize992 = { sizeof (InterpreterFactory_t556462562), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable992[4] = { InterpreterFactory_t556462562::get_offset_of_mapping_0(), InterpreterFactory_t556462562::get_offset_of_pattern_1(), InterpreterFactory_t556462562::get_offset_of_namesMapping_2(), InterpreterFactory_t556462562::get_offset_of_gap_3(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize993 = { sizeof (PatternCompiler_t637049905), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable993[1] = { PatternCompiler_t637049905::get_offset_of_pgm_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize994 = { sizeof (PatternLinkStack_t3979537293), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable994[1] = { PatternLinkStack_t3979537293::get_offset_of_link_1(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize995 = { sizeof (Link_t3337276394)+ sizeof (Il2CppObject), sizeof(Link_t3337276394 ), 0, 0 }; extern const int32_t g_FieldOffsetTable995[2] = { Link_t3337276394::get_offset_of_base_addr_0() + static_cast(sizeof(Il2CppObject)), Link_t3337276394::get_offset_of_offset_addr_1() + static_cast(sizeof(Il2CppObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize996 = { sizeof (LinkStack_t954792760), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable996[1] = { LinkStack_t954792760::get_offset_of_stack_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize997 = { sizeof (Mark_t2724874473)+ sizeof (Il2CppObject), sizeof(Mark_t2724874473 ), 0, 0 }; extern const int32_t g_FieldOffsetTable997[3] = { Mark_t2724874473::get_offset_of_Start_0() + static_cast(sizeof(Il2CppObject)), Mark_t2724874473::get_offset_of_End_1() + static_cast(sizeof(Il2CppObject)), Mark_t2724874473::get_offset_of_Previous_2() + static_cast(sizeof(Il2CppObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize998 = { sizeof (Interpreter_t3731288230), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable998[16] = { Interpreter_t3731288230::get_offset_of_program_1(), Interpreter_t3731288230::get_offset_of_program_start_2(), Interpreter_t3731288230::get_offset_of_text_3(), Interpreter_t3731288230::get_offset_of_text_end_4(), Interpreter_t3731288230::get_offset_of_group_count_5(), Interpreter_t3731288230::get_offset_of_match_min_6(), Interpreter_t3731288230::get_offset_of_qs_7(), Interpreter_t3731288230::get_offset_of_scan_ptr_8(), Interpreter_t3731288230::get_offset_of_repeat_9(), Interpreter_t3731288230::get_offset_of_fast_10(), Interpreter_t3731288230::get_offset_of_stack_11(), Interpreter_t3731288230::get_offset_of_deep_12(), Interpreter_t3731288230::get_offset_of_marks_13(), Interpreter_t3731288230::get_offset_of_mark_start_14(), Interpreter_t3731288230::get_offset_of_mark_end_15(), Interpreter_t3731288230::get_offset_of_groups_16(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize999 = { sizeof (IntStack_t273560425)+ sizeof (Il2CppObject), sizeof(IntStack_t273560425_marshaled_pinvoke), 0, 0 }; extern const int32_t g_FieldOffsetTable999[2] = { IntStack_t273560425::get_offset_of_values_0() + static_cast(sizeof(Il2CppObject)), IntStack_t273560425::get_offset_of_count_1() + static_cast(sizeof(Il2CppObject)), }; #ifdef __clang__ #pragma clang diagnostic pop #endif ",16223,True,4182.334244350178,median "[[jdbc]] == JDBC Support Spring Integration provides channel adapters for receiving and sending messages by using database queries. Through those adapters, Spring Integration supports not only plain JDBC SQL queries but also stored procedure and stored function calls. You need to include this dependency into your project: ==== [source, xml, subs=""normal"", role=""primary""] .Maven ---- org.springframework.integration spring-integration-jdbc {project-version} ---- [source, groovy, subs=""normal"", role=""secondary""] .Gradle ---- compile ""org.springframework.integration:spring-integration-jdbc:{project-version}"" ---- ==== By default, the following JDBC components are available: * <> * <> * <> * <> * <> * <> The Spring Integration JDBC Module also provides a <>. [[jdbc-inbound-channel-adapter]] === Inbound Channel Adapter The main function of an inbound channel adapter is to execute a SQL `SELECT` query and turn the result set into a message. The message payload is the whole result set (expressed as a `List`), and the types of the items in the list depend on the row-mapping strategy. The default strategy is a generic mapper that returns a `Map` for each row in the query result. Optionally, you can change this by adding a reference to a `RowMapper` instance (see the https://docs.spring.io/spring/docs/current/spring-framework-reference/html/jdbc.html[Spring JDBC] documentation for more detailed information about row mapping). NOTE: If you want to convert rows in the `SELECT` query result to individual messages, you can use a downstream splitter. The inbound adapter also requires a reference to either a `JdbcTemplate` instance or a `DataSource`. As well as the `SELECT` statement to generate the messages, the adapter also has an `UPDATE` statement that marks the records as processed so that they do not show up in the next poll. The update can be parameterized by the list of IDs from the original select. By default, this is done through a naming convention (a column in the input result set called `id` is translated into a list in the parameter map for the update called `id`). The following example defines an inbound channel adapter with an update query and a `DataSource` reference. ==== [source,xml] ---- ---- ==== NOTE: The parameters in the update query are specified with a colon (`:`) prefix to the name of a parameter (which, in the preceding example, is an expression to be applied to each of the rows in the polled result set). This is a standard feature of the named parameter JDBC support in Spring JDBC, combined with a convention (projection onto the polled result list) adopted in Spring Integration. The underlying Spring JDBC features limit the available expressions (for example, most special characters other than a period are disallowed), but since the target is usually a list of objects (possibly a list of one) that are addressable by bean paths this is not unduly restrictive. To change the parameter generation strategy, you can inject a `SqlParameterSourceFactory` into the adapter to override the default behavior (the adapter has a `sql-parameter-source-factory` attribute). Spring Integration provides `ExpressionEvaluatingSqlParameterSourceFactory`, which creates a SpEL-based parameter source, with the results of the query as the `#root` object. (If `update-per-row` is true, the root object is the row). If the same parameter name appears multiple times in the update query, it is evaluated only once, and its result is cached. You can also use a parameter source for the select query. In this case, since there is no ""`result`"" object to evaluate against, a single parameter source is used each time (rather than using a parameter source factory). Starting with version 4.0, you can use Spring to create a SpEL based parameter source, as the following example shows: ==== [source,xml] ---- ---- ==== The `value` in each parameter expression can be any valid SpEL expression. The `#root` object for the expression evaluation is the constructor argument defined on the `parameterSource` bean. It is static for all evaluations (in the preceding example, an empty `String`). Starting with version 5.0, you ca supply `ExpressionEvaluatingSqlParameterSourceFactory` with `sqlParameterTypes` to specify the target SQL type for the particular parameter. The following example provides SQL types for the parameters being used in the query: ==== [source,xml] ---- ---- ==== IMPORTANT: Use the `createParameterSourceNoCache` factory method. Otherwise, the parameter source caches the result of the evaluation. Also note that, because caching is disabled, if the same parameter name appears in the select query multiple times, it is re-evaluated for each occurrence. [[jdbc-polling-transactions]] ==== Polling and Transactions The inbound adapter accepts a regular Spring Integration poller as a child element. Consequently, the frequency of the polling can be controlled (among other uses). An important feature of the poller for JDBC usage is the option to wrap the poll operation in a transaction, as the following example shows: ==== [source,xml] ---- ---- ==== NOTE: If you do not explicitly specify a poller, a default value is used. As is normal with Spring Integration, it can be defined as a top-level bean). In the preceding example, the database is polled every 1000 milliseconds (or once a second), and the update and select queries are both executed in the same transaction. The transaction manager configuration is not shown. However, as long as it is aware of the data source, the poll is transactional. A common use case is for the downstream channels to be direct channels (the default), so that the endpoints are invoked in the same thread and, hence, the same transaction. That way, if any of them fail, the transaction rolls back and the input data is reverted to its original state. [[jdbc-max-rows-versus-max-messages-per-poll]] ==== `max-rows` Versus `max-messages-per-poll` The JDBC inbound channel adapter defines an attribute called `max-rows`. When you specify the adapter's poller, you can also define a property called `max-messages-per-poll`. While these two attributes look similar, their meaning is quite different. `max-messages-per-poll` specifies the number of times the query is executed per polling interval, whereas `max-rows` specifies the number of rows returned for each execution. Under normal circumstances, you would likely not want to set the poller's `max-messages-per-poll` property when you use the JDBC inbound channel adapter. Its default value is `1`, which means that the JDBC inbound channel adapter's https://docs.spring.io/spring-integration/api/org/springframework/integration/jdbc/JdbcPollingChannelAdapter.html#receive()[`receive()`] method is executed exactly once for each poll interval. Setting the `max-messages-per-poll` attribute to a larger value means that the query is executed that many times back to back. For more information regarding the `max-messages-per-poll` attribute, see <<./channel-adapter.adoc#channel-adapter-namespace-inbound,Configuring An Inbound Channel Adapter>>. In contrast, the `max-rows` attribute, if greater than `0`, specifies the maximum number of rows to be used from the query result set created by the `receive()` method. If the attribute is set to `0`, all rows are included in the resulting message. The attribute defaults to `0`. NOTE: It is recommended to use result set limiting via vendor-specific query options, for example MySQL `LIMIT` or SQL Server `TOP` or Oracle's `ROWNUM`. See the particular vendor documentation for more information. [[jdbc-outbound-channel-adapter]] === Outbound Channel Adapter The outbound channel adapter is the inverse of the inbound: its role is to handle a message and use it to execute a SQL query. By default, the message payload and headers are available as input parameters to the query, as the following example shows: ==== [source,xml] ---- ---- ==== In the preceding example, messages arriving at the channel labelled `input` have a payload of a map with a key of `something`, so the `[]` operator dereferences that value from the map. The headers are also accessed as a map. NOTE: The parameters in the preceding query are bean property expressions on the incoming message (not SpEL expressions). This behavior is part of the `SqlParameterSource`, which is the default source created by the outbound adapter. You can inject a different `SqlParameterSourceFactory` to get different behavior. The outbound adapter requires a reference to either a `DataSource` or a `JdbcTemplate`. You can also inject a `SqlParameterSourceFactory` to control the binding of each incoming message to a query. If the input channel is a direct channel, the outbound adapter runs its query in the same thread and, therefore, the same transaction (if there is one) as the sender of the message. ==== Passing Parameters by Using SpEL Expressions A common requirement for most JDBC channel adapters is to pass parameters as part of SQL queries or stored procedures or functions. As mentioned earlier, these parameters are by default bean property expressions, not SpEL expressions. However, if you need to pass SpEL expression as parameters, you must explicitly inject a `SqlParameterSourceFactory`. The following example uses a `ExpressionEvaluatingSqlParameterSourceFactory` to achieve that requirement: ==== [source,xml] ---- ---- ==== For further information, see <>. ==== Using the `PreparedStatement` Callback Sometimes, the flexibility and loose-coupling of `SqlParameterSourceFactory` does not do what we need for the target `PreparedStatement` or we need to do some low-level JDBC work. The Spring JDBC module provides APIs to configure the execution environment (such as `ConnectionCallback` or `PreparedStatementCreator`) and manipulate parameter values (such as `SqlParameterSource`). It can even access APIs for low-level operations, such as `StatementCallback`. Starting with Spring Integration 4.2, `MessagePreparedStatementSetter` allows the specification of parameters on the `PreparedStatement` manually, in the `requestMessage` context. This class plays exactly the same role as `PreparedStatementSetter` in the standard Spring JDBC API. Actually, it is invoked directly from an inline `PreparedStatementSetter` implementation when the `JdbcMessageHandler` invokes `execute` on the `JdbcTemplate`. This functional interface option is mutually exclusive with `sqlParameterSourceFactory` and can be used as a more powerful alternative to populate parameters of the `PreparedStatement` from the `requestMessage`. For example, it is useful when we need to store `File` data to the DataBase `BLOB` column in a streaming manner. The following example shows how to do so: ==== [source,java] ---- @Bean @ServiceActivator(inputChannel = ""storeFileChannel"") public MessageHandler jdbcMessageHandler(DataSource dataSource) { JdbcMessageHandler jdbcMessageHandler = new JdbcMessageHandler(dataSource, ""INSERT INTO imagedb (image_name, content, description) VALUES (?, ?, ?)""); jdbcMessageHandler.setPreparedStatementSetter((ps, m) -> { ps.setString(1, m.getHeaders().get(FileHeaders.FILENAME)); try (FileInputStream inputStream = new FileInputStream((File) m.getPayload()); ) { ps.setBlob(2, inputStream); } catch (Exception e) { throw new MessageHandlingException(m, e); } ps.setClob(3, new StringReader(m.getHeaders().get(""description"", String.class))); }); return jdbcMessageHandler; } ---- ==== From the XML configuration perspective, the `prepared-statement-setter` attribute is available on the `` component. It lets you specify a `MessagePreparedStatementSetter` bean reference. ==== Batch Update Starting with version 5.1, the `JdbcMessageHandler` performs a `JdbcOperations.batchUpdate()` if the payload of the request message is an `Iterable` instance. Each element of the `Iterable` is wrapped to a `Message` with the headers from the request message. In the case of regular `SqlParameterSourceFactory`-based configuration these messages are used to build an `SqlParameterSource[]` for an argument used in the mentioned `JdbcOperations.batchUpdate()` function. When a `MessagePreparedStatementSetter` configuration is applied, a `BatchPreparedStatementSetter` variant is used to iterate over those messages for each item and the provided `MessagePreparedStatementSetter` is called against them. The batch update is not supported when `keysGenerated` mode is selected. [[jdbc-outbound-gateway]] === Outbound Gateway The outbound gateway is like a combination of the outbound and inbound adapters: Its role is to handle a message and use it to execute a SQL query and then respond with the result by sending it to a reply channel. By default, the message payload and headers are available as input parameters to the query, as the following example shows: ==== [source,xml] ---- ---- ==== The result of the preceding example is to insert a record into the `mythings` table and return a message that indicates the number of rows affected (the payload is a map: `{UPDATED=1}`) to the output channel . If the update query is an insert with auto-generated keys, you can populate the reply message with the generated keys by adding `keys-generated=""true""` to the preceding example (this is not the default because it is not supported by some database platforms). The following example shows the changed configuration: ==== [source,xml] ---- ---- ==== Instead of the update count or the generated keys, you can also provide a select query to execute and generate a reply message from the result (such as the inbound adapter), as the following example shows: ==== [source,xml] ---- ---- ==== Since Spring Integration 2.2, the update SQL query is no longer mandatory. You can now provide only a select query, by using either the `query` attribute or the `query` element. This is extremely useful if you need to actively retrieve data by using, for example, a generic gateway or a payload enricher. The reply message is then generated from the result (similar to how the inbound adapter works) and passed to the reply channel. The following example show to use the `query` attribute: ==== [source,xml] ---- ---- ==== [IMPORTANT] ==== By default, the component for the `SELECT` query returns only one (the first) row from the cursor. You can adjust this behavior with the `max-rows` option. If you need to return all the rows from the SELECT, consider specifying `max-rows=""0""`. ==== As with the channel adapters, you can also provide `SqlParameterSourceFactory` instances for request and reply. The default is the same as for the outbound adapter, so the request message is available as the root of an expression. If `keys-generated=""true""`, the root of the expression is the generated keys (a map if there is only one or a list of maps if multi-valued). The outbound gateway requires a reference to either a `DataSource` or a `JdbcTemplate`. It can also have a `SqlParameterSourceFactory` injected to control the binding of the incoming message to the query. Starting with the version 4.2, the `request-prepared-statement-setter` attribute is available on the `` as an alternative to `request-sql-parameter-source-factory`. It lets you specify a `MessagePreparedStatementSetter` bean reference, which implements more sophisticated `PreparedStatement` preparation before its execution. See <> for more information about `MessagePreparedStatementSetter`. [[jdbc-message-store]] === JDBC Message Store Spring Integration provides two JDBC specific message store implementations. The `JdbcMessageStore` is suitable for use with aggregators and the claim check pattern. The `JdbcChannelMessageStore` implementation provides a more targeted and scalable implementation specifically for message channel. Note that you can use a `JdbcMessageStore` to back a message channel, `JdbcChannelMessageStore` is optimized for that purpose. IMPORTANT: Starting with versions 5.0.11, 5.1.2, the indexes for the `JdbcChannelMessageStore` have been optimized. If you have large message groups in such a store, you may wish to alter the indexes. Furthermore, the index for `PriorityChannel` is commented out because it is not needed unless you are using such channels backed by JDBC. NOTE: When using the `OracleChannelMessageStoreQueryProvider`, the priority channel index **must** be added because it is included in a hint in the query. ==== Initializing the Database Before starting to use JDBC message store components, you should provision a target database with the appropriate objects. Spring Integration ships with some sample scripts that can be used to initialize a database. In the `spring-integration-jdbc` JAR file, you can find scripts in the `org.springframework.integration.jdbc` package. It provides an example create and an example drop script for a range of common database platforms. A common way to use these scripts is to reference them in a https://docs.spring.io/spring/docs/current/spring-framework-reference/html/jdbc.html#jdbc-intializing-datasource[Spring JDBC data source initializer]. Note that the scripts are provided as samples and as specifications of the required table and column names. You may find that you need to enhance them for production use (for, example, by adding index declarations). [[jdbc-message-store-generic]] ==== The Generic JDBC Message Store The JDBC module provides an implementation of the Spring Integration `MessageStore` (important in the claim check pattern) and `MessageGroupStore` (important in stateful patterns such as an aggregator) backed by a database. Both interfaces are implemented by the `JdbcMessageStore`, and there is support for configuring store instances in XML, as the following example shows: ==== [source,xml] ---- ---- ==== You can specify a `JdbcTemplate` instead of a `DataSource`. The following example shows some other optional attributes: ==== [source,xml] ---- ---- ==== In the preceding example, we have specified a `LobHandler` for dealing with messages as large objects (which is often necessary for Oracle) and a prefix for the table names in the queries generated by the store. The table name prefix defaults to `INT_`. [[jdbc-message-store-channels]] ==== Backing Message Channels If you intend to back message channels with JDBC, we recommend using the `JdbcChannelMessageStore` implementation. It works only in conjunction with Message Channels. ===== Supported Databases The `JdbcChannelMessageStore` uses database-specific SQL queries to retrieve messages from the database. Therefore, you must set the `ChannelMessageStoreQueryProvider` property on the `JdbcChannelMessageStore`. This `channelMessageStoreQueryProvider` provides the SQL queries for the particular database you specify. Spring Integration provides support for the following relational databases: * PostgreSQL * HSQLDB * MySQL * Oracle * Derby * H2 * SqlServer * Sybase * DB2 If your database is not listed, you can extend the `AbstractChannelMessageStoreQueryProvider` class and provide your own custom queries. Version 4.0 added the `MESSAGE_SEQUENCE` column to the table to ensure first-in-first-out (FIFO) queueing even when messages are stored in the same millisecond. ===== Custom Message Insertion Since version 5.0, by overloading the `ChannelMessageStorePreparedStatementSetter` class, you can provide a custom implementation for message insertion in the `JdbcChannelMessageStore`. You can use it to set different columns or change the table structure or serialization strategy. For example, instead of default serialization to `byte[]`, you can store its structure as a JSON string. The following example uses the default implementation of `setValues` to store common columns and overrides the behavior to store the message payload as a `varchar`: ==== [source,java] ---- public class JsonPreparedStatementSetter extends ChannelMessageStorePreparedStatementSetter { @Override public void setValues(PreparedStatement preparedStatement, Message requestMessage, Object groupId, String region, boolean priorityEnabled) throws SQLException { // Populate common columns super.setValues(preparedStatement, requestMessage, groupId, region, priorityEnabled); // Store message payload as varchar preparedStatement.setString(6, requestMessage.getPayload().toString()); } } ---- ==== [IMPORTANT] ==== Generally, we do not recommend using a relational database for queuing. Instead, if possible, consider using either JMS- or AMQP-backed channels instead. For further reference, see the following resources: * https://www.engineyard.com/blog/2011/5-subtle-ways-youre-using-mysql-as-a-queue-and-why-itll-bite-you/[5 subtle ways you’re using MySQL as a queue, and why it’ll bite you]. * https://mikehadlow.blogspot.com/2012/04/database-as-queue-anti-pattern.html[The Database As Queue Anti-Pattern]. ==== ===== Concurrent Polling When polling a message channel, you have the option to configure the associated `Poller` with a `TaskExecutor` reference. [IMPORTANT] ==== Keep in mind, though, that if you use a JDBC backed message channel and you plan to poll the channel and consequently the message store transactionally with multiple threads, you should ensure that you use a relational database that supports https://en.wikipedia.org/wiki/Multiversion_concurrency_control[Multiversion Concurrency Control] (MVCC). Otherwise, locking may be an issue and the performance, when using multiple threads, may not materialize as expected. For example, Apache Derby is problematic in that regard. To achieve better JDBC queue throughput and avoid issues when different threads may poll the same `Message` from the queue, it is *important* to set the `usingIdCache` property of `JdbcChannelMessageStore` to `true` when using databases that do not support MVCC. The following example shows how to do so: [source,xml] ---- ---- ==== ===== Priority Channel Starting with version 4.0, `JdbcChannelMessageStore` implements `PriorityCapableChannelMessageStore` and provides the `priorityEnabled` option, letting it be used as a `message-store` reference for `priority-queue` instances. For this purpose, the `INT_CHANNEL_MESSAGE` table has a `MESSAGE_PRIORITY` column to store the value of `PRIORITY` message headers. In addition, a new `MESSAGE_SEQUENCE` column lets us achieve a robust first-in-first-out (FIFO) polling mechanism, even when multiple messages are stored with the same priority in the same millisecond. Messages are polled (selected) from the database with `order by MESSAGE_PRIORITY DESC NULLS LAST, CREATED_DATE, MESSAGE_SEQUENCE`. NOTE: We do not recommend using the same `JdbcChannelMessageStore` bean for priority and non-priority queue channels, because the `priorityEnabled` option applies to the entire store and proper FIFO queue semantics are not retained for the queue channel. However, the same `INT_CHANNEL_MESSAGE` table (and even `region`) can be used for both `JdbcChannelMessageStore` types. To configure that scenario, you can extend one message store bean from the other, as the following example shows: ==== [source,xml] ---- ---- ==== ==== Partitioning a Message Store It is common to use a `JdbcMessageStore` as a global store for a group of applications or nodes in the same application. To provide some protection against name clashes and to give control over the database meta-data configuration, the message store lets the tables be partitioned in two ways. One way is to use separate table names, by changing the prefix (as <>). The other way is to specify a `region` name for partitioning data within a single table. An important use case for the second approach is when the `MessageStore` is managing persistent queues that back a Spring Integration Message Channel. The message data for a persistent channel is keyed in the store on the channel name. Consequently, if the channel names are not globally unique, the channels can pick up data that is not intended for them. To avoid this danger, you can use the message store `region` to keep data separate for different physical channels that have the same logical name. [[stored-procedures]] === Stored Procedures In certain situations, plain JDBC support is not sufficient. Maybe you deal with legacy relational database schemas or you have complex data processing needs, but, ultimately, you have to use https://en.wikipedia.org/wiki/Stored_procedure[stored procedures] or stored functions. Since Spring Integration 2.1, we provide three components to execute stored procedures or stored functions: * Stored Procedures Inbound Channel Adapter * Stored Procedures Outbound Channel Adapter * Stored Procedures Outbound Gateway [[sp-supported-databases]] ==== Supported Databases In order to enable calls to stored procedures and stored functions, the stored procedure components use the https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/jdbc/core/simple/SimpleJdbcCall.html[`org.springframework.jdbc.core.simple.SimpleJdbcCall`] class. Consequently, the following databases are fully supported for executing stored procedures: * Apache Derby * DB2 * MySQL * Microsoft SQL Server * Oracle * PostgreSQL * Sybase If you want to execute stored functions instead, the following databases are fully supported: * MySQL * Microsoft SQL Server * Oracle * PostgreSQL [NOTE] ===== Even though your particular database may not be fully supported, chances are that you can use the stored procedure Spring Integration components quite successfully anyway, provided your RDBMS supports stored procedures or stored functions. As a matter of fact, some provided integration tests use the https://www.h2database.com/[H2 database]. Nevertheless, it is very important to thoroughly test those usage scenarios. ===== [[sp-configuration]] ==== Configuration The stored procedure components provide full XML Namespace support, and configuring the components is similar as for the general purpose JDBC components discussed earlier. [[sp-common-config-params]] ==== Common Configuration Attributes All stored procedure components share certain configuration parameters: * `auto-startup`: Lifecycle attribute signaling whether this component should be started during application context startup. It defaults to `true`. Optional. * `data-source`: Reference to a `javax.sql.DataSource`, which is used to access the database. Required. * `id`: Identifies the underlying Spring bean definition, which is an instance of either `EventDrivenConsumer` or `PollingConsumer`, depending on whether the outbound channel adapter's `channel` attribute references a `SubscribableChannel` or a `PollableChannel`. Optional. * `ignore-column-meta-data`: For fully supported databases, the underlying https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/jdbc/core/simple/SimpleJdbcCall.html[`SimpleJdbcCall`] class can automatically retrieve the parameter information for the stored procedure or stored function from the JDBC metadata. + However, if the database does not support metadata lookups or if you need to provide customized parameter definitions, this flag can be set to `true`. It defaults to `false`. Optional. * `is-function`: If `true`, a SQL Function is called. In that case, the `stored-procedure-name` or `stored-procedure-name-expression` attributes define the name of the called function. It defaults to `false`. Optional. * `stored-procedure-name`: This attribute specifies the name of the stored procedure. If the `is-function` attribute is set to `true`, this attribute specifies the function name instead. Either this property or `stored-procedure-name-expression` must be specified. * `stored-procedure-name-expression`: This attribute specifies the name of the stored procedure by using a SpEL expression. By using SpEL, you have access to the full message (if available), including its headers and payload. You can use this attribute to invoke different stored procedures at runtime. For example, you can provide stored procedure names that you would like to execute as a message header. The expression must resolve to a `String`. + If the `is-function` attribute is set to `true`, this attribute specifies a stored function. Either this property or `stored-procedure-name` must be specified. * `jdbc-call-operations-cache-size`: Defines the maximum number of cached `SimpleJdbcCallOperations` instances. Basically, for each stored procedure name, a new https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/jdbc/core/simple/SimpleJdbcCallOperations.html[`SimpleJdbcCallOperations`] instance is created that, in return, is cached. + NOTE: Spring Integration 2.2 added the `stored-procedure-name-expression` attribute and the `jdbc-call-operations-cache-size` attribute. + The default cache size is `10`. A value of `0` disables caching. Negative values are not permitted. + If you enable JMX, statistical information about the `jdbc-call-operations-cache` is exposed as an MBean. See <<./jmx.adoc#jmx-mbean-exporter,MBean Exporter>> for more information. * `sql-parameter-source-factory`: (Not available for the stored procedure inbound channel adapter.) Reference to a `SqlParameterSourceFactory`. By default, bean properties of the passed in `Message` payload are used as a source for the stored procedure's input parameters by using a `BeanPropertySqlParameterSourceFactory`. + This may suffice for basic use cases. For more sophisticated options, consider passing in one or more `ProcedureParameter` values. See <>. Optional. * `use-payload-as-parameter-source`: (Not available for the stored procedure inbound channel adapter.) If set to `true`, the payload of the `Message` is used as a source for providing parameters. If set to `false`, however, the entire `Message` is available as a source for parameters. + If no procedure parameters are passed in, this property defaults to `true`. This means that, by using a default `BeanPropertySqlParameterSourceFactory`, the bean properties of the payload are used as a source for parameter values for the stored procedure or stored function. + However, if procedure parameters are passed in, this property (by default) evaluates to `false`. `ProcedureParameter` lets SpEL Expressions be provided. Therefore, it is highly beneficial to have access to the entire `Message`. The property is set on the underlying `StoredProcExecutor`. Optional. [[sp-common-config-subelements]] ==== Common Configuration Sub-Elements The stored procedure components share a common set of child elements that you can use to define and pass parameters to stored procedures or stored functions. The following elements are available: * `parameter` * `returning-resultset` * `sql-parameter-definition` * `poller` * `parameter`: Provides a mechanism to provide stored procedure parameters. Parameters can be either static or provided by using a SpEL Expressions. + ==== [source,xml] ---- type="""" <2> value=""""/> <3> <4> ---- + <1> The name of the parameter to be passed into the Stored Procedure or Stored Function. Required. <2> This attribute specifies the type of the value. If nothing is provided, this attribute defaults to `java.lang.String`. This attribute is used only when the `value` attribute is used. Optional. <3> The value of the parameter. You must provide either this attribute or the `expression` attribute. Optional. <4> Instead of the `value` attribute, you can specify a SpEL expression for passing the value of the parameter. If you specify the `expression`, the `value` attribute is not allowed. Optional. ==== Optional. + * `returning-resultset`: Stored procedures may return multiple result sets. By setting one or more `returning-resultset` elements, you can specify `RowMappers` to convert each returned `ResultSet` to meaningful objects. Optional. + ==== [source,xml] ---- ---- ==== * `sql-parameter-definition`: If you use a database that is fully supported, you typically do not have to specify the stored procedure parameter definitions. Instead, those parameters can be automatically derived from the JDBC metadata. However, if you use databases that are not fully supported, you must set those parameters explicitly by using the `sql-parameter-definition` element. + You can also choose to turn off any processing of parameter metadata information obtained through JDBC by using the `ignore-column-meta-data` attribute. + ==== [source,xml] ---- direction=""IN"" <2> type=""STRING"" <3> scale=""5"" <4> type-name=""FOO_STRUCT"" <5> return-type=""fooSqlReturnType""/> <6> ---- <1> Specifies the name of the SQL parameter. Required. <2> Specifies the direction of the SQL parameter definition. Defaults to `IN`. Valid values are: `IN`, `OUT`, and `INOUT`. If your procedure is returning result sets, use the `returning-resultset` element. Optional. <3> The SQL type used for this SQL parameter definition. Translates into an integer value, as defined by `java.sql.Types`. Alternatively, you can provide the integer value as well. If this attribute is not explicitly set, it defaults to 'VARCHAR'. Optional. <4> The scale of the SQL parameter. Only used for numeric and decimal parameters. Optional. <5> The `typeName` for types that are user-named, such as: `STRUCT`, `DISTINCT`, `JAVA_OBJECT`, and named array types. This attribute is mutually exclusive with the `scale` attribute. Optional. <6> The reference to a custom value handler for complex types. An implementation of https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/jdbc/core/SqlReturnType.html[`SqlReturnType`]. This attribute is mutually exclusive with the `scale` attribute and is only applicable for OUT and INOUT parameters. Optional. ==== * `poller`: Lets you configure a message poller if this endpoint is a `PollingConsumer`. Optional. [[sp-defining-parameter-sources]] ==== Defining Parameter Sources Parameter sources govern the techniques of retrieving and mapping the Spring Integration message properties to the relevant stored procedure input parameters. The stored procedure components follow certain rules. By default, the bean properties of the `Message` payload are used as a source for the stored procedure's input parameters. In that case, a `BeanPropertySqlParameterSourceFactory` is used. This may suffice for basic use cases. The next example illustrates that default behavior. IMPORTANT: For the ""`automatic`"" lookup of bean properties by using the `BeanPropertySqlParameterSourceFactory` to work, your bean properties must be defined in lower case. This is due to the fact that in `org.springframework.jdbc.core.metadata.CallMetaDataContext` (the Java method is `matchInParameterValuesWithCallParameters()`), the retrieved stored procedure parameter declarations are converted to lower case. As a result, if you have camel-case bean properties (such as `lastName`), the lookup fails. In that case, provide an explicit `ProcedureParameter`. Suppose we have a payload that consists of a simple bean with the following three properties: `id`, `name`, and `description`. Furthermore, we have a simplistic Stored Procedure called `INSERT_COFFEE` that accepts three input parameters: `id`, `name`, and `description`. We also use a fully supported database. In that case, the following configuration for a stored procedure outbound adapter suffices: ==== [source,xml] ---- ---- ==== For more sophisticated options, consider passing in one or more `ProcedureParameter` values. If you do provide `ProcedureParameter` values explicitly, by default, an `ExpressionEvaluatingSqlParameterSourceFactory` is used for parameter processing, to enable the full power of SpEL expressions. If you need even more control over how parameters are retrieved, consider passing in a custom implementation of `SqlParameterSourceFactory` by using the `sql-parameter-source-factory` attribute. [[stored-procedure-inbound-channel-adapter]] ==== Stored Procedure Inbound Channel Adapter The following listing calls out the attributes that matter for a stored procedure inbound channel adapter: ==== [source,xml] ---- stored-procedure-name="""" data-source="""" auto-startup=""true"" id="""" ignore-column-meta-data=""false"" is-function=""false"" skip-undeclared-results="""" <2> return-value-required=""false"" <3> ---- <1> Channel to which polled messages are sent. If the stored procedure or function does not return any data, the payload of the `Message` is null. Required. <2> If this attribute is set to `true`, all results from a stored procedure call that do not have a corresponding `SqlOutParameter` declaration are bypassed. For example, stored procedures can return an update count value, even though your stored procedure declared only a single result parameter. The exact behavior depends on the database implementation. The value is set on the underlying `JdbcTemplate`. The value defaults to `true`. Optional. <3> Indicates whether this procedure's return value should be included. Since Spring Integration 3.0. Optional. ==== [[stored-procedure-outbound-channel-adapter]] ==== Stored Procedure Outbound Channel Adapter The following listing calls out the attributes that matter for a stored procedure outbound channel adapter: ==== [source,xml] ---- stored-procedure-name="""" data-source="""" auto-startup=""true"" id="""" ignore-column-meta-data=""false"" order="""" <2> sql-parameter-source-factory="""" use-payload-as-parameter-source=""""> ---- <1> The receiving message channel of this endpoint. Required. <2> Specifies the order for invocation when this endpoint is connected as a subscriber to a channel. This is particularly relevant when that channel is using a `failover` dispatching strategy. It has no effect when this endpoint is itself a polling consumer for a channel with a queue. Optional. ==== [[stored-procedure-outbound-gateway]] ==== Stored Procedure Outbound Gateway The following listing calls out the attributes that matter for a stored procedure outbound channel adapter: ==== [source,xml] ---- stored-procedure-name="""" data-source="""" auto-startup=""true"" id="""" ignore-column-meta-data=""false"" is-function=""false"" order="""" reply-channel="""" <2> reply-timeout="""" <3> return-value-required=""false"" <4> skip-undeclared-results="""" <5> sql-parameter-source-factory="""" use-payload-as-parameter-source=""""> ---- <1> The receiving message channel of this endpoint. Required. <2> Message channel to which replies should be sent after receiving the database response. Optional. <3> Lets you specify how long this gateway waits for the reply message to be sent successfully before throwing an exception. Keep in mind that, when sending to a `DirectChannel`, the invocation occurs in the sender's thread. Consequently, the failing of the send operation may be caused by other components further downstream. By default, the gateway waits indefinitely. The value is specified in milliseconds. Optional. <4> Indicates whether this procedure's return value should be included. Optional. <5> If the `skip-undeclared-results` attribute is set to `true`, all results from a stored procedure call that do not have a corresponding `SqlOutParameter` declaration are bypassed. For example, stored procedures may return an update count value, even though your stored procedure only declared a single result parameter. The exact behavior depends on the database. The value is set on the underlying `JdbcTemplate`. The value defaults to `true`. Optional. ==== [[sp-examples]] ==== Examples This section contains two examples that call https://db.apache.org/derby/[Apache Derby] stored procedures. The first procedure calls a stored procedure that returns a `ResultSet`. By using a `RowMapper`, the data is converted into a domain object, which then becomes the Spring Integration message payload. In the second sample, we call a stored procedure that uses output parameters to return data instead. [NOTE] ===== Have a look at the https://github.com/spring-projects/spring-integration-samples[Spring Integration Samples project]. The project contains the Apache Derby example referenced here, as well as instructions on how to run it. The Spring Integration Samples project also provides an https://github.com/spring-projects/spring-integration-samples/tree/main/intermediate/stored-procedures-oracle[example] of using Oracle stored procedures. ===== In the first example, we call a stored procedure named `FIND_ALL_COFFEE_BEVERAGES` that does not define any input parameters but that returns a `ResultSet`. In Apache Derby, stored procedures are implemented in Java. The following listing shows the method signature: ==== [source,java] ---- public static void findAllCoffeeBeverages(ResultSet[] coffeeBeverages) throws SQLException { ... } ---- ==== The following listing shows the corresponding SQL: ==== [source,sql] ---- CREATE PROCEDURE FIND_ALL_COFFEE_BEVERAGES() \\ PARAMETER STYLE JAVA LANGUAGE JAVA MODIFIES SQL DATA DYNAMIC RESULT SETS 1 \\ EXTERNAL NAME 'o.s.i.jdbc.storedproc.derby.DerbyStoredProcedures.findAllCoffeeBeverages'; ---- ==== In Spring Integration, you can now call this stored procedure by using, for example, a `stored-proc-outbound-gateway`, as the following example shows: ==== [source,xml] ---- ---- ==== In the second example, we call a stored procedure named `FIND_COFFEE` that has one input parameter. Instead of returning a `ResultSet`, it uses an output parameter. The following example shows the method signature: ==== [source,java] ---- public static void findCoffee(int coffeeId, String[] coffeeDescription) throws SQLException { ... } ---- ==== The following listing shows the corresponding SQL: ==== [source,sql] ---- CREATE PROCEDURE FIND_COFFEE(IN ID INTEGER, OUT COFFEE_DESCRIPTION VARCHAR(200)) \\ PARAMETER STYLE JAVA LANGUAGE JAVA EXTERNAL NAME \\ 'org.springframework.integration.jdbc.storedproc.derby.DerbyStoredProcedures.findCoffee'; ---- ==== In Spring Integration, you can now call this Stored Procedure by using, for example, a `stored-proc-outbound-gateway`, as the following example shows: ==== [source,xml] ---- ---- ==== [[jdbc-lock-registry]] === JDBC Lock Registry Version 4.3 introduced the `JdbcLockRegistry`. Certain components (for example, aggregator and resequencer) use a lock obtained from a `LockRegistry` instance to ensure that only one thread manipulates a group at a time. The `DefaultLockRegistry` performs this function within a single component. You can now configure an external lock registry on these components. When used with a shared `MessageGroupStore`, you can use the `JdbcLockRegistry` to provide this functionality across multiple application instances, such that only one instance can manipulate the group at a time. When a lock is released by a local thread, another local thread can generally acquire the lock immediately. If a lock is released by a thread that uses a different registry instance, it can take up to 100ms to acquire the lock. The `JdbcLockRegistry` is based on the `LockRepository` abstraction, which has a `DefaultLockRepository` implementation. The database schema scripts are located in the `org.springframework.integration.jdbc` package, which is divided for the particular RDBMS vendors. For example, the following listing shows the H2 DDL for the lock table: ==== [source,sql] ---- CREATE TABLE INT_LOCK ( LOCK_KEY CHAR(36), REGION VARCHAR(100), CLIENT_ID CHAR(36), CREATED_DATE TIMESTAMP NOT NULL, constraint INT_LOCK_PK primary key (LOCK_KEY, REGION) ); ---- ==== The `INT_` can be changed according to the target database design requirements. Therefore, you must use `prefix` property on the `DefaultLockRepository` bean definition. Sometimes, one application has moved to such a state that it cannot release the distributed lock and remove the particular record in the database. For this purpose, such dead-locks can be expired by the other application on the next locking invocation. The `timeToLive` (TTL) option on the `DefaultLockRepository` is provided for this purpose. You may also want to specify `CLIENT_ID` for the locks stored for a given `DefaultLockRepository` instance. If so, you can specify the `id` to be associated with the `DefaultLockRepository` as a constructor parameter. Starting with version 5.1.8, the `JdbcLockRegistry` can be configured with the `idleBetweenTries` - a `Duration` to sleep between lock record insert/update executions. By default, it is `100` milliseconds and in some environments non-leaders pollute connections with data source too often. Starting with version 5.4, the `RenewableLockRegistry` interface has been introduced and added to `JdbcLockRegistry`. The `renewLock()` method must be called during locked process in case of the locked process would be longer than time to live of the lock. So the time to live can be highly reduce and deployments can retake a lost lock quickly. NOTE: The lock renewal can be done only if the lock is held by the current thread. String with version 5.5.6, the `JdbcLockRegistry` is support automatically clean up cache for JdbcLock in `JdbcLockRegistry.locks` via `JdbcLockRegistry.setCacheCapacity()`. See its JavaDocs for more information. String with version 6.0, the `DefaultLockRepository` can be supplied with a `PlatformTransactionManager` instead of relying on the primary bean from the application context. [[jdbc-metadata-store]] === JDBC Metadata Store Version 5.0 introduced the JDBC `MetadataStore` (see <<./meta-data-store.adoc#metadata-store,Metadata Store>>) implementation. You can use the `JdbcMetadataStore` to maintain the metadata state across application restarts. This `MetadataStore` implementation can be used with adapters such as the following: * <<./feed.adoc#feed-inbound-channel-adapter,Feed inbound channel adapters>> * <<./file.adoc#file-reading,File inbound channel adapters>> * <<./ftp.adoc#ftp-inbound,FTP inbound channel adapters>> * <<./sftp.adoc#sftp-inbound,SFTP inbound channel adapters>> To configure these adapters to use the `JdbcMetadataStore`, declare a Spring bean by using a bean name of `metadataStore`. The Feed inbound channel adapter and the feed inbound channel adapter both automatically pick up and use the declared `JdbcMetadataStore`, as the following example shows: ==== [source,java] ---- @Bean public MetadataStore metadataStore(DataSource dataSource) { return new JdbcMetadataStore(dataSource); } ---- ==== The `org.springframework.integration.jdbc` package has Database schema scripts for several RDMBS vendors. For example, the following listing shows the H2 DDL for the metadata table: ==== [source,sql] ---- CREATE TABLE INT_METADATA_STORE ( METADATA_KEY VARCHAR(255) NOT NULL, METADATA_VALUE VARCHAR(4000), REGION VARCHAR(100) NOT NULL, constraint INT_METADATA_STORE_PK primary key (METADATA_KEY, REGION) ); ---- ==== You can change the `INT_` prefix to match the target database design requirements. You can also configure `JdbcMetadataStore` to use the custom prefix. The `JdbcMetadataStore` implements `ConcurrentMetadataStore`, letting it be reliably shared across multiple application instances, where only one instance can store or modify a key's value. All of these operations are atomic, thanks to transaction guarantees. Transaction management must use `JdbcMetadataStore`. Inbound channel adapters can be supplied with a reference to the `TransactionManager` in the poller configuration. Unlike non-transactional `MetadataStore` implementations, with `JdbcMetadataStore`, the entry appears in the target table only after the transaction commits. When a rollback occurs, no entries are added to the `INT_METADATA_STORE` table. Since version 5.0.7, you can configure the `JdbcMetadataStore` with the RDBMS vendor-specific `lockHint` option for lock-based queries on metadata store entries. By default, it is `FOR UPDATE` and can be configured with an empty string if the target database does not support row locking functionality. Consult with your vendor for particular and possible hints in the `SELECT` expression for locking rows before updates. ",12114,False,2166.785504609555,median "open util/ordering [State] as ord pred test35 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Chicken0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State1->Chicken0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Grain0,Fox0,none,Farmer0 + Grain0] }}}}}} } run test35 for 4 expect 1 pred test51 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Farmer0 + State1->Fox0 + State1->Chicken0 + State1->Grain0 + State2->Fox0 + State2->Grain0 + State3->Farmer0 + State3->Fox0 + State3->Grain0 far = State2->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test51 for 4 expect 0 pred test13 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State1->Chicken0 + State2->Chicken0 + State3->Farmer0 + State3->Chicken0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Farmer0,none,Farmer0] }}}}}} } run test13 for 4 expect 0 pred test9 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Grain0,Fox0 + Grain0,none,Farmer0] }}}}}} } run test9 for 4 expect 1 pred test36 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0,Fox0,Fox0,Farmer0 + Fox0 + Chicken0] }}}}}} } run test36 for 4 expect 1 pred test4 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Grain0: Grain {some disj Farmer0, Fox0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 no Chicken Grain = Grain0 Object = Farmer0 + Fox0 + Grain0 no eats State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State3->Fox0 far = State1->Farmer0 + State1->Grain0 + State2->Grain0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}} } run test4 for 4 expect 0 pred test29 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Grain0,Fox0,none,Farmer0 + Grain0] }}}}}} } run test29 for 4 expect 1 pred test37 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Farmer0 + Fox0 + Grain0,Fox0,none,Farmer0 + Grain0] }}}}}} } run test37 for 4 expect 1 pred test18 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Chicken0,Chicken0,none,Farmer0] }}}}}} } run test18 for 4 expect 1 pred test14 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Grain0,Fox0 + Grain0,Grain0,Fox0 + Chicken0] }}}}}} } run test14 for 4 expect 0 pred test25 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Chicken0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State1->Chicken0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Farmer0,Grain0,Fox0 + Chicken0] }}}}}} } run test25 for 4 expect 0 pred test42 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Fox0 + Grain0,Fox0 + Grain0,Farmer0 + Fox0] }}}}}} } run test42 for 4 expect 0 pred test28 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Chicken0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State1->Chicken0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Chicken0,Fox0 + Grain0,Chicken0] }}}}}} } run test28 for 4 expect 0 pred test1 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State1->Chicken0 + State2->Chicken0 + State3->Farmer0 + State3->Chicken0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test1 for 4 expect 1 pred test22 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State1->Chicken0 + State2->Chicken0 + State3->Farmer0 + State3->Chicken0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Grain0,Fox0 + Grain0,Fox0 + Chicken0 + Grain0,none] }}}}}} } run test22 for 4 expect 0 pred test40 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Chicken0,none,Farmer0 + Fox0] }}}}}} } run test40 for 4 expect 1 pred test15 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State1->Chicken0 + State2->Chicken0 + State3->Farmer0 + State3->Chicken0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Grain0,none,Farmer0] }}}}}} } run test15 for 4 expect 0 pred test11 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Grain0,Fox0,none,Farmer0 + Grain0] }}}}}} } run test11 for 4 expect 1 pred test34 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Chicken0 + State2->Farmer0 + State2->Chicken0 far = State1->Farmer0 + State1->Fox0 + State2->Fox0 + State3->Farmer0 + State3->Fox0 + State3->Chicken0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Fox0 + Grain0,Fox0 + Grain0,Farmer0 + Fox0 + Chicken0 + Grain0] }}}}}} } run test34 for 4 expect 1 pred test32 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Chicken0 + Grain0,Chicken0,none,Farmer0 + Grain0] }}}}}} } run test32 for 4 expect 1 pred test8 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Farmer0,Grain0,Fox0 + Chicken0] }}}}}} } run test8 for 4 expect 0 pred test10 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Grain0,Fox0 + Grain0,none,Farmer0] }}}}}} } run test10 for 4 expect 1 pred test38 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Grain0,Grain0,Fox0 + Grain0,Farmer0 + Fox0 + Grain0] }}}}}} } run test38 for 4 expect 1 pred test24 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Chicken0,none,none,Farmer0 + Grain0] }}}}}} } run test24 for 4 expect 0 pred test53 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State0->Fox0 + State1->Farmer0 + State1->Fox0 + State1->Chicken0 + State2->Chicken0 + State3->Farmer0 + State3->Chicken0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test53 for 4 expect 0 pred test2 { some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { no Farmer Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Chicken0 far = State1->Fox0 + State2->Fox0 + State2->Chicken0 + State3->Fox0 + State3->Chicken0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}} } run test2 for 4 expect 0 pred test19 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Farmer0 + Fox0 + Grain0,Fox0 + Grain0,none,Farmer0] }}}}}} } run test19 for 4 expect 1 pred test7 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test7 for 4 expect 1 ",8162,True,3211.99264604226,median "open util/ordering [State] as ord pred test33 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0,Chicken0,none,Farmer0 + Fox0] }}}}}} } run test33 for 4 expect 1 pred test50 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State1->Farmer0 + State3->Farmer0 + State3->Fox0 far = State0->Fox0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test50 for 4 expect 0 pred test53 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State0->Fox0 + State1->Farmer0 + State1->Fox0 + State1->Chicken0 + State2->Chicken0 + State3->Farmer0 + State3->Chicken0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test53 for 4 expect 0 pred test6 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Chicken0 + State2->Farmer0 + State2->Chicken0 far = State1->Farmer0 + State1->Fox0 + State2->Fox0 + State3->Farmer0 + State3->Fox0 + State3->Chicken0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test6 for 4 expect 1 pred test11 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Grain0,Fox0,none,Farmer0 + Grain0] }}}}}} } run test11 for 4 expect 1 pred test2 { some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { no Farmer Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Chicken0 far = State1->Fox0 + State2->Fox0 + State2->Chicken0 + State3->Fox0 + State3->Chicken0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}} } run test2 for 4 expect 0 pred test30 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Chicken0,Fox0 + Chicken0 + Grain0,Farmer0 + Fox0 + Chicken0 + Grain0] }}}}}} } run test30 for 4 expect 1 pred test18 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Chicken0,Chicken0,none,Farmer0] }}}}}} } run test18 for 4 expect 1 pred test12 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Farmer0,none,Farmer0] }}}}}} } run test12 for 4 expect 0 pred test14 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Grain0,Fox0 + Grain0,Grain0,Fox0 + Chicken0] }}}}}} } run test14 for 4 expect 0 pred test42 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Fox0 + Grain0,Fox0 + Grain0,Farmer0 + Fox0] }}}}}} } run test42 for 4 expect 0 pred test46 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State1->Chicken0 + State2->Chicken0 + State3->Farmer0 + State3->Chicken0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 solvePuzzle[] }}}}}} } run test46 for 4 expect 0 pred test54 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Chicken0 + State2->Grain0 + State3->Fox0 + State3->Chicken0 far = State1->Farmer0 + State2->Fox0 + State2->Chicken0 + State2->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test54 for 4 expect 0 pred test32 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Chicken0 + Grain0,Chicken0,none,Farmer0 + Grain0] }}}}}} } run test32 for 4 expect 1 pred test16 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Chicken0 + Grain0,Chicken0,none,Farmer0] }}}}}} } run test16 for 4 expect 1 pred test25 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Chicken0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State1->Chicken0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Farmer0,Grain0,Fox0 + Chicken0] }}}}}} } run test25 for 4 expect 0 pred test17 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Chicken0,Chicken0,none,Farmer0] }}}}}} } run test17 for 4 expect 1 pred test4 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Grain0: Grain {some disj Farmer0, Fox0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 no Chicken Grain = Grain0 Object = Farmer0 + Fox0 + Grain0 no eats State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State3->Fox0 far = State1->Farmer0 + State1->Grain0 + State2->Grain0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}} } run test4 for 4 expect 0 pred test36 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0,Fox0,Fox0,Farmer0 + Fox0 + Chicken0] }}}}}} } run test36 for 4 expect 1 pred test1 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State1->Chicken0 + State2->Chicken0 + State3->Farmer0 + State3->Chicken0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test1 for 4 expect 1 pred test47 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Chicken0 + State2->Farmer0 + State2->Fox0 + State2->Chicken0 + State2->Grain0 + State3->Fox0 + State3->Chicken0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test47 for 4 expect 0 pred test10 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Grain0,Fox0 + Grain0,none,Farmer0] }}}}}} } run test10 for 4 expect 1 pred test5 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Farmer0, Fox0, Chicken0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 no Grain Object = Farmer0 + Fox0 + Chicken0 eats = Fox0->Chicken0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State3->Fox0 far = State1->Farmer0 + State1->Chicken0 + State2->Chicken0 + State3->Farmer0 + State3->Chicken0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}} } run test5 for 4 expect 0 pred test7 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test7 for 4 expect 1 pred test41 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Fox0 + Grain0,none,Farmer0 + Chicken0] }}}}}} } run test41 for 4 expect 1 pred test52 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State0->Chicken0 + State0->Grain0 + State1->Farmer0 + State1->Chicken0 + State1->Grain0 + State2->Chicken0 + State3->Farmer0 + State3->Chicken0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test52 for 4 expect 0 pred test45 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Chicken0,Fox0,Farmer0 + Fox0] }}}}}} } run test45 for 4 expect 1 pred test23 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Chicken0,none,Farmer0 + Fox0] }}}}}} } run test23 for 4 expect 1 ",7956,True,2998.6016938971175,median "[[flowableApps]] == Flowable applications Flowable provides several ui web applications to demonstrate and leverage the functionality provided by the Flowable project: * Flowable IDM: an Identity Management application that provides single sign-on authentication functionality for all the Flowable UI applications, and, for users with the IDM administrative privilege, it also provides functionality to manage users, groups and privileges. * Flowable Modeler: an application that allows users with modeler privileges to model processes, forms, decision tables and application definitions. * Flowable Task: a runtime task application that provides functionality to start process instances, edit task forms, complete tasks and query on tasks and process instances. * Flowable Admin: an administrative application that allows users with admin privilege to query the BPMN, DMN, form and content engines and provides several options to change process instances, tasks, jobs and so on. The admin application connects to the engines through the REST API that is deployed together with the Flowable Task app and the Flowable REST app. The Flowable IDM is required for all other apps to enable authentication. The WAR files for each app can be deployed to the same servlet container (such as Apache Tomcat), but can also be deployed on different servlet containers. Because the same cookie is used for authentication with each app, the apps need to run on the same domain. Flowable also provides the `flowable-rest.war` which contains the Flowable REST API. More about this can be read in the <> chapter. The apps are Spring Boot 2.0 based, which means that that the WAR files are actually executable and can be run as a normal standalone applications. See https://docs.spring.io/spring-boot/docs/current/reference/html/build-tool-plugins-maven-plugin.html#build-tool-plugins-maven-packaging[The Executable Jar Format] in the Spring Boot reference documentation. [[uiAppInstallation]] === Flowable UI Applications installation As mentioned before, all four UI apps can be deployed together on the same Tomcat server, and to get started this is probably the easiest approach. You can choose to only install the Modeler app, for example, but make sure the Flowable IDM app is always running/deployed as well. For this installation guide we'll describe the installation of all four apps to a Tomcat server. 1. Download a recent stable version of link:$$http://tomcat.apache.org$$[Apache Tomcat]. 2. Download the latest stable link:$$http://www.flowable.org/downloads.html$$[Flowable 6 version]. 3. Copy the flowable-admin.war, flowable-idm.war, flowable-modeler.war and flowable-task.war files from the Flowable distribution __wars__ folder to the Tomcat webapps folder. 4. Startup the Tomcat server by running the bin/startup.sh (Mac OS and Linux) or bin/startup.bat (Windows) script. 5. Open a web browser and go to link:$$http://localhost:8080/flowable-modeler$$[http://localhost:8080/flowable-modeler]. All Flowable UI apps should now be running with an H2 in-memory database and the following login screen should be shown in your web browser: image::images/flowable_idm_login_screen.png[align=""center""] By default, the Flowable IDM application will create an admin user that has privileges to all the Flowable UI apps. You can login with admin/test and the browser should redirect to the Flowable Modeler application: image::images/flowable_modeler_startup_screen.png[align=""center""] Since the UI apps are Spring Boot executable apps it is possible to run them as standalone applications without the need of an application server. Starting single application looks like: ``` java -jar flowable-idm.war ``` Usually, you will want to change the default H2 in-memory database configuration to a MySQL or Postgres (or other persistent database) configuration. You can do this per app by changing the application.properties file in the _WEB-INF/classes/_ directory of each app. However, it is easier to use the Spring Boot https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html[Externalized Configuration]. An example configuration can be found on link:$$https://github.com/flowable/flowable-engine/blob/master/modules/flowable-ui-task/flowable-ui-task-app/src/main/resources/flowable-default.properties$$[Github] To change the default configuration to MySQL the following changes are needed to the properties file: [source,linenums] ---- spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://127.0.0.1:3306/flowable?characterEncoding=UTF-8 spring.datasource.username=flowable spring.datasource.password=flowable ---- This configuration will expect a flowable database to be present in the MySQL server and the UI apps will automatically generate the necessary database tables. For Postgres the following changes are necessary: [source,linenums] ---- spring.datasource.driver-class-name=org.postgresql.Driver spring.datasource.url=jdbc:postgresql://localhost:5432/flowable spring.datasource.username=flowable spring.datasource.password=flowable ---- In addition to changing the configuration, make sure the database driver is available on the classpath. Again, you could do this for every web application separately by adding the driver JAR file to the WEB-INF/lib folder, but you can also copy the JAR file once to the Tomcat lib folder. For MySQL and Postgres the database drivers can be downloaded from: * MySQL: link:$$https://dev.mysql.com/downloads/connector/j$$[https://dev.mysql.com/downloads/connector/j] * Postgres: link:$$https://jdbc.postgresql.org/$$[https://jdbc.postgresql.org/] When running the apps as standalone applications the database driver can be added by using the `loader.path` property. ``` java -Dloader.path=/location/to/your/driverfolder -jar flowable-idm.war ``` See the https://docs.spring.io/spring-boot/docs/current/reference/html/executable-jar.html#executable-jar-property-launcher-features[`PropertiesLauncher` Features] in the Spring Boot reference documentation for more information. === Flowable UI Applications Configurations As the Flowable UI apps are Spring Boot applications you can use all the properties Spring Boot provides. In order to provide custom configuration for the apps have a look at the https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html[Externalized Configuration] section of the Spring Boot documentation. [TIP] ----- You can also use YAML based properties. ----- .Common UI App Properties [cols=""4*"",options=""header""] |=============== |Property name |Old Property |Default value |Description |flowable.common.app.idm-url |idm.app.url |- |The URL to the IDM application, used for the user info and token info REST GET calls. It's also used as a fallback for the redirect url to the login page in the UI apps. |flowable.common.app.idm-redirect-url |idm.app.redirect.url |- |The redirect URL to the IDM application, used for the login redirect when the cookie isn't set or is invalid. |flowable.common.app.redirect-on-auth-success |app.redirect.url.on.authsuccess |- |The URL to which the redirect should occur after a successful authentication. |flowable.common.app.role-prefix |- |ROLE_ |The default role prefix that needs to be used by Spring Security. |flowable.common.app.tenant-id |- |- |The static tenant id used for the DefaultTenantProvider. The modeler app uses this to determine under which tenant id to store and publish models. When not provided, empty or only contains whitespace it defaults to the user's tenant id if available otherwise it uses no tenant id. |flowable.common.app.cache-login-tokens.max-age |cache.login-tokens.max.age |30 |The max age in seconds after which the entry should be invalidated. |flowable.common.app.cache-login-tokens.max-size |cache.login-tokens.max.size |2048 |The maximum number of entries that the cache should contain. |flowable.common.app.cache-login-users.max-age |cache.login-users.max.age |30 |The max age in seconds after which the entry should be invalidated. |flowable.common.app.cache-login-users.max-size |cache.login-users.max.size |2048 |The maximum number of entries that the cache should contain. |flowable.common.app.cache-users.max-age |cache.users.max.age |30 |The max age in seconds after which the entry should be invalidated. |flowable.common.app.cache-users.max-size |cache.users.max.size |2048 |The maximum number of entries that the cache should contain. |flowable.common.app.idm-admin.password |idm.admin.password |- |The password used for executing the REST calls (with basic auth) to the IDM REST services. Default is test. |flowable.common.app.idm-admin.user |idm.admin.user |admin |The username used for executing the REST calls (with basic auth) to the IDM REST services. Default is admin |flowable.rest.app.authentication-mode |rest.authentication.mode |verify-privilege |Configures the way user credentials are verified when doing a REST API call: 'any-user' : the user needs to exist and the password need to match. Any user is allowed to do the call (this is the pre 6.3.0 behavior) 'verify-privilege' : the user needs to exist, the password needs to match and the user needs to have the 'rest-api' privilege If nothing set, defaults to 'verify-privilege' |=============== Some of the old properties have been moved to be managed by the Flowable Spring Boot starter (or Spring Boot itself) .Old properties managed by the Flowable Spring Boot Starter [cols=""4*"",options=""header""] |=============== |Property name |Old Property |Default value |Description |flowable.async-executor-activate |engine.process.asyncexecutor.activate |true |Whether the async executor should be activated. |flowable.database-schema-update |engine.process.schema.update |true |The strategy that should be used for the database schema. |flowable.history-level |engine.process.history.level |- |The history level that needs to be used. |flowable.process.servlet.name |flowable.rest-api-servlet-name |Flowable BPMN Rest API |The name of the Process servlet. |flowable.process.servlet.path |flowable.rest-api-mapping |/process-api |The context path for the Process rest servlet. |flowable.content.storage.create-root |contentstorage.fs.create-root |true |If the root folder doesn't exist, should it be created? |flowable.content.storage.root-folder |contentstorage.fs.root-folder |- |Root folder location where content files will be stored, for example, task attachments or form file uploads. |flowable.idm.enabled |flowable.db-identity-used |true |Whether the idm engine needs to be started. |flowable.idm.password-encoder |security.passwordencoder |- |The type of the password encoder that needs to be used. |flowable.idm.ldap.base-dn |ldap.basedn |- |The base 'distinguished name' (DN) from which the searches for users and groups are started. Use 'user-base-dn' or 'group-base-dn' when needing to differentiate between user and group base DN. |flowable.idm.ldap.enabled |ldap.enabled |false |Whether to enable LDAP IDM Service. |flowable.idm.ldap.password |ldap.password |- |The password that is used to connect to the LDAP system. |flowable.idm.ldap.port |ldap.port |-1 |The port on which the LDAP system is running. |flowable.idm.ldap.server |ldap.server |- |The server host on which the LDAP system can be reached. For example 'ldap://localhost'. |flowable.idm.ldap.user |ldap.user |- |The user id that is used to connect to the LDAP system. |flowable.idm.ldap.attribute.email |ldap.attribute.email |- |Name of the attribute that matches the user email. This property is used when looking for an 'org.flowable.idm.api.User' object and the mapping between the LDAP object and the Flowable 'org.flowable.idm.api.User' object is done. |flowable.idm.ldap.attribute.first-name |ldap.attribute.firstname |- |Name of the attribute that matches the user first name. This property is used when looking for a 'org.flowable.idm.api.User' object and the mapping between the LDAP object and the Flowable 'org.flowable.idm.api.User' object is done. |flowable.idm.ldap.attribute.group-id |ldap.attribute.groupid |- |Name of the attribute that matches the group id. This property is used when looking for a 'org.flowable.idm.api.Group' object and the mapping between the LDAP object and the Flowable 'org.flowable.idm.api.Group' object is done. |flowable.idm.ldap.attribute.group-name |ldap.attribute.groupname |- |Name of the attribute that matches the group name. This property is used when looking for a 'org.flowable.idm.api.Group' object and the mapping between the LDAP object and the Flowable 'org.flowable.idm.api.Group' object is done. |flowable.idm.ldap.attribute.last-name |ldap.attribute.lastname |- |Name of the attribute that matches the user last name. This property is used when looking for a 'org.flowable.idm.api.User' object and the mapping between the LDAP object and the Flowable 'org.flowable.idm.api.User' object is done. |flowable.idm.ldap.attribute.user-id |ldap.attribute.userid |- |Name of the attribute that matches the user id. This property is used when looking for a 'org.flowable.idm.api.User' object and the mapping between the LDAP object and the Flowable 'org.flowable.idm.api.User' object is done. This property is optional and is only needed if searching for 'org.flowable.idm.api.User' objects using the Flowable API. |flowable.idm.ldap.cache.group-size |ldap.cache.groupsize |-1 |Allows to set the size of the 'org.flowable.ldap.LDAPGroupCache'. This is an LRU cache that caches groups for users and thus avoids hitting the LDAP system each time the groups of a user needs to be known. The cache will not be instantiated if the value is less then zero. By default set to -1, so no caching is done. Note that the group cache is instantiated on the 'org.flowable.ldap.LDAPIdentityServiceImpl'. As such, if you have a custom implementation of the 'org.flowable.ldap.LDAPIdentityServiceImpl', do not forget to add the group cache functionality. |flowable.idm.ldap.query.all-groups |ldap.query.groupall |- |The query that is executed when searching for all groups. |flowable.idm.ldap.query.all-users |ldap.query.userall |- |The query that is executed when searching for all users. |flowable.idm.ldap.query.groups-for-user |ldap.query.groupsforuser |- |The query that is executed when searching for the groups of a specific user. For example: `(&(objectClass=groupOfUniqueNames)(uniqueMember={0}))` Here, all the objects in LDAP with the class 'groupOfUniqueNames' and where the provided DN is a 'uniqueMember' are returned. As shown in the example, the user id is injected by the typical {@link java.text.MessageFormat}, ie by using _{0}_ If setting the query alone is insufficient for your specific LDAP setup, you can alternatively plug in a different `org.flowable.ldap.LDAPQueryBuilder`, which allows for more customization than only the query. |flowable.idm.ldap.query.user-by-full-name-like |ldap.query.userbyname |- |The query that is executed when searching for a user by full name. For example: `(&(objectClass=inetOrgPerson)(\\|({0}=**{1}**)({2}={3})))` Here, all the objects in LDAP with the class 'inetOrgPerson' and who have the matching first name or last name will be returned Several things will be injected in the expression: {0} : the first name attribute {1} : the search text {2} : the last name attribute {3} : the search text If setting the query alone is insufficient for your specific LDAP setup, you can alternatively plug in a different 'org.flowable.ldap.LDAPQueryBuilder', which allows for more customization than only the query. |flowable.idm.ldap.query.user-by-id |ldap.query.userbyid |- |The query that is executed when searching for a user by userId. For example: `(&(objectClass=inetOrgPerson)(uid={0}))` Here, all the objects in LDAP with the class 'inetOrgPerson' and who have the matching 'uid' attribute value will be returned. As shown in the example, the user id is injected by the typical {@link java.text.MessageFormat}, ie by using _{0}_ If setting the query alone is insufficient for your specific LDAP setup, you can alternatively plug in a different 'org.flowable.ldap.LDAPQueryBuilder', which allows for more customization than only the query. |flowable.mail.server.host |email.host |localhost |The host of the mail server. |flowable.mail.server.password |email.password |- |The password for the mail server authentication. |flowable.mail.server.port |email.port |1025 |The port of the mail server. |flowable.mail.server.use-ssl |email.use-ssl |false |Sets whether SSL/TLS encryption should be enabled for the SMTP transport upon connection (SMTPS/POPS). |flowable.mail.server.use-tls |email.use-tls |false |Set or disable the STARTTLS encryption. |flowable.mail.server.username |email.username |- |The username that needs to be used for the mail server authentication. If empty no authentication would be used. |flowable.process.definition-cache-limit |flowable.process-definitions.cache.max |-1 |The maximum amount of process definitions available in the process definition cache. Per default it is -1 (all process definitions). |=============== .Old properties managed by Spring Boot [cols=""4*"",options=""header""] |=============== |Property name |Old Property |Default value |Description |spring.datasource.driver-class-name |datasource.driver |- |Fully qualified name of the JDBC driver. Auto-detected based on the URL by default. |spring.datasource.jndi-name |datasource.jndi.name |- |JNDI location of the datasource. Class, url, username & password are ignored when set. |spring.datasource.password |datasource.password |- |Login password of the database. |spring.datasource.url |datasource.url |- |JDBC URL of the database. |spring.datasource.username |datasource.username |- |Login username of the database. |spring.datasource.hikari.connection-test-query |datasource.preferred-test-query |- |The SQL query to be executed to test the validity of connections. |spring.datasource.hikari.connection-timeout |datasource.connection.timeout |- |The maximum number of milliseconds that a client will wait for a connection from the pool. If this time is exceeded without a connection becoming available, a SQLException will be thrown when getting a connection. |spring.datasource.hikari.idle-timeout |datasource.connection.idletimeout |- |The maximum amount of time (in milliseconds) that a connection is allowed to sit idle in the pool. Whether a connection is retired as idle or not is subject to a maximum variation of +30 seconds, and average variation of +15 seconds. A connection will never be retired as idle before this timeout. A value of 0 means that idle connections are never removed from the pool. |spring.datasource.hikari.max-lifetime |datasource.connection.maxlifetime |- |This property controls the maximum lifetime of a connection in the pool. When a connection reaches this timeout, even if recently used, it will be retired from the pool. An in-use connection will never be retired, only when it is idle will it be removed. |spring.datasource.hikari.maximum-pool-size |datasource.connection.maxpoolsize |- |The property controls the maximum size that the pool is allowed to reach, including both idle and in-use connections. Basically this value will determine the maximum number of actual connections to the database backend. When the pool reaches this size, and no idle connections are available, calls to getConnection() will block for up to connectionTimeout milliseconds before timing out. |spring.datasource.hikari.minimum-idle |datasource.connection.minidle |- |The property controls the minimum number of idle connections that HikariCP tries to maintain in the pool, including both idle and in-use connections. If the idle connections dip below this value, HikariCP will make a best effort to restore them quickly and efficiently. |spring.servlet.multipart.max-file-size |file.upload.max.size |10MB |Max file size. Values can use the suffixes ""MB"" or ""KB"" to indicate megabytes or kilobytes, respectively. |=============== .Not used old properties [cols=""2*"",options=""header""] |=============== |Old property |Description |datasource.jndi.resource-ref |Spring Boot does not support configuring JNDI resourceRef. Use entire resource reference in the name. |email.use-credentials |In case you don't want to use credentials, set the password and user to empty. |=============== [[flowableIDMApp]] === Flowable IDM application The Flowable IDM application is used by all other three Flowable web applications for authentication and authorization and is therefore required to be available when you want to run the Modeler, Task or Admin application. The Flowable IDM application is a simple identity management application and is targeted at providing single sign-on capabilities to the Flowable web applications, including providing a central place to define users, groups and privileges. The IDM application boots the IDM engine at startup and will create the identity tables as defined in the IDM engine in the datasource defined in the properties configuration. When the Flowable IDM application is deployed and started, it will check if there's a user available in the ACT_ID_USER table, and if not it will use the `flowable.common.app.idm-admin.user` property to create a new default admin user in this table. It will also add all available privileges in the Flowable project to the newly created admin user: * access-idm: provides the privilege to manage users, groups and privileges * access-admin: allows the user to login to the Flowable Admin application, manage the Flowable engines and access the Actuator endpoints of all the applications * access-modeler: enables access to the Flowable Modeler application * access-task: provides the privilege to login to the Flowable Task application * access-rest-api: allows the user to do call the REST API. Otherwise a 403 (forbidden) http status will be returned. Note that _flowable.rest.app.authentication-mode_ nees to be set to _verify-privilege_, which is the default. When logging in to link:$$http://localhost:8080/flowable-idm$$[http://localhost:8080/flowable-idm] with admin/test for the first time the following user overview screen is shown: image::images/flowable_idm_startup_screen.png[align=""center""] In this screen users can be added, removed and updated. The groups section can be used to create, delete and update groups. In the group details view you can also add and remove users to and from the group. The privilege screen allows you to add and remove privileges from users and groups: image::images/flowable_idm_privilege_screen.png[align=""center""] There's no option to define new privileges yet, but you can add and remove users and groups for the existing four privileges. This are the IDM UI App specific properties. .IDM UI App Properties [cols=""4*"",options=""header""] |=============== |Property name |Old Property |Default value |Description |flowable.idm.app.bootstrap |idm.bootstrap.enabled |true |Whether the IDM App needs to be bootstrapped. |flowable.idm.app.rest-enabled |rest.idm-app.enabled |true |Enables the REST API (this is not the REST api used by the UI, but an api that's available over basic auth authentication). |flowable.idm.app.admin.email |admin.email |- |The email of the admin user. |flowable.idm.app.admin.first-name |admin.firstname |- |The first name of the admin user. |flowable.idm.app.admin.last-name |admin.lastname |- |The last name of the admin user. |flowable.idm.app.admin.password |admin.password |- |The password for the admin user. |flowable.idm.app.admin.user-id |admin.userid |- |The id of the admin user. |flowable.idm.app.security.remember-me-key |security.rememberme.key |testKey |The hash key that is used by Spring Security to hash the password values in the applications. Make sure that you change the value of this property. |flowable.idm.app.security.user-validity-period |cache.users.recheck.period |30000 |How long should a user be cached before invalidating it in the cache for the cacheable CustomUserDetailsService. |flowable.idm.app.security.cookie.domain |security.cookie.domain |- |The domain for the cookie. |flowable.idm.app.security.cookie.max-age |security.cookie.max-age |2678400 |The max age of the security cookie in seconds. Default is 31 days. |flowable.idm.app.security.cookie.refresh-age |security.cookie.refresh-age |86400 |The refresh age of the cookie in seconds. Default is 1 day. |=============== In addition to the default identity tables, the IDM application can also be configured to use an LDAP server. To connect to a LDAP server, additional properties in the application.properties file (or any other way of configuring the application) are needed: [source,linenums] ---- # # LDAP # flowable.idm.ldap.enabled=true flowable.idm.ldap.server=ldap://localhost flowable.idm.ldap.port=10389 flowable.idm.ldap.user=uid=admin, ou=system flowable.idm.ldap.password=secret flowable.idm.ldap.base-dn=o=flowable flowable.idm.ldap.query.user-by-id=(&(objectClass=inetOrgPerson)(uid={0})) flowable.idm.ldap.query.user-by-full-name-like=(&(objectClass=inetOrgPerson)(|({0}=*{1}*)({2}=*{3}*))) flowable.idm.ldap.query.all-users=(objectClass=inetOrgPerson) flowable.idm.ldap.query.groups-for-user=(&(objectClass=groupOfUniqueNames)(uniqueMember={0})) flowable.idm.ldap.query.all-groups=(objectClass=groupOfUniqueNames) flowable.idm.ldap.query.group-by-id=(&(objectClass=groupOfUniqueNames)(uniqueId={0})) flowable.idm.ldap.attribute.user-id=uid flowable.idm.ldap.attribute.first-name=cn flowable.idm.ldap.attribute.last-name=sn flowable.idm.ldap.attribute.group-id=cn flowable.idm.ldap.attribute.group-name=cn flowable.idm.ldap.cache.group-size=10000 flowable.idm.ldap.cache.group-expiration=180000 ---- When the `flowable.idm.ldap.enabled` property is set to true, the IDM app will expect the other LDAP properties to have been filled-in. In this example configuration the server configuration + LDAP queries for the Apache Directory Server are provided. For other LDAP servers, like Active Directory, other configuration values are needed. When LDAP is configured, authentication and group retrieval for a user will be done through the LDAP server. Only privileges will still be retrieved from the Flowable identity tables. So make sure each LDAP user has the correct privileges defined in the IDM application. If the IDM application is booted with LDAP configuration the bootstrap logic will check if there are already privileges present in the Flowable identity tables. If there are no privileges (only when booting the first time), the 4 default privileges will be created and the `flowable.idm.app.admin.user-id` property value (from application.properties or configured in the environment) will be used as the user id to get all 4 privileges. So make sure that the `flowable.idm.app.admin.user-id` property value is set to a valid LDAP user, otherwise nobody will be able to login to any of the Flowable UI apps. [[flowableModelerApp]] === Flowable Modeler application The Flowable Modeler application can be used to model BPMN processes, DMN decision table, Form definitions and create app definitions. The BPMN modeler uses the same Oryx and Angular foundation as in Flowable 5, but the functionality has now been moved into a separate Modeler application. When using the Flowable Modeler application, make sure the Flowable IDM application is deployed and running as well (for authentication and authorization purposes). When you login to the Modeler application (link:$$http://localhost:8080/flowable-modeler$$[http://localhost:8080/flowable-modeler]) with your user (or the default admin/test user), you will see the process overview screen. From here you can start creating new BPMN process models by clicking on the Create Process or Import Process button. image::images/flowable_modeler_createmodel_popup.png[align=""center"", width=""600""] When creating a process model (but also any other model), it's important to think carefully about the model key value. The model key is a unique identifier for the model across the full model repository. If you choose a model key that already exists in the model repository, an error message is shown and the model is not saved. After creating the model with the popup, the BPMN modeling canvas is shown. The BPMN editor is very similar to the Flowable 5 BPMN editor that was part of the Explorer application. All BPMN elements supported by the Flowable engine are available to be used in the design of a process model. image::images/flowable_modeler_design_screen.png[align=""center""] The BPMN editor is divided into 4 parts: * Palette: the palette of BPMN elements available to design a process model * Toolbar: actions to change the model canvas, such as zooming, layout and saving a model * Model canvas: the modeling canvas on which to drag and drop BPMN elements and design the process model * Properties panel: the properties for the main process model if no element is select and otherwise the properties of the selected BPMN element For a User task element there's a _Referenced form_ property in the properties panel. If you select this property, a popup is opened where you can select a form definition from the repository or create a new form. When creating a new form, a similar create dialog to the process model create dialog is presented. After filling in the name and form model key, the form editor is opened. image::images/flowable_modeler_formdesign_screen.png[align=""center""] Form fields can be dragged from the form palette on to the form canvas. In this example, a name textfield, two date fields and a remarks multiline textfield are added to the form canvas. When editing a form field, the label, id, required status and placeholder can be filled in. image::images/flowable_modeler_editfield_popup.png[align=""center"", width=""600""] The id field is an important value, because a process variable will be created with the form field value using the id property value. When filling in the label property, the id property is automatically filled. If needed, you can also provide the id property value yourself by checking the override id checkbox. After saving the form model and closing the form editor, you are automatically navigated back to the process model (when the form editor was opened via the BPMN editor). When selecting the User task element again and clicking on the _Referenced form_ property you will see that the newly created form definition is now attached to the User task. When clicking on the _Form_ tab in the header of the Modeler application, all form definitions available in the model repository are shown. image::images/flowable_modeler_formoverview_screen.png[align=""center""] You can preview every form definition by opening the details view of a form definition. In the details view, the form name, key and description can be edited and the history of form models is available. You can also duplicate the form definition to create a new form definition with the same form fields. Now let's open the vacation request process model in the BPMN editor again and add a Script task to the process model, that will calculate the number of days between the vacation start and end dates. Click on the _Script format_ property and fill in a value of _groovy_ to instruct the Flowable engine to use the Groovy scripting engine. Now click on the _Script_ property and fill in the script that calculates the number of days. image::images/flowable_modeler_script_popup.png[align=""center"", width=""600""] Now we have a _amountOfVacationDays_ process variable we can add a Decision task to the process model. A decision task can be used to execute a DMN decision table in the Flowable DMN engine. Through the _Decision table reference_ property, a new decision table model can be created and the DMN editor is opened. image::images/flowable_modeler_dmneditor_screen.png[align=""center""] The DMN editor provides a table editor with input columns, where input conditions can be defined with the process variables available in the process context, and output columns, where output variable values can be defined. In this very simple example there's one input column using the _amountOfVacationDays_ variable that checks if it's less than 10 or higher or equal to 10. When the amount of days is less than 10, an output variable _managerApprovalNeeded_ is returned with value false, and otherwise a value of true is returned. You can define multiple input columns and have multiple input conditions per rule. It's also possible to leave an input column empty, which means that it's evaluated to true for that part of the rule. You can define one or multiple output variables. Another important part of the DMN decision table definition is the hit policy. Currently, Flowable supports the First and Any hit policy. With the First hit policy, when the first rule is found that evaluates to true the DMN execution will stop and its output variables are returned. For the Any hit policy, all rules will be executed and the output variables for the last rule that evaluates to true are returned. When the DMN editor is saved and closed, the Modeler application navigates back to the BPMN editor and the newly created DMN decision table is now attached to the Decision task. The decision task will be generated in the BPMN XML like; [source,xml,linenums] ---- ---- With the _managerApprovalNeeded_ variable available in the process instance context, we can now create an exclusive gateway with a sequence flow condition that evaluates the calculated value of the DMN Engine. image::images/flowable_modeler_sequenceflowcondition_popup.png[align=""center"", width=""500""] The full BPMN process model now looks like this: image::images/flowable_modeler_vacationrequest_screen.png[align=""center""] With the process model completed, we can now create an app definition that combines one or more process models with all their associated models (for example, decision tables and form definitions) into a single artifact. An app definition can be exported as a BAR file (zip format) that can be deployed on the Flowable engine. When creating a vacation request app definition, the app editor will look something like the screen below. image::images/flowable_modeler_appeditor_screen.png[align=""center""] In the app editor, an icon and a theme color can be selected that will be used in the Flowable Task application to show the application in the dashboard. The important step is to add the vacation request process model, and by selecting the process model, automatically include any form definitions and DMN decision tables. image::images/flowable_modeler_modelselection_popup.png[align=""center""] A process model can be selected by clicking on the model thumbnail. When one or more models are selected, you can close the popup, save the app definition and close it. When navigating to the details view of the newly created vacation request app definition, the following details screen is shown: image::images/flowable_modeler_appdetails_screen.png[align=""center""] From this view, you can download the app definition in two different formats. The first download button (with the arrow pointing downwards) can be used to download the app definition with the JSON model files for each included model. This makes it easy to share app definitions between different Flowable Modeler applications. The second download button (with the arrow point to upper right) will provide a BAR file of the app definition models, which can be deployed on the Flowable engine. In the BAR file, only the deployable artifacts are included, such as the BPMN 2.0 XML file and the DMN XML file, and not the JSON model files. All files in a BAR file deployed on a Flowable engine are stored in the database, so therefore only the deployable files are included. From the app definition details view, you can also _Publish_ the app definition directly to the Flowable engine. The Flowable Modeler uses the URL defined in the application.properties file with the _flowable.modeler.app.deployment-api-url_ property key. By default, the deployment URL is configured so the app definition will be deployed on the Flowable Task application when it's running. However, this can be changed to use the Flowable REST application, for example. Make sure the Flowable Task application is running and click on the _Publish_ button. The app definition is now deployed as a BAR file to the Flowable Task application. This are the Modeler UI App specific properties. .Modeler UI App Properties [cols=""4*"",options=""header""] |=============== |Property name |Old Property |Default value |Description |flowable.modeler.app.data-source-prefix |datasource.prefix |- |The prefix for the database tables. |flowable.modeler.app.deployment-api-url |deployment.api.url |http://localhost:8080/flowable-task/app-api |The root URI to the REST services of the Flowable engine, used by the Flowable Modeler application to deploy the application definition BAR file to the engine. Default url for the Flowable Task application is http://localhost:8080/flowable-task/app-api |flowable.modeler.app.rest-enabled |rest.modeler-app.enabled |true |Enables the REST API (this is not the REST api used by the UI, but an api that's available over basic auth authentication). |=============== [[flowableTaskApp]] === Flowable Task application The Flowable Task application is the runtime application of the Flowable project and includes the Flowable BPMN, DMN, Form and Content engines by default. With the Flowable Task application, new process instances can be started, tasks can be completed, task forms can be rendered and so on. In the previous section, the vacation request app definition was deployed on the Flowable Task application REST API, and through that deployed on the Flowable engine. If you look in the Flowable database, you can see a new deployment entry has been added to the ACT_RE_DEPLOYMENT table for the BPMN Engine. Also, new entries haven been created in the ACT_DMN_DEPLOYMENT and ACT_FO_FORM_DEPLOYMENT tables for the DMN and Form engines. On the dashboard on link:$$http://localhost:8080/flowable-task$$[http://localhost:8080/flowable-task], you can see a vacation request app in addition to the default Task app, and any other apps that have been deployed to the Flowable engine already. image::images/flowable_task_dashboard_screen.png[align=""center""] When clicking on the vacation request app, the task list for the logged-in user is shown (which is probably empty for now). image::images/flowable_task_tasklist_screen.png[align=""center""] When clicking on the _Processes_ tab you can choose to start a new process instance by clicking on the _Start a process_ button. The list of available process definitions within the context of this app definition is now displayed. In the general Task app this works in a similar way, but in the Task app, all process definitions deployed on the Flowable engine are shown. After selecting the vacation request process definition, the _Start process_ button can be clicked to start a new vacation request process instance. The Flowable Task application automatically navigates to the process instance details view. You can see the _Provide vacation information_ task is active and, for example, comments can be added and the process instance state can be shown diagrammatically using the _Show diagram_ button. image::images/flowable_task_processdetails_screen.png[align=""center""] When navigating to the task list, you can also see the _Provide vacation information_ task listed there as well. The task details are shown in this view, with the vacation info form being rendered. You can also switch to the details view by clicking on the _Show details_ button. In the details view, comments can be added, users can involved in the task and attachments can be added to the task. You can also change the due date and the assignee of a task. image::images/flowable_task_taskdetails_screen.png[align=""center""] Let's fill in the form and complete the task. First, select a start date and end date that have more than 10 days in between, so we can validate that a _Manager approval_ task is being generated. After filling in the vacation info form and clicking the _Complete_ button, the Flowable task app navigates directly to the _Manager approval_ task view. When you also complete this task (without a task form), the process instance is completed. When navigating to the _Processes_ tab and clicking on the _Showing running processes_ section, you can select an option to show completed process instances. The list of completed process instances is now shown and when clicking on the just completed vacation request process you can see the two completed tasks. image::images/flowable_task_processhistory_screen.png[align=""center""] The completed form of each task is stored in the ACT_FO_FORM_INSTANCE table of the Flowable Form engine. So it's possible to look at the values of each completed form when you navigate to the completed task. image::images/flowable_task_completedform_screen.png[align=""center""] Make sure to switch back to showing running processes instead of the completed ones, otherwise you won't see newly started process instances. You can also filter tasks in the task list view. There are options to search on the name of a task, the task state, only tasks for a specific process definition and change the assignment filter. image::images/flowable_task_taskfilter_screen.png[align=""center"", width=""400""] By default, the assignment filter is set to _Tasks where I am involved_. This doesn't show the tasks where you are a candidate, such as tasks that are available to a specific candidate group before they are assigned to a specific person. To show candidate tasks you can select the _Tasks where I am one of the candidates_ assignment filter option. This are the Task UI App specific properties. .Task UI App Properties [cols=""4*"",options=""header""] |=============== |Property name |Old Property |Default value |Description |flowable.experimental.debugger.enabled |debugger.enabled |false |Whether the process debugger should be enabled. |flowable.task.app.rest-enabled |rest.task-app.enabled |true |Enables the REST API (this is not the REST api used by the UI, but an api that's available over basic auth authentication). |=============== [[flowableAdminApp]] === Flowable Admin application The fourth UI application the Flowable project provides is the Flowable Admin application. This application provides ways to, for example, query deployments in the BPMN, DMN and Form Engines, but also shows the active state of a process instance with its active tasks and process variables. It also provides actions to assign a task to a different assignee and to complete an active task. The Flowable Admin application uses the REST API to communicate with the Flowable engines. By default, it is configured to connect to the Flowable Task REST API, but you can easily change this to use the Flowable REST app REST API instead. When going to link:$$http://localhost:8080/flowable-admin$$[http://localhost:8080/flowable-admin], the configuration screen is shown (which is also available by clicking on the arrow at the top right near the Flowable logo). image:images/flowable_admin_configuration_screen.png[align=""center""] For each engine, the REST endpoint can be configured with the basic authentication values. The configuration is done per engine, because it's possible to, for example, deploy the DMN Engine on a separate server from the BPMN Engine. When the configuration is defined with the correct values, the _Process Engine_ can be selected to administer the Flowable BPMN engine. By default, the deployments of the Flowable BPMN engine are shown. image::images/flowable_admin_deployments_screen.png[align=""center""] You can filter the deployments based on name and tenant identifier. In this view, it's also possible to deploy a new BPMN XML file or BAR file to the Flowable engine. When clicking on one of the deployments, the deployment details view is shown. image::images/flowable_admin_deploymentdetails_screen.png[align=""center""] More details of a deployment are shown here and also the process definitions that are part of this deployment on which you click to get more details. It's also possible to delete a deployment here. When you want to delete a deployed app definition, this is also the way to delete the app definition from the Flowable Task app dashboard. When clicking on one of the process definitions, the process definition details view is shown. image::images/flowable_admin_processdefinitiondetails_screen.png[align=""center""] In the process definition details view, the first page of process instances is shown, together with optional decision table definitions and form definitions that are used in the process definition. For the vacation request process definition, there's one connected decision table and one connected form definition. Clicking on the decision table definition navigates the Flowable Admin application to the DMN engine. You can always navigate back to the Process engine by clicking on the _Parent Deployment ID_ link. In addition to the deployments and definitions, you can also query on process instances, tasks, jobs and event subscriptions in the Process engine. The views all work in a similar way to what's already been described. This are the Admin UI App specific properties .Admin UI App Properties [cols=""4*"",options=""header""] |=============== |Property name |Old Property |Default value |Description |flowable.admin.app.data-source-prefix |datasource.prefix | |The prefix for the database tables. |flowable.admin.app.security.encryption.credentials-i-v-spec |security.encryption.credentials-i-v-spec |- |The string that needs to be used to create an IvParameterSpec object using it's the bytes. |flowable.admin.app.security.encryption.credentials-secret-spec |security.encryption.credentials-secret-spec |- |The string that needs to be used to create a SecretKeySpec using it's bytes. |flowable.admin.app.security.preemptive-basic-authentication | |false |Perform a preemptive basic authentication when issuing requests to the flowable REST API. **NB:** This is an experimental property and might be removed without notice. |=============== In addition to these properties, the Flowable admin application has a few more properties. The full content of the properties file can be viewed on {sc-flowable-ui-admin}/flowable-ui-admin-app/src/main/resources/application.properties[Github]. The additional properties are mainly used for defining the initial values for the REST endpoints for the different engines. The Admin application uses the initial values to make a connection to the Flowable engines, but the values can be overridden in the Admin application configuration view and these values are stored in the __ACT\\_ADM\\_SERVER\\_CONFIG__ table. An example of the BPMN Engine REST properties is shown below: [source,linenums] ---- flowable.admin.app.server-config.process.name=Flowable Process app flowable.admin.app.server-config.process.description=Flowable Process REST config flowable.admin.app.server-config.process.server-address=http://localhost flowable.admin.app.server-config.process.port=8080 flowable.admin.app.server-config.process.context-root=flowable-task flowable.admin.app.server-config.process.rest-root=process-api flowable.admin.app.server-config.process.user-name=admin flowable.admin.app.server-config.process.password=test ---- These values can be used when the Flowable Task app (with all the Flowable engines included) is managed by the Flowable Admin application. .Admin UI App Properties managed by Spring Boot [cols=""2*"",options=""header""] |=============== |Old property |Description |message.reloading.enabled |Using Spring Boot MessageSourceAutoConfiguration. Set the duration with `spring.messages.cache-duration`. |=============== === Internationalization The Flowable UI apps support internationalization (i18n). The project maintains the English translations. It is however possible to provide your own translation files in order to support other languages. The link:$$https://github.com/angular-translate/angular-translate[Angular Translate] library tries to load a specific translation file based on the browser's locale located in the _i18n_ folder (present in each UI module). When a matching translation file cannot be loaded the framework will fallback to the English translation. Mapping multiple browser locale keys to specific translations additional configuration can be provided (located in the Angular app config); [source,linenums] ---- // Initialize angular-translate $translateProvider.useStaticFilesLoader({ prefix: './i18n/', suffix: '.json' }) /* This can be used to map multiple browser language keys to a angular translate language key. */ // .registerAvailableLanguageKeys(['en'], { // 'en-*': 'en' // }) .useCookieStorage() .useSanitizeValueStrategy('sanitizeParameters') .uniformLanguageTag('bcp47') .determinePreferredLanguage(); ---- For example; your browser is configured for English (United States) and provides the language key _en-US_. Without the mapping Angular Translate will try to fetch the corresponding translation file _en-US.json_. (If this is not available it will fallback to 'en' and load the _en.json_ translation file) By uncommenting the _.registerAvailableLanguageKeys_ block you can map _en-US_ (and all other _en_ language keys) to the _en.json_ language file. === Production ready endpoints The https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-endpoints.html[Production ready endpoints] from Spring Boot are present for all applications. To have an overview of all the available Endpoints have a look at the https://docs.spring.io/spring-boot/docs/current/actuator-api/html/[Actuator Web API Documentation]. This properties are set per default: [source,linenums] ----- # Expose all actuator endpoints to the web # They are exposed, but only authenticated users can see /info and /health abd users with access-admin can see the others management.endpoints.web.exposure.include=* # Full health details should only be displayed when a user is authorized management.endpoint.health.show-details=when_authorized # Only users with role access-admin can access full health details management.endpoint.health.roles=access-admin ----- The security is configured in such way that the `info` and `health` endpoint are exposed to all authenticated users. Full details of the `health` endpoint can only be seen by users with the privilege `access-admin`. In case you want to change that you need to configure `management.endpoint.health.show-details`. All the rest of the endpoints are accessing only to users with the `access-admin` privilege. [[custom-bean-deployment]] === Custom bean deployment There are multiple ways of providing custom beans to the Flowable applications. [[custom-bean-deployment-spring-boot-auto]] ==== Using Spring Boot auto configuration The Flowable applications are Spring Boot 2 applications. Which means that normal Spring Boot auto configuration can be used to make the beans to Flowable. This can be done in the following manner ``` package com.your.own.package.configuration; @Configuration @AutoConfigureOrder(Ordered.LOWEST_PRECEDENCE) // Makes sure that this configuration will be processed last by Spring Boot @ConditionalOnBean(type = ""org.flowable.engine.ProcessEngine"") // The configuration will only be used when the ProcessEngine bean is present public class YourOwnConfiguration { @Configuration @ComponentScan (""com.your.own.package.beans"") public static class ComponentScanConfiguration { // This class is needed in order to conditionally perform the component scan (i.e. when the ProcessEngine bean is present) // It is an optional class, in case you don't need component scanning then you don't need to do this } @Bean public CustomBean customBean() { // create your bean } @Bean public EngineConfigurationConfigurer customProcessEngineConfigurationConfigurer() { return engineConfiguration -> { // You can use this to add extra configuration to the process engine } } } ``` Note that when using Spring Boot the configuration class can be under your own package and not under some Flowable package. In order to make this class an auto configuration class a file named `spring.factories` should be created in the `META-INF` folder of your jar. In this file you should add ``` org.springframework.boot.autoconfigure.EnableAutoConfiguration=\\ com.your.own.package.configuration.YourOwnCustomConfiguration ``` In order to use this approach you would need to include your jar in the `WEB-INF/lib` folder of the exploded war. Placing this jar in the lib folder of the servlet container (e.g. Tomcat) is not going to work due to the way Spring proxies the `@Configuration` classes. [[custom-bean-deployment-component-scan]] ==== Component scan Another way to provide custom Spring beans to the Flowable engine is to put them under a certain package and have the Flowable application component scan that package. Based on the used application this package is different: * `org.flowable.rest.app` for the `flowable-rest.war` * `org.flowable.ui.task.application` for the `flowable-task.war` The custom beans can be located in a single JAR and this jar should be present on the classpath when the applications are starting up. Depending where there JAR is placed, the lib folder of the servlet container (e.g. Tomcat) or the `WEB-INF/lib` folder of the exploded war, there are different possibilities. When using the lib folder of the servlet container then the created classes should be self contained, i.e. they should only use classes from within the jar. You can use any of the Spring `@Component` annotations (with the exception of `@Configuration`). The reason for not being able to use `@Configuration` classes is the fact that each configuration class is proxied by Spring with the help of the `ConfigurationClassPostProcessor`. However, the classloader loading the `@Configuration` class does not have access to the needed classes by Spring. When including the jar in the `WEB-INF/lib` folder of the exploded war then `@Configuration` classes and dependencies to other jars is possible. [[custom-bean-deployment-own-spring-boot]] ==== Creating your own Spring Boot application This approach is the most flexible and most powerful approach of all. In order to follow this approach have a look at the <> section of this documentation.",12229,False,2064.951035481452,median "open util/ordering [State] as ord pred test14 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Grain0,Fox0 + Grain0,Grain0,Fox0 + Chicken0] }}}}}} } run test14 for 4 expect 0 pred test36 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0,Fox0,Fox0,Farmer0 + Fox0 + Chicken0] }}}}}} } run test36 for 4 expect 1 pred test38 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Grain0,Grain0,Fox0 + Grain0,Farmer0 + Fox0 + Grain0] }}}}}} } run test38 for 4 expect 1 pred test49 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test49 for 4 expect 1 pred test37 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Farmer0 + Fox0 + Grain0,Fox0,none,Farmer0 + Grain0] }}}}}} } run test37 for 4 expect 1 pred test40 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Chicken0,none,Farmer0 + Fox0] }}}}}} } run test40 for 4 expect 1 pred test56 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Chicken0 + State2->Farmer0 + State2->Chicken0 + State3->Chicken0 far = State1->Farmer0 + State1->Fox0 + State2->Fox0 + State3->Farmer0 + State3->Fox0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test56 for 4 expect 1 pred test50 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State1->Farmer0 + State3->Farmer0 + State3->Fox0 far = State0->Fox0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test50 for 4 expect 0 pred test3 { some disj Farmer0: Farmer {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 no Fox Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Chicken0 + Grain0 eats = Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Chicken0 + State0->Grain0 + State1->Grain0 + State2->Farmer0 + State2->Grain0 + State3->Grain0 far = State1->Farmer0 + State1->Chicken0 + State2->Chicken0 + State3->Farmer0 + State3->Chicken0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}} } run test3 for 4 expect 0 pred test39 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Chicken0 + State2->Farmer0 + State2->Chicken0 + State3->Chicken0 far = State1->Farmer0 + State1->Fox0 + State2->Fox0 + State3->Farmer0 + State3->Fox0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Fox0,Fox0 + Chicken0 + Grain0,Farmer0 + Fox0 + Chicken0 + Grain0] }}}}}} } run test39 for 4 expect 1 pred test32 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Chicken0 + Grain0,Chicken0,none,Farmer0 + Grain0] }}}}}} } run test32 for 4 expect 1 pred test52 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State0->Chicken0 + State0->Grain0 + State1->Farmer0 + State1->Chicken0 + State1->Grain0 + State2->Chicken0 + State3->Farmer0 + State3->Chicken0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test52 for 4 expect 0 pred test48 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Chicken0 + State2->Farmer0 + State2->Fox0 + State2->Chicken0 + State2->Grain0 + State3->Fox0 + State3->Chicken0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test48 for 4 expect 0 pred test25 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Chicken0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State1->Chicken0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Farmer0,Grain0,Fox0 + Chicken0] }}}}}} } run test25 for 4 expect 0 pred test24 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Chicken0,none,none,Farmer0 + Grain0] }}}}}} } run test24 for 4 expect 0 pred test43 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0,Fox0,none,Farmer0 + Chicken0] }}}}}} } run test43 for 4 expect 1 pred test26 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Chicken0 + State2->Farmer0 + State2->Fox0 + State2->Chicken0 + State3->Fox0 far = State1->Farmer0 + State1->Fox0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Chicken0 + Grain0,Grain0,Fox0 + Chicken0 + Grain0,Farmer0 + Fox0 + Chicken0 + Grain0] }}}}}} } run test26 for 4 expect 1 pred test28 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Chicken0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State1->Chicken0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Chicken0,Fox0 + Grain0,Chicken0] }}}}}} } run test28 for 4 expect 0 pred test18 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Chicken0,Chicken0,none,Farmer0] }}}}}} } run test18 for 4 expect 1 pred test55 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Farmer0 + State1->Grain0 + State2->Grain0 + State3->Fox0 + State3->Chicken0 far = State1->Fox0 + State1->Chicken0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Chicken0 + State2->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test55 for 4 expect 0 pred test9 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Grain0,Fox0 + Grain0,none,Farmer0] }}}}}} } run test9 for 4 expect 1 pred test23 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Chicken0,none,Farmer0 + Fox0] }}}}}} } run test23 for 4 expect 1 pred test21 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Chicken0 + State2->Farmer0 + State2->Fox0 + State2->Chicken0 + State3->Fox0 far = State1->Farmer0 + State1->Fox0 + State3->Farmer0 + State3->Chicken0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Grain0,Fox0 + Grain0,none,Farmer0] }}}}}} } run test21 for 4 expect 1 pred test19 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Farmer0 + Fox0 + Grain0,Fox0 + Grain0,none,Farmer0] }}}}}} } run test19 for 4 expect 1 pred test13 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State1->Chicken0 + State2->Chicken0 + State3->Farmer0 + State3->Chicken0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Farmer0,none,Farmer0] }}}}}} } run test13 for 4 expect 0 pred test10 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Grain0,Fox0 + Grain0,none,Farmer0] }}}}}} } run test10 for 4 expect 1 pred test2 { some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { no Farmer Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Chicken0 far = State1->Fox0 + State2->Fox0 + State2->Chicken0 + State3->Fox0 + State3->Chicken0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}} } run test2 for 4 expect 0 pred test22 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State1->Chicken0 + State2->Chicken0 + State3->Farmer0 + State3->Chicken0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Grain0,Fox0 + Grain0,Fox0 + Chicken0 + Grain0,none] }}}}}} } run test22 for 4 expect 0 ",8097,True,3125.1577176996684,median "open util/ordering [State] as ord pred test54 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Chicken0 + State2->Grain0 + State3->Fox0 + State3->Chicken0 far = State1->Farmer0 + State2->Fox0 + State2->Chicken0 + State2->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test54 for 4 expect 0 pred test35 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Chicken0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State1->Chicken0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Grain0,Fox0,none,Farmer0 + Grain0] }}}}}} } run test35 for 4 expect 1 pred test44 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Chicken0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Chicken0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Grain0,none,none,Farmer0 + Grain0] }}}}}} } run test44 for 4 expect 1 pred test25 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Chicken0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State1->Chicken0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Farmer0,Grain0,Fox0 + Chicken0] }}}}}} } run test25 for 4 expect 0 pred test45 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Chicken0,Fox0,Farmer0 + Fox0] }}}}}} } run test45 for 4 expect 1 pred test3 { some disj Farmer0: Farmer {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 no Fox Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Chicken0 + Grain0 eats = Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Chicken0 + State0->Grain0 + State1->Grain0 + State2->Farmer0 + State2->Grain0 + State3->Grain0 far = State1->Farmer0 + State1->Chicken0 + State2->Chicken0 + State3->Farmer0 + State3->Chicken0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}} } run test3 for 4 expect 0 pred test8 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Farmer0,Grain0,Fox0 + Chicken0] }}}}}} } run test8 for 4 expect 0 pred test33 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0,Chicken0,none,Farmer0 + Fox0] }}}}}} } run test33 for 4 expect 1 pred test5 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Farmer0, Fox0, Chicken0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 no Grain Object = Farmer0 + Fox0 + Chicken0 eats = Fox0->Chicken0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State3->Fox0 far = State1->Farmer0 + State1->Chicken0 + State2->Chicken0 + State3->Farmer0 + State3->Chicken0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}} } run test5 for 4 expect 0 pred test49 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test49 for 4 expect 1 pred test56 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Chicken0 + State2->Farmer0 + State2->Chicken0 + State3->Chicken0 far = State1->Farmer0 + State1->Fox0 + State2->Fox0 + State3->Farmer0 + State3->Fox0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test56 for 4 expect 1 pred test29 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Grain0,Fox0,none,Farmer0 + Grain0] }}}}}} } run test29 for 4 expect 1 pred test24 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Chicken0,none,none,Farmer0 + Grain0] }}}}}} } run test24 for 4 expect 0 pred test48 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Chicken0 + State2->Farmer0 + State2->Fox0 + State2->Chicken0 + State2->Grain0 + State3->Fox0 + State3->Chicken0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test48 for 4 expect 0 pred test7 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test7 for 4 expect 1 pred test50 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State1->Farmer0 + State3->Farmer0 + State3->Fox0 far = State0->Fox0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test50 for 4 expect 0 pred test31 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Chicken0 + Grain0,Chicken0,none,Farmer0 + Grain0] }}}}}} } run test31 for 4 expect 1 pred test6 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Chicken0 + State2->Farmer0 + State2->Chicken0 far = State1->Farmer0 + State1->Fox0 + State2->Fox0 + State3->Farmer0 + State3->Fox0 + State3->Chicken0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test6 for 4 expect 1 pred test13 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State1->Chicken0 + State2->Chicken0 + State3->Farmer0 + State3->Chicken0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Farmer0,none,Farmer0] }}}}}} } run test13 for 4 expect 0 pred test38 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Grain0,Grain0,Fox0 + Grain0,Farmer0 + Fox0 + Grain0] }}}}}} } run test38 for 4 expect 1 pred test16 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Chicken0 + Grain0,Chicken0,none,Farmer0] }}}}}} } run test16 for 4 expect 1 pred test43 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0,Fox0,none,Farmer0 + Chicken0] }}}}}} } run test43 for 4 expect 1 pred test4 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Grain0: Grain {some disj Farmer0, Fox0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 no Chicken Grain = Grain0 Object = Farmer0 + Fox0 + Grain0 no eats State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State3->Fox0 far = State1->Farmer0 + State1->Grain0 + State2->Grain0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}} } run test4 for 4 expect 0 pred test47 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Chicken0 + State2->Farmer0 + State2->Fox0 + State2->Chicken0 + State2->Grain0 + State3->Fox0 + State3->Chicken0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test47 for 4 expect 0 pred test55 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Farmer0 + State1->Grain0 + State2->Grain0 + State3->Fox0 + State3->Chicken0 far = State1->Fox0 + State1->Chicken0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Chicken0 + State2->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test55 for 4 expect 0 pred test34 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Chicken0 + State2->Farmer0 + State2->Chicken0 far = State1->Farmer0 + State1->Fox0 + State2->Fox0 + State3->Farmer0 + State3->Fox0 + State3->Chicken0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Fox0 + Grain0,Fox0 + Grain0,Farmer0 + Fox0 + Chicken0 + Grain0] }}}}}} } run test34 for 4 expect 1 pred test41 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Fox0 + Grain0,none,Farmer0 + Chicken0] }}}}}} } run test41 for 4 expect 1 pred test20 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Chicken0 + State2->Farmer0 + State2->Fox0 + State2->Chicken0 + State3->Chicken0 far = State1->Farmer0 + State1->Fox0 + State3->Farmer0 + State3->Fox0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0,Fox0,none,Farmer0] }}}}}} } run test20 for 4 expect 1 ",7936,True,3065.147520517729,median "// Copyright 2012 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // A Disassembler object is used to disassemble a block of code instruction by // instruction. The default implementation of the NameConverter object can be // overriden to modify register names or to do symbol lookup on addresses. // // The example below will disassemble a block of code and print it to stdout. // // NameConverter converter; // Disassembler d(converter); // for (byte* pc = begin; pc < end;) { // v8::internal::EmbeddedVector buffer; // byte* prev_pc = pc; // pc += d.InstructionDecode(buffer, pc); // printf(""%p %08x %s\\n"", // prev_pc, *reinterpret_cast(prev_pc), buffer); // } // // The Disassembler class also has a convenience method to disassemble a block // of code into a FILE*, meaning that the above functionality could also be // achieved by just calling Disassembler::Disassemble(stdout, begin, end); #include #include #include #include #if V8_TARGET_ARCH_MIPS64 #include ""src/base/platform/platform.h"" #include ""src/disasm.h"" #include ""src/macro-assembler.h"" #include ""src/mips64/constants-mips64.h"" namespace v8 { namespace internal { //------------------------------------------------------------------------------ // Decoder decodes and disassembles instructions into an output buffer. // It uses the converter to convert register names and call destinations into // more informative description. class Decoder { public: Decoder(const disasm::NameConverter& converter, v8::internal::Vector out_buffer) : converter_(converter), out_buffer_(out_buffer), out_buffer_pos_(0) { out_buffer_[out_buffer_pos_] = '\\0'; } ~Decoder() {} // Writes one disassembled instruction into 'buffer' (0-terminated). // Returns the length of the disassembled machine instruction in bytes. int InstructionDecode(byte* instruction); private: // Bottleneck functions to print into the out_buffer. void PrintChar(const char ch); void Print(const char* str); // Printing of common values. void PrintRegister(int reg); void PrintFPURegister(int freg); void PrintRs(Instruction* instr); void PrintRt(Instruction* instr); void PrintRd(Instruction* instr); void PrintFs(Instruction* instr); void PrintFt(Instruction* instr); void PrintFd(Instruction* instr); void PrintSa(Instruction* instr); void PrintSd(Instruction* instr); void PrintSs1(Instruction* instr); void PrintSs2(Instruction* instr); void PrintBc(Instruction* instr); void PrintCc(Instruction* instr); void PrintFunction(Instruction* instr); void PrintSecondaryField(Instruction* instr); void PrintUImm16(Instruction* instr); void PrintSImm16(Instruction* instr); void PrintXImm16(Instruction* instr); void PrintPCImm16(Instruction* instr, int delta_pc, int n_bits); void PrintXImm18(Instruction* instr); void PrintSImm18(Instruction* instr); void PrintXImm19(Instruction* instr); void PrintSImm19(Instruction* instr); void PrintXImm21(Instruction* instr); void PrintPCImm21(Instruction* instr, int delta_pc, int n_bits); void PrintXImm26(Instruction* instr); void PrintSImm26(Instruction* instr); void PrintPCImm26(Instruction* instr, int delta_pc, int n_bits); void PrintPCImm26(Instruction* instr); void PrintCode(Instruction* instr); // For break and trap instructions. void PrintFormat(Instruction* instr); // For floating format postfix. void PrintBp2(Instruction* instr); void PrintBp3(Instruction* instr); // Printing of instruction name. void PrintInstructionName(Instruction* instr); // Handle formatting of instructions and their options. int FormatRegister(Instruction* instr, const char* option); int FormatFPURegister(Instruction* instr, const char* option); int FormatOption(Instruction* instr, const char* option); void Format(Instruction* instr, const char* format); void Unknown(Instruction* instr); int DecodeBreakInstr(Instruction* instr); // Each of these functions decodes one particular instruction type. bool DecodeTypeRegisterRsType(Instruction* instr); void DecodeTypeRegisterSRsType(Instruction* instr); void DecodeTypeRegisterDRsType(Instruction* instr); void DecodeTypeRegisterLRsType(Instruction* instr); void DecodeTypeRegisterWRsType(Instruction* instr); void DecodeTypeRegisterSPECIAL(Instruction* instr); void DecodeTypeRegisterSPECIAL2(Instruction* instr); void DecodeTypeRegisterSPECIAL3(Instruction* instr); void DecodeTypeRegisterCOP1(Instruction* instr); void DecodeTypeRegisterCOP1X(Instruction* instr); int DecodeTypeRegister(Instruction* instr); void DecodeTypeImmediateCOP1(Instruction* instr); void DecodeTypeImmediateREGIMM(Instruction* instr); void DecodeTypeImmediate(Instruction* instr); void DecodeTypeJump(Instruction* instr); const disasm::NameConverter& converter_; v8::internal::Vector out_buffer_; int out_buffer_pos_; DISALLOW_COPY_AND_ASSIGN(Decoder); }; // Support for assertions in the Decoder formatting functions. #define STRING_STARTS_WITH(string, compare_string) \\ (strncmp(string, compare_string, strlen(compare_string)) == 0) // Append the ch to the output buffer. void Decoder::PrintChar(const char ch) { out_buffer_[out_buffer_pos_++] = ch; } // Append the str to the output buffer. void Decoder::Print(const char* str) { char cur = *str++; while (cur != '\\0' && (out_buffer_pos_ < (out_buffer_.length() - 1))) { PrintChar(cur); cur = *str++; } out_buffer_[out_buffer_pos_] = 0; } // Print the register name according to the active name converter. void Decoder::PrintRegister(int reg) { Print(converter_.NameOfCPURegister(reg)); } void Decoder::PrintRs(Instruction* instr) { int reg = instr->RsValue(); PrintRegister(reg); } void Decoder::PrintRt(Instruction* instr) { int reg = instr->RtValue(); PrintRegister(reg); } void Decoder::PrintRd(Instruction* instr) { int reg = instr->RdValue(); PrintRegister(reg); } // Print the FPUregister name according to the active name converter. void Decoder::PrintFPURegister(int freg) { Print(converter_.NameOfXMMRegister(freg)); } void Decoder::PrintFs(Instruction* instr) { int freg = instr->RsValue(); PrintFPURegister(freg); } void Decoder::PrintFt(Instruction* instr) { int freg = instr->RtValue(); PrintFPURegister(freg); } void Decoder::PrintFd(Instruction* instr) { int freg = instr->RdValue(); PrintFPURegister(freg); } // Print the integer value of the sa field. void Decoder::PrintSa(Instruction* instr) { int sa = instr->SaValue(); out_buffer_pos_ += SNPrintF(out_buffer_ + out_buffer_pos_, ""%d"", sa); } // Print the integer value of the rd field, when it is not used as reg. void Decoder::PrintSd(Instruction* instr) { int sd = instr->RdValue(); out_buffer_pos_ += SNPrintF(out_buffer_ + out_buffer_pos_, ""%d"", sd); } // Print the integer value of the rd field, when used as 'ext' size. void Decoder::PrintSs1(Instruction* instr) { int ss = instr->RdValue(); out_buffer_pos_ += SNPrintF(out_buffer_ + out_buffer_pos_, ""%d"", ss + 1); } // Print the integer value of the rd field, when used as 'ins' size. void Decoder::PrintSs2(Instruction* instr) { int ss = instr->RdValue(); int pos = instr->SaValue(); out_buffer_pos_ += SNPrintF(out_buffer_ + out_buffer_pos_, ""%d"", ss - pos + 1); } // Print the integer value of the cc field for the bc1t/f instructions. void Decoder::PrintBc(Instruction* instr) { int cc = instr->FBccValue(); out_buffer_pos_ += SNPrintF(out_buffer_ + out_buffer_pos_, ""%d"", cc); } // Print the integer value of the cc field for the FP compare instructions. void Decoder::PrintCc(Instruction* instr) { int cc = instr->FCccValue(); out_buffer_pos_ += SNPrintF(out_buffer_ + out_buffer_pos_, ""cc(%d)"", cc); } // Print 16-bit unsigned immediate value. void Decoder::PrintUImm16(Instruction* instr) { int32_t imm = instr->Imm16Value(); out_buffer_pos_ += SNPrintF(out_buffer_ + out_buffer_pos_, ""%u"", imm); } // Print 16-bit signed immediate value. void Decoder::PrintSImm16(Instruction* instr) { int32_t imm = ((instr->Imm16Value()) << (32 - kImm16Bits)) >> (32 - kImm16Bits); out_buffer_pos_ += SNPrintF(out_buffer_ + out_buffer_pos_, ""%d"", imm); } // Print 16-bit hexa immediate value. void Decoder::PrintXImm16(Instruction* instr) { int32_t imm = instr->Imm16Value(); out_buffer_pos_ += SNPrintF(out_buffer_ + out_buffer_pos_, ""0x%x"", imm); } // Print absoulte address for 16-bit offset or immediate value. // The absolute address is calculated according following expression: // PC + delta_pc + (offset << n_bits) void Decoder::PrintPCImm16(Instruction* instr, int delta_pc, int n_bits) { int16_t offset = instr->Imm16Value(); out_buffer_pos_ += SNPrintF(out_buffer_ + out_buffer_pos_, ""%s"", converter_.NameOfAddress(reinterpret_cast(instr) + delta_pc + (offset << n_bits))); } // Print 18-bit signed immediate value. void Decoder::PrintSImm18(Instruction* instr) { int32_t imm = ((instr->Imm18Value()) << (32 - kImm18Bits)) >> (32 - kImm18Bits); out_buffer_pos_ += SNPrintF(out_buffer_ + out_buffer_pos_, ""%d"", imm); } // Print 18-bit hexa immediate value. void Decoder::PrintXImm18(Instruction* instr) { int32_t imm = instr->Imm18Value(); out_buffer_pos_ += SNPrintF(out_buffer_ + out_buffer_pos_, ""0x%x"", imm); } // Print 19-bit hexa immediate value. void Decoder::PrintXImm19(Instruction* instr) { int32_t imm = instr->Imm19Value(); out_buffer_pos_ += SNPrintF(out_buffer_ + out_buffer_pos_, ""0x%x"", imm); } // Print 19-bit signed immediate value. void Decoder::PrintSImm19(Instruction* instr) { int32_t imm19 = instr->Imm19Value(); // set sign imm19 <<= (32 - kImm19Bits); imm19 >>= (32 - kImm19Bits); out_buffer_pos_ += SNPrintF(out_buffer_ + out_buffer_pos_, ""%d"", imm19); } // Print 21-bit immediate value. void Decoder::PrintXImm21(Instruction* instr) { uint32_t imm = instr->Imm21Value(); out_buffer_pos_ += SNPrintF(out_buffer_ + out_buffer_pos_, ""0x%x"", imm); } // Print absoulte address for 21-bit offset or immediate value. // The absolute address is calculated according following expression: // PC + delta_pc + (offset << n_bits) void Decoder::PrintPCImm21(Instruction* instr, int delta_pc, int n_bits) { int32_t imm21 = instr->Imm21Value(); // set sign imm21 <<= (32 - kImm21Bits); imm21 >>= (32 - kImm21Bits); out_buffer_pos_ += SNPrintF(out_buffer_ + out_buffer_pos_, ""%s"", converter_.NameOfAddress(reinterpret_cast(instr) + delta_pc + (imm21 << n_bits))); } // Print 26-bit hex immediate value. void Decoder::PrintXImm26(Instruction* instr) { uint64_t target = static_cast(instr->Imm26Value()) << kImmFieldShift; target = (reinterpret_cast(instr) & ~0xfffffff) | target; out_buffer_pos_ += SNPrintF(out_buffer_ + out_buffer_pos_, ""0x%lx"", target); } // Print 26-bit signed immediate value. void Decoder::PrintSImm26(Instruction* instr) { int32_t imm26 = instr->Imm26Value(); // set sign imm26 <<= (32 - kImm26Bits); imm26 >>= (32 - kImm26Bits); out_buffer_pos_ += SNPrintF(out_buffer_ + out_buffer_pos_, ""%d"", imm26); } // Print absoulte address for 26-bit offset or immediate value. // The absolute address is calculated according following expression: // PC + delta_pc + (offset << n_bits) void Decoder::PrintPCImm26(Instruction* instr, int delta_pc, int n_bits) { int32_t imm26 = instr->Imm26Value(); // set sign imm26 <<= (32 - kImm26Bits); imm26 >>= (32 - kImm26Bits); out_buffer_pos_ += SNPrintF(out_buffer_ + out_buffer_pos_, ""%s"", converter_.NameOfAddress(reinterpret_cast(instr) + delta_pc + (imm26 << n_bits))); } // Print absoulte address for 26-bit offset or immediate value. // The absolute address is calculated according following expression: // PC[GPRLEN-1 .. 28] || instr_index26 || 00 void Decoder::PrintPCImm26(Instruction* instr) { int32_t imm26 = instr->Imm26Value(); uint64_t pc_mask = ~0xfffffff; uint64_t pc = ((uint64_t)(instr + 1) & pc_mask) | (imm26 << 2); out_buffer_pos_ += SNPrintF(out_buffer_ + out_buffer_pos_, ""%s"", converter_.NameOfAddress((reinterpret_cast(pc)))); } void Decoder::PrintBp2(Instruction* instr) { int bp2 = instr->Bp2Value(); out_buffer_pos_ += SNPrintF(out_buffer_ + out_buffer_pos_, ""%d"", bp2); } void Decoder::PrintBp3(Instruction* instr) { int bp3 = instr->Bp3Value(); out_buffer_pos_ += SNPrintF(out_buffer_ + out_buffer_pos_, ""%d"", bp3); } // Print 26-bit immediate value. void Decoder::PrintCode(Instruction* instr) { if (instr->OpcodeFieldRaw() != SPECIAL) return; // Not a break or trap instruction. switch (instr->FunctionFieldRaw()) { case BREAK: { int32_t code = instr->Bits(25, 6); out_buffer_pos_ += SNPrintF(out_buffer_ + out_buffer_pos_, ""0x%05x (%d)"", code, code); break; } case TGE: case TGEU: case TLT: case TLTU: case TEQ: case TNE: { int32_t code = instr->Bits(15, 6); out_buffer_pos_ += SNPrintF(out_buffer_ + out_buffer_pos_, ""0x%03x"", code); break; } default: // Not a break or trap instruction. break; } } void Decoder::PrintFormat(Instruction* instr) { char formatLetter = ' '; switch (instr->RsFieldRaw()) { case S: formatLetter = 's'; break; case D: formatLetter = 'd'; break; case W: formatLetter = 'w'; break; case L: formatLetter = 'l'; break; default: UNREACHABLE(); break; } PrintChar(formatLetter); } // Printing of instruction name. void Decoder::PrintInstructionName(Instruction* instr) { } // Handle all register based formatting in this function to reduce the // complexity of FormatOption. int Decoder::FormatRegister(Instruction* instr, const char* format) { DCHECK(format[0] == 'r'); if (format[1] == 's') { // 'rs: Rs register. int reg = instr->RsValue(); PrintRegister(reg); return 2; } else if (format[1] == 't') { // 'rt: rt register. int reg = instr->RtValue(); PrintRegister(reg); return 2; } else if (format[1] == 'd') { // 'rd: rd register. int reg = instr->RdValue(); PrintRegister(reg); return 2; } UNREACHABLE(); return -1; } // Handle all FPUregister based formatting in this function to reduce the // complexity of FormatOption. int Decoder::FormatFPURegister(Instruction* instr, const char* format) { DCHECK(format[0] == 'f'); if (format[1] == 's') { // 'fs: fs register. int reg = instr->FsValue(); PrintFPURegister(reg); return 2; } else if (format[1] == 't') { // 'ft: ft register. int reg = instr->FtValue(); PrintFPURegister(reg); return 2; } else if (format[1] == 'd') { // 'fd: fd register. int reg = instr->FdValue(); PrintFPURegister(reg); return 2; } else if (format[1] == 'r') { // 'fr: fr register. int reg = instr->FrValue(); PrintFPURegister(reg); return 2; } UNREACHABLE(); return -1; } // FormatOption takes a formatting string and interprets it based on // the current instructions. The format string points to the first // character of the option string (the option escape has already been // consumed by the caller.) FormatOption returns the number of // characters that were consumed from the formatting string. int Decoder::FormatOption(Instruction* instr, const char* format) { switch (format[0]) { case 'c': { // 'code for break or trap instructions. DCHECK(STRING_STARTS_WITH(format, ""code"")); PrintCode(instr); return 4; } case 'i': { // 'imm16u or 'imm26. if (format[3] == '1') { if (format[4] == '6') { DCHECK(STRING_STARTS_WITH(format, ""imm16"")); switch (format[5]) { case 's': DCHECK(STRING_STARTS_WITH(format, ""imm16s"")); PrintSImm16(instr); break; case 'u': DCHECK(STRING_STARTS_WITH(format, ""imm16u"")); PrintSImm16(instr); break; case 'x': DCHECK(STRING_STARTS_WITH(format, ""imm16x"")); PrintXImm16(instr); break; case 'p': { // The PC relative address. DCHECK(STRING_STARTS_WITH(format, ""imm16p"")); int delta_pc = 0; int n_bits = 0; switch (format[6]) { case '4': { DCHECK(STRING_STARTS_WITH(format, ""imm16p4"")); delta_pc = 4; switch (format[8]) { case '2': DCHECK(STRING_STARTS_WITH(format, ""imm16p4s2"")); n_bits = 2; PrintPCImm16(instr, delta_pc, n_bits); return 9; } } } } } return 6; } else if (format[4] == '8') { DCHECK(STRING_STARTS_WITH(format, ""imm18"")); switch (format[5]) { case 's': DCHECK(STRING_STARTS_WITH(format, ""imm18s"")); PrintSImm18(instr); break; case 'x': DCHECK(STRING_STARTS_WITH(format, ""imm18x"")); PrintXImm18(instr); break; } return 6; } else if (format[4] == '9') { DCHECK(STRING_STARTS_WITH(format, ""imm19"")); switch (format[5]) { case 's': DCHECK(STRING_STARTS_WITH(format, ""imm19s"")); PrintSImm19(instr); break; case 'x': DCHECK(STRING_STARTS_WITH(format, ""imm19x"")); PrintXImm19(instr); break; } return 6; } } else if (format[3] == '2' && format[4] == '1') { DCHECK(STRING_STARTS_WITH(format, ""imm21"")); switch (format[5]) { case 'x': DCHECK(STRING_STARTS_WITH(format, ""imm21x"")); PrintXImm21(instr); break; case 'p': { // The PC relative address. DCHECK(STRING_STARTS_WITH(format, ""imm21p"")); int delta_pc = 0; int n_bits = 0; switch (format[6]) { case '4': { DCHECK(STRING_STARTS_WITH(format, ""imm21p4"")); delta_pc = 4; switch (format[8]) { case '2': DCHECK(STRING_STARTS_WITH(format, ""imm21p4s2"")); n_bits = 2; PrintPCImm21(instr, delta_pc, n_bits); return 9; } } } } } return 6; } else if (format[3] == '2' && format[4] == '6') { DCHECK(STRING_STARTS_WITH(format, ""imm26"")); switch (format[5]) { case 's': DCHECK(STRING_STARTS_WITH(format, ""imm26s"")); PrintSImm26(instr); break; case 'x': DCHECK(STRING_STARTS_WITH(format, ""imm26x"")); PrintXImm26(instr); break; case 'p': { // The PC relative address. DCHECK(STRING_STARTS_WITH(format, ""imm26p"")); int delta_pc = 0; int n_bits = 0; switch (format[6]) { case '4': { DCHECK(STRING_STARTS_WITH(format, ""imm26p4"")); delta_pc = 4; switch (format[8]) { case '2': DCHECK(STRING_STARTS_WITH(format, ""imm26p4s2"")); n_bits = 2; PrintPCImm26(instr, delta_pc, n_bits); return 9; } } } } case 'j': { // Absolute address for jump instructions. DCHECK(STRING_STARTS_WITH(format, ""imm26j"")); PrintPCImm26(instr); break; } } return 6; } } case 'r': { // 'r: registers. return FormatRegister(instr, format); } case 'f': { // 'f: FPUregisters. return FormatFPURegister(instr, format); } case 's': { // 'sa. switch (format[1]) { case 'a': { DCHECK(STRING_STARTS_WITH(format, ""sa"")); PrintSa(instr); return 2; } case 'd': { DCHECK(STRING_STARTS_WITH(format, ""sd"")); PrintSd(instr); return 2; } case 's': { if (format[2] == '1') { DCHECK(STRING_STARTS_WITH(format, ""ss1"")); /* ext size */ PrintSs1(instr); return 3; } else { DCHECK(STRING_STARTS_WITH(format, ""ss2"")); /* ins size */ PrintSs2(instr); return 3; } } } } case 'b': { switch (format[1]) { case 'c': { // 'bc - Special for bc1 cc field. DCHECK(STRING_STARTS_WITH(format, ""bc"")); PrintBc(instr); return 2; } case 'p': { switch (format[2]) { case '2': { // 'bp2 DCHECK(STRING_STARTS_WITH(format, ""bp2"")); PrintBp2(instr); return 3; } case '3': { // 'bp3 DCHECK(STRING_STARTS_WITH(format, ""bp3"")); PrintBp3(instr); return 3; } } } } } case 'C': { // 'Cc - Special for c.xx.d cc field. DCHECK(STRING_STARTS_WITH(format, ""Cc"")); PrintCc(instr); return 2; } case 't': PrintFormat(instr); return 1; } UNREACHABLE(); return -1; } // Format takes a formatting string for a whole instruction and prints it into // the output buffer. All escaped options are handed to FormatOption to be // parsed further. void Decoder::Format(Instruction* instr, const char* format) { char cur = *format++; while ((cur != 0) && (out_buffer_pos_ < (out_buffer_.length() - 1))) { if (cur == '\\'') { // Single quote is used as the formatting escape. format += FormatOption(instr, format); } else { out_buffer_[out_buffer_pos_++] = cur; } cur = *format++; } out_buffer_[out_buffer_pos_] = '\\0'; } // For currently unimplemented decodings the disassembler calls Unknown(instr) // which will just print ""unknown"" of the instruction bits. void Decoder::Unknown(Instruction* instr) { Format(instr, ""unknown""); } int Decoder::DecodeBreakInstr(Instruction* instr) { // This is already known to be BREAK instr, just extract the code. if (instr->Bits(25, 6) == static_cast(kMaxStopCode)) { // This is stop(msg). Format(instr, ""break, code: 'code""); out_buffer_pos_ += SNPrintF(out_buffer_ + out_buffer_pos_, ""\\n%p %08lx stop msg: %s"", static_cast (reinterpret_cast(instr + Instruction::kInstrSize)), reinterpret_cast (*reinterpret_cast(instr + Instruction::kInstrSize)), *reinterpret_cast(instr + Instruction::kInstrSize)); // Size 3: the break_ instr, plus embedded 64-bit char pointer. return 3 * Instruction::kInstrSize; } else { Format(instr, ""break, code: 'code""); return Instruction::kInstrSize; } } bool Decoder::DecodeTypeRegisterRsType(Instruction* instr) { switch (instr->FunctionFieldRaw()) { case RINT: Format(instr, ""rint.'t 'fd, 'fs""); break; case SEL: Format(instr, ""sel.'t 'fd, 'fs, 'ft""); break; case SELEQZ_C: Format(instr, ""seleqz.'t 'fd, 'fs, 'ft""); break; case SELNEZ_C: Format(instr, ""selnez.'t 'fd, 'fs, 'ft""); break; case MOVZ_C: Format(instr, ""movz.'t 'fd, 'fs, 'rt""); break; case MOVN_C: Format(instr, ""movn.'t 'fd, 'fs, 'rt""); break; case MOVF: if (instr->Bit(16)) { Format(instr, ""movt.'t 'fd, 'fs, 'Cc""); } else { Format(instr, ""movf.'t 'fd, 'fs, 'Cc""); } break; case MIN: Format(instr, ""min.'t 'fd, 'fs, 'ft""); break; case MAX: Format(instr, ""max.'t 'fd, 'fs, 'ft""); break; case MINA: Format(instr, ""mina.'t 'fd, 'fs, 'ft""); break; case MAXA: Format(instr, ""maxa.'t 'fd, 'fs, 'ft""); break; case ADD_D: Format(instr, ""add.'t 'fd, 'fs, 'ft""); break; case SUB_D: Format(instr, ""sub.'t 'fd, 'fs, 'ft""); break; case MUL_D: Format(instr, ""mul.'t 'fd, 'fs, 'ft""); break; case DIV_D: Format(instr, ""div.'t 'fd, 'fs, 'ft""); break; case ABS_D: Format(instr, ""abs.'t 'fd, 'fs""); break; case MOV_D: Format(instr, ""mov.'t 'fd, 'fs""); break; case NEG_D: Format(instr, ""neg.'t 'fd, 'fs""); break; case SQRT_D: Format(instr, ""sqrt.'t 'fd, 'fs""); break; case RECIP_D: Format(instr, ""recip.'t 'fd, 'fs""); break; case RSQRT_D: Format(instr, ""rsqrt.'t 'fd, 'fs""); break; case CVT_W_D: Format(instr, ""cvt.w.'t 'fd, 'fs""); break; case CVT_L_D: Format(instr, ""cvt.l.'t 'fd, 'fs""); break; case TRUNC_W_D: Format(instr, ""trunc.w.'t 'fd, 'fs""); break; case TRUNC_L_D: Format(instr, ""trunc.l.'t 'fd, 'fs""); break; case ROUND_W_D: Format(instr, ""round.w.'t 'fd, 'fs""); break; case ROUND_L_D: Format(instr, ""round.l.'t 'fd, 'fs""); break; case FLOOR_W_D: Format(instr, ""floor.w.'t 'fd, 'fs""); break; case FLOOR_L_D: Format(instr, ""floor.l.'t 'fd, 'fs""); break; case CEIL_W_D: Format(instr, ""ceil.w.'t 'fd, 'fs""); break; case CEIL_L_D: Format(instr, ""ceil.l.'t 'fd, 'fs""); break; case CLASS_D: Format(instr, ""class.'t 'fd, 'fs""); break; case CVT_S_D: Format(instr, ""cvt.s.'t 'fd, 'fs""); break; case C_F_D: Format(instr, ""c.f.'t 'fs, 'ft, 'Cc""); break; case C_UN_D: Format(instr, ""c.un.'t 'fs, 'ft, 'Cc""); break; case C_EQ_D: Format(instr, ""c.eq.'t 'fs, 'ft, 'Cc""); break; case C_UEQ_D: Format(instr, ""c.ueq.'t 'fs, 'ft, 'Cc""); break; case C_OLT_D: Format(instr, ""c.olt.'t 'fs, 'ft, 'Cc""); break; case C_ULT_D: Format(instr, ""c.ult.'t 'fs, 'ft, 'Cc""); break; case C_OLE_D: Format(instr, ""c.ole.'t 'fs, 'ft, 'Cc""); break; case C_ULE_D: Format(instr, ""c.ule.'t 'fs, 'ft, 'Cc""); break; default: return false; } return true; } void Decoder::DecodeTypeRegisterSRsType(Instruction* instr) { if (!DecodeTypeRegisterRsType(instr)) { switch (instr->FunctionFieldRaw()) { case CVT_D_S: Format(instr, ""cvt.d.'t 'fd, 'fs""); break; default: Format(instr, ""unknown.cop1.'t""); break; } } } void Decoder::DecodeTypeRegisterDRsType(Instruction* instr) { if (!DecodeTypeRegisterRsType(instr)) { Format(instr, ""unknown.cop1.'t""); } } void Decoder::DecodeTypeRegisterLRsType(Instruction* instr) { switch (instr->FunctionFieldRaw()) { case CVT_D_L: Format(instr, ""cvt.d.l 'fd, 'fs""); break; case CVT_S_L: Format(instr, ""cvt.s.l 'fd, 'fs""); break; case CMP_AF: Format(instr, ""cmp.af.d 'fd, 'fs, 'ft""); break; case CMP_UN: Format(instr, ""cmp.un.d 'fd, 'fs, 'ft""); break; case CMP_EQ: Format(instr, ""cmp.eq.d 'fd, 'fs, 'ft""); break; case CMP_UEQ: Format(instr, ""cmp.ueq.d 'fd, 'fs, 'ft""); break; case CMP_LT: Format(instr, ""cmp.lt.d 'fd, 'fs, 'ft""); break; case CMP_ULT: Format(instr, ""cmp.ult.d 'fd, 'fs, 'ft""); break; case CMP_LE: Format(instr, ""cmp.le.d 'fd, 'fs, 'ft""); break; case CMP_ULE: Format(instr, ""cmp.ule.d 'fd, 'fs, 'ft""); break; case CMP_OR: Format(instr, ""cmp.or.d 'fd, 'fs, 'ft""); break; case CMP_UNE: Format(instr, ""cmp.une.d 'fd, 'fs, 'ft""); break; case CMP_NE: Format(instr, ""cmp.ne.d 'fd, 'fs, 'ft""); break; default: UNREACHABLE(); } } void Decoder::DecodeTypeRegisterWRsType(Instruction* instr) { switch (instr->FunctionValue()) { case CVT_S_W: // Convert word to float (single). Format(instr, ""cvt.s.w 'fd, 'fs""); break; case CVT_D_W: // Convert word to double. Format(instr, ""cvt.d.w 'fd, 'fs""); break; case CMP_AF: Format(instr, ""cmp.af.s 'fd, 'fs, 'ft""); break; case CMP_UN: Format(instr, ""cmp.un.s 'fd, 'fs, 'ft""); break; case CMP_EQ: Format(instr, ""cmp.eq.s 'fd, 'fs, 'ft""); break; case CMP_UEQ: Format(instr, ""cmp.ueq.s 'fd, 'fs, 'ft""); break; case CMP_LT: Format(instr, ""cmp.lt.s 'fd, 'fs, 'ft""); break; case CMP_ULT: Format(instr, ""cmp.ult.s 'fd, 'fs, 'ft""); break; case CMP_LE: Format(instr, ""cmp.le.s 'fd, 'fs, 'ft""); break; case CMP_ULE: Format(instr, ""cmp.ule.s 'fd, 'fs, 'ft""); break; case CMP_OR: Format(instr, ""cmp.or.s 'fd, 'fs, 'ft""); break; case CMP_UNE: Format(instr, ""cmp.une.s 'fd, 'fs, 'ft""); break; case CMP_NE: Format(instr, ""cmp.ne.s 'fd, 'fs, 'ft""); break; default: UNREACHABLE(); } } void Decoder::DecodeTypeRegisterCOP1(Instruction* instr) { switch (instr->RsFieldRaw()) { case MFC1: Format(instr, ""mfc1 'rt, 'fs""); break; case DMFC1: Format(instr, ""dmfc1 'rt, 'fs""); break; case MFHC1: Format(instr, ""mfhc1 'rt, 'fs""); break; case MTC1: Format(instr, ""mtc1 'rt, 'fs""); break; case DMTC1: Format(instr, ""dmtc1 'rt, 'fs""); break; // These are called ""fs"" too, although they are not FPU registers. case CTC1: Format(instr, ""ctc1 'rt, 'fs""); break; case CFC1: Format(instr, ""cfc1 'rt, 'fs""); break; case MTHC1: Format(instr, ""mthc1 'rt, 'fs""); break; case S: DecodeTypeRegisterSRsType(instr); break; case D: DecodeTypeRegisterDRsType(instr); break; case W: DecodeTypeRegisterWRsType(instr); break; case L: DecodeTypeRegisterLRsType(instr); break; default: UNREACHABLE(); } } void Decoder::DecodeTypeRegisterCOP1X(Instruction* instr) { switch (instr->FunctionFieldRaw()) { case MADD_D: Format(instr, ""madd.d 'fd, 'fr, 'fs, 'ft""); break; default: UNREACHABLE(); } } void Decoder::DecodeTypeRegisterSPECIAL(Instruction* instr) { switch (instr->FunctionFieldRaw()) { case JR: Format(instr, ""jr 'rs""); break; case JALR: Format(instr, ""jalr 'rs, 'rd""); break; case SLL: if (0x0 == static_cast(instr->InstructionBits())) Format(instr, ""nop""); else Format(instr, ""sll 'rd, 'rt, 'sa""); break; case DSLL: Format(instr, ""dsll 'rd, 'rt, 'sa""); break; case D_MUL_MUH: // Equals to DMUL. if (kArchVariant != kMips64r6) { Format(instr, ""dmult 'rs, 'rt""); } else { if (instr->SaValue() == MUL_OP) { Format(instr, ""dmul 'rd, 'rs, 'rt""); } else { Format(instr, ""dmuh 'rd, 'rs, 'rt""); } } break; case DSLL32: Format(instr, ""dsll32 'rd, 'rt, 'sa""); break; case SRL: if (instr->RsValue() == 0) { Format(instr, ""srl 'rd, 'rt, 'sa""); } else { if (kArchVariant == kMips64r2) { Format(instr, ""rotr 'rd, 'rt, 'sa""); } else { Unknown(instr); } } break; case DSRL: if (instr->RsValue() == 0) { Format(instr, ""dsrl 'rd, 'rt, 'sa""); } else { if (kArchVariant == kMips64r2) { Format(instr, ""drotr 'rd, 'rt, 'sa""); } else { Unknown(instr); } } break; case DSRL32: Format(instr, ""dsrl32 'rd, 'rt, 'sa""); break; case SRA: Format(instr, ""sra 'rd, 'rt, 'sa""); break; case DSRA: Format(instr, ""dsra 'rd, 'rt, 'sa""); break; case DSRA32: Format(instr, ""dsra32 'rd, 'rt, 'sa""); break; case SLLV: Format(instr, ""sllv 'rd, 'rt, 'rs""); break; case DSLLV: Format(instr, ""dsllv 'rd, 'rt, 'rs""); break; case SRLV: if (instr->SaValue() == 0) { Format(instr, ""srlv 'rd, 'rt, 'rs""); } else { if (kArchVariant == kMips64r2) { Format(instr, ""rotrv 'rd, 'rt, 'rs""); } else { Unknown(instr); } } break; case DSRLV: if (instr->SaValue() == 0) { Format(instr, ""dsrlv 'rd, 'rt, 'rs""); } else { if (kArchVariant == kMips64r2) { Format(instr, ""drotrv 'rd, 'rt, 'rs""); } else { Unknown(instr); } } break; case SRAV: Format(instr, ""srav 'rd, 'rt, 'rs""); break; case DSRAV: Format(instr, ""dsrav 'rd, 'rt, 'rs""); break; case MFHI: if (instr->Bits(25, 16) == 0) { Format(instr, ""mfhi 'rd""); } else { if ((instr->FunctionFieldRaw() == CLZ_R6) && (instr->FdValue() == 1)) { Format(instr, ""clz 'rd, 'rs""); } else if ((instr->FunctionFieldRaw() == CLO_R6) && (instr->FdValue() == 1)) { Format(instr, ""clo 'rd, 'rs""); } } break; case MFLO: Format(instr, ""mflo 'rd""); break; case D_MUL_MUH_U: // Equals to DMULTU. if (kArchVariant != kMips64r6) { Format(instr, ""dmultu 'rs, 'rt""); } else { if (instr->SaValue() == MUL_OP) { Format(instr, ""dmulu 'rd, 'rs, 'rt""); } else { Format(instr, ""dmuhu 'rd, 'rs, 'rt""); } } break; case MULT: // @Mips64r6 == MUL_MUH. if (kArchVariant != kMips64r6) { Format(instr, ""mult 'rs, 'rt""); } else { if (instr->SaValue() == MUL_OP) { Format(instr, ""mul 'rd, 'rs, 'rt""); } else { Format(instr, ""muh 'rd, 'rs, 'rt""); } } break; case MULTU: // @Mips64r6 == MUL_MUH_U. if (kArchVariant != kMips64r6) { Format(instr, ""multu 'rs, 'rt""); } else { if (instr->SaValue() == MUL_OP) { Format(instr, ""mulu 'rd, 'rs, 'rt""); } else { Format(instr, ""muhu 'rd, 'rs, 'rt""); } } break; case DIV: // @Mips64r6 == DIV_MOD. if (kArchVariant != kMips64r6) { Format(instr, ""div 'rs, 'rt""); } else { if (instr->SaValue() == DIV_OP) { Format(instr, ""div 'rd, 'rs, 'rt""); } else { Format(instr, ""mod 'rd, 'rs, 'rt""); } } break; case DDIV: // @Mips64r6 == D_DIV_MOD. if (kArchVariant != kMips64r6) { Format(instr, ""ddiv 'rs, 'rt""); } else { if (instr->SaValue() == DIV_OP) { Format(instr, ""ddiv 'rd, 'rs, 'rt""); } else { Format(instr, ""dmod 'rd, 'rs, 'rt""); } } break; case DIVU: // @Mips64r6 == DIV_MOD_U. if (kArchVariant != kMips64r6) { Format(instr, ""divu 'rs, 'rt""); } else { if (instr->SaValue() == DIV_OP) { Format(instr, ""divu 'rd, 'rs, 'rt""); } else { Format(instr, ""modu 'rd, 'rs, 'rt""); } } break; case DDIVU: // @Mips64r6 == D_DIV_MOD_U. if (kArchVariant != kMips64r6) { Format(instr, ""ddivu 'rs, 'rt""); } else { if (instr->SaValue() == DIV_OP) { Format(instr, ""ddivu 'rd, 'rs, 'rt""); } else { Format(instr, ""dmodu 'rd, 'rs, 'rt""); } } break; case ADD: Format(instr, ""add 'rd, 'rs, 'rt""); break; case DADD: Format(instr, ""dadd 'rd, 'rs, 'rt""); break; case ADDU: Format(instr, ""addu 'rd, 'rs, 'rt""); break; case DADDU: Format(instr, ""daddu 'rd, 'rs, 'rt""); break; case SUB: Format(instr, ""sub 'rd, 'rs, 'rt""); break; case DSUB: Format(instr, ""dsub 'rd, 'rs, 'rt""); break; case SUBU: Format(instr, ""subu 'rd, 'rs, 'rt""); break; case DSUBU: Format(instr, ""dsubu 'rd, 'rs, 'rt""); break; case AND: Format(instr, ""and 'rd, 'rs, 'rt""); break; case OR: if (0 == instr->RsValue()) { Format(instr, ""mov 'rd, 'rt""); } else if (0 == instr->RtValue()) { Format(instr, ""mov 'rd, 'rs""); } else { Format(instr, ""or 'rd, 'rs, 'rt""); } break; case XOR: Format(instr, ""xor 'rd, 'rs, 'rt""); break; case NOR: Format(instr, ""nor 'rd, 'rs, 'rt""); break; case SLT: Format(instr, ""slt 'rd, 'rs, 'rt""); break; case SLTU: Format(instr, ""sltu 'rd, 'rs, 'rt""); break; case TGE: Format(instr, ""tge 'rs, 'rt, code: 'code""); break; case TGEU: Format(instr, ""tgeu 'rs, 'rt, code: 'code""); break; case TLT: Format(instr, ""tlt 'rs, 'rt, code: 'code""); break; case TLTU: Format(instr, ""tltu 'rs, 'rt, code: 'code""); break; case TEQ: Format(instr, ""teq 'rs, 'rt, code: 'code""); break; case TNE: Format(instr, ""tne 'rs, 'rt, code: 'code""); break; case MOVZ: Format(instr, ""movz 'rd, 'rs, 'rt""); break; case MOVN: Format(instr, ""movn 'rd, 'rs, 'rt""); break; case MOVCI: if (instr->Bit(16)) { Format(instr, ""movt 'rd, 'rs, 'bc""); } else { Format(instr, ""movf 'rd, 'rs, 'bc""); } break; case SELEQZ_S: Format(instr, ""seleqz 'rd, 'rs, 'rt""); break; case SELNEZ_S: Format(instr, ""selnez 'rd, 'rs, 'rt""); break; default: UNREACHABLE(); } } void Decoder::DecodeTypeRegisterSPECIAL2(Instruction* instr) { switch (instr->FunctionFieldRaw()) { case MUL: Format(instr, ""mul 'rd, 'rs, 'rt""); break; case CLZ: if (kArchVariant != kMips64r6) { Format(instr, ""clz 'rd, 'rs""); } break; default: UNREACHABLE(); } } void Decoder::DecodeTypeRegisterSPECIAL3(Instruction* instr) { switch (instr->FunctionFieldRaw()) { case INS: { Format(instr, ""ins 'rt, 'rs, 'sa, 'ss2""); break; } case EXT: { Format(instr, ""ext 'rt, 'rs, 'sa, 'ss1""); break; } case DEXT: { Format(instr, ""dext 'rt, 'rs, 'sa, 'ss1""); break; } case BSHFL: { int sa = instr->SaFieldRaw() >> kSaShift; switch (sa) { case BITSWAP: { Format(instr, ""bitswap 'rd, 'rt""); break; } case SEB: case SEH: case WSBH: UNREACHABLE(); break; default: { sa >>= kBp2Bits; switch (sa) { case ALIGN: { Format(instr, ""align 'rd, 'rs, 'rt, 'bp2""); break; } default: UNREACHABLE(); break; } break; } } break; } case DBSHFL: { int sa = instr->SaFieldRaw() >> kSaShift; switch (sa) { case DBITSWAP: { switch (instr->SaFieldRaw() >> kSaShift) { case DBITSWAP_SA: Format(instr, ""dbitswap 'rd, 'rt""); break; default: UNREACHABLE(); break; } break; } case DSBH: case DSHD: UNREACHABLE(); break; default: { sa >>= kBp3Bits; switch (sa) { case DALIGN: { Format(instr, ""dalign 'rd, 'rs, 'rt, 'bp3""); break; } default: UNREACHABLE(); break; } break; } } break; } default: UNREACHABLE(); } } int Decoder::DecodeTypeRegister(Instruction* instr) { switch (instr->OpcodeFieldRaw()) { case COP1: // Coprocessor instructions. DecodeTypeRegisterCOP1(instr); break; case COP1X: DecodeTypeRegisterCOP1X(instr); break; case SPECIAL: switch (instr->FunctionFieldRaw()) { case BREAK: return DecodeBreakInstr(instr); default: DecodeTypeRegisterSPECIAL(instr); break; } break; case SPECIAL2: DecodeTypeRegisterSPECIAL2(instr); break; case SPECIAL3: DecodeTypeRegisterSPECIAL3(instr); break; default: UNREACHABLE(); } return Instruction::kInstrSize; } void Decoder::DecodeTypeImmediateCOP1(Instruction* instr) { switch (instr->RsFieldRaw()) { case BC1: if (instr->FBtrueValue()) { Format(instr, ""bc1t 'bc, 'imm16u -> 'imm16p4s2""); } else { Format(instr, ""bc1f 'bc, 'imm16u -> 'imm16p4s2""); } break; case BC1EQZ: Format(instr, ""bc1eqz 'ft, 'imm16u -> 'imm16p4s2""); break; case BC1NEZ: Format(instr, ""bc1nez 'ft, 'imm16u -> 'imm16p4s2""); break; default: UNREACHABLE(); } } void Decoder::DecodeTypeImmediateREGIMM(Instruction* instr) { switch (instr->RtFieldRaw()) { case BLTZ: Format(instr, ""bltz 'rs, 'imm16u -> 'imm16p4s2""); break; case BLTZAL: Format(instr, ""bltzal 'rs, 'imm16u -> 'imm16p4s2""); break; case BGEZ: Format(instr, ""bgez 'rs, 'imm16u -> 'imm16p4s2""); break; case BGEZAL: { if (instr->RsValue() == 0) Format(instr, ""bal 'imm16s -> 'imm16p4s2""); else Format(instr, ""bgezal 'rs, 'imm16u -> 'imm16p4s2""); break; } case BGEZALL: Format(instr, ""bgezall 'rs, 'imm16u -> 'imm16p4s2""); break; case DAHI: Format(instr, ""dahi 'rs, 'imm16u""); break; case DATI: Format(instr, ""dati 'rs, 'imm16u""); break; default: UNREACHABLE(); } } void Decoder::DecodeTypeImmediate(Instruction* instr) { switch (instr->OpcodeFieldRaw()) { case COP1: DecodeTypeImmediateCOP1(instr); break; // Case COP1. // ------------- REGIMM class. case REGIMM: DecodeTypeImmediateREGIMM(instr); break; // Case REGIMM. // ------------- Branch instructions. case BEQ: Format(instr, ""beq 'rs, 'rt, 'imm16u -> 'imm16p4s2""); break; case BC: Format(instr, ""bc 'imm26s -> 'imm26p4s2""); break; case BALC: Format(instr, ""balc 'imm26s -> 'imm26p4s2""); break; case BNE: Format(instr, ""bne 'rs, 'rt, 'imm16u -> 'imm16p4s2""); break; case BLEZ: if ((instr->RtValue() == 0) && (instr->RsValue() != 0)) { Format(instr, ""blez 'rs, 'imm16u -> 'imm16p4s2""); } else if ((instr->RtValue() != instr->RsValue()) && (instr->RsValue() != 0) && (instr->RtValue() != 0)) { Format(instr, ""bgeuc 'rs, 'rt, 'imm16u -> 'imm16p4s2""); } else if ((instr->RtValue() == instr->RsValue()) && (instr->RtValue() != 0)) { Format(instr, ""bgezalc 'rs, 'imm16u -> 'imm16p4s2""); } else if ((instr->RsValue() == 0) && (instr->RtValue() != 0)) { Format(instr, ""blezalc 'rt, 'imm16u -> 'imm16p4s2""); } else { UNREACHABLE(); } break; case BGTZ: if ((instr->RtValue() == 0) && (instr->RsValue() != 0)) { Format(instr, ""bgtz 'rs, 'imm16u -> 'imm16p4s2""); } else if ((instr->RtValue() != instr->RsValue()) && (instr->RsValue() != 0) && (instr->RtValue() != 0)) { Format(instr, ""bltuc 'rs, 'rt, 'imm16u -> 'imm16p4s2""); } else if ((instr->RtValue() == instr->RsValue()) && (instr->RtValue() != 0)) { Format(instr, ""bltzalc 'rt, 'imm16u -> 'imm16p4s2""); } else if ((instr->RsValue() == 0) && (instr->RtValue() != 0)) { Format(instr, ""bgtzalc 'rt, 'imm16u -> 'imm16p4s2""); } else { UNREACHABLE(); } break; case BLEZL: if ((instr->RtValue() == instr->RsValue()) && (instr->RtValue() != 0)) { Format(instr, ""bgezc 'rt, 'imm16u -> 'imm16p4s2""); } else if ((instr->RtValue() != instr->RsValue()) && (instr->RsValue() != 0) && (instr->RtValue() != 0)) { Format(instr, ""bgec 'rs, 'rt, 'imm16u -> 'imm16p4s2""); } else if ((instr->RsValue() == 0) && (instr->RtValue() != 0)) { Format(instr, ""blezc 'rt, 'imm16u -> 'imm16p4s2""); } else { UNREACHABLE(); } break; case BGTZL: if ((instr->RtValue() == instr->RsValue()) && (instr->RtValue() != 0)) { Format(instr, ""bltzc 'rt, 'imm16u -> 'imm16p4s2""); } else if ((instr->RtValue() != instr->RsValue()) && (instr->RsValue() != 0) && (instr->RtValue() != 0)) { Format(instr, ""bltc 'rs, 'rt, 'imm16u -> 'imm16p4s2""); } else if ((instr->RsValue() == 0) && (instr->RtValue() != 0)) { Format(instr, ""bgtzc 'rt, 'imm16u -> 'imm16p4s2""); } else { UNREACHABLE(); } break; case POP66: if (instr->RsValue() == JIC) { Format(instr, ""jic 'rt, 'imm16s""); } else { Format(instr, ""beqzc 'rs, 'imm21x -> 'imm21p4s2""); } break; case POP76: if (instr->RsValue() == JIALC) { Format(instr, ""jialc 'rt, 'imm16x""); } else { Format(instr, ""bnezc 'rs, 'imm21x -> 'imm21p4s2""); } break; // ------------- Arithmetic instructions. case ADDI: if (kArchVariant != kMips64r6) { Format(instr, ""addi 'rt, 'rs, 'imm16s""); } else { // Check if BOVC or BEQC instruction. if (instr->RsValue() >= instr->RtValue()) { Format(instr, ""bovc 'rs, 'rt, 'imm16s -> 'imm16p4s2""); } else if (instr->RsValue() < instr->RtValue()) { Format(instr, ""beqc 'rs, 'rt, 'imm16s -> 'imm16p4s2""); } else { UNREACHABLE(); } } break; case DADDI: if (kArchVariant != kMips64r6) { Format(instr, ""daddi 'rt, 'rs, 'imm16s""); } else { // Check if BNVC or BNEC instruction. if (instr->RsValue() >= instr->RtValue()) { Format(instr, ""bnvc 'rs, 'rt, 'imm16s -> 'imm16p4s2""); } else if (instr->RsValue() < instr->RtValue()) { Format(instr, ""bnec 'rs, 'rt, 'imm16s -> 'imm16p4s2""); } else { UNREACHABLE(); } } break; case ADDIU: Format(instr, ""addiu 'rt, 'rs, 'imm16s""); break; case DADDIU: Format(instr, ""daddiu 'rt, 'rs, 'imm16s""); break; case SLTI: Format(instr, ""slti 'rt, 'rs, 'imm16s""); break; case SLTIU: Format(instr, ""sltiu 'rt, 'rs, 'imm16u""); break; case ANDI: Format(instr, ""andi 'rt, 'rs, 'imm16x""); break; case ORI: Format(instr, ""ori 'rt, 'rs, 'imm16x""); break; case XORI: Format(instr, ""xori 'rt, 'rs, 'imm16x""); break; case LUI: if (kArchVariant != kMips64r6) { Format(instr, ""lui 'rt, 'imm16x""); } else { if (instr->RsValue() != 0) { Format(instr, ""aui 'rt, 'imm16x""); } else { Format(instr, ""lui 'rt, 'imm16x""); } } break; case DAUI: Format(instr, ""daui 'rt, 'imm16x""); break; // ------------- Memory instructions. case LB: Format(instr, ""lb 'rt, 'imm16s('rs)""); break; case LH: Format(instr, ""lh 'rt, 'imm16s('rs)""); break; case LWL: Format(instr, ""lwl 'rt, 'imm16s('rs)""); break; case LDL: Format(instr, ""ldl 'rt, 'imm16s('rs)""); break; case LW: Format(instr, ""lw 'rt, 'imm16s('rs)""); break; case LWU: Format(instr, ""lwu 'rt, 'imm16s('rs)""); break; case LD: Format(instr, ""ld 'rt, 'imm16s('rs)""); break; case LBU: Format(instr, ""lbu 'rt, 'imm16s('rs)""); break; case LHU: Format(instr, ""lhu 'rt, 'imm16s('rs)""); break; case LWR: Format(instr, ""lwr 'rt, 'imm16s('rs)""); break; case LDR: Format(instr, ""ldr 'rt, 'imm16s('rs)""); break; case PREF: Format(instr, ""pref 'rt, 'imm16s('rs)""); break; case SB: Format(instr, ""sb 'rt, 'imm16s('rs)""); break; case SH: Format(instr, ""sh 'rt, 'imm16s('rs)""); break; case SWL: Format(instr, ""swl 'rt, 'imm16s('rs)""); break; case SW: Format(instr, ""sw 'rt, 'imm16s('rs)""); break; case SD: Format(instr, ""sd 'rt, 'imm16s('rs)""); break; case SWR: Format(instr, ""swr 'rt, 'imm16s('rs)""); break; case LWC1: Format(instr, ""lwc1 'ft, 'imm16s('rs)""); break; case LDC1: Format(instr, ""ldc1 'ft, 'imm16s('rs)""); break; case SWC1: Format(instr, ""swc1 'ft, 'imm16s('rs)""); break; case SDC1: Format(instr, ""sdc1 'ft, 'imm16s('rs)""); break; case PCREL: { int32_t imm21 = instr->Imm21Value(); // rt field: 5-bits checking uint8_t rt = (imm21 >> kImm16Bits); switch (rt) { case ALUIPC: Format(instr, ""aluipc 'rs, 'imm16s""); break; case AUIPC: Format(instr, ""auipc 'rs, 'imm16s""); break; default: { // rt field: checking of the most significant 3-bits rt = (imm21 >> kImm18Bits); switch (rt) { case LDPC: Format(instr, ""ldpc 'rs, 'imm18s""); break; default: { // rt field: checking of the most significant 2-bits rt = (imm21 >> kImm19Bits); switch (rt) { case LWUPC: Format(instr, ""lwupc 'rs, 'imm19s""); break; case LWPC: Format(instr, ""lwpc 'rs, 'imm19s""); break; case ADDIUPC: Format(instr, ""addiupc 'rs, 'imm19s""); break; default: UNREACHABLE(); break; } break; } } break; } } break; } default: printf(""a 0x%x \\n"", instr->OpcodeFieldRaw()); UNREACHABLE(); break; } } void Decoder::DecodeTypeJump(Instruction* instr) { switch (instr->OpcodeFieldRaw()) { case J: Format(instr, ""j 'imm26x -> 'imm26j""); break; case JAL: Format(instr, ""jal 'imm26x -> 'imm26j""); break; default: UNREACHABLE(); } } // Disassemble the instruction at *instr_ptr into the output buffer. // All instructions are one word long, except for the simulator // psuedo-instruction stop(msg). For that one special case, we return // size larger than one kInstrSize. int Decoder::InstructionDecode(byte* instr_ptr) { Instruction* instr = Instruction::At(instr_ptr); // Print raw instruction bytes. out_buffer_pos_ += SNPrintF(out_buffer_ + out_buffer_pos_, ""%08x "", instr->InstructionBits()); switch (instr->InstructionType(Instruction::TypeChecks::EXTRA)) { case Instruction::kRegisterType: { return DecodeTypeRegister(instr); } case Instruction::kImmediateType: { DecodeTypeImmediate(instr); break; } case Instruction::kJumpType: { DecodeTypeJump(instr); break; } default: { Format(instr, ""UNSUPPORTED""); UNSUPPORTED_MIPS(); } } return Instruction::kInstrSize; } } // namespace internal } // namespace v8 //------------------------------------------------------------------------------ namespace disasm { const char* NameConverter::NameOfAddress(byte* addr) const { v8::internal::SNPrintF(tmp_buffer_, ""%p"", addr); return tmp_buffer_.start(); } const char* NameConverter::NameOfConstant(byte* addr) const { return NameOfAddress(addr); } const char* NameConverter::NameOfCPURegister(int reg) const { return v8::internal::Registers::Name(reg); } const char* NameConverter::NameOfXMMRegister(int reg) const { return v8::internal::FPURegisters::Name(reg); } const char* NameConverter::NameOfByteCPURegister(int reg) const { UNREACHABLE(); // MIPS does not have the concept of a byte register. return ""nobytereg""; } const char* NameConverter::NameInCode(byte* addr) const { // The default name converter is called for unknown code. So we will not try // to access any memory. return """"; } //------------------------------------------------------------------------------ Disassembler::Disassembler(const NameConverter& converter) : converter_(converter) {} Disassembler::~Disassembler() {} int Disassembler::InstructionDecode(v8::internal::Vector buffer, byte* instruction) { v8::internal::Decoder d(converter_, buffer); return d.InstructionDecode(instruction); } // The MIPS assembler does not currently use constant pools. int Disassembler::ConstantPoolSizeAt(byte* instruction) { return -1; } void Disassembler::Disassemble(FILE* f, byte* begin, byte* end) { NameConverter converter; Disassembler d(converter); for (byte* pc = begin; pc < end;) { v8::internal::EmbeddedVector buffer; buffer[0] = '\\0'; byte* prev_pc = pc; pc += d.InstructionDecode(buffer, pc); v8::internal::PrintF(f, ""%p %08x %s\\n"", prev_pc, *reinterpret_cast(prev_pc), buffer.start()); } } #undef UNSUPPORTED } // namespace disasm #endif // V8_TARGET_ARCH_MIPS64 ",16219,True,2992.6833414064795,median "********************************************************************** ********************************************************************** CLASS lcl_ex_sheet IMPLEMENTATION. *--------------------------------------------------------------------* METHOD constructor. "" Set owner me->mo_xlsx = io_xlsx. "" Path to the sheet etc _index_original = _index = iv_index. "" Init XML node _read_dom( ). *************************************** "" Loop through excels rows io_xlsx->row_read_xml( io_sheet = me it_shared_strings = io_xlsx->mt_shared_strings ). "" No need already sorted ""SORT mt_cells BY table_line->c_row table_line->c_col_ind. *************************************** "" Loop through excels columns io_xlsx->column_read_xml( me ). *************************************** merged_cells_read( ). *************************************** "" Data validation read io_xlsx->data_validation_read_xml( me ). *************************************** "" Find related list objects io_xlsx->list_object_read_xml( io_sheet = me ). *************************************** "" later in merge write_cells_offset( ). *************************************** mr_drawing = mo_xlsx->drawing_read_xml( io_sheet = me ). *************************************** io_xlsx->autofilter_read_xml( io_sheet = me ). ENDMETHOD. ""constructor METHOD defined_names_read. IF io_node IS NOT INITIAL. _name = io_node->get_attribute( `name` ). ""#EC NOTEXT _state = io_node->get_attribute( `state` ). ""#EC NOTEXT ELSEIF io_src IS NOT INITIAL. _name = io_src->_name. ENDIF. INSERT _name INTO TABLE mo_xlsx->_all_sheet_name. DATA ls_defined_name TYPE REF TO ts_ex_defined_name. DATA ls_area TYPE REF TO ts_ex_area. DATA ls_cell TYPE REF TO ts_ex_cell. _t_defined_names = mo_xlsx->defined_name_read_xml( me ). LOOP AT _t_defined_names REFERENCE INTO ls_defined_name. LOOP AT ls_defined_name->d_areas REFERENCE INTO ls_area. "" Reference to reference LOOP AT ls_area->a_cells REFERENCE INTO ls_cell. "" Get existing cell Or insert new one find_cell( ir_cell = ls_cell->* iv_def_name = ls_defined_name->d_name ). ENDLOOP. ENDLOOP. ENDLOOP. ENDMETHOD. *--------------------------------------------------------------------* METHOD merged_cells_read. DATA lo_merge_cell TYPE REF TO if_ixml_element. lo_merge_cell ?= mo_document->find_from_name( 'mergeCell' ). ""#EC NOTEXT WHILE lo_merge_cell IS BOUND. "" Create new area DATA ls_area TYPE REF TO ts_ex_area. DATA l_val TYPE string. l_val = lo_merge_cell->get_attribute( 'ref' ). ""#EC NOTEXT CREATE DATA ls_area. zcl_xtt_excel_xlsx=>area_read_xml( iv_value = l_val is_area = ls_area ). "" Always 2 cells DATA ls_cell_beg TYPE REF TO ts_ex_cell. DATA ls_cell_end TYPE REF TO ts_ex_cell. DATA lv_subrc TYPE sysubrc. READ TABLE ls_area->a_cells REFERENCE INTO ls_cell_beg INDEX 1. lv_subrc = sy-subrc. READ TABLE ls_area->a_cells REFERENCE INTO ls_cell_end INDEX 2. "" Get ref to existing or ls_cell_beg cell IF sy-subrc = 0 AND lv_subrc = 0. DATA ls_cell TYPE REF TO ts_ex_cell. ls_cell = find_cell( ls_cell_beg->* ). "" Fill dx ls_cell->c_merge_row_dx = ls_cell_end->c_row - ls_cell_beg->c_row. ls_cell->c_merge_col_dx = ls_cell_end->c_col_ind - ls_cell_beg->c_col_ind. ENDIF. "" Next lo_merge_cell ?= lo_merge_cell->get_next( ). ENDWHILE. ENDMETHOD. *--------------------------------------------------------------------* METHOD write_cells_offset. "" 1 time only CHECK mv_has_offset <> abap_true. mv_has_offset = abap_true. DATA ls_cell TYPE REF TO ts_ex_cell. DATA l_prev_row TYPE i VALUE 0. DATA l_prev_col TYPE i VALUE 0. LOOP AT mt_cells REFERENCE INTO ls_cell. "" If new row ls_cell->c_row_dx > 0 ls_cell->c_row_dx = ls_cell->c_row - l_prev_row. "" If new row then column also from 0 IF ls_cell->c_row_dx <> 0. l_prev_col = 0. ENDIF. ls_cell->c_col_dx = ls_cell->c_col_ind - l_prev_col. l_prev_row = ls_cell->c_row. l_prev_col = ls_cell->c_col_ind. ENDLOOP. ENDMETHOD. *--------------------------------------------------------------------* METHOD find_cell. DATA ls_row TYPE ts_ex_row. READ TABLE mt_cells BINARY SEARCH REFERENCE INTO rr_ex_cell WITH KEY "" with table key c_row = ir_cell-c_row c_col_ind = ir_cell-c_col_ind. IF sy-subrc <> 0 AND iv_add = abap_true. * ev_new_tabix = sy-tabix. INSERT ir_cell INTO mt_cells INDEX sy-tabix REFERENCE INTO rr_ex_cell. READ TABLE mt_rows TRANSPORTING NO FIELDS WITH TABLE KEY r = ir_cell-c_row. IF sy-subrc <> 0. ls_row-r = sy-tabix. INSERT ls_row INTO TABLE mt_rows. ENDIF. ENDIF. CHECK rr_ex_cell IS NOT INITIAL. rr_ex_cell->c_def_name = iv_def_name. ENDMETHOD. *--------------------------------------------------------------------* METHOD fill_shared_strings. DATA ls_cell TYPE REF TO ts_ex_cell. "" Add one by one LOOP AT mt_cells REFERENCE INTO ls_cell. ""WHERE c_value IS NOT INITIAL. CHECK zcl_xtt_excel_xlsx=>cell_is_string( ls_cell ) = abap_true. APPEND ls_cell->c_value TO ct_shared_strings. ENDLOOP. ENDMETHOD. *--------------------------------------------------------------------* METHOD save. "" Late initilization (without merge) write_cells_offset( ). mv_has_offset = abap_false. "" Blank sheet CHECK mt_cells IS NOT INITIAL. *************************************** "" Find old -> new match cells_create_refs( ). *************************************** "" Replace existing text. Work with dom DATA ls_transmit TYPE ts_transmit. ls_transmit = _cells_write_xml( ). ls_transmit-iv_sid = iv_sid. *************************************** "" Data validation (Use dom) mo_xlsx->data_validation_save_xml( io_sheet = me ). mo_xlsx->autofilter_save_xml( io_sheet = me ). *************************************** _replace_by_transmit( ls_transmit ). *************************************** defined_name_save( EXPORTING iv_sid = iv_sid CHANGING ct_defined_names = ct_defined_names ). *************************************** "" List object mo_xlsx->list_object_save_xml( io_sheet = me iv_sid = iv_sid ). ENDMETHOD. *--------------------------------------------------------------------* METHOD get_tag. rv_tag = `` INTO rv_tag RESPECTING BLANKS. ENDMETHOD. *--------------------------------------------------------------------* METHOD get_rel_tag. rv_tag = get_indexed( mc_path-rel_tag ). ENDMETHOD. *--------------------------------------------------------------------* METHOD get_indexed. rv_path = iv_mask. IF iv_original = abap_true. REPLACE ALL OCCURRENCES OF `{1}` IN rv_path WITH _index_original. RETURN. ENDIF. REPLACE ALL OCCURRENCES OF `{1}` IN rv_path WITH _index. CHECK iv_2 IS SUPPLIED. REPLACE FIRST OCCURRENCE OF `{2}` IN rv_path WITH iv_2. ENDMETHOD. *--------------------------------------------------------------------* METHOD _read_dom. "" Content as an object DATA lv_path TYPE string. lv_path = get_indexed( iv_mask = mc_path-full_path iv_original = abap_true ). CREATE OBJECT _xml_xl_worksheet EXPORTING io_zip = mo_xlsx->mo_zip iv_path = lv_path. mo_document = _xml_xl_worksheet->obj_get_document( ). ENDMETHOD. *--------------------------------------------------------------------* METHOD change_xml_doc. CHECK _is_new( ) = abap_true AND iv_sid >= 0. "" Could call several times DATA: lv_mask TYPE string, lv_name TYPE string. CONCATENATE iv_mask `{1}` INTO lv_mask. lv_name = get_indexed( lv_mask ). ""#EC NOTEXT REPLACE ALL OCCURRENCES OF REGEX lv_name IN cv_doc WITH iv_mask. ""#EC NOTEXT "" Set new names CONCATENATE iv_mask `{1}$1` INTO lv_mask. lv_name = get_indexed( lv_mask ). ""#EC NOTEXT "" $1 - as in get_new_id( ) CONCATENATE iv_mask `([0-9]+)` INTO lv_mask. REPLACE FIRST OCCURRENCE OF `/` IN lv_mask WITH `\\/`. REPLACE ALL OCCURRENCES OF REGEX lv_mask IN cv_doc WITH lv_name. ""#EC NOTEXT ENDMETHOD. METHOD get_new_id. rv_id = get_indexed( iv_mask = `{1}{2}` iv_2 = iv_id ). ENDMETHOD. METHOD get_new_name. rv_name = get_indexed( iv_mask = `{2}_{1}` iv_2 = iv_name ). ENDMETHOD. *--------------------------------------------------------------------* METHOD cells_create_refs. DATA ls_cell TYPE REF TO ts_ex_cell. DATA ls_cell_ref TYPE ts_cell_ref. DATA lr_cell_ref TYPE REF TO ts_cell_ref. CLEAR _t_cell_ref[]. LOOP AT mt_cells REFERENCE INTO ls_cell. READ TABLE _t_cell_ref REFERENCE INTO lr_cell_ref WITH TABLE KEY r = ls_cell->c_row c = ls_cell->c_col_ind. IF sy-subrc <> 0. ls_cell_ref-r = ls_cell->c_row. ls_cell_ref-c = ls_cell->c_col_ind. ls_cell_ref-beg = ls_cell. INSERT ls_cell_ref INTO TABLE _t_cell_ref REFERENCE INTO lr_cell_ref. ENDIF. lr_cell_ref->end = ls_cell. APPEND ls_cell TO lr_cell_ref->all. ENDLOOP. ENDMETHOD. *--------------------------------------------------------------------* METHOD _cells_write_xml. DATA l_new_row_ind TYPE i VALUE 0. DATA l_new_col_ind TYPE i VALUE 0. DATA lt_columns LIKE mt_columns. "" Write cells data one by one DATA ls_cell TYPE REF TO ts_ex_cell. LOOP AT mt_cells REFERENCE INTO ls_cell. mo_xlsx->cell_write_new_row( EXPORTING is_cell = ls_cell io_sheet = me CHANGING cs_transmit = rs_transmit cv_current_row = l_new_row_ind cv_current_col = l_new_col_ind ). mo_xlsx->cell_write_new_col( EXPORTING is_cell = ls_cell io_sheet = me CHANGING ct_columns = lt_columns cv_current_col = l_new_col_ind ). "" Complex saving mo_xlsx->drawing_add( ir_me = mr_drawing ir_cell = ls_cell iv_new_row = l_new_row_ind iv_new_col = l_new_col_ind ). "" Append cell info mo_xlsx->cell_write_xml( EXPORTING io_sheet = me is_cell = ls_cell iv_new_row = l_new_row_ind iv_new_col_ind = l_new_col_ind CHANGING cs_transmit = rs_transmit ). ENDLOOP. "" Rows & cells Closing tag _add_end_of_row( CHANGING cs_transmit = rs_transmit ). "" Columns rs_transmit-cols = mo_xlsx->column_write_xml( lt_columns ). FIELD-SYMBOLS LIKE LINE OF lt_columns. LOOP AT lt_columns ASSIGNING . DELETE mt_columns WHERE min = -min. INSERT INTO TABLE mt_columns. ENDLOOP. ENDMETHOD. *--------------------------------------------------------------------* METHOD _add_end_of_row. DATA: lv_last_row TYPE string, lv_last_index TYPE i. lv_last_index = lines( cs_transmit-rows_cells ). READ TABLE cs_transmit-rows_cells INTO lv_last_row INDEX lv_last_index. CHECK sy-subrc = 0. IF lv_last_row CS `` TO cs_transmit-rows_cells. ENDMETHOD. *--------------------------------------------------------------------* METHOD _replace_by_transmit. DATA lo_mc TYPE REF TO if_ixml_element. _xml_xl_worksheet->obj_replace( iv_tag = 'sheetData' ""#EC NOTEXT it_tags = is_transmit-rows_cells ). _xml_xl_worksheet->obj_replace( iv_tag = 'cols' ""#EC NOTEXT it_tags = is_transmit-cols ). lo_mc = _xml_xl_worksheet->obj_replace( iv_tag = 'mergeCells' ""#EC NOTEXT iv_tag_relat = '+sheetData' ""#EC NOTEXT After `sheetData` it_tags = is_transmit-merge_cells ). "" Change count IF lo_mc IS NOT INITIAL AND is_transmit-merge_cells IS NOT INITIAL. DATA lv_merge_cnt TYPE i. lv_merge_cnt = lines( is_transmit-merge_cells ). int_to_text lv_merge_cnt. lo_mc->set_attribute( name = 'count' value = lv_merge_cnt_txt ). ""#EC NOTEXT ENDIF. *************************************** "" In sheet Read relations DATA lv_path_rel TYPE string. DATA lo_xml_sheet_rels TYPE REF TO zcl_xtt_xml_updater. lv_path_rel = get_indexed( iv_mask = mc_path-rel_path iv_original = abap_true ). CREATE OBJECT lo_xml_sheet_rels EXPORTING io_zip = mo_xlsx->mo_zip iv_path = lv_path_rel iv_str_tag = `Relationships` ""#EC NOTEXT iv_str_doc = ``. DATA: lv_draw_path TYPE string, lv_draw_path_rel TYPE string. IF _is_new( ) = abap_true AND is_transmit-iv_sid >= 0. lv_draw_path = get_indexed( `xl/drawings/drawing{1}1.xml` ). lv_draw_path_rel = get_indexed( `xl/drawings/_rels/drawing{1}1.xml.rels` ). ENDIF. "" Add ref to images mo_xlsx->drawing_save_xml( ir_me = mr_drawing iv_path = lv_draw_path iv_path_rel = lv_draw_path_rel io_xml_xl_worksheet = _xml_xl_worksheet io_xml_sheet_rels = lo_xml_sheet_rels ). IF ( _is_new( ) = abap_true AND is_transmit-iv_sid >= 0 ) OR lo_xml_sheet_rels->str_status = zcl_xtt_xml_updater=>c_status-changed. DATA lv_rel TYPE string. lv_rel = get_indexed( `` ). mo_xlsx->_xml_content_types->str_add( lv_rel ). DATA lv_xml_sheet_rels TYPE string. lv_xml_sheet_rels = lo_xml_sheet_rels->str_get_document( ). "" N1 change_xml_doc( EXPORTING iv_sid = is_transmit-iv_sid iv_mask = `drawings/drawing` CHANGING cv_doc = lv_xml_sheet_rels ). "" N2 change_xml_doc( EXPORTING iv_sid = is_transmit-iv_sid iv_mask = `tables/table` CHANGING cv_doc = lv_xml_sheet_rels ). "" And save relation lv_path_rel = get_indexed( iv_mask = mc_path-rel_path iv_original = abap_false ). zcl_eui_conv=>xml_to_zip( io_zip = mo_xlsx->mo_zip iv_name = lv_path_rel iv_sdoc = lv_xml_sheet_rels ). ENDIF. *************************************** "" Replace anchors & Save XML file DATA lv_path TYPE string. lv_path = get_indexed( mc_path-full_path ). _xml_xl_worksheet->save( lv_path ). ENDMETHOD. *--------------------------------------------------------------------* METHOD defined_name_save. DATA lt_defined_name TYPE tt_ex_defined_name. DATA lr_defined_name TYPE REF TO ts_ex_defined_name. DATA ls_defined_name TYPE ts_ex_defined_name. DATA lv_skip_name TYPE abap_bool. DATA ls_area TYPE REF TO ts_ex_area. LOOP AT _t_defined_names REFERENCE INTO lr_defined_name. CLEAR lv_skip_name. "" Make all names local ls_defined_name = lr_defined_name->*. IF _is_new( ) = abap_true AND iv_sid >= 0. int_2_text iv_sid ls_defined_name-d_local_sid. ENDIF. LOOP AT lr_defined_name->d_areas REFERENCE INTO ls_area. ls_area->a_sheet_name = me->_name. replace_with_new( EXPORTING ir_area = ls_area is_defined_name = ls_defined_name "" <--- Copy IMPORTING ev_skip_name = lv_skip_name CHANGING ct_defined_name = lt_defined_name ). ENDLOOP. "" Delete old range name CHECK lv_skip_name <> abap_true. INSERT lr_defined_name->* INTO TABLE ct_defined_names. ENDLOOP. "" Add new names INSERT LINES OF lt_defined_name INTO TABLE ct_defined_names. ENDMETHOD. *--------------------------------------------------------------------* METHOD replace_with_new. DATA: lr_cell TYPE REF TO ts_ex_cell, lr_cell_ref TYPE REF TO ts_cell_ref, lv_tabix TYPE sytabix, lv_cell_cnt TYPE i, lv_area_cnt TYPE i, ls_defined_name LIKE is_defined_name, ls_area TYPE ts_ex_area, ls_ex_cell TYPE REF TO ts_ex_cell. lv_cell_cnt = lines( ir_area->a_cells ). lv_area_cnt = lines( is_defined_name-d_areas ). CLEAR ev_skip_name. LOOP AT ir_area->a_cells REFERENCE INTO lr_cell. lv_tabix = sy-tabix. "" OLD -> NEW READ TABLE _t_cell_ref REFERENCE INTO lr_cell_ref WITH TABLE KEY r = lr_cell->c_row c = lr_cell->c_col_ind. CHECK sy-subrc = 0. "" Add new names IF is_defined_name-d_name CP lcl_ex_sheet=>mc_dyn_def_name AND lv_cell_cnt = 1 AND lv_area_cnt = 1 AND ct_defined_name IS REQUESTED. LOOP AT lr_cell_ref->all INTO ls_ex_cell. "" Define name CLEAR ls_defined_name. ls_defined_name-d_name = ls_ex_cell->c_def_name. ls_defined_name-d_local_sid = is_defined_name-d_local_sid. "" Add cell ls_area = ir_area->*. CLEAR ls_area-a_cells. INSERT ls_ex_cell->* INTO TABLE ls_area-a_cells. INSERT ls_area INTO TABLE ls_defined_name-d_areas. "" Add new range name INSERT ls_defined_name INTO TABLE ct_defined_name. ENDLOOP. ev_skip_name = abap_true. RETURN. ENDIF. CASE lv_tabix. "" First occurrence WHEN 1. lr_cell->* = lr_cell_ref->beg->*. "" Last occurrence WHEN 2. lr_cell->* = lr_cell_ref->end->*. ENDCASE. ENDLOOP. "" Add additional cell to the end CHECK lv_tabix = 1 AND lr_cell_ref IS NOT INITIAL. APPEND lr_cell_ref->end->* TO ir_area->a_cells. ENDMETHOD. *--------------------------------------------------------------------* METHOD merge. DATA lo_scope TYPE REF TO zcl_xtt_scope. read_scopes( EXPORTING io_block = io_block iv_tabix = iv_tabix iv_force = iv_force IMPORTING eo_scope = lo_scope CHANGING ct_cells = ct_cells ). write_cells_offset( ). "" Already found scopes FIELD-SYMBOLS LIKE LINE OF lo_scope->mt_scope. LOOP AT lo_scope->mt_scope ASSIGNING . "" Current -> ms_cell READ TABLE ct_cells REFERENCE INTO ms_cell INDEX -index. IF sy-subrc <> 0. MESSAGE e019(zsy_xtt) WITH -field INTO sy-msgli. mo_xlsx->add_log_message( iv_syst = abap_true ). CONTINUE. ENDIF. "" if equal then merge cells ms_cell->c_merge_me = -merge_me. "" @see match_found io_block->find_match( EXPORTING io_xtt = mo_xlsx is_scope = CHANGING cv_content = ms_cell->c_value ). ENDLOOP. DATA lr_field TYPE REF TO zcl_xtt_replace_block=>ts_field. LOOP AT io_block->mt_fields REFERENCE INTO lr_field. CASE lr_field->typ. "" merge-2 Structures and objects WHEN zcl_xtt_replace_block=>mc_type-struct OR zcl_xtt_replace_block=>mc_type-object. merge_sub_structures( EXPORTING ir_field = lr_field CHANGING ct_cells = ct_cells ). "" merge-3,4 Array types and trees WHEN zcl_xtt_replace_block=>mc_type-table OR zcl_xtt_replace_block=>mc_type-tree. merge_tables_trees( EXPORTING ir_field = lr_field io_scope = lo_scope CHANGING ct_cells = ct_cells ). ENDCASE. ENDLOOP. ENDMETHOD. *--------------------------------------------------------------------* METHOD read_scopes. "" Position holder DATA lv_new TYPE abap_bool. mo_xlsx->_get_scope( EXPORTING io_block = io_block iv_force = iv_force IMPORTING eo_scope = eo_scope ev_new = lv_new ). IF lv_new = abap_true. DATA lr_cell TYPE REF TO ts_ex_cell. LOOP AT ct_cells REFERENCE INTO lr_cell WHERE c_formula IS INITIAL. DATA lv_tabix TYPE sytabix. lv_tabix = sy-tabix. DATA lv_inline_tree TYPE abap_bool. eo_scope->get_scopes( EXPORTING iv_index = lv_tabix io_xtt = mo_xlsx IMPORTING ev_inline_tree = lv_inline_tree CHANGING cv_content = lr_cell->c_value ). "" No need the cell value CHECK lv_inline_tree = abap_true. CLEAR lr_cell->c_value. "" Add blank cell CHECK lr_cell->c_col_ind > 1. DATA ls_blank TYPE ts_ex_cell. ls_blank-c_row = lr_cell->c_row. ls_blank-c_col_ind = lr_cell->c_col_ind - 1. find_cell( ls_blank ). "" Calc dx again mv_has_offset = abap_false. ENDLOOP. ENDIF. eo_scope->calc_cond_matches( io_xtt = mo_xlsx io_block = io_block iv_tabix = iv_tabix iv_init = lv_new ). ENDMETHOD. *--------------------------------------------------------------------* METHOD merge_sub_structures. "" No data ? IF ir_field->typ = zcl_xtt_replace_block=>mc_type-struct. CHECK ir_field->dref IS NOT INITIAL. ENDIF. IF ir_field->typ = zcl_xtt_replace_block=>mc_type-object. CHECK ir_field->oref IS NOT INITIAL. ENDIF. "" Based on nested structure DATA lo_new_replace_block TYPE REF TO zcl_xtt_replace_block. CREATE OBJECT lo_new_replace_block EXPORTING io_xtt = mo_xlsx is_field = ir_field. "" Recursion me->merge( EXPORTING io_block = lo_new_replace_block CHANGING ct_cells = ct_cells ). ENDMETHOD. *--------------------------------------------------------------------* METHOD merge_tables_trees. DATA: lv_by_column TYPE abap_bool, lt_cells_end LIKE ct_cells, lt_cells_mid LIKE ct_cells, lo_tree_handler TYPE REF TO lcl_tree_handler. "" Tree or Table Find for replication split_2_content( EXPORTING ir_field = ir_field io_scope = io_scope IMPORTING ev_by_column = lv_by_column et_cells_mid = lt_cells_mid et_cells_end = lt_cells_end eo_tree_handler = lo_tree_handler CHANGING ct_cells = ct_cells ). ********************************************************************** CASE ir_field->typ. WHEN zcl_xtt_replace_block=>mc_type-tree. "" if equal then merge cells CLEAR _t_merge_me. lo_tree_handler->init( EXPORTING io_owner = me ir_field = ir_field CHANGING ct_cells = ct_cells ). merge_me( lv_by_column ). WHEN zcl_xtt_replace_block=>mc_type-table. merge_table_ext( EXPORTING ir_field = ir_field it_cells_mid = lt_cells_mid CHANGING ct_cells = ct_cells ). ENDCASE. ********************************************************************** "" Rest of the cells APPEND LINES OF lt_cells_end TO ct_cells. "" Set the order back IF lv_by_column = abap_true. SORT ct_cells STABLE BY c_row. ENDIF. "" Recalc CHECK lv_by_column EQ abap_true. save( iv_sid = -1 ). ENDMETHOD. *--------------------------------------------------------------------* METHOD merge_table_ext. CHECK it_cells_mid IS NOT INITIAL. "" Replicate middle FIELD-SYMBOLS TYPE ANY TABLE. ASSIGN ir_field->dref->* TO . "" Use copy DATA lr_field2 TYPE REF TO zcl_xtt_replace_block=>ts_field. CREATE DATA lr_field2. lr_field2->* = ir_field->*. DATA lt_copy LIKE ct_cells. "" Index for hashed table DATA lv_tabix TYPE sytabix. lv_tabix = 0. LOOP AT REFERENCE INTO lr_field2->dref. lv_tabix = lv_tabix + 1. lt_copy[] = it_cells_mid[]. DATA lv_first TYPE abap_bool. IF lv_tabix = 1. lv_first = abap_true. ELSE. lv_first = abap_false. ENDIF. "" Create merge description, Create copy first DATA lo_new_replace_block TYPE REF TO zcl_xtt_replace_block. IF lo_new_replace_block IS INITIAL OR lo_new_replace_block->reuse_check( lr_field2 ) <> abap_true. CREATE OBJECT lo_new_replace_block EXPORTING io_xtt = mo_xlsx is_field = lr_field2. ENDIF. "" Recursion me->merge( EXPORTING io_block = lo_new_replace_block iv_tabix = lv_tabix iv_force = lv_first CHANGING ct_cells = lt_copy ). APPEND LINES OF lt_copy TO ct_cells. ENDLOOP. ENDMETHOD. *--------------------------------------------------------------------* METHOD split_2_content. DATA: lv_find_str TYPE string, ls_cell TYPE REF TO ts_ex_cell, lt_row_begs TYPE tt_pair, lt_row_ends TYPE tt_pair, lv_row_first TYPE i, lv_row_last TYPE i, ls_cur_pair TYPE ts_pair, ls_pair_ref TYPE REF TO ts_pair, ls_row_off TYPE zcl_xtt_tree_function=>ts_row_offset. "" All positions CLEAR: et_cells_end, et_cells_mid, eo_tree_handler. ev_by_column = io_scope->is_by_column( ir_field->name ). IF ev_by_column = abap_true. SORT ct_cells STABLE BY c_col_ind c_row. ENDIF. "" CONCATENATE zcl_xtt_replace_block=>mc_char_block_begin iv_fld_name INTO lv_find_str. CONCATENATE `\\{` ir_field->name `\\b[^}]*\\}` INTO lv_find_str. IF ir_field->typ = zcl_xtt_replace_block=>mc_type-tree. CREATE OBJECT eo_tree_handler EXPORTING io_xtt = mo_xlsx iv_block_name = ir_field->name. ENDIF. "" Find matches LOOP AT ct_cells REFERENCE INTO ls_cell. "" Current values ls_cur_pair-array_ind = sy-tabix. "" What field to use IF ev_by_column = abap_true. ls_cur_pair-position = ls_cell->c_col_ind. "" ls_cur_pair-position + ls_cell->c_col_dx. ELSE. ls_cur_pair-position = ls_cell->c_row. "" ls_cur_pair-position + ls_cell->c_row_dx. ENDIF. "" Find row range READ TABLE lt_row_begs WITH TABLE KEY position = ls_cur_pair-position TRANSPORTING NO FIELDS. IF sy-subrc <> 0. INSERT ls_cur_pair INTO TABLE lt_row_begs. ENDIF. "" Make range bigger READ TABLE lt_row_ends REFERENCE INTO ls_pair_ref WITH TABLE KEY position = ls_cur_pair-position. IF sy-subrc = 0. ls_pair_ref->array_ind = ls_cur_pair-array_ind. ELSE. INSERT ls_cur_pair INTO TABLE lt_row_ends. ENDIF. "" Rows range DATA lv_offset TYPE i. DATA lv_length TYPE i. FIND FIRST OCCURRENCE OF REGEX lv_find_str IN ls_cell->c_value MATCH OFFSET lv_offset MATCH LENGTH lv_length. CHECK sy-subrc = 0. lv_row_last = ls_cur_pair-position. "" Set 1 time only IF lv_row_first IS INITIAL. lv_row_first = lv_row_last. ENDIF. *************************** "" TREE begin or is_field->typ = zcl_xtt_replace_block=>mc_type-tree. CHECK eo_tree_handler IS NOT INITIAL. "" Delete surrounding {} lv_offset = lv_offset + 1. lv_length = lv_length - 2. DATA lv_text TYPE string. lv_text = ls_cell->c_value+lv_offset(lv_length). "" Read from texts eo_tree_handler->detect_options( EXPORTING iv_text = lv_text iv_pos = ls_cur_pair-position iv_par_fld = ir_field->name CHANGING cs_row_offset = ls_row_off ). "" TREE end *************************** ENDLOOP. CHECK is_row_off_ok( is_field = ir_field iv_row_first = lv_row_first iv_row_last = lv_row_last ) = abap_true. IF eo_tree_handler IS NOT INITIAL. eo_tree_handler->fill_cell_match( iv_tr_id = ir_field->name it_row_begs = lt_row_begs it_row_ends = lt_row_ends it_cells = ct_cells ). ENDIF. move_cell_content( EXPORTING it_row_begs = lt_row_begs it_row_ends = lt_row_ends iv_row_first = lv_row_first iv_row_last = lv_row_last CHANGING ct_cells = ct_cells ct_cells_mid = et_cells_mid ct_cells_end = et_cells_end ). ENDMETHOD. *--------------------------------------------------------------------* METHOD is_row_off_ok. "" Skip IF iv_row_first IS INITIAL AND iv_row_last IS INITIAL. RETURN. ENDIF. "" Oops not found IF iv_row_first IS INITIAL OR iv_row_last IS INITIAL. MESSAGE e009(zsy_xtt) WITH is_field->name INTO sy-msgli. zcx_eui_no_check=>raise_sys_error( ). ENDIF. rv_ok = abap_true. ENDMETHOD. METHOD move_cell_content. DATA ls_pair_ref TYPE REF TO ts_pair. DATA lv_ind_beg TYPE i. DATA lv_ind_end TYPE i. DATA lv_ind_end_1 TYPE i. "" Detect middle READ TABLE it_row_begs REFERENCE INTO ls_pair_ref WITH TABLE KEY position = iv_row_first. lv_ind_beg = ls_pair_ref->array_ind. READ TABLE it_row_ends REFERENCE INTO ls_pair_ref WITH TABLE KEY position = iv_row_last. lv_ind_end = ls_pair_ref->array_ind. "" End lv_ind_end_1 = lv_ind_end + 1. APPEND LINES OF ct_cells FROM lv_ind_end_1 TO ct_cells_end. "" Middle APPEND LINES OF ct_cells FROM lv_ind_beg TO lv_ind_end TO ct_cells_mid. "" Begin! DELETE ct_cells FROM lv_ind_beg. ENDMETHOD. *--------------------------------------------------------------------* METHOD clone. "" ro_copy->_state IS EMPTY -> visible. CREATE OBJECT ro_copy EXPORTING iv_index = me->_index_original io_xlsx = me->mo_xlsx. int_2_text iv_new_index ro_copy->_index. ro_copy->defined_names_read( io_src = me ). ro_copy->_name = zcl_xtt_html=>format( iv_template = me->_name is_root = is_block iv_root_name = iv_block_name ). IF ro_copy->_name IS INITIAL. zcx_xtt_exception=>raise_dump( iv_message = 'Sheet name is initial'(shi) ). ENDIF. INSERT ro_copy->_name INTO TABLE mo_xlsx->_all_sheet_name. CHECK sy-subrc <> 0. MESSAGE e027(zsy_xtt) WITH ro_copy->_name INTO sy-msgli. zcx_xtt_exception=>raise_dump( iv_message = sy-msgli ). ENDMETHOD. *--------------------------------------------------------------------* METHOD _is_new. CHECK _index <> _index_original. rv_new = abap_true. ENDMETHOD. *--------------------------------------------------------------------* METHOD merge_me. DATA lr_prev_cell TYPE REF TO ts_ex_cell. DATA lr_cell TYPE REF TO ts_ex_cell. DATA lv_merge_cnt TYPE i. CHECK _t_merge_me[] IS NOT INITIAL. """""" DATA(lt_ex_cell1) = VALUE tt_ex_cell( FOR lr_cell_line IN _t_merge_me ( lr_cell_line->* ) ). BREAK-POINT. CASE iv_by_column. WHEN abap_false. SORT _t_merge_me STABLE BY table_line->c_col. WHEN abap_true. "" Revers c_col <---> c_row? SORT _t_merge_me STABLE BY table_line->c_row. ENDCASE. """""" DATA(lt_ex_cell2) = VALUE tt_ex_cell( FOR lr_cell_line IN _t_merge_me ( lr_cell_line->* ) ). BREAK-POINT. ""DATA lt_unq_cell TYPE SORTED TABLE OF ts_ex_cell WITH UNIQUE KEY table_line. DATA lt_level TYPE SORTED TABLE OF i WITH UNIQUE KEY table_line. DATA: lv_is_same_pos TYPE abap_bool. LOOP AT _t_merge_me INTO lr_cell. lv_is_same_pos = abap_true. *** INSERT lr_cell->* INTO TABLE lt_unq_cell. *** IF sy-subrc <> 0. *** lv_is_same_pos = abap_false. *** ENDIF. INSERT lr_cell->c_merge_tr_level INTO TABLE lt_level. IF lr_prev_cell IS INITIAL. lr_prev_cell = lr_cell. CONTINUE. ENDIF. CASE iv_by_column. WHEN abap_false. IF lr_cell->c_col <> lr_prev_cell->c_col. lv_is_same_pos = abap_false. ENDIF. WHEN abap_true. IF lr_cell->c_row <> lr_prev_cell->c_row. lv_is_same_pos = abap_false. ENDIF. ENDCASE. "" Merge with parent level ? IF lines( lt_level ) = 1 AND lr_cell->c_merge_tabix <= lr_prev_cell->c_merge_tabix. lv_is_same_pos = abap_false. ENDIF. IF lr_cell->c_value = lr_prev_cell->c_value AND lv_is_same_pos = abap_true. CLEAR: "" lr_cell->c_value, "" Several times ? lr_cell->c_merge_row_dx, lr_cell->c_merge_col_dx. ADD 1 TO lv_merge_cnt. CONTINUE. ENDIF. _do_merge_me( ir_cell = lr_prev_cell iv_count = lv_merge_cnt iv_by_column = iv_by_column ). lr_prev_cell = lr_cell. CLEAR: lt_level, "" ***lt_unq_cell lv_merge_cnt. *** INSERT lr_cell->* INTO TABLE lt_unq_cell. INSERT lr_cell->c_merge_tr_level INTO TABLE lt_level. ENDLOOP. _do_merge_me( ir_cell = lr_prev_cell iv_count = lv_merge_cnt iv_by_column = iv_by_column ). ENDMETHOD. METHOD _do_merge_me. CHECK ir_cell IS NOT INITIAL. "" AND iv_count > 0 CASE iv_by_column. WHEN abap_false. ir_cell->c_merge_row_dx = iv_count. WHEN abap_true. ir_cell->c_merge_col_dx = iv_count. ENDCASE. ENDMETHOD. ENDCLASS. ""lcl_ex_sheet IMPLEMENTATION ********************************************************************** ********************************************************************** CLASS lcl_tree_handler IMPLEMENTATION. METHOD fill_cell_match. "" TREE begin Check overlaps FIELD-SYMBOLS TYPE zcl_xtt_tree_function=>ts_row_offset. FIELD-SYMBOLS TYPE zcl_xtt_tree_function=>ts_row_offset. DATA lv_from TYPE sytabix. LOOP AT mt_row_offset ASSIGNING . lv_from = sy-tabix + 1. LOOP AT mt_row_offset ASSIGNING FROM lv_from WHERE ( first <= -last AND first >= -first ) OR ( last <= -last AND last >= -first ). MESSAGE e011(zsy_xtt) WITH me->mv_block_name INTO sy-msgli. zcx_eui_no_check=>raise_sys_error( ). ENDLOOP. ENDLOOP. LOOP AT mt_row_offset ASSIGNING . DATA lr_cache TYPE REF TO ts_match_cache. create_tr_cache lr_cache. DATA ls_pair_beg TYPE REF TO ts_pair. READ TABLE it_row_begs REFERENCE INTO ls_pair_beg WITH TABLE KEY position = -first. DATA ls_pair_end TYPE REF TO ts_pair. READ TABLE it_row_ends REFERENCE INTO ls_pair_end WITH TABLE KEY position = -last. "" And add APPEND LINES OF it_cells FROM ls_pair_beg->array_ind TO ls_pair_end->array_ind TO lr_cache->tr_cells. -_data = lr_cache. ENDLOOP. ENDMETHOD. METHOD init. mo_owner = io_owner. DATA lr_tree TYPE REF TO zcl_xtt_replace_block=>ts_tree. lr_tree ?= ir_field->dref. "" If there are dynamic levels generate_prog( lr_tree ). "" iv_cond_id = ir_field->name ). add_tree_data( EXPORTING ir_tree = lr_tree iv_tabix = 0 CHANGING ct_cells = ct_cells ). ENDMETHOD. METHOD add_tree_data. DATA lt_row_top TYPE tt_ex_cell. DATA lt_row_bottom TYPE tt_ex_cell. DATA lr_tree_attr TYPE REF TO zcl_xtt_replace_block=>ts_tree_attr. DATA lr_tree TYPE REF TO zcl_xtt_replace_block=>ts_tree. DATA: lv_top TYPE abap_bool, lv_insert_merge_index TYPE i VALUE -1. add_tree_data_own( EXPORTING ir_tree = ir_tree iv_tabix = iv_tabix IMPORTING et_row_top = lt_row_top et_row_bottom = lt_row_bottom ev_top = lv_top CHANGING ct_dyn_def_name = ct_dyn_def_name ). IF lv_top = abap_true. lv_insert_merge_index = lines( mo_owner->_t_merge_me ). ENDIF. "" row before DATA lt_cells_ref TYPE tt_ex_cell_ref. append_to( EXPORTING it_cells = lt_row_top CHANGING ct_cells = ct_cells ct_cells_ref = lt_cells_ref ). "" children rows DATA lt_dyn_def_name LIKE ct_dyn_def_name. "" Index for hashed table DATA lv_tabix TYPE sytabix. lv_tabix = 0. LOOP AT ir_tree->sub_nodes REFERENCE INTO lr_tree_attr. lv_tabix = lv_tabix + 1. lr_tree ?= lr_tree_attr->attr. add_tree_data( EXPORTING ir_tree = lr_tree iv_tabix = lv_tabix CHANGING ct_cells = ct_cells ct_dyn_def_name = lt_dyn_def_name ). ENDLOOP. "" row after append_to( EXPORTING it_cells = lt_row_bottom CHANGING ct_cells = ct_cells ct_cells_ref = lt_cells_ref ). update_cells_ref( EXPORTING it_dyn_def_name = lt_dyn_def_name CHANGING ct_cells_ref = lt_cells_ref ). "" if equal then merge cells DATA lr_cell TYPE REF TO ts_ex_cell. LOOP AT lt_cells_ref INTO lr_cell WHERE table_line->c_merge_me = abap_true. * IF lines( mt_row_offset ) = ir_tree->level + 1. lr_cell->c_merge_tabix = iv_tabix. * ENDIF. lr_cell->c_merge_tr_level = ir_tree->level. IF lv_insert_merge_index = -1. APPEND lr_cell TO mo_owner->_t_merge_me. ELSE. lv_insert_merge_index = lv_insert_merge_index + 1. INSERT lr_cell INTO mo_owner->_t_merge_me INDEX lv_insert_merge_index. ENDIF. ENDLOOP. ENDMETHOD. METHOD add_tree_data_own. DATA lo_replace_block TYPE REF TO zcl_xtt_replace_block. "" result ev_top = `~`. CLEAR: et_row_top, et_row_bottom. "" Main data FIELD-SYMBOLS TYPE any. ASSIGN ir_tree->data->* TO . "" Create merge description CREATE OBJECT lo_replace_block EXPORTING io_xtt = mo_xtt is_block = iv_block_name = mv_block_name. "" Check amount of level's templates DATA lv_templ_lev_cnt TYPE i. lv_templ_lev_cnt = lines( mt_row_offset ). DATA: lv_found TYPE abap_bool, lr_found TYPE REF TO abap_bool. GET REFERENCE OF lv_found INTO lr_found. FIELD-SYMBOLS TYPE tt_ex_cell. DATA lv_top LIKE ev_top. DO 3 TIMES. CASE sy-index. WHEN 1. ASSIGN et_row_top TO . lv_top = abap_true. WHEN 2. ASSIGN et_row_bottom TO . lv_top = abap_false. WHEN 3. "" 3-d try CHECK et_row_top IS INITIAL AND et_row_bottom IS INITIAL AND lv_found <> abap_true. ASSIGN et_row_top TO . lv_top = abap_undefined. ENDCASE. "" Find match DATA lr_cache TYPE REF TO ts_match_cache. lr_cache ?= find_match( ir_tree = ir_tree iv_top = lv_top cr_found = lr_found ). "" Next attempt? CHECK lr_cache IS NOT INITIAL. ev_top = lv_top. "" Merge with data [] = lr_cache->tr_cells[]. "" Unique ID lo_replace_block->set_id( lr_cache->tr_id ). "" For new rows & columns only (+ for groups) IF lv_templ_lev_cnt = 1. set_outline( EXPORTING iv_level = ir_tree->level CHANGING ct_block_cells = ). ENDIF. create_new_names( CHANGING ct_block_cells = ct_dyn_def_name = ct_dyn_def_name ). mo_owner->merge( EXPORTING io_block = lo_replace_block iv_tabix = iv_tabix CHANGING ct_cells = ). ENDDO. ENDMETHOD. METHOD set_outline. DATA ls_cell TYPE REF TO ts_ex_cell. DATA ls_row TYPE REF TO ts_ex_row. DATA ls_column TYPE REF TO ts_ex_column. LOOP AT ct_block_cells REFERENCE INTO ls_cell. "" Rows DO 1 TIMES. "" WHERE c_row_dx IS NOT INITIAL. ? "" Have outline ot not READ TABLE mo_owner->mt_rows WITH TABLE KEY r = ls_cell->c_row REFERENCE INTO ls_row. CHECK sy-subrc = 0 AND ls_row->outlinelevel IS NOT INITIAL. ls_cell->c_row_outline = iv_level. ls_row->outline_skip = abap_true. ENDDO. "" Columns DO 1 TIMES. "" Have outline ot not READ TABLE mo_owner->mt_columns WITH TABLE KEY min = ls_cell->c_col_ind REFERENCE INTO ls_column. CHECK sy-subrc = 0 AND ls_column->outlinelevel IS NOT INITIAL. ls_cell->c_column_outline = iv_level. ls_column->outline_skip = abap_true. ENDDO. ENDLOOP. ENDMETHOD. METHOD create_new_names. DATA ls_dyn_def_name LIKE LINE OF ct_dyn_def_name. DATA lr_cell TYPE REF TO ts_ex_cell. LOOP AT ct_block_cells REFERENCE INTO lr_cell WHERE c_def_name CP lcl_ex_sheet=>mc_dyn_def_name. "" Find in parent of parent FIELD-SYMBOLS TYPE ts_ex_defined_name. READ TABLE mo_owner->_t_defined_names ASSIGNING BINARY SEARCH "" TODOOOOOOOOOOOOOOOOOOOOOOO!!!!!!!!!!!!! WITH KEY d_name = lr_cell->c_def_name. "" TABLE KEY CHECK sy-subrc = 0. "" Add new group FIELD-SYMBOLS LIKE LINE OF ct_dyn_def_name. READ TABLE ct_dyn_def_name ASSIGNING WITH TABLE KEY name = lr_cell->c_def_name. IF sy-subrc <> 0. ls_dyn_def_name-name = lr_cell->c_def_name. CONCATENATE `*(` ls_dyn_def_name-name `)*` INTO ls_dyn_def_name-mask. INSERT ls_dyn_def_name INTO TABLE ct_dyn_def_name ASSIGNING . ENDIF. "" Create new name ADD 1 TO -d_count. lr_cell->c_def_name = -d_count. CONDENSE lr_cell->c_def_name. CONCATENATE -d_name lr_cell->c_def_name INTO lr_cell->c_def_name. "" And add to result INSERT lr_cell->c_def_name INTO TABLE -t_all_def. ENDLOOP. ENDMETHOD. METHOD update_cells_ref. DATA lv_new_formula TYPE string. DATA lv_part TYPE string. DATA lr_cell TYPE REF TO ts_ex_cell. DATA lv_cnt TYPE i. DATA lv_len TYPE i. FIELD-SYMBOLS LIKE LINE OF it_dyn_def_name. CHECK it_dyn_def_name IS NOT INITIAL. LOOP AT it_dyn_def_name ASSIGNING . CLEAR lv_new_formula. "" Number of arguments lv_cnt = lines( -t_all_def ). "" New formula separeted by space LOOP AT -t_all_def INTO lv_part. IF lv_new_formula IS INITIAL. lv_new_formula = lv_part. CONTINUE. ENDIF. CONCATENATE lv_new_formula `,` lv_part INTO lv_new_formula. ENDLOOP. LOOP AT ct_cells_ref INTO lr_cell WHERE table_line->c_formula CP -mask. REPLACE ALL OCCURRENCES OF -name IN lr_cell->c_formula WITH lv_new_formula. "" Formula length lv_len = strlen( lr_cell->c_formula ). IF lv_len > 8192 OR lv_cnt > 255. MESSAGE s006(zsy_xtt) WITH lr_cell->c_col lr_cell->c_row INTO sy-msgli. zcx_xtt_exception=>raise_dump( iv_message = sy-msgli ). ENDIF. ENDLOOP. ENDLOOP. ENDMETHOD. METHOD append_to. DATA lv_from TYPE i. DATA lr_cell TYPE REF TO ts_ex_cell. lv_from = lines( ct_cells ) + 1. APPEND LINES OF it_cells TO ct_cells. "" Refs to new cells LOOP AT ct_cells REFERENCE INTO lr_cell FROM lv_from. APPEND lr_cell TO ct_cells_ref. ENDLOOP. ENDMETHOD. ENDCLASS. ",11276,False,2280.6649662789787,median "/* * Copyright 2015 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include ""FakeStreams.h"" #include ""Resources.h"" #include ""SkAndroidCodec.h"" #include ""SkAutoMalloc.h"" #include ""SkBitmap.h"" #include ""SkCodec.h"" #include ""SkCodecImageGenerator.h"" #include ""SkColorSpace_XYZ.h"" #include ""SkColorSpacePriv.h"" #include ""SkData.h"" #include ""SkFrontBufferedStream.h"" #include ""SkImageEncoder.h"" #include ""SkImageEncoderPriv.h"" #include ""SkMD5.h"" #include ""SkOSPath.h"" #include ""SkJpegEncoder.h"" #include ""SkPngChunkReader.h"" #include ""SkPngEncoder.h"" #include ""SkRandom.h"" #include ""SkStream.h"" #include ""SkStreamPriv.h"" #include ""SkWebpEncoder.h"" #include ""Test.h"" #include ""png.h"" #include ""sk_tool_utils.h"" #if PNG_LIBPNG_VER_MAJOR == 1 && PNG_LIBPNG_VER_MINOR < 5 // FIXME (scroggo): Google3 needs to be updated to use a newer version of libpng. In // the meantime, we had to break some pieces of SkPngCodec in order to support Google3. // The parts that are broken are likely not used by Google3. #define SK_PNG_DISABLE_TESTS #endif static void md5(const SkBitmap& bm, SkMD5::Digest* digest) { SkASSERT(bm.getPixels()); SkMD5 md5; size_t rowLen = bm.info().bytesPerPixel() * bm.width(); for (int y = 0; y < bm.height(); ++y) { md5.write(bm.getAddr(0, y), rowLen); } md5.finish(*digest); } /** * Compute the digest for bm and compare it to a known good digest. * @param r Reporter to assert that bm's digest matches goodDigest. * @param goodDigest The known good digest to compare to. * @param bm The bitmap to test. */ static void compare_to_good_digest(skiatest::Reporter* r, const SkMD5::Digest& goodDigest, const SkBitmap& bm) { SkMD5::Digest digest; md5(bm, &digest); REPORTER_ASSERT(r, digest == goodDigest); } /** * Test decoding an SkCodec to a particular SkImageInfo. * * Calling getPixels(info) should return expectedResult, and if goodDigest is non nullptr, * the resulting decode should match. */ template static void test_info(skiatest::Reporter* r, Codec* codec, const SkImageInfo& info, SkCodec::Result expectedResult, const SkMD5::Digest* goodDigest) { SkBitmap bm; bm.allocPixels(info); SkCodec::Result result = codec->getPixels(info, bm.getPixels(), bm.rowBytes()); REPORTER_ASSERT(r, result == expectedResult); if (goodDigest) { compare_to_good_digest(r, *goodDigest, bm); } } SkIRect generate_random_subset(SkRandom* rand, int w, int h) { SkIRect rect; do { rect.fLeft = rand->nextRangeU(0, w); rect.fTop = rand->nextRangeU(0, h); rect.fRight = rand->nextRangeU(0, w); rect.fBottom = rand->nextRangeU(0, h); rect.sort(); } while (rect.isEmpty()); return rect; } static void test_incremental_decode(skiatest::Reporter* r, SkCodec* codec, const SkImageInfo& info, const SkMD5::Digest& goodDigest) { SkBitmap bm; bm.allocPixels(info); REPORTER_ASSERT(r, SkCodec::kSuccess == codec->startIncrementalDecode(info, bm.getPixels(), bm.rowBytes())); REPORTER_ASSERT(r, SkCodec::kSuccess == codec->incrementalDecode()); compare_to_good_digest(r, goodDigest, bm); } // Test in stripes, similar to DM's kStripe_Mode static void test_in_stripes(skiatest::Reporter* r, SkCodec* codec, const SkImageInfo& info, const SkMD5::Digest& goodDigest) { SkBitmap bm; bm.allocPixels(info); bm.eraseColor(SK_ColorYELLOW); const int height = info.height(); // Note that if numStripes does not evenly divide height there will be an extra // stripe. const int numStripes = 4; if (numStripes > height) { // Image is too small. return; } const int stripeHeight = height / numStripes; // Iterate through the image twice. Once to decode odd stripes, and once for even. for (int oddEven = 1; oddEven >= 0; oddEven--) { for (int y = oddEven * stripeHeight; y < height; y += 2 * stripeHeight) { SkIRect subset = SkIRect::MakeLTRB(0, y, info.width(), SkTMin(y + stripeHeight, height)); SkCodec::Options options; options.fSubset = ⊂ if (SkCodec::kSuccess != codec->startIncrementalDecode(info, bm.getAddr(0, y), bm.rowBytes(), &options)) { ERRORF(r, ""failed to start incremental decode!\\ttop: %i\\tbottom%i\\n"", subset.top(), subset.bottom()); return; } if (SkCodec::kSuccess != codec->incrementalDecode()) { ERRORF(r, ""failed incremental decode starting from line %i\\n"", y); return; } } } compare_to_good_digest(r, goodDigest, bm); } template static void test_codec(skiatest::Reporter* r, Codec* codec, SkBitmap& bm, const SkImageInfo& info, const SkISize& size, SkCodec::Result expectedResult, SkMD5::Digest* digest, const SkMD5::Digest* goodDigest) { REPORTER_ASSERT(r, info.dimensions() == size); bm.allocPixels(info); SkCodec::Result result = codec->getPixels(info, bm.getPixels(), bm.rowBytes()); REPORTER_ASSERT(r, result == expectedResult); md5(bm, digest); if (goodDigest) { REPORTER_ASSERT(r, *digest == *goodDigest); } { // Test decoding to 565 SkImageInfo info565 = info.makeColorType(kRGB_565_SkColorType); if (info.alphaType() == kOpaque_SkAlphaType) { // Decoding to 565 should succeed. SkBitmap bm565; bm565.allocPixels(info565); // This will allow comparison even if the image is incomplete. bm565.eraseColor(SK_ColorBLACK); REPORTER_ASSERT(r, expectedResult == codec->getPixels(info565, bm565.getPixels(), bm565.rowBytes())); SkMD5::Digest digest565; md5(bm565, &digest565); // A dumb client's request for non-opaque should also succeed. for (auto alpha : { kPremul_SkAlphaType, kUnpremul_SkAlphaType }) { info565 = info565.makeAlphaType(alpha); test_info(r, codec, info565, expectedResult, &digest565); } } else { test_info(r, codec, info565, SkCodec::kInvalidConversion, nullptr); } } if (codec->getInfo().colorType() == kGray_8_SkColorType) { SkImageInfo grayInfo = codec->getInfo(); SkBitmap grayBm; grayBm.allocPixels(grayInfo); grayBm.eraseColor(SK_ColorBLACK); REPORTER_ASSERT(r, expectedResult == codec->getPixels(grayInfo, grayBm.getPixels(), grayBm.rowBytes())); SkMD5::Digest grayDigest; md5(grayBm, &grayDigest); for (auto alpha : { kPremul_SkAlphaType, kUnpremul_SkAlphaType }) { grayInfo = grayInfo.makeAlphaType(alpha); test_info(r, codec, grayInfo, expectedResult, &grayDigest); } } // Verify that re-decoding gives the same result. It is interesting to check this after // a decode to 565, since choosing to decode to 565 may result in some of the decode // options being modified. These options should return to their defaults on another // decode to kN32, so the new digest should match the old digest. test_info(r, codec, info, expectedResult, digest); { // Check alpha type conversions if (info.alphaType() == kOpaque_SkAlphaType) { test_info(r, codec, info.makeAlphaType(kUnpremul_SkAlphaType), expectedResult, digest); test_info(r, codec, info.makeAlphaType(kPremul_SkAlphaType), expectedResult, digest); } else { // Decoding to opaque should fail test_info(r, codec, info.makeAlphaType(kOpaque_SkAlphaType), SkCodec::kInvalidConversion, nullptr); SkAlphaType otherAt = info.alphaType(); if (kPremul_SkAlphaType == otherAt) { otherAt = kUnpremul_SkAlphaType; } else { otherAt = kPremul_SkAlphaType; } // The other non-opaque alpha type should always succeed, but not match. test_info(r, codec, info.makeAlphaType(otherAt), expectedResult, nullptr); } } } static bool supports_partial_scanlines(const char path[]) { static const char* const exts[] = { ""jpg"", ""jpeg"", ""png"", ""webp"" ""JPG"", ""JPEG"", ""PNG"", ""WEBP"" }; for (uint32_t i = 0; i < SK_ARRAY_COUNT(exts); i++) { if (SkStrEndsWith(path, exts[i])) { return true; } } return false; } // FIXME: Break up this giant function static void check(skiatest::Reporter* r, const char path[], SkISize size, bool supportsScanlineDecoding, bool supportsSubsetDecoding, bool supportsIncomplete, bool supportsNewScanlineDecoding = false) { std::unique_ptr stream(GetResourceAsStream(path)); if (!stream) { return; } std::unique_ptr codec(nullptr); bool isIncomplete = supportsIncomplete; if (isIncomplete) { size_t size = stream->getLength(); sk_sp data((SkData::MakeFromStream(stream.get(), 2 * size / 3))); codec.reset(SkCodec::NewFromData(data)); } else { codec.reset(SkCodec::NewFromStream(stream.release())); } if (!codec) { ERRORF(r, ""Unable to decode '%s'"", path); return; } // Test full image decodes with SkCodec SkMD5::Digest codecDigest; const SkImageInfo info = codec->getInfo().makeColorType(kN32_SkColorType); SkBitmap bm; SkCodec::Result expectedResult = isIncomplete ? SkCodec::kIncompleteInput : SkCodec::kSuccess; test_codec(r, codec.get(), bm, info, size, expectedResult, &codecDigest, nullptr); // Scanline decoding follows. if (supportsNewScanlineDecoding && !isIncomplete) { test_incremental_decode(r, codec.get(), info, codecDigest); // This is only supported by codecs that use incremental decoding to // support subset decodes - png and jpeg (once SkJpegCodec is // converted). if (SkStrEndsWith(path, ""png"") || SkStrEndsWith(path, ""PNG"")) { test_in_stripes(r, codec.get(), info, codecDigest); } } // Need to call startScanlineDecode() first. REPORTER_ASSERT(r, codec->getScanlines(bm.getAddr(0, 0), 1, 0) == 0); REPORTER_ASSERT(r, !codec->skipScanlines(1)); const SkCodec::Result startResult = codec->startScanlineDecode(info); if (supportsScanlineDecoding) { bm.eraseColor(SK_ColorYELLOW); REPORTER_ASSERT(r, startResult == SkCodec::kSuccess); for (int y = 0; y < info.height(); y++) { const int lines = codec->getScanlines(bm.getAddr(0, y), 1, 0); if (!isIncomplete) { REPORTER_ASSERT(r, 1 == lines); } } // verify that scanline decoding gives the same result. if (SkCodec::kTopDown_SkScanlineOrder == codec->getScanlineOrder()) { compare_to_good_digest(r, codecDigest, bm); } // Cannot continue to decode scanlines beyond the end REPORTER_ASSERT(r, codec->getScanlines(bm.getAddr(0, 0), 1, 0) == 0); // Interrupting a scanline decode with a full decode starts from // scratch REPORTER_ASSERT(r, codec->startScanlineDecode(info) == SkCodec::kSuccess); const int lines = codec->getScanlines(bm.getAddr(0, 0), 1, 0); if (!isIncomplete) { REPORTER_ASSERT(r, lines == 1); } REPORTER_ASSERT(r, codec->getPixels(bm.info(), bm.getPixels(), bm.rowBytes()) == expectedResult); REPORTER_ASSERT(r, codec->getScanlines(bm.getAddr(0, 0), 1, 0) == 0); REPORTER_ASSERT(r, codec->skipScanlines(1) == 0); // Test partial scanline decodes if (supports_partial_scanlines(path) && info.width() >= 3) { SkCodec::Options options; int width = info.width(); int height = info.height(); SkIRect subset = SkIRect::MakeXYWH(2 * (width / 3), 0, width / 3, height); options.fSubset = ⊂ const SkCodec::Result partialStartResult = codec->startScanlineDecode(info, &options, nullptr, nullptr); REPORTER_ASSERT(r, partialStartResult == SkCodec::kSuccess); for (int y = 0; y < height; y++) { const int lines = codec->getScanlines(bm.getAddr(0, y), 1, 0); if (!isIncomplete) { REPORTER_ASSERT(r, 1 == lines); } } } } else { REPORTER_ASSERT(r, startResult == SkCodec::kUnimplemented); } // The rest of this function tests decoding subsets, and will decode an arbitrary number of // random subsets. // Do not attempt to decode subsets of an image of only once pixel, since there is no // meaningful subset. if (size.width() * size.height() == 1) { return; } SkRandom rand; SkIRect subset; SkCodec::Options opts; opts.fSubset = ⊂ for (int i = 0; i < 5; i++) { subset = generate_random_subset(&rand, size.width(), size.height()); SkASSERT(!subset.isEmpty()); const bool supported = codec->getValidSubset(&subset); REPORTER_ASSERT(r, supported == supportsSubsetDecoding); SkImageInfo subsetInfo = info.makeWH(subset.width(), subset.height()); SkBitmap bm; bm.allocPixels(subsetInfo); const SkCodec::Result result = codec->getPixels(bm.info(), bm.getPixels(), bm.rowBytes(), &opts, nullptr, nullptr); if (supportsSubsetDecoding) { if (expectedResult == SkCodec::kSuccess) { REPORTER_ASSERT(r, result == expectedResult); } else { SkASSERT(expectedResult == SkCodec::kIncompleteInput); REPORTER_ASSERT(r, result == SkCodec::kIncompleteInput || result == SkCodec::kSuccess); } // Webp is the only codec that supports subsets, and it will have modified the subset // to have even left/top. REPORTER_ASSERT(r, SkIsAlign2(subset.fLeft) && SkIsAlign2(subset.fTop)); } else { // No subsets will work. REPORTER_ASSERT(r, result == SkCodec::kUnimplemented); } } // SkAndroidCodec tests if (supportsScanlineDecoding || supportsSubsetDecoding || supportsNewScanlineDecoding) { std::unique_ptr stream(GetResourceAsStream(path)); if (!stream) { return; } std::unique_ptr androidCodec(nullptr); if (isIncomplete) { size_t size = stream->getLength(); sk_sp data((SkData::MakeFromStream(stream.get(), 2 * size / 3))); androidCodec.reset(SkAndroidCodec::NewFromData(data)); } else { androidCodec.reset(SkAndroidCodec::NewFromStream(stream.release())); } if (!androidCodec) { ERRORF(r, ""Unable to decode '%s'"", path); return; } SkBitmap bm; SkMD5::Digest androidCodecDigest; test_codec(r, androidCodec.get(), bm, info, size, expectedResult, &androidCodecDigest, &codecDigest); } if (!isIncomplete) { // Test SkCodecImageGenerator std::unique_ptr stream(GetResourceAsStream(path)); sk_sp fullData(SkData::MakeFromStream(stream.get(), stream->getLength())); std::unique_ptr gen( SkCodecImageGenerator::MakeFromEncodedCodec(fullData)); SkBitmap bm; bm.allocPixels(info); REPORTER_ASSERT(r, gen->getPixels(info, bm.getPixels(), bm.rowBytes())); compare_to_good_digest(r, codecDigest, bm); #ifndef SK_PNG_DISABLE_TESTS // Test using SkFrontBufferedStream, as Android does SkStream* bufferedStream = SkFrontBufferedStream::Create( new SkMemoryStream(std::move(fullData)), SkCodec::MinBufferedBytesNeeded()); REPORTER_ASSERT(r, bufferedStream); codec.reset(SkCodec::NewFromStream(bufferedStream)); REPORTER_ASSERT(r, codec); if (codec) { test_info(r, codec.get(), info, SkCodec::kSuccess, &codecDigest); } #endif } // If we've just tested incomplete decodes, let's run the same test again on full decodes. if (isIncomplete) { check(r, path, size, supportsScanlineDecoding, supportsSubsetDecoding, false, supportsNewScanlineDecoding); } } DEF_TEST(Codec_wbmp, r) { check(r, ""mandrill.wbmp"", SkISize::Make(512, 512), true, false, true); } DEF_TEST(Codec_webp, r) { check(r, ""baby_tux.webp"", SkISize::Make(386, 395), false, true, true); check(r, ""color_wheel.webp"", SkISize::Make(128, 128), false, true, true); check(r, ""yellow_rose.webp"", SkISize::Make(400, 301), false, true, true); } DEF_TEST(Codec_bmp, r) { check(r, ""randPixels.bmp"", SkISize::Make(8, 8), true, false, true); check(r, ""rle.bmp"", SkISize::Make(320, 240), true, false, true); } DEF_TEST(Codec_ico, r) { // FIXME: We are not ready to test incomplete ICOs // These two tests examine interestingly different behavior: // Decodes an embedded BMP image check(r, ""color_wheel.ico"", SkISize::Make(128, 128), true, false, false); // Decodes an embedded PNG image check(r, ""google_chrome.ico"", SkISize::Make(256, 256), false, false, false, true); } DEF_TEST(Codec_gif, r) { check(r, ""box.gif"", SkISize::Make(200, 55), false, false, true, true); check(r, ""color_wheel.gif"", SkISize::Make(128, 128), false, false, true, true); // randPixels.gif is too small to test incomplete check(r, ""randPixels.gif"", SkISize::Make(8, 8), false, false, false, true); } DEF_TEST(Codec_jpg, r) { check(r, ""CMYK.jpg"", SkISize::Make(642, 516), true, false, true); check(r, ""color_wheel.jpg"", SkISize::Make(128, 128), true, false, true); // grayscale.jpg is too small to test incomplete check(r, ""grayscale.jpg"", SkISize::Make(128, 128), true, false, false); check(r, ""mandrill_512_q075.jpg"", SkISize::Make(512, 512), true, false, true); // randPixels.jpg is too small to test incomplete check(r, ""randPixels.jpg"", SkISize::Make(8, 8), true, false, false); } DEF_TEST(Codec_png, r) { check(r, ""arrow.png"", SkISize::Make(187, 312), false, false, true, true); check(r, ""baby_tux.png"", SkISize::Make(240, 246), false, false, true, true); check(r, ""color_wheel.png"", SkISize::Make(128, 128), false, false, true, true); // half-transparent-white-pixel.png is too small to test incomplete check(r, ""half-transparent-white-pixel.png"", SkISize::Make(1, 1), false, false, false, true); check(r, ""mandrill_128.png"", SkISize::Make(128, 128), false, false, true, true); check(r, ""mandrill_16.png"", SkISize::Make(16, 16), false, false, true, true); check(r, ""mandrill_256.png"", SkISize::Make(256, 256), false, false, true, true); check(r, ""mandrill_32.png"", SkISize::Make(32, 32), false, false, true, true); check(r, ""mandrill_512.png"", SkISize::Make(512, 512), false, false, true, true); check(r, ""mandrill_64.png"", SkISize::Make(64, 64), false, false, true, true); check(r, ""plane.png"", SkISize::Make(250, 126), false, false, true, true); check(r, ""plane_interlaced.png"", SkISize::Make(250, 126), false, false, true, true); check(r, ""randPixels.png"", SkISize::Make(8, 8), false, false, true, true); check(r, ""yellow_rose.png"", SkISize::Make(400, 301), false, false, true, true); } // Disable RAW tests for Win32. #if defined(SK_CODEC_DECODES_RAW) && (!defined(_WIN32)) DEF_TEST(Codec_raw, r) { check(r, ""sample_1mp.dng"", SkISize::Make(600, 338), false, false, false); check(r, ""sample_1mp_rotated.dng"", SkISize::Make(600, 338), false, false, false); check(r, ""dng_with_preview.dng"", SkISize::Make(600, 338), true, false, false); } #endif static void test_invalid_stream(skiatest::Reporter* r, const void* stream, size_t len) { // Neither of these calls should return a codec. Bots should catch us if we leaked anything. SkCodec* codec = SkCodec::NewFromStream(new SkMemoryStream(stream, len, false)); REPORTER_ASSERT(r, !codec); SkAndroidCodec* androidCodec = SkAndroidCodec::NewFromStream(new SkMemoryStream(stream, len, false)); REPORTER_ASSERT(r, !androidCodec); } // Ensure that SkCodec::NewFromStream handles freeing the passed in SkStream, // even on failure. Test some bad streams. DEF_TEST(Codec_leaks, r) { // No codec should claim this as their format, so this tests SkCodec::NewFromStream. const char nonSupportedStream[] = ""hello world""; // The other strings should look like the beginning of a file type, so we'll call some // internal version of NewFromStream, which must also delete the stream on failure. const unsigned char emptyPng[] = { 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a }; const unsigned char emptyJpeg[] = { 0xFF, 0xD8, 0xFF }; const char emptyWebp[] = ""RIFF1234WEBPVP""; const char emptyBmp[] = { 'B', 'M' }; const char emptyIco[] = { '\\x00', '\\x00', '\\x01', '\\x00' }; const char emptyGif[] = ""GIFVER""; test_invalid_stream(r, nonSupportedStream, sizeof(nonSupportedStream)); test_invalid_stream(r, emptyPng, sizeof(emptyPng)); test_invalid_stream(r, emptyJpeg, sizeof(emptyJpeg)); test_invalid_stream(r, emptyWebp, sizeof(emptyWebp)); test_invalid_stream(r, emptyBmp, sizeof(emptyBmp)); test_invalid_stream(r, emptyIco, sizeof(emptyIco)); test_invalid_stream(r, emptyGif, sizeof(emptyGif)); } DEF_TEST(Codec_null, r) { // Attempting to create an SkCodec or an SkAndroidCodec with null should not // crash. SkCodec* codec = SkCodec::NewFromStream(nullptr); REPORTER_ASSERT(r, !codec); SkAndroidCodec* androidCodec = SkAndroidCodec::NewFromStream(nullptr); REPORTER_ASSERT(r, !androidCodec); } static void test_dimensions(skiatest::Reporter* r, const char path[]) { // Create the codec from the resource file std::unique_ptr stream(GetResourceAsStream(path)); if (!stream) { return; } std::unique_ptr codec(SkAndroidCodec::NewFromStream(stream.release())); if (!codec) { ERRORF(r, ""Unable to create codec '%s'"", path); return; } // Check that the decode is successful for a variety of scales for (int sampleSize = 1; sampleSize < 32; sampleSize++) { // Scale the output dimensions SkISize scaledDims = codec->getSampledDimensions(sampleSize); SkImageInfo scaledInfo = codec->getInfo() .makeWH(scaledDims.width(), scaledDims.height()) .makeColorType(kN32_SkColorType); // Set up for the decode size_t rowBytes = scaledDims.width() * sizeof(SkPMColor); size_t totalBytes = scaledInfo.getSafeSize(rowBytes); SkAutoTMalloc pixels(totalBytes); SkAndroidCodec::AndroidOptions options; options.fSampleSize = sampleSize; SkCodec::Result result = codec->getAndroidPixels(scaledInfo, pixels.get(), rowBytes, &options); REPORTER_ASSERT(r, SkCodec::kSuccess == result); } } // Ensure that onGetScaledDimensions returns valid image dimensions to use for decodes DEF_TEST(Codec_Dimensions, r) { // JPG test_dimensions(r, ""CMYK.jpg""); test_dimensions(r, ""color_wheel.jpg""); test_dimensions(r, ""grayscale.jpg""); test_dimensions(r, ""mandrill_512_q075.jpg""); test_dimensions(r, ""randPixels.jpg""); // Decoding small images with very large scaling factors is a potential // source of bugs and crashes. We disable these tests in Gold because // tiny images are not very useful to look at. // Here we make sure that we do not crash or access illegal memory when // performing scaled decodes on small images. test_dimensions(r, ""1x1.png""); test_dimensions(r, ""2x2.png""); test_dimensions(r, ""3x3.png""); test_dimensions(r, ""3x1.png""); test_dimensions(r, ""1x1.png""); test_dimensions(r, ""16x1.png""); test_dimensions(r, ""1x16.png""); test_dimensions(r, ""mandrill_16.png""); // RAW // Disable RAW tests for Win32. #if defined(SK_CODEC_DECODES_RAW) && (!defined(_WIN32)) test_dimensions(r, ""sample_1mp.dng""); test_dimensions(r, ""sample_1mp_rotated.dng""); test_dimensions(r, ""dng_with_preview.dng""); #endif } static void test_invalid(skiatest::Reporter* r, const char path[]) { std::unique_ptr stream(GetResourceAsStream(path)); if (!stream) { return; } std::unique_ptr codec(SkCodec::NewFromStream(stream.release())); REPORTER_ASSERT(r, nullptr == codec); } DEF_TEST(Codec_Empty, r) { // Test images that should not be able to create a codec test_invalid(r, ""empty_images/zero-dims.gif""); test_invalid(r, ""empty_images/zero-embedded.ico""); test_invalid(r, ""empty_images/zero-width.bmp""); test_invalid(r, ""empty_images/zero-height.bmp""); test_invalid(r, ""empty_images/zero-width.jpg""); test_invalid(r, ""empty_images/zero-height.jpg""); test_invalid(r, ""empty_images/zero-width.png""); test_invalid(r, ""empty_images/zero-height.png""); test_invalid(r, ""empty_images/zero-width.wbmp""); test_invalid(r, ""empty_images/zero-height.wbmp""); // This image is an ico with an embedded mask-bmp. This is illegal. test_invalid(r, ""invalid_images/mask-bmp-ico.ico""); // It is illegal for a webp frame to not be fully contained by the canvas. test_invalid(r, ""invalid_images/invalid-offset.webp""); #if defined(SK_CODEC_DECODES_RAW) && (!defined(_WIN32)) test_invalid(r, ""empty_images/zero_height.tiff""); #endif } static void test_invalid_parameters(skiatest::Reporter* r, const char path[]) { std::unique_ptr stream(GetResourceAsStream(path)); if (!stream) { return; } std::unique_ptr decoder(SkCodec::NewFromStream(stream.release())); if (!decoder) { SkDebugf(""Missing codec for %s\\n"", path); return; } const SkImageInfo info = decoder->getInfo().makeColorType(kIndex_8_SkColorType); // This should return kSuccess because kIndex8 is supported. SkPMColor colorStorage[256]; int colorCount; SkCodec::Result result = decoder->startScanlineDecode(info, nullptr, colorStorage, &colorCount); if (SkCodec::kSuccess == result) { // This should return kInvalidParameters because, in kIndex_8 mode, we must pass in a valid // colorPtr and a valid colorCountPtr. result = decoder->startScanlineDecode(info, nullptr, nullptr, nullptr); REPORTER_ASSERT(r, SkCodec::kInvalidParameters == result); result = decoder->startScanlineDecode(info); REPORTER_ASSERT(r, SkCodec::kInvalidParameters == result); } else if (SkCodec::kUnimplemented == result) { // New method should be supported: SkBitmap bm; bm.allocPixels(info, SkColorTable::Make(colorStorage, 256)); result = decoder->startIncrementalDecode(info, bm.getPixels(), bm.rowBytes(), nullptr, colorStorage, &colorCount); REPORTER_ASSERT(r, SkCodec::kSuccess == result); result = decoder->startIncrementalDecode(info, bm.getPixels(), bm.rowBytes()); REPORTER_ASSERT(r, SkCodec::kInvalidParameters == result); } else { // The test is uninteresting if kIndex8 is not supported ERRORF(r, ""Should not call test_invalid_parameters for non-Index8 file: %s\\n"", path); return; } } DEF_TEST(Codec_Params, r) { test_invalid_parameters(r, ""index8.png""); test_invalid_parameters(r, ""mandrill.wbmp""); } #ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED #ifndef SK_PNG_DISABLE_TESTS // reading chunks does not work properly with older versions. // It does not appear that anyone in Google3 is reading chunks. static void codex_test_write_fn(png_structp png_ptr, png_bytep data, png_size_t len) { SkWStream* sk_stream = (SkWStream*)png_get_io_ptr(png_ptr); if (!sk_stream->write(data, len)) { png_error(png_ptr, ""sk_write_fn Error!""); } } DEF_TEST(Codec_pngChunkReader, r) { // Create a dummy bitmap. Use unpremul RGBA for libpng. SkBitmap bm; const int w = 1; const int h = 1; const SkImageInfo bmInfo = SkImageInfo::Make(w, h, kRGBA_8888_SkColorType, kUnpremul_SkAlphaType); bm.setInfo(bmInfo); bm.allocPixels(); bm.eraseColor(SK_ColorBLUE); SkMD5::Digest goodDigest; md5(bm, &goodDigest); // Write to a png file. png_structp png = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr); REPORTER_ASSERT(r, png); if (!png) { return; } png_infop info = png_create_info_struct(png); REPORTER_ASSERT(r, info); if (!info) { png_destroy_write_struct(&png, nullptr); return; } if (setjmp(png_jmpbuf(png))) { ERRORF(r, ""failed writing png""); png_destroy_write_struct(&png, &info); return; } SkDynamicMemoryWStream wStream; png_set_write_fn(png, (void*) (&wStream), codex_test_write_fn, nullptr); png_set_IHDR(png, info, (png_uint_32)w, (png_uint_32)h, 8, PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); // Create some chunks that match the Android framework's use. static png_unknown_chunk gUnknowns[] = { { ""npOl"", (png_byte*)""outline"", sizeof(""outline""), PNG_HAVE_IHDR }, { ""npLb"", (png_byte*)""layoutBounds"", sizeof(""layoutBounds""), PNG_HAVE_IHDR }, { ""npTc"", (png_byte*)""ninePatchData"", sizeof(""ninePatchData""), PNG_HAVE_IHDR }, }; png_set_keep_unknown_chunks(png, PNG_HANDLE_CHUNK_ALWAYS, (png_byte*)""npOl\\0npLb\\0npTc\\0"", 3); png_set_unknown_chunks(png, info, gUnknowns, SK_ARRAY_COUNT(gUnknowns)); #if PNG_LIBPNG_VER < 10600 /* Deal with unknown chunk location bug in 1.5.x and earlier */ png_set_unknown_chunk_location(png, info, 0, PNG_HAVE_IHDR); png_set_unknown_chunk_location(png, info, 1, PNG_HAVE_IHDR); #endif png_write_info(png, info); for (int j = 0; j < h; j++) { png_bytep row = (png_bytep)(bm.getAddr(0, j)); png_write_rows(png, &row, 1); } png_write_end(png, info); png_destroy_write_struct(&png, &info); class ChunkReader : public SkPngChunkReader { public: ChunkReader(skiatest::Reporter* r) : fReporter(r) { this->reset(); } bool readChunk(const char tag[], const void* data, size_t length) override { for (size_t i = 0; i < SK_ARRAY_COUNT(gUnknowns); ++i) { if (!strcmp(tag, (const char*) gUnknowns[i].name)) { // Tag matches. This should have been the first time we see it. REPORTER_ASSERT(fReporter, !fSeen[i]); fSeen[i] = true; // Data and length should match REPORTER_ASSERT(fReporter, length == gUnknowns[i].size); REPORTER_ASSERT(fReporter, !strcmp((const char*) data, (const char*) gUnknowns[i].data)); return true; } } ERRORF(fReporter, ""Saw an unexpected unknown chunk.""); return true; } bool allHaveBeenSeen() { bool ret = true; for (auto seen : fSeen) { ret &= seen; } return ret; } void reset() { sk_bzero(fSeen, sizeof(fSeen)); } private: skiatest::Reporter* fReporter; // Unowned bool fSeen[3]; }; ChunkReader chunkReader(r); // Now read the file with SkCodec. std::unique_ptr codec(SkCodec::NewFromData(wStream.detachAsData(), &chunkReader)); REPORTER_ASSERT(r, codec); if (!codec) { return; } // Now compare to the original. SkBitmap decodedBm; decodedBm.setInfo(codec->getInfo()); decodedBm.allocPixels(); SkCodec::Result result = codec->getPixels(codec->getInfo(), decodedBm.getPixels(), decodedBm.rowBytes()); REPORTER_ASSERT(r, SkCodec::kSuccess == result); if (decodedBm.colorType() != bm.colorType()) { SkBitmap tmp; bool success = sk_tool_utils::copy_to(&tmp, bm.colorType(), decodedBm); REPORTER_ASSERT(r, success); if (!success) { return; } tmp.swap(decodedBm); } compare_to_good_digest(r, goodDigest, decodedBm); REPORTER_ASSERT(r, chunkReader.allHaveBeenSeen()); // Decoding again will read the chunks again. chunkReader.reset(); REPORTER_ASSERT(r, !chunkReader.allHaveBeenSeen()); result = codec->getPixels(codec->getInfo(), decodedBm.getPixels(), decodedBm.rowBytes()); REPORTER_ASSERT(r, SkCodec::kSuccess == result); REPORTER_ASSERT(r, chunkReader.allHaveBeenSeen()); } #endif // SK_PNG_DISABLE_TESTS #endif // PNG_READ_UNKNOWN_CHUNKS_SUPPORTED // Stream that can only peek up to a limit class LimitedPeekingMemStream : public SkStream { public: LimitedPeekingMemStream(sk_sp data, size_t limit) : fStream(std::move(data)) , fLimit(limit) {} size_t peek(void* buf, size_t bytes) const override { return fStream.peek(buf, SkTMin(bytes, fLimit)); } size_t read(void* buf, size_t bytes) override { return fStream.read(buf, bytes); } bool rewind() override { return fStream.rewind(); } bool isAtEnd() const override { return fStream.isAtEnd(); } private: SkMemoryStream fStream; const size_t fLimit; }; // Disable RAW tests for Win32. #if defined(SK_CODEC_DECODES_RAW) && (!defined(_WIN32)) // Test that the RawCodec works also for not asset stream. This will test the code path using // SkRawBufferedStream instead of SkRawAssetStream. DEF_TEST(Codec_raw_notseekable, r) { const char* path = ""dng_with_preview.dng""; SkString fullPath(GetResourcePath(path)); sk_sp data(SkData::MakeFromFileName(fullPath.c_str())); if (!data) { SkDebugf(""Missing resource '%s'\\n"", path); return; } std::unique_ptr codec(SkCodec::NewFromStream(new NotAssetMemStream(std::move(data)))); REPORTER_ASSERT(r, codec); test_info(r, codec.get(), codec->getInfo(), SkCodec::kSuccess, nullptr); } #endif // Test that even if webp_parse_header fails to peek enough, it will fall back to read() // + rewind() and succeed. DEF_TEST(Codec_webp_peek, r) { const char* path = ""baby_tux.webp""; SkString fullPath(GetResourcePath(path)); auto data = SkData::MakeFromFileName(fullPath.c_str()); if (!data) { SkDebugf(""Missing resource '%s'\\n"", path); return; } // The limit is less than webp needs to peek or read. std::unique_ptr codec(SkCodec::NewFromStream( new LimitedPeekingMemStream(data, 25))); REPORTER_ASSERT(r, codec); test_info(r, codec.get(), codec->getInfo(), SkCodec::kSuccess, nullptr); // Similarly, a stream which does not peek should still succeed. codec.reset(SkCodec::NewFromStream(new LimitedPeekingMemStream(data, 0))); REPORTER_ASSERT(r, codec); test_info(r, codec.get(), codec->getInfo(), SkCodec::kSuccess, nullptr); } // SkCodec's wbmp decoder was initially unnecessarily restrictive. // It required the second byte to be zero. The wbmp specification allows // a couple of bits to be 1 (so long as they do not overlap with 0x9F). // Test that SkCodec now supports an image with these bits set. DEF_TEST(Codec_wbmp_restrictive, r) { const char* path = ""mandrill.wbmp""; std::unique_ptr stream(GetResourceAsStream(path)); if (!stream) { return; } // Modify the stream to contain a second byte with some bits set. auto data = SkCopyStreamToData(stream.get()); uint8_t* writeableData = static_cast(data->writable_data()); writeableData[1] = static_cast(~0x9F); // SkCodec should support this. std::unique_ptr codec(SkCodec::NewFromData(data)); REPORTER_ASSERT(r, codec); if (!codec) { return; } test_info(r, codec.get(), codec->getInfo(), SkCodec::kSuccess, nullptr); } // wbmp images have a header that can be arbitrarily large, depending on the // size of the image. We cap the size at 65535, meaning we only need to look at // 8 bytes to determine whether we can read the image. This is important // because SkCodec only passes 14 bytes to SkWbmpCodec to determine whether the // image is a wbmp. DEF_TEST(Codec_wbmp_max_size, r) { const unsigned char maxSizeWbmp[] = { 0x00, 0x00, // Header 0x83, 0xFF, 0x7F, // W: 65535 0x83, 0xFF, 0x7F }; // H: 65535 std::unique_ptr stream(new SkMemoryStream(maxSizeWbmp, sizeof(maxSizeWbmp), false)); std::unique_ptr codec(SkCodec::NewFromStream(stream.release())); REPORTER_ASSERT(r, codec); if (!codec) return; REPORTER_ASSERT(r, codec->getInfo().width() == 65535); REPORTER_ASSERT(r, codec->getInfo().height() == 65535); // Now test an image which is too big. Any image with a larger header (i.e. // has bigger width/height) is also too big. const unsigned char tooBigWbmp[] = { 0x00, 0x00, // Header 0x84, 0x80, 0x00, // W: 65536 0x84, 0x80, 0x00 }; // H: 65536 stream.reset(new SkMemoryStream(tooBigWbmp, sizeof(tooBigWbmp), false)); codec.reset(SkCodec::NewFromStream(stream.release())); REPORTER_ASSERT(r, !codec); } DEF_TEST(Codec_jpeg_rewind, r) { const char* path = ""mandrill_512_q075.jpg""; sk_sp data(GetResourceAsData(path)); if (!data) { return; } data = SkData::MakeSubset(data.get(), 0, data->size() / 2); std::unique_ptr codec(SkAndroidCodec::NewFromData(data)); if (!codec) { ERRORF(r, ""Unable to create codec '%s'."", path); return; } const int width = codec->getInfo().width(); const int height = codec->getInfo().height(); size_t rowBytes = sizeof(SkPMColor) * width; SkAutoMalloc pixelStorage(height * rowBytes); // Perform a sampled decode. SkAndroidCodec::AndroidOptions opts; opts.fSampleSize = 12; auto sampledInfo = codec->getInfo().makeWH(width / 12, height / 12); auto result = codec->getAndroidPixels(sampledInfo, pixelStorage.get(), rowBytes, &opts); REPORTER_ASSERT(r, SkCodec::kIncompleteInput == result); // Rewind the codec and perform a full image decode. result = codec->getPixels(codec->getInfo(), pixelStorage.get(), rowBytes); REPORTER_ASSERT(r, SkCodec::kIncompleteInput == result); // Now perform a subset decode. { opts.fSampleSize = 1; SkIRect subset = SkIRect::MakeWH(100, 100); opts.fSubset = ⊂ result = codec->getAndroidPixels(codec->getInfo().makeWH(100, 100), pixelStorage.get(), rowBytes, &opts); // Though we only have half the data, it is enough to decode this subset. REPORTER_ASSERT(r, SkCodec::kSuccess == result); } // Perform another full image decode. ASAN will detect if we look at the subset when it is // out of scope. This would happen if we depend on the old state in the codec. // This tests two layers of bugs: both SkJpegCodec::readRows and SkCodec::fillIncompleteImage // used to look at the old subset. opts.fSubset = nullptr; result = codec->getAndroidPixels(codec->getInfo(), pixelStorage.get(), rowBytes, &opts); REPORTER_ASSERT(r, SkCodec::kIncompleteInput == result); } static void check_color_xform(skiatest::Reporter* r, const char* path) { std::unique_ptr codec(SkAndroidCodec::NewFromStream(GetResourceAsStream(path))); SkAndroidCodec::AndroidOptions opts; opts.fSampleSize = 3; const int subsetWidth = codec->getInfo().width() / 2; const int subsetHeight = codec->getInfo().height() / 2; SkIRect subset = SkIRect::MakeWH(subsetWidth, subsetHeight); opts.fSubset = ⊂ const int dstWidth = subsetWidth / opts.fSampleSize; const int dstHeight = subsetHeight / opts.fSampleSize; sk_sp data = SkData::MakeFromFileName( GetResourcePath(""icc_profiles/HP_ZR30w.icc"").c_str()); sk_sp colorSpace = SkColorSpace::MakeICC(data->data(), data->size()); SkImageInfo dstInfo = codec->getInfo().makeWH(dstWidth, dstHeight) .makeColorType(kN32_SkColorType) .makeColorSpace(colorSpace); size_t rowBytes = dstInfo.minRowBytes(); SkAutoMalloc pixelStorage(dstInfo.getSafeSize(rowBytes)); SkCodec::Result result = codec->getAndroidPixels(dstInfo, pixelStorage.get(), rowBytes, &opts); REPORTER_ASSERT(r, SkCodec::kSuccess == result); } DEF_TEST(Codec_ColorXform, r) { check_color_xform(r, ""mandrill_512_q075.jpg""); check_color_xform(r, ""mandrill_512.png""); } static bool color_type_match(SkColorType origColorType, SkColorType codecColorType) { switch (origColorType) { case kRGBA_8888_SkColorType: case kBGRA_8888_SkColorType: return kRGBA_8888_SkColorType == codecColorType || kBGRA_8888_SkColorType == codecColorType; default: return origColorType == codecColorType; } } static bool alpha_type_match(SkAlphaType origAlphaType, SkAlphaType codecAlphaType) { switch (origAlphaType) { case kUnpremul_SkAlphaType: case kPremul_SkAlphaType: return kUnpremul_SkAlphaType == codecAlphaType || kPremul_SkAlphaType == codecAlphaType; default: return origAlphaType == codecAlphaType; } } static void check_round_trip(skiatest::Reporter* r, SkCodec* origCodec, const SkImageInfo& info) { SkBitmap bm1; SkPMColor colors[256]; sk_sp colorTable1 = SkColorTable::Make(colors, 256); bm1.allocPixels(info, colorTable1); int numColors; SkCodec::Result result = origCodec->getPixels(info, bm1.getPixels(), bm1.rowBytes(), nullptr, const_cast(colorTable1->readColors()), &numColors); // This will fail to update colorTable1->count() but is fine for the purpose of this test. REPORTER_ASSERT(r, SkCodec::kSuccess == result); // Encode the image to png. sk_sp data = sk_sp(sk_tool_utils::EncodeImageToData(bm1, SkEncodedImageFormat::kPNG, 100)); std::unique_ptr codec(SkCodec::NewFromData(data)); REPORTER_ASSERT(r, color_type_match(info.colorType(), codec->getInfo().colorType())); REPORTER_ASSERT(r, alpha_type_match(info.alphaType(), codec->getInfo().alphaType())); SkBitmap bm2; sk_sp colorTable2 = SkColorTable::Make(colors, 256); bm2.allocPixels(info, colorTable2); result = codec->getPixels(info, bm2.getPixels(), bm2.rowBytes(), nullptr, const_cast(colorTable2->readColors()), &numColors); REPORTER_ASSERT(r, SkCodec::kSuccess == result); SkMD5::Digest d1, d2; md5(bm1, &d1); md5(bm2, &d2); REPORTER_ASSERT(r, d1 == d2); } DEF_TEST(Codec_PngRoundTrip, r) { const char* path = ""mandrill_512_q075.jpg""; std::unique_ptr stream(GetResourceAsStream(path)); std::unique_ptr codec(SkCodec::NewFromStream(stream.release())); SkColorType colorTypesOpaque[] = { kRGB_565_SkColorType, kRGBA_8888_SkColorType, kBGRA_8888_SkColorType }; for (SkColorType colorType : colorTypesOpaque) { SkImageInfo newInfo = codec->getInfo().makeColorType(colorType); check_round_trip(r, codec.get(), newInfo); } path = ""grayscale.jpg""; stream.reset(GetResourceAsStream(path)); codec.reset(SkCodec::NewFromStream(stream.release())); check_round_trip(r, codec.get(), codec->getInfo()); path = ""yellow_rose.png""; stream.reset(GetResourceAsStream(path)); codec.reset(SkCodec::NewFromStream(stream.release())); SkColorType colorTypesWithAlpha[] = { kRGBA_8888_SkColorType, kBGRA_8888_SkColorType }; SkAlphaType alphaTypes[] = { kUnpremul_SkAlphaType, kPremul_SkAlphaType }; for (SkColorType colorType : colorTypesWithAlpha) { for (SkAlphaType alphaType : alphaTypes) { // Set color space to nullptr because color correct premultiplies do not round trip. SkImageInfo newInfo = codec->getInfo().makeColorType(colorType) .makeAlphaType(alphaType) .makeColorSpace(nullptr); check_round_trip(r, codec.get(), newInfo); } } path = ""index8.png""; stream.reset(GetResourceAsStream(path)); codec.reset(SkCodec::NewFromStream(stream.release())); for (SkAlphaType alphaType : alphaTypes) { SkImageInfo newInfo = codec->getInfo().makeAlphaType(alphaType) .makeColorSpace(nullptr); check_round_trip(r, codec.get(), newInfo); } } static void test_conversion_possible(skiatest::Reporter* r, const char* path, bool supportsScanlineDecoder, bool supportsIncrementalDecoder) { std::unique_ptr stream(GetResourceAsStream(path)); if (!stream) { return; } std::unique_ptr codec(SkCodec::NewFromStream(stream.release())); if (!codec) { ERRORF(r, ""failed to create a codec for %s"", path); return; } SkImageInfo infoF16 = codec->getInfo().makeColorType(kRGBA_F16_SkColorType); SkBitmap bm; bm.allocPixels(infoF16); SkCodec::Result result = codec->getPixels(infoF16, bm.getPixels(), bm.rowBytes()); REPORTER_ASSERT(r, SkCodec::kInvalidConversion == result); result = codec->startScanlineDecode(infoF16); if (supportsScanlineDecoder) { REPORTER_ASSERT(r, SkCodec::kInvalidConversion == result); } else { REPORTER_ASSERT(r, SkCodec::kUnimplemented == result); } result = codec->startIncrementalDecode(infoF16, bm.getPixels(), bm.rowBytes()); if (supportsIncrementalDecoder) { REPORTER_ASSERT(r, SkCodec::kInvalidConversion == result); } else { REPORTER_ASSERT(r, SkCodec::kUnimplemented == result); } SkASSERT(SkColorSpace_Base::Type::kXYZ == as_CSB(infoF16.colorSpace())->type()); SkColorSpace_XYZ* csXYZ = static_cast(infoF16.colorSpace()); infoF16 = infoF16.makeColorSpace(csXYZ->makeLinearGamma()); result = codec->getPixels(infoF16, bm.getPixels(), bm.rowBytes()); REPORTER_ASSERT(r, SkCodec::kSuccess == result); result = codec->startScanlineDecode(infoF16); if (supportsScanlineDecoder) { REPORTER_ASSERT(r, SkCodec::kSuccess == result); } else { REPORTER_ASSERT(r, SkCodec::kUnimplemented == result); } result = codec->startIncrementalDecode(infoF16, bm.getPixels(), bm.rowBytes()); if (supportsIncrementalDecoder) { REPORTER_ASSERT(r, SkCodec::kSuccess == result); } else { REPORTER_ASSERT(r, SkCodec::kUnimplemented == result); } } DEF_TEST(Codec_F16ConversionPossible, r) { test_conversion_possible(r, ""color_wheel.webp"", false, false); test_conversion_possible(r, ""mandrill_512_q075.jpg"", true, false); test_conversion_possible(r, ""yellow_rose.png"", false, true); } static void decode_frame(skiatest::Reporter* r, SkCodec* codec, size_t frame) { SkBitmap bm; auto info = codec->getInfo().makeColorType(kN32_SkColorType); bm.allocPixels(info); SkCodec::Options opts; opts.fFrameIndex = frame; REPORTER_ASSERT(r, SkCodec::kSuccess == codec->getPixels(info, bm.getPixels(), bm.rowBytes(), &opts, nullptr, nullptr)); } // For an animated image, we should only read enough to decode the requested // frame if the client never calls getFrameInfo. DEF_TEST(Codec_skipFullParse, r) { auto path = ""test640x479.gif""; SkStream* stream(GetResourceAsStream(path)); if (!stream) { return; } // Note that we cheat and hold on to the stream pointer, but SkCodec will // take ownership. We will not refer to the stream after the SkCodec // deletes it. std::unique_ptr codec(SkCodec::NewFromStream(stream)); if (!codec) { ERRORF(r, ""Failed to create codec for %s"", path); return; } REPORTER_ASSERT(r, stream->hasPosition()); const size_t sizePosition = stream->getPosition(); REPORTER_ASSERT(r, stream->hasLength() && sizePosition < stream->getLength()); // This should read more of the stream, but not the whole stream. decode_frame(r, codec.get(), 0); const size_t positionAfterFirstFrame = stream->getPosition(); REPORTER_ASSERT(r, positionAfterFirstFrame > sizePosition && positionAfterFirstFrame < stream->getLength()); // Again, this should read more of the stream. decode_frame(r, codec.get(), 2); const size_t positionAfterThirdFrame = stream->getPosition(); REPORTER_ASSERT(r, positionAfterThirdFrame > positionAfterFirstFrame && positionAfterThirdFrame < stream->getLength()); // This does not need to read any more of the stream, since it has already // parsed the second frame. decode_frame(r, codec.get(), 1); REPORTER_ASSERT(r, stream->getPosition() == positionAfterThirdFrame); // This should read the rest of the frames. decode_frame(r, codec.get(), 3); const size_t finalPosition = stream->getPosition(); REPORTER_ASSERT(r, finalPosition > positionAfterThirdFrame); // There may be more data in the stream. auto frameInfo = codec->getFrameInfo(); REPORTER_ASSERT(r, frameInfo.size() == 4); REPORTER_ASSERT(r, stream->getPosition() >= finalPosition); } // Only rewinds up to a limit. class LimitedRewindingStream : public SkStream { public: static SkStream* Make(const char path[], size_t limit) { SkStream* stream = GetResourceAsStream(path); if (!stream) { return nullptr; } return new LimitedRewindingStream(stream, limit); } size_t read(void* buffer, size_t size) override { const size_t bytes = fStream->read(buffer, size); fPosition += bytes; return bytes; } bool isAtEnd() const override { return fStream->isAtEnd(); } bool rewind() override { if (fPosition <= fLimit && fStream->rewind()) { fPosition = 0; return true; } return false; } private: std::unique_ptr fStream; const size_t fLimit; size_t fPosition; LimitedRewindingStream(SkStream* stream, size_t limit) : fStream(stream) , fLimit(limit) , fPosition(0) { SkASSERT(fStream); } }; DEF_TEST(Codec_fallBack, r) { // SkAndroidCodec needs to be able to fall back to scanline decoding // if incremental decoding does not work. Make sure this does not // require a rewind. // Formats that currently do not support incremental decoding auto files = { ""CMYK.jpg"", ""color_wheel.ico"", ""mandrill.wbmp"", ""randPixels.bmp"", }; for (auto file : files) { SkStream* stream = LimitedRewindingStream::Make(file, 14); if (!stream) { SkDebugf(""Missing resources (%s). Set --resourcePath.\\n"", file); return; } std::unique_ptr codec(SkCodec::NewFromStream(stream)); if (!codec) { ERRORF(r, ""Failed to create codec for %s,"", file); continue; } SkImageInfo info = codec->getInfo().makeColorType(kN32_SkColorType); SkBitmap bm; bm.allocPixels(info); if (SkCodec::kUnimplemented != codec->startIncrementalDecode(info, bm.getPixels(), bm.rowBytes())) { ERRORF(r, ""Is scanline decoding now implemented for %s?"", file); continue; } // Scanline decoding should not require a rewind. SkCodec::Result result = codec->startScanlineDecode(info); if (SkCodec::kSuccess != result) { ERRORF(r, ""Scanline decoding failed for %s with %i"", file, result); } } } // This test verifies that we fixed an assert statement that fired when reusing a png codec // after scaling. DEF_TEST(Codec_reusePng, r) { std::unique_ptr stream(GetResourceAsStream(""plane.png"")); if (!stream) { return; } std::unique_ptr codec(SkAndroidCodec::NewFromStream(stream.release())); if (!codec) { ERRORF(r, ""Failed to create codec\\n""); return; } SkAndroidCodec::AndroidOptions opts; opts.fSampleSize = 5; auto size = codec->getSampledDimensions(opts.fSampleSize); auto info = codec->getInfo().makeWH(size.fWidth, size.fHeight).makeColorType(kN32_SkColorType); SkBitmap bm; bm.allocPixels(info); auto result = codec->getAndroidPixels(info, bm.getPixels(), bm.rowBytes(), &opts); REPORTER_ASSERT(r, result == SkCodec::kSuccess); info = codec->getInfo().makeColorType(kN32_SkColorType); bm.allocPixels(info); opts.fSampleSize = 1; result = codec->getAndroidPixels(info, bm.getPixels(), bm.rowBytes(), &opts); REPORTER_ASSERT(r, result == SkCodec::kSuccess); } DEF_TEST(Codec_rowsDecoded, r) { auto file = ""plane_interlaced.png""; std::unique_ptr stream(GetResourceAsStream(file)); if (!stream) { return; } // This is enough to read the header etc, but no rows. auto data = SkData::MakeFromStream(stream.get(), 99); std::unique_ptr codec(SkCodec::NewFromData(data)); if (!codec) { ERRORF(r, ""Failed to create codec\\n""); return; } auto info = codec->getInfo().makeColorType(kN32_SkColorType); SkBitmap bm; bm.allocPixels(info); auto result = codec->startIncrementalDecode(info, bm.getPixels(), bm.rowBytes()); REPORTER_ASSERT(r, result == SkCodec::kSuccess); // This is an arbitrary value. The important fact is that it is not zero, and rowsDecoded // should get set to zero by incrementalDecode. int rowsDecoded = 77; result = codec->incrementalDecode(&rowsDecoded); REPORTER_ASSERT(r, result == SkCodec::kIncompleteInput); REPORTER_ASSERT(r, rowsDecoded == 0); } static void test_invalid_images(skiatest::Reporter* r, const char* path, SkCodec::Result expectedResult) { auto* stream = GetResourceAsStream(path); if (!stream) { return; } std::unique_ptr codec(SkCodec::NewFromStream(stream)); REPORTER_ASSERT(r, codec); test_info(r, codec.get(), codec->getInfo().makeColorType(kN32_SkColorType), expectedResult, nullptr); } DEF_TEST(Codec_InvalidImages, r) { // ASAN will complain if there is an issue. test_invalid_images(r, ""invalid_images/skbug5887.gif"", SkCodec::kIncompleteInput); test_invalid_images(r, ""invalid_images/many-progressive-scans.jpg"", SkCodec::kInvalidInput); test_invalid_images(r, ""invalid_images/b33251605.bmp"", SkCodec::kIncompleteInput); test_invalid_images(r, ""invalid_images/bad_palette.png"", SkCodec::kInvalidInput); } static void test_invalid_header(skiatest::Reporter* r, const char* path) { SkString resourcePath = GetResourcePath(path); std::unique_ptr stream(new SkFILEStream(resourcePath.c_str())); if (!stream->isValid()) { return; } std::unique_ptr codec(SkCodec::NewFromStream(stream.release())); REPORTER_ASSERT(r, !codec); } DEF_TEST(Codec_InvalidHeader, r) { test_invalid_header(r, ""invalid_images/int_overflow.ico""); // These files report values that have caused problems with SkFILEStreams. // They are invalid, and should not create SkCodecs. test_invalid_header(r, ""invalid_images/b33651913.bmp""); test_invalid_header(r, ""invalid_images/b34778578.bmp""); } DEF_TEST(Codec_InvalidAnimated, r) { // ASAN will complain if there is an issue. auto path = ""invalid_images/skbug6046.gif""; auto* stream = GetResourceAsStream(path); if (!stream) { return; } std::unique_ptr codec(SkCodec::NewFromStream(stream)); REPORTER_ASSERT(r, codec); if (!codec) { return; } const auto info = codec->getInfo().makeColorType(kN32_SkColorType); SkBitmap bm; bm.allocPixels(info); auto frameInfos = codec->getFrameInfo(); SkCodec::Options opts; for (int i = 0; static_cast(i) < frameInfos.size(); i++) { opts.fFrameIndex = i; opts.fHasPriorFrame = frameInfos[i].fRequiredFrame == i - 1; auto result = codec->startIncrementalDecode(info, bm.getPixels(), bm.rowBytes(), &opts); if (result != SkCodec::kSuccess) { ERRORF(r, ""Failed to start decoding frame %i (out of %i) with error %i\\n"", i, frameInfos.size(), result); continue; } codec->incrementalDecode(); } } static void encode_format(SkDynamicMemoryWStream* stream, const SkPixmap& pixmap, SkTransferFunctionBehavior unpremulBehavior, SkEncodedImageFormat format) { SkPngEncoder::Options pngOptions; SkWebpEncoder::Options webpOptions; pngOptions.fUnpremulBehavior = unpremulBehavior; webpOptions.fUnpremulBehavior = unpremulBehavior; switch (format) { case SkEncodedImageFormat::kPNG: SkPngEncoder::Encode(stream, pixmap, pngOptions); break; case SkEncodedImageFormat::kJPEG: SkJpegEncoder::Encode(stream, pixmap, SkJpegEncoder::Options()); break; case SkEncodedImageFormat::kWEBP: SkWebpEncoder::Encode(stream, pixmap, webpOptions); break; default: SkASSERT(false); break; } } static void test_encode_icc(skiatest::Reporter* r, SkEncodedImageFormat format, SkTransferFunctionBehavior unpremulBehavior) { // Test with sRGB color space. SkBitmap srgbBitmap; SkImageInfo srgbInfo = SkImageInfo::MakeS32(1, 1, kOpaque_SkAlphaType); srgbBitmap.allocPixels(srgbInfo); *srgbBitmap.getAddr32(0, 0) = 0; SkPixmap pixmap; srgbBitmap.peekPixels(&pixmap); SkDynamicMemoryWStream srgbBuf; encode_format(&srgbBuf, pixmap, unpremulBehavior, format); sk_sp srgbData = srgbBuf.detachAsData(); std::unique_ptr srgbCodec(SkCodec::NewFromData(srgbData)); REPORTER_ASSERT(r, srgbCodec->getInfo().colorSpace() == SkColorSpace::MakeSRGB().get()); // Test with P3 color space. SkDynamicMemoryWStream p3Buf; sk_sp p3 = SkColorSpace::MakeRGB(SkColorSpace::kSRGB_RenderTargetGamma, SkColorSpace::kDCIP3_D65_Gamut); pixmap.setColorSpace(p3); encode_format(&p3Buf, pixmap, unpremulBehavior, format); sk_sp p3Data = p3Buf.detachAsData(); std::unique_ptr p3Codec(SkCodec::NewFromData(p3Data)); REPORTER_ASSERT(r, p3Codec->getInfo().colorSpace()->gammaCloseToSRGB()); SkMatrix44 mat0(SkMatrix44::kUninitialized_Constructor); SkMatrix44 mat1(SkMatrix44::kUninitialized_Constructor); bool success = p3->toXYZD50(&mat0); REPORTER_ASSERT(r, success); success = p3Codec->getInfo().colorSpace()->toXYZD50(&mat1); REPORTER_ASSERT(r, success); for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { REPORTER_ASSERT(r, color_space_almost_equal(mat0.get(i, j), mat1.get(i, j))); } } } DEF_TEST(Codec_EncodeICC, r) { test_encode_icc(r, SkEncodedImageFormat::kPNG, SkTransferFunctionBehavior::kRespect); test_encode_icc(r, SkEncodedImageFormat::kJPEG, SkTransferFunctionBehavior::kRespect); test_encode_icc(r, SkEncodedImageFormat::kWEBP, SkTransferFunctionBehavior::kRespect); test_encode_icc(r, SkEncodedImageFormat::kPNG, SkTransferFunctionBehavior::kIgnore); test_encode_icc(r, SkEncodedImageFormat::kJPEG, SkTransferFunctionBehavior::kIgnore); test_encode_icc(r, SkEncodedImageFormat::kWEBP, SkTransferFunctionBehavior::kIgnore); } ",16162,True,3187.422342006099,median "/* -*- Mode:C++; c-file-style:""gnu""; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2010 TELEMATICS LAB, DEE - Politecnico di Bari * Copyright (c) 2018 Fraunhofer ESK : RLF extensions * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Giuseppe Piro * Marco Miozzo * Nicola Baldo * Modified by: * Vignesh Babu (RLF extensions) */ #include #include #include #include #include #include #include #include ""lte-ue-phy.h"" #include ""lte-enb-phy.h"" #include ""lte-net-device.h"" #include ""lte-ue-net-device.h"" #include ""lte-enb-net-device.h"" #include ""lte-spectrum-value-helper.h"" #include ""lte-amc.h"" #include ""lte-ue-mac.h"" #include ""ff-mac-common.h"" #include ""lte-chunk-processor.h"" #include #include #include #include namespace ns3 { NS_LOG_COMPONENT_DEFINE (""LteUePhy""); /** * Duration of the data portion of a UL subframe. * Equals to ""TTI length - 1 symbol length for SRS - margin"". * The margin is 1 nanosecond and is intended to avoid overlapping simulator * events. The duration of one symbol is TTI/14 (rounded). In other words, * duration of data portion of UL subframe = 1 ms * (13/14) - 1 ns. */ static const Time UL_DATA_DURATION = NanoSeconds (1e6 - 71429 - 1); /** * Delay from subframe start to transmission of SRS. * Equals to ""TTI length - 1 symbol for SRS"". */ static const Time UL_SRS_DELAY_FROM_SUBFRAME_START = NanoSeconds (1e6 - 71429); //////////////////////////////////////// // member SAP forwarders //////////////////////////////////////// /// UeMemberLteUePhySapProvider class class UeMemberLteUePhySapProvider : public LteUePhySapProvider { public: /** * Constructor * * \\param phy the LTE UE Phy */ UeMemberLteUePhySapProvider (LteUePhy* phy); // inherited from LtePhySapProvider virtual void SendMacPdu (Ptr p); virtual void SendLteControlMessage (Ptr msg); virtual void SendRachPreamble (uint32_t prachId, uint32_t raRnti); virtual void NotifyConnectionSuccessful (); private: LteUePhy* m_phy; ///< the Phy }; UeMemberLteUePhySapProvider::UeMemberLteUePhySapProvider (LteUePhy* phy) : m_phy (phy) { } void UeMemberLteUePhySapProvider::SendMacPdu (Ptr p) { m_phy->DoSendMacPdu (p); } void UeMemberLteUePhySapProvider::SendLteControlMessage (Ptr msg) { m_phy->DoSendLteControlMessage (msg); } void UeMemberLteUePhySapProvider::SendRachPreamble (uint32_t prachId, uint32_t raRnti) { m_phy->DoSendRachPreamble (prachId, raRnti); } void UeMemberLteUePhySapProvider::NotifyConnectionSuccessful () { m_phy->DoNotifyConnectionSuccessful (); } //////////////////////////////////////// // LteUePhy methods //////////////////////////////////////// /// Map each of UE PHY states to its string representation. static const std::string g_uePhyStateName[LteUePhy::NUM_STATES] = { ""CELL_SEARCH"", ""SYNCHRONIZED"" }; /** * \\param s The UE PHY state. * \\return The string representation of the given state. */ static inline const std::string & ToString (LteUePhy::State s) { return g_uePhyStateName[s]; } NS_OBJECT_ENSURE_REGISTERED (LteUePhy); LteUePhy::LteUePhy () { NS_LOG_FUNCTION (this); NS_FATAL_ERROR (""This constructor should not be called""); } LteUePhy::LteUePhy (Ptr dlPhy, Ptr ulPhy) : LtePhy (dlPhy, ulPhy), m_uePhySapUser (0), m_ueCphySapUser (0), m_state (CELL_SEARCH), m_subframeNo (0), m_rsReceivedPowerUpdated (false), m_rsInterferencePowerUpdated (false), m_dataInterferencePowerUpdated (false), m_pssReceived (false), m_ueMeasurementsFilterPeriod (MilliSeconds (200)), m_ueMeasurementsFilterLast (MilliSeconds (0)), m_rsrpSinrSampleCounter (0), m_imsi (0) { m_amc = CreateObject (); m_powerControl = CreateObject (); m_uePhySapProvider = new UeMemberLteUePhySapProvider (this); m_ueCphySapProvider = new MemberLteUeCphySapProvider (this); m_macChTtiDelay = UL_PUSCH_TTIS_DELAY; NS_ASSERT_MSG (Simulator::Now ().GetNanoSeconds () == 0, ""Cannot create UE devices after simulation started""); Simulator::Schedule (m_ueMeasurementsFilterPeriod, &LteUePhy::ReportUeMeasurements, this); DoReset (); } LteUePhy::~LteUePhy () { m_txModeGain.clear (); } void LteUePhy::DoDispose () { NS_LOG_FUNCTION (this); delete m_uePhySapProvider; delete m_ueCphySapProvider; LtePhy::DoDispose (); } TypeId LteUePhy::GetTypeId (void) { static TypeId tid = TypeId (""ns3::LteUePhy"") .SetParent () .SetGroupName(""Lte"") .AddConstructor () .AddAttribute (""TxPower"", ""Transmission power in dBm"", DoubleValue (10.0), MakeDoubleAccessor (&LteUePhy::SetTxPower, &LteUePhy::GetTxPower), MakeDoubleChecker ()) .AddAttribute (""NoiseFigure"", ""Loss (dB) in the Signal-to-Noise-Ratio due to non-idealities in the receiver."" "" According to Wikipedia (http://en.wikipedia.org/wiki/Noise_figure), this is "" ""\\""the difference in decibels (dB) between"" "" the noise output of the actual receiver to the noise output of an "" "" ideal receiver with the same overall gain and bandwidth when the receivers "" "" are connected to sources at the standard noise temperature T0.\\"" "" ""In this model, we consider T0 = 290K."", DoubleValue (9.0), MakeDoubleAccessor (&LteUePhy::SetNoiseFigure, &LteUePhy::GetNoiseFigure), MakeDoubleChecker ()) .AddAttribute (""TxMode1Gain"", ""Transmission mode 1 gain in dB"", DoubleValue (0.0), MakeDoubleAccessor (&LteUePhy::SetTxMode1Gain), MakeDoubleChecker ()) .AddAttribute (""TxMode2Gain"", ""Transmission mode 2 gain in dB"", DoubleValue (4.2), MakeDoubleAccessor (&LteUePhy::SetTxMode2Gain), MakeDoubleChecker ()) .AddAttribute (""TxMode3Gain"", ""Transmission mode 3 gain in dB"", DoubleValue (-2.8), MakeDoubleAccessor (&LteUePhy::SetTxMode3Gain), MakeDoubleChecker ()) .AddAttribute (""TxMode4Gain"", ""Transmission mode 4 gain in dB"", DoubleValue (0.0), MakeDoubleAccessor (&LteUePhy::SetTxMode4Gain), MakeDoubleChecker ()) .AddAttribute (""TxMode5Gain"", ""Transmission mode 5 gain in dB"", DoubleValue (0.0), MakeDoubleAccessor (&LteUePhy::SetTxMode5Gain), MakeDoubleChecker ()) .AddAttribute (""TxMode6Gain"", ""Transmission mode 6 gain in dB"", DoubleValue (0.0), MakeDoubleAccessor (&LteUePhy::SetTxMode6Gain), MakeDoubleChecker ()) .AddAttribute (""TxMode7Gain"", ""Transmission mode 7 gain in dB"", DoubleValue (0.0), MakeDoubleAccessor (&LteUePhy::SetTxMode7Gain), MakeDoubleChecker ()) .AddTraceSource (""ReportCurrentCellRsrpSinr"", ""RSRP and SINR statistics."", MakeTraceSourceAccessor (&LteUePhy::m_reportCurrentCellRsrpSinrTrace), ""ns3::LteUePhy::RsrpSinrTracedCallback"") .AddAttribute (""RsrpSinrSamplePeriod"", ""The sampling period for reporting RSRP-SINR stats (default value 1)"", UintegerValue (1), MakeUintegerAccessor (&LteUePhy::m_rsrpSinrSamplePeriod), MakeUintegerChecker ()) .AddTraceSource (""UlPhyTransmission"", ""DL transmission PHY layer statistics."", MakeTraceSourceAccessor (&LteUePhy::m_ulPhyTransmission), ""ns3::PhyTransmissionStatParameters::TracedCallback"") .AddAttribute (""DlSpectrumPhy"", ""The downlink LteSpectrumPhy associated to this LtePhy"", TypeId::ATTR_GET, PointerValue (), MakePointerAccessor (&LteUePhy::GetDlSpectrumPhy), MakePointerChecker ()) .AddAttribute (""UlSpectrumPhy"", ""The uplink LteSpectrumPhy associated to this LtePhy"", TypeId::ATTR_GET, PointerValue (), MakePointerAccessor (&LteUePhy::GetUlSpectrumPhy), MakePointerChecker ()) .AddAttribute (""RsrqUeMeasThreshold"", ""Receive threshold for PSS on RSRQ [dB]"", DoubleValue (-1000.0), MakeDoubleAccessor (&LteUePhy::m_pssReceptionThreshold), MakeDoubleChecker ()) .AddAttribute (""UeMeasurementsFilterPeriod"", ""Time period for reporting UE measurements, i.e., the"" ""length of layer-1 filtering."", TimeValue (MilliSeconds (200)), MakeTimeAccessor (&LteUePhy::m_ueMeasurementsFilterPeriod), MakeTimeChecker ()) .AddAttribute (""DownlinkCqiPeriodicity"", ""Periodicity in milliseconds for reporting the"" ""wideband and subband downlink CQIs to the eNB"", TimeValue (MilliSeconds (1)), MakeTimeAccessor (&LteUePhy::SetDownlinkCqiPeriodicity), MakeTimeChecker ()) .AddTraceSource (""ReportUeMeasurements"", ""Report UE measurements RSRP (dBm) and RSRQ (dB)."", MakeTraceSourceAccessor (&LteUePhy::m_reportUeMeasurements), ""ns3::LteUePhy::RsrpRsrqTracedCallback"") .AddTraceSource (""StateTransition"", ""Trace fired upon every UE PHY state transition"", MakeTraceSourceAccessor (&LteUePhy::m_stateTransitionTrace), ""ns3::LteUePhy::StateTracedCallback"") .AddAttribute (""EnableUplinkPowerControl"", ""If true, Uplink Power Control will be enabled."", BooleanValue (true), MakeBooleanAccessor (&LteUePhy::m_enableUplinkPowerControl), MakeBooleanChecker ()) .AddAttribute (""Qout"", ""corresponds to 10% block error rate of a hypothetical PDCCH transmission"" ""taking into account the PCFICH errors with transmission parameters."" ""see 3GPP TS 36.213 4.2.1 and TS 36.133 7.6"", DoubleValue (-5), MakeDoubleAccessor (&LteUePhy::m_qOut), MakeDoubleChecker ()) .AddAttribute (""Qin"", ""corresponds to 2% block error rate of a hypothetical PDCCH transmission"" ""taking into account the PCFICH errors with transmission parameters."" ""see 3GPP TS 36.213 4.2.1 and TS 36.133 7.6"", DoubleValue (-3.9), MakeDoubleAccessor (&LteUePhy::m_qIn), MakeDoubleChecker ()) .AddAttribute (""NumQoutEvalSf"", ""This specifies the total number of consecutive subframes"" ""which corresponds to the Qout evaluation period"", UintegerValue (200), //see 3GPP 3GPP TS 36.133 7.6.2.1 MakeUintegerAccessor (&LteUePhy::SetNumQoutEvalSf, &LteUePhy::GetNumQoutEvalSf), MakeUintegerChecker ()) .AddAttribute (""NumQinEvalSf"", ""This specifies the total number of consecutive subframes"" ""which corresponds to the Qin evaluation period"", UintegerValue (100), //see 3GPP 3GPP TS 36.133 7.6.2.1 MakeUintegerAccessor (&LteUePhy::SetNumQinEvalSf, &LteUePhy::GetNumQinEvalSf), MakeUintegerChecker ()) .AddAttribute (""EnableRlfDetection"", ""If true, RLF detection will be enabled."", BooleanValue (true), MakeBooleanAccessor (&LteUePhy::m_enableRlfDetection), MakeBooleanChecker ()) ; return tid; } void LteUePhy::DoInitialize () { NS_LOG_FUNCTION (this); NS_ABORT_MSG_IF (m_netDevice == nullptr, ""LteNetDevice is not available in LteUePhy""); Ptr node = m_netDevice->GetNode (); NS_ABORT_MSG_IF (node == nullptr, ""Node is not available in the LteNetDevice of LteUePhy""); uint32_t nodeId = node->GetId (); //ScheduleWithContext() is needed here to set context for logs, //because Initialize() is called outside of Node::AddDevice(). Simulator::ScheduleWithContext (nodeId, Seconds (0), &LteUePhy::SubframeIndication, this, 1, 1); LtePhy::DoInitialize (); } void LteUePhy::SetLteUePhySapUser (LteUePhySapUser* s) { NS_LOG_FUNCTION (this); m_uePhySapUser = s; } LteUePhySapProvider* LteUePhy::GetLteUePhySapProvider () { NS_LOG_FUNCTION (this); return (m_uePhySapProvider); } void LteUePhy::SetLteUeCphySapUser (LteUeCphySapUser* s) { NS_LOG_FUNCTION (this); m_ueCphySapUser = s; } LteUeCphySapProvider* LteUePhy::GetLteUeCphySapProvider () { NS_LOG_FUNCTION (this); return (m_ueCphySapProvider); } void LteUePhy::SetNoiseFigure (double nf) { NS_LOG_FUNCTION (this << nf); m_noiseFigure = nf; } double LteUePhy::GetNoiseFigure () const { NS_LOG_FUNCTION (this); return m_noiseFigure; } void LteUePhy::SetTxPower (double pow) { NS_LOG_FUNCTION (this << pow); m_txPower = pow; m_powerControl->SetTxPower (pow); } double LteUePhy::GetTxPower () const { NS_LOG_FUNCTION (this); return m_txPower; } Ptr LteUePhy::GetUplinkPowerControl () const { NS_LOG_FUNCTION (this); return m_powerControl; } uint8_t LteUePhy::GetMacChDelay (void) const { return (m_macChTtiDelay); } Ptr LteUePhy::GetDlSpectrumPhy () const { return m_downlinkSpectrumPhy; } Ptr LteUePhy::GetUlSpectrumPhy () const { return m_uplinkSpectrumPhy; } void LteUePhy::SetNumQoutEvalSf (uint16_t numSubframes) { NS_LOG_FUNCTION (this << numSubframes); NS_ABORT_MSG_IF (numSubframes % 10 != 0, ""Number of subframes used for Qout "" ""evaluation must be multiple of 10""); m_numOfQoutEvalSf = numSubframes; } void LteUePhy::SetNumQinEvalSf (uint16_t numSubframes) { NS_LOG_FUNCTION (this << numSubframes); NS_ABORT_MSG_IF (numSubframes % 10 != 0, ""Number of subframes used for Qin "" ""evaluation must be multiple of 10""); m_numOfQinEvalSf = numSubframes; } uint16_t LteUePhy::GetNumQoutEvalSf (void) const { NS_LOG_FUNCTION (this); return m_numOfQoutEvalSf; } uint16_t LteUePhy::GetNumQinEvalSf (void) const { NS_LOG_FUNCTION (this); return m_numOfQinEvalSf; } void LteUePhy::DoSendMacPdu (Ptr p) { NS_LOG_FUNCTION (this); SetMacPdu (p); } void LteUePhy::PhyPduReceived (Ptr p) { m_uePhySapUser->ReceivePhyPdu (p); } void LteUePhy::SetSubChannelsForTransmission (std::vector mask) { NS_LOG_FUNCTION (this); m_subChannelsForTransmission = mask; Ptr txPsd = CreateTxPowerSpectralDensity (); m_uplinkSpectrumPhy->SetTxPowerSpectralDensity (txPsd); } void LteUePhy::SetSubChannelsForReception (std::vector mask) { NS_LOG_FUNCTION (this); m_subChannelsForReception = mask; } std::vector LteUePhy::GetSubChannelsForTransmission () { NS_LOG_FUNCTION (this); return m_subChannelsForTransmission; } std::vector LteUePhy::GetSubChannelsForReception () { NS_LOG_FUNCTION (this); return m_subChannelsForReception; } Ptr LteUePhy::CreateTxPowerSpectralDensity () { NS_LOG_FUNCTION (this); LteSpectrumValueHelper psdHelper; Ptr psd = psdHelper.CreateUlTxPowerSpectralDensity (m_ulEarfcn, m_ulBandwidth, m_txPower, GetSubChannelsForTransmission ()); return psd; } void LteUePhy::GenerateCtrlCqiReport (const SpectrumValue& sinr) { NS_LOG_FUNCTION (this); /** * We do not generate the CQI report * when the UE is not synchronized to any cell. * * Also, the RLF is detected after the DL CTRL * is received by the UE,therefore, we do not need * to generate the CQI reports and the UE measurements * for a CTRL for which the RLF has been detected. */ if (m_cellId == 0) { return; } m_ctrlSinrForRlf = sinr; GenerateCqiRsrpRsrq (sinr); } void LteUePhy::GenerateCqiRsrpRsrq (const SpectrumValue& sinr) { NS_LOG_FUNCTION (this << sinr); NS_ASSERT (m_state != CELL_SEARCH); NS_ASSERT (m_cellId > 0); if (m_dlConfigured && m_ulConfigured && (m_rnti > 0)) { // check periodic wideband CQI if (Simulator::Now () > m_p10CqiLast + m_p10CqiPeriodicity) { NS_LOG_DEBUG(""Reporting P10 CQI at : "" << Simulator::Now().GetMilliSeconds() << "" ms. Last reported at : "" << m_p10CqiLast.GetMilliSeconds() << "" ms""); Ptr thisDevice = GetDevice ()->GetObject (); Ptr msg = CreateDlCqiFeedbackMessage (sinr); if (msg) { DoSendLteControlMessage (msg); } m_p10CqiLast = Simulator::Now (); } // check aperiodic high-layer configured subband CQI if (Simulator::Now () > m_a30CqiLast + m_a30CqiPeriodicity) { NS_LOG_DEBUG(""Reporting A30 CQI at : "" << Simulator::Now().GetMilliSeconds() << "" ms. Last reported at : "" << m_a30CqiLast.GetMilliSeconds() << "" ms""); Ptr thisDevice = GetDevice ()->GetObject (); Ptr msg = CreateDlCqiFeedbackMessage (sinr); if (msg) { DoSendLteControlMessage (msg); } m_a30CqiLast = Simulator::Now (); } } // Generate PHY trace m_rsrpSinrSampleCounter++; if (m_rsrpSinrSampleCounter==m_rsrpSinrSamplePeriod) { NS_ASSERT_MSG (m_rsReceivedPowerUpdated, "" RS received power info obsolete""); // RSRP evaluated as averaged received power among RBs double sum = 0.0; uint8_t rbNum = 0; Values::const_iterator it; for (it = m_rsReceivedPower.ConstValuesBegin (); it != m_rsReceivedPower.ConstValuesEnd (); it++) { // convert PSD [W/Hz] to linear power [W] for the single RE // we consider only one RE for the RS since the channel is // flat within the same RB double powerTxW = ((*it) * 180000.0) / 12.0; sum += powerTxW; rbNum++; } double rsrp = (rbNum > 0) ? (sum / rbNum) : DBL_MAX; // averaged SINR among RBs double avSinr = ComputeAvgSinr (sinr); NS_LOG_INFO (this << "" cellId "" << m_cellId << "" rnti "" << m_rnti << "" RSRP "" << rsrp << "" SINR "" << avSinr << "" ComponentCarrierId "" << (uint16_t) m_componentCarrierId); //trigger RLF detection only when UE has an active RRC connection //and RLF detection attribute is set to true if (m_isConnected && m_enableRlfDetection) { double avrgSinrForRlf = ComputeAvgSinr (m_ctrlSinrForRlf); RlfDetection (10 * log10 (avrgSinrForRlf)); } m_reportCurrentCellRsrpSinrTrace (m_cellId, m_rnti, rsrp, avSinr, (uint16_t) m_componentCarrierId); m_rsrpSinrSampleCounter = 0; } if (m_pssReceived) { // measure instantaneous RSRQ now NS_ASSERT_MSG (m_rsInterferencePowerUpdated, "" RS interference power info obsolete""); std::list ::iterator itPss = m_pssList.begin (); while (itPss != m_pssList.end ()) { uint16_t rbNum = 0; double rssiSum = 0.0; Values::const_iterator itIntN = m_rsInterferencePower.ConstValuesBegin (); Values::const_iterator itPj = m_rsReceivedPower.ConstValuesBegin (); for (itPj = m_rsReceivedPower.ConstValuesBegin (); itPj != m_rsReceivedPower.ConstValuesEnd (); itIntN++, itPj++) { rbNum++; // convert PSD [W/Hz] to linear power [W] for the single RE double interfPlusNoisePowerTxW = ((*itIntN) * 180000.0) / 12.0; double signalPowerTxW = ((*itPj) * 180000.0) / 12.0; rssiSum += (2 * (interfPlusNoisePowerTxW + signalPowerTxW)); } NS_ASSERT (rbNum == (*itPss).nRB); double rsrq_dB = 10 * log10 ((*itPss).pssPsdSum / rssiSum); if (rsrq_dB > m_pssReceptionThreshold) { NS_LOG_INFO (this << "" PSS RNTI "" << m_rnti << "" cellId "" << m_cellId << "" has RSRQ "" << rsrq_dB << "" and RBnum "" << rbNum); // store measurements std::map ::iterator itMeasMap; itMeasMap = m_ueMeasurementsMap.find ((*itPss).cellId); if (itMeasMap != m_ueMeasurementsMap.end ()) { (*itMeasMap).second.rsrqSum += rsrq_dB; (*itMeasMap).second.rsrqNum++; } else { NS_LOG_WARN (""race condition of bug 2091 occurred""); } } itPss++; } // end of while (itPss != m_pssList.end ()) m_pssList.clear (); } // end of if (m_pssReceived) } // end of void LteUePhy::GenerateCtrlCqiReport (const SpectrumValue& sinr) double LteUePhy::ComputeAvgSinr (const SpectrumValue& sinr) { NS_LOG_FUNCTION (this); // averaged SINR among RBs double sum = 0.0; uint8_t rbNum = 0; Values::const_iterator it; for (it = sinr.ConstValuesBegin (); it != sinr.ConstValuesEnd (); it++) { sum += (*it); rbNum++; } double avrgSinr = (rbNum > 0) ? (sum / rbNum) : DBL_MAX; return avrgSinr; } void LteUePhy::GenerateDataCqiReport (const SpectrumValue& sinr) { // Not used by UE, CQI are based only on RS } void LteUePhy::GenerateMixedCqiReport (const SpectrumValue& sinr) { NS_LOG_FUNCTION (this); /** * We do not generate the CQI report * when the UE is not synchronized to any cell. * * Also, the RLF is detected after the DL CTRL * is received by the UE,therefore, we do not need * to generate the CQI reports and the UE measurements * for a CTRL for which the RLF has been detected. */ if (m_cellId == 0) { return; } NS_ASSERT (m_state != CELL_SEARCH); //NOTE: The SINR received by this method is //based on CTRL, which is not used to compute //PDSCH (i.e., data) based SINR. It is used //for RLF detection. m_ctrlSinrForRlf = sinr; SpectrumValue mixedSinr = (m_rsReceivedPower * m_paLinear); if (m_dataInterferencePowerUpdated) { // we have a measurement of interf + noise for the denominator // of SINR = S/(I+N) mixedSinr /= m_dataInterferencePower; m_dataInterferencePowerUpdated = false; NS_LOG_LOGIC (""data interf measurement available, SINR = "" << mixedSinr); } else { // we did not see any interference on data, so interference is // there and we have only noise at the denominator of SINR mixedSinr /= (*m_noisePsd); NS_LOG_LOGIC (""no data interf measurement available, SINR = "" << mixedSinr); } /* * some RBs are not used in PDSCH and their SINR is very high * for example with bandwidth 25, last RB is not used * it can make avgSinr value very high, what is incorrect */ uint32_t rbgSize = GetRbgSize (); uint32_t modulo = m_dlBandwidth % rbgSize; double avgMixedSinr = 0; uint32_t usedRbgNum = 0; for(uint32_t i = 0; i < (m_dlBandwidth-1-modulo); i++) { usedRbgNum++; avgMixedSinr+=mixedSinr[i]; } avgMixedSinr = avgMixedSinr/usedRbgNum; for(uint32_t i = 0; i < modulo; i++) { mixedSinr[m_dlBandwidth-1-i] = avgMixedSinr; } GenerateCqiRsrpRsrq (mixedSinr); } void LteUePhy::ReportInterference (const SpectrumValue& interf) { NS_LOG_FUNCTION (this << interf); m_rsInterferencePowerUpdated = true; m_rsInterferencePower = interf; } void LteUePhy::ReportDataInterference (const SpectrumValue& interf) { NS_LOG_FUNCTION (this << interf); m_dataInterferencePowerUpdated = true; m_dataInterferencePower = interf; } void LteUePhy::ReportRsReceivedPower (const SpectrumValue& power) { NS_LOG_FUNCTION (this << power); m_rsReceivedPowerUpdated = true; m_rsReceivedPower = power; if (m_enableUplinkPowerControl) { double sum = 0; uint32_t rbNum = 0; Values::const_iterator it; for (it = m_rsReceivedPower.ConstValuesBegin (); it != m_rsReceivedPower.ConstValuesEnd (); it++) { double powerTxW = ((*it) * 180000); sum += powerTxW; rbNum++; } double rsrp = 10 * log10 (sum) + 30; NS_LOG_INFO (""RSRP: "" << rsrp); m_powerControl->SetRsrp (rsrp); } } Ptr LteUePhy::CreateDlCqiFeedbackMessage (const SpectrumValue& sinr) { NS_LOG_FUNCTION (this); // apply transmission mode gain NS_ASSERT (m_transmissionMode < m_txModeGain.size ()); SpectrumValue newSinr = sinr; newSinr *= m_txModeGain.at (m_transmissionMode); // CREATE DlCqiLteControlMessage Ptr msg = Create (); CqiListElement_s dlcqi; std::vector cqi; if (Simulator::Now () > m_p10CqiLast + m_p10CqiPeriodicity) { cqi = m_amc->CreateCqiFeedbacks (newSinr, m_dlBandwidth); int nLayer = TransmissionModesLayers::TxMode2LayerNum (m_transmissionMode); int nbSubChannels = cqi.size (); double cqiSum = 0.0; int activeSubChannels = 0; // average the CQIs of the different RBs for (int i = 0; i < nbSubChannels; i++) { if (cqi.at (i) != -1) { cqiSum += cqi.at (i); activeSubChannels++; } NS_LOG_DEBUG (this << "" subch "" << i << "" cqi "" << cqi.at (i)); } dlcqi.m_rnti = m_rnti; dlcqi.m_ri = 1; // not yet used dlcqi.m_cqiType = CqiListElement_s::P10; // Peridic CQI using PUCCH wideband NS_ASSERT_MSG (nLayer > 0, "" nLayer negative""); NS_ASSERT_MSG (nLayer < 3, "" nLayer limit is 2s""); for (int i = 0; i < nLayer; i++) { if (activeSubChannels > 0) { dlcqi.m_wbCqi.push_back ((uint16_t) cqiSum / activeSubChannels); } else { // approximate with the worst case -> CQI = 1 dlcqi.m_wbCqi.push_back (1); } } //NS_LOG_DEBUG (this << "" Generate P10 CQI feedback "" << (uint16_t) cqiSum / activeSubChannels); dlcqi.m_wbPmi = 0; // not yet used // dl.cqi.m_sbMeasResult others CQI report modes: not yet implemented } else if (Simulator::Now () > m_a30CqiLast + m_a30CqiPeriodicity) { cqi = m_amc->CreateCqiFeedbacks (newSinr, GetRbgSize ()); int nLayer = TransmissionModesLayers::TxMode2LayerNum (m_transmissionMode); int nbSubChannels = cqi.size (); int rbgSize = GetRbgSize (); double cqiSum = 0.0; int cqiNum = 0; SbMeasResult_s rbgMeas; //NS_LOG_DEBUG (this << "" Create A30 CQI feedback, RBG "" << rbgSize << "" cqiNum "" << nbSubChannels << "" band "" << (uint16_t)m_dlBandwidth); for (int i = 0; i < nbSubChannels; i++) { if (cqi.at (i) != -1) { cqiSum += cqi.at (i); } // else ""nothing"" no CQI is treated as CQI = 0 (worst case scenario) cqiNum++; if (cqiNum == rbgSize) { // average the CQIs of the different RBGs //NS_LOG_DEBUG (this << "" RBG CQI "" << (uint16_t) cqiSum / rbgSize); HigherLayerSelected_s hlCqi; hlCqi.m_sbPmi = 0; // not yet used for (int i = 0; i < nLayer; i++) { hlCqi.m_sbCqi.push_back ((uint16_t) cqiSum / rbgSize); } rbgMeas.m_higherLayerSelected.push_back (hlCqi); cqiSum = 0.0; cqiNum = 0; } } dlcqi.m_rnti = m_rnti; dlcqi.m_ri = 1; // not yet used dlcqi.m_cqiType = CqiListElement_s::A30; // Aperidic CQI using PUSCH //dlcqi.m_wbCqi.push_back ((uint16_t) cqiSum / nbSubChannels); dlcqi.m_wbPmi = 0; // not yet used dlcqi.m_sbMeasResult = rbgMeas; } msg->SetDlCqi (dlcqi); return msg; } void LteUePhy::ReportUeMeasurements () { NS_LOG_FUNCTION (this << Simulator::Now ()); NS_LOG_DEBUG (this << "" Report UE Measurements ""); LteUeCphySapUser::UeMeasurementsParameters ret; std::map ::iterator it; for (it = m_ueMeasurementsMap.begin (); it != m_ueMeasurementsMap.end (); it++) { double avg_rsrp = (*it).second.rsrpSum / (double)(*it).second.rsrpNum; double avg_rsrq = (*it).second.rsrqSum / (double)(*it).second.rsrqNum; /* * In CELL_SEARCH state, this may result in avg_rsrq = 0/0 = -nan. * UE RRC must take this into account when receiving measurement reports. * TODO remove this shortcoming by calculating RSRQ during CELL_SEARCH */ NS_LOG_DEBUG (this << "" CellId "" << (*it).first << "" RSRP "" << avg_rsrp << "" (nSamples "" << (uint16_t)(*it).second.rsrpNum << "")"" << "" RSRQ "" << avg_rsrq << "" (nSamples "" << (uint16_t)(*it).second.rsrqNum << "")"" << "" ComponentCarrierID "" << (uint16_t)m_componentCarrierId); LteUeCphySapUser::UeMeasurementsElement newEl; newEl.m_cellId = (*it).first; newEl.m_rsrp = avg_rsrp; newEl.m_rsrq = avg_rsrq; ret.m_ueMeasurementsList.push_back (newEl); ret.m_componentCarrierId = m_componentCarrierId; // report to UE measurements trace m_reportUeMeasurements (m_rnti, (*it).first, avg_rsrp, avg_rsrq, ((*it).first == m_cellId ? 1 : 0), m_componentCarrierId); } // report to RRC m_ueCphySapUser->ReportUeMeasurements (ret); m_ueMeasurementsMap.clear (); Simulator::Schedule (m_ueMeasurementsFilterPeriod, &LteUePhy::ReportUeMeasurements, this); } void LteUePhy::SetDownlinkCqiPeriodicity (Time cqiPeriodicity) { NS_LOG_FUNCTION (this << cqiPeriodicity); m_a30CqiPeriodicity = cqiPeriodicity; m_p10CqiPeriodicity = cqiPeriodicity; } void LteUePhy::DoSendLteControlMessage (Ptr msg) { NS_LOG_FUNCTION (this << msg); SetControlMessages (msg); } void LteUePhy::DoSendRachPreamble (uint32_t raPreambleId, uint32_t raRnti) { NS_LOG_FUNCTION (this << raPreambleId); // unlike other control messages, RACH preamble is sent ASAP Ptr msg = Create (); msg->SetRapId (raPreambleId); m_raPreambleId = raPreambleId; m_raRnti = raRnti; m_controlMessagesQueue.at (0).push_back (msg); } void LteUePhy::DoNotifyConnectionSuccessful () { /** * Radio link failure detection should take place only on the * primary carrier to avoid errors due to multiple calls to the * same methods at the RRC layer */ if (m_componentCarrierId == 0) { m_isConnected = true; // Initialize the parameters for radio link failure detection InitializeRlfParams (); } } void LteUePhy::ReceiveLteControlMessageList (std::list > msgList) { NS_LOG_FUNCTION (this); std::list >::iterator it; NS_LOG_DEBUG (this << "" I am rnti = "" << m_rnti << "" and I received msgs "" << (uint16_t) msgList.size ()); for (it = msgList.begin (); it != msgList.end (); it++) { Ptr msg = (*it); if (msg->GetMessageType () == LteControlMessage::DL_DCI) { Ptr msg2 = DynamicCast (msg); DlDciListElement_s dci = msg2->GetDci (); if (dci.m_rnti != m_rnti) { // DCI not for me continue; } if (dci.m_resAlloc != 0) { NS_FATAL_ERROR (""Resource Allocation type not implemented""); } std::vector dlRb; // translate the DCI to Spectrum framework uint32_t mask = 0x1; for (int i = 0; i < 32; i++) { if (((dci.m_rbBitmap & mask) >> i) == 1) { for (int k = 0; k < GetRbgSize (); k++) { dlRb.push_back ((i * GetRbgSize ()) + k); // NS_LOG_DEBUG(this << "" RNTI "" << m_rnti << "" RBG "" << i << "" DL-DCI allocated PRB "" << (i*GetRbgSize()) + k); } } mask = (mask << 1); } if (m_enableUplinkPowerControl) { m_powerControl->ReportTpc (dci.m_tpc); } // send TB info to LteSpectrumPhy NS_LOG_DEBUG (this << "" UE "" << m_rnti << "" DL-DCI "" << dci.m_rnti << "" bitmap "" << dci.m_rbBitmap); for (uint8_t i = 0; i < dci.m_tbsSize.size (); i++) { m_downlinkSpectrumPhy->AddExpectedTb (dci.m_rnti, dci.m_ndi.at (i), dci.m_tbsSize.at (i), dci.m_mcs.at (i), dlRb, i, dci.m_harqProcess, dci.m_rv.at (i), true /* DL */); } SetSubChannelsForReception (dlRb); } else if (msg->GetMessageType () == LteControlMessage::UL_DCI) { // set the uplink bandwidth according to the UL-CQI Ptr msg2 = DynamicCast (msg); UlDciListElement_s dci = msg2->GetDci (); if (dci.m_rnti != m_rnti) { // DCI not for me continue; } NS_LOG_INFO (this << "" UL DCI""); std::vector ulRb; for (int i = 0; i < dci.m_rbLen; i++) { ulRb.push_back (i + dci.m_rbStart); //NS_LOG_DEBUG (this << "" UE RB "" << i + dci.m_rbStart); } QueueSubChannelsForTransmission (ulRb); // fire trace of UL Tx PHY stats HarqProcessInfoList_t harqInfoList = m_harqPhyModule->GetHarqProcessInfoUl (m_rnti, 0); PhyTransmissionStatParameters params; params.m_cellId = m_cellId; params.m_imsi = 0; // it will be set by DlPhyTransmissionCallback in LteHelper params.m_timestamp = Simulator::Now ().GetMilliSeconds () + UL_PUSCH_TTIS_DELAY; params.m_rnti = m_rnti; params.m_txMode = 0; // always SISO for UE params.m_layer = 0; params.m_mcs = dci.m_mcs; params.m_size = dci.m_tbSize; params.m_rv = harqInfoList.size (); params.m_ndi = dci.m_ndi; params.m_ccId = m_componentCarrierId; m_ulPhyTransmission (params); // pass the info to the MAC m_uePhySapUser->ReceiveLteControlMessage (msg); } else if (msg->GetMessageType () == LteControlMessage::RAR) { Ptr rarMsg = DynamicCast (msg); if (rarMsg->GetRaRnti () == m_raRnti) { for (std::list::const_iterator it = rarMsg->RarListBegin (); it != rarMsg->RarListEnd (); ++it) { if (it->rapId != m_raPreambleId) { // UL grant not for me continue; } else { NS_LOG_INFO (""received RAR RNTI "" << m_raRnti); // set the uplink bandwidth according to the UL grant std::vector ulRb; for (int i = 0; i < it->rarPayload.m_grant.m_rbLen; i++) { ulRb.push_back (i + it->rarPayload.m_grant.m_rbStart); } QueueSubChannelsForTransmission (ulRb); // pass the info to the MAC m_uePhySapUser->ReceiveLteControlMessage (msg); // reset RACH variables with out of range values m_raPreambleId = 255; m_raRnti = 11; } } } } else if (msg->GetMessageType () == LteControlMessage::MIB) { NS_LOG_INFO (""received MIB""); NS_ASSERT (m_cellId > 0); Ptr msg2 = DynamicCast (msg); m_ueCphySapUser->RecvMasterInformationBlock (m_cellId, msg2->GetMib ()); } else if (msg->GetMessageType () == LteControlMessage::SIB1) { NS_LOG_INFO (""received SIB1""); NS_ASSERT (m_cellId > 0); Ptr msg2 = DynamicCast (msg); m_ueCphySapUser->RecvSystemInformationBlockType1 (m_cellId, msg2->GetSib1 ()); } else { // pass the message to UE-MAC m_uePhySapUser->ReceiveLteControlMessage (msg); } } } void LteUePhy::ReceivePss (uint16_t cellId, Ptr p) { NS_LOG_FUNCTION (this << cellId << (*p)); double sum = 0.0; uint16_t nRB = 0; Values::const_iterator itPi; for (itPi = p->ConstValuesBegin (); itPi != p->ConstValuesEnd (); itPi++) { // convert PSD [W/Hz] to linear power [W] for the single RE double powerTxW = ((*itPi) * 180000.0) / 12.0; sum += powerTxW; nRB++; } // measure instantaneous RSRP now double rsrp_dBm = 10 * log10 (1000 * (sum / (double)nRB)); NS_LOG_INFO (this << "" PSS RNTI "" << m_rnti << "" cellId "" << m_cellId << "" has RSRP "" << rsrp_dBm << "" and RBnum "" << nRB); // note that m_pssReceptionThreshold does not apply here // store measurements std::map ::iterator itMeasMap = m_ueMeasurementsMap.find (cellId); if (itMeasMap == m_ueMeasurementsMap.end ()) { // insert new entry UeMeasurementsElement newEl; newEl.rsrpSum = rsrp_dBm; newEl.rsrpNum = 1; newEl.rsrqSum = 0; newEl.rsrqNum = 0; m_ueMeasurementsMap.insert (std::pair (cellId, newEl)); } else { (*itMeasMap).second.rsrpSum += rsrp_dBm; (*itMeasMap).second.rsrpNum++; } /* * Collect the PSS for later processing in GenerateCtrlCqiReport() * (to be called from ChunkProcessor after RX is finished). */ m_pssReceived = true; PssElement el; el.cellId = cellId; el.pssPsdSum = sum; el.nRB = nRB; m_pssList.push_back (el); } // end of void LteUePhy::ReceivePss (uint16_t cellId, Ptr p) void LteUePhy::QueueSubChannelsForTransmission (std::vector rbMap) { m_subChannelsForTransmissionQueue.at (m_macChTtiDelay - 1) = rbMap; } void LteUePhy::SubframeIndication (uint32_t frameNo, uint32_t subframeNo) { NS_LOG_FUNCTION (this << frameNo << subframeNo); NS_ASSERT_MSG (frameNo > 0, ""the SRS index check code assumes that frameNo starts at 1""); // refresh internal variables m_rsReceivedPowerUpdated = false; m_rsInterferencePowerUpdated = false; m_pssReceived = false; if (m_ulConfigured) { // update uplink transmission mask according to previous UL-CQIs std::vector rbMask = m_subChannelsForTransmissionQueue.at (0); SetSubChannelsForTransmission (m_subChannelsForTransmissionQueue.at (0)); // shift the queue for (uint8_t i = 1; i < m_macChTtiDelay; i++) { m_subChannelsForTransmissionQueue.at (i-1) = m_subChannelsForTransmissionQueue.at (i); } m_subChannelsForTransmissionQueue.at (m_macChTtiDelay-1).clear (); if (m_srsConfigured && (m_srsStartTime <= Simulator::Now ())) { NS_ASSERT_MSG (subframeNo > 0 && subframeNo <= 10, ""the SRS index check code assumes that subframeNo starts at 1""); if ((((frameNo-1)*10 + (subframeNo-1)) % m_srsPeriodicity) == m_srsSubframeOffset) { NS_LOG_INFO (""frame "" << frameNo << "" subframe "" << subframeNo << "" sending SRS (offset="" << m_srsSubframeOffset << "", period="" << m_srsPeriodicity << "")""); m_sendSrsEvent = Simulator::Schedule (UL_SRS_DELAY_FROM_SUBFRAME_START, &LteUePhy::SendSrs, this); } } std::list > ctrlMsg = GetControlMessages (); // send packets in queue NS_LOG_LOGIC (this << "" UE - start slot for PUSCH + PUCCH - RNTI "" << m_rnti << "" CELLID "" << m_cellId); // send the current burts of packets Ptr pb = GetPacketBurst (); if (pb) { if (m_enableUplinkPowerControl) { m_txPower = m_powerControl->GetPuschTxPower (rbMask); SetSubChannelsForTransmission (rbMask); } m_uplinkSpectrumPhy->StartTxDataFrame (pb, ctrlMsg, UL_DATA_DURATION); } else { // send only PUCCH (ideal: fake null bandwidth signal) if (ctrlMsg.size ()>0) { NS_LOG_LOGIC (this << "" UE - start TX PUCCH (NO PUSCH)""); std::vector dlRb; if (m_enableUplinkPowerControl) { m_txPower = m_powerControl->GetPucchTxPower (dlRb); } SetSubChannelsForTransmission (dlRb); m_uplinkSpectrumPhy->StartTxDataFrame (pb, ctrlMsg, UL_DATA_DURATION); } else { NS_LOG_LOGIC (this << "" UE - UL NOTHING TO SEND""); } } } // m_configured // trigger the MAC m_uePhySapUser->SubframeIndication (frameNo, subframeNo); m_subframeNo = subframeNo; ++subframeNo; if (subframeNo > 10) { ++frameNo; subframeNo = 1; } // schedule next subframe indication Simulator::Schedule (Seconds (GetTti ()), &LteUePhy::SubframeIndication, this, frameNo, subframeNo); } void LteUePhy::SendSrs () { NS_LOG_FUNCTION (this << "" UE "" << m_rnti << "" start tx SRS, cell Id "" << (uint32_t) m_cellId); NS_ASSERT (m_cellId > 0); // set the current tx power spectral density (full bandwidth) std::vector dlRb; for (uint8_t i = 0; i < m_ulBandwidth; i++) { dlRb.push_back (i); } if (m_enableUplinkPowerControl) { m_txPower = m_powerControl->GetSrsTxPower (dlRb); } SetSubChannelsForTransmission (dlRb); m_uplinkSpectrumPhy->StartTxUlSrsFrame (); } void LteUePhy::DoReset () { NS_LOG_FUNCTION (this); m_rnti = 0; m_cellId = 0; m_isConnected = false; m_transmissionMode = 0; m_srsPeriodicity = 0; m_srsConfigured = false; m_dlConfigured = false; m_ulConfigured = false; m_raPreambleId = 255; // value out of range m_raRnti = 11; // value out of range m_rsrpSinrSampleCounter = 0; m_p10CqiLast = Simulator::Now (); m_a30CqiLast = Simulator::Now (); m_paLinear = 1; m_packetBurstQueue.clear (); m_controlMessagesQueue.clear (); m_subChannelsForTransmissionQueue.clear (); for (int i = 0; i < m_macChTtiDelay; i++) { Ptr pb = CreateObject (); m_packetBurstQueue.push_back (pb); std::list > l; m_controlMessagesQueue.push_back (l); } std::vector ulRb; m_subChannelsForTransmissionQueue.resize (m_macChTtiDelay, ulRb); m_sendSrsEvent.Cancel (); m_downlinkSpectrumPhy->Reset (); m_uplinkSpectrumPhy->Reset (); m_pssList.clear (); /** * Call the EndRx() method of the interference model for DL control and data * to cancel any ongoing downlink reception of control and data info. */ m_downlinkSpectrumPhy->m_interferenceCtrl->EndRx (); m_downlinkSpectrumPhy->m_interferenceData->EndRx (); } // end of void LteUePhy::DoReset () void LteUePhy::DoStartCellSearch (uint32_t dlEarfcn) { NS_LOG_FUNCTION (this << dlEarfcn); m_dlEarfcn = dlEarfcn; DoSetDlBandwidth (6); // configure DL for receiving PSS SwitchToState (CELL_SEARCH); } void LteUePhy::DoSynchronizeWithEnb (uint16_t cellId, uint32_t dlEarfcn) { NS_LOG_FUNCTION (this << cellId << dlEarfcn); m_dlEarfcn = dlEarfcn; DoSynchronizeWithEnb (cellId); } void LteUePhy::DoSynchronizeWithEnb (uint16_t cellId) { NS_LOG_FUNCTION (this << cellId); if (cellId == 0) { NS_FATAL_ERROR (""Cell ID shall not be zero""); } m_cellId = cellId; m_downlinkSpectrumPhy->SetCellId (cellId); m_uplinkSpectrumPhy->SetCellId (cellId); // configure DL for receiving the BCH with the minimum bandwidth DoSetDlBandwidth (6); m_dlConfigured = false; m_ulConfigured = false; SwitchToState (SYNCHRONIZED); } void LteUePhy::DoSetDlBandwidth (uint8_t dlBandwidth) { NS_LOG_FUNCTION (this << (uint32_t) dlBandwidth); if (m_dlBandwidth != dlBandwidth or !m_dlConfigured) { m_dlBandwidth = dlBandwidth; static const int Type0AllocationRbg[4] = { 10, // RGB size 1 26, // RGB size 2 63, // RGB size 3 110 // RGB size 4 }; // see table 7.1.6.1-1 of 36.213 for (int i = 0; i < 4; i++) { if (dlBandwidth < Type0AllocationRbg[i]) { m_rbgSize = i + 1; break; } } m_noisePsd = LteSpectrumValueHelper::CreateNoisePowerSpectralDensity (m_dlEarfcn, m_dlBandwidth, m_noiseFigure); m_downlinkSpectrumPhy->SetNoisePowerSpectralDensity (m_noisePsd); m_downlinkSpectrumPhy->GetChannel ()->AddRx (m_downlinkSpectrumPhy); } m_dlConfigured = true; } void LteUePhy::DoConfigureUplink (uint32_t ulEarfcn, uint8_t ulBandwidth) { m_ulEarfcn = ulEarfcn; m_ulBandwidth = ulBandwidth; m_ulConfigured = true; } void LteUePhy::DoConfigureReferenceSignalPower (int8_t referenceSignalPower) { NS_LOG_FUNCTION (this); m_powerControl->ConfigureReferenceSignalPower (referenceSignalPower); } void LteUePhy::DoSetRnti (uint16_t rnti) { NS_LOG_FUNCTION (this << rnti); m_rnti = rnti; m_powerControl->SetCellId (m_cellId); m_powerControl->SetRnti (m_rnti); } void LteUePhy::DoSetTransmissionMode (uint8_t txMode) { NS_LOG_FUNCTION (this << (uint16_t)txMode); m_transmissionMode = txMode; m_downlinkSpectrumPhy->SetTransmissionMode (txMode); } void LteUePhy::DoSetSrsConfigurationIndex (uint16_t srcCi) { NS_LOG_FUNCTION (this << srcCi); m_srsPeriodicity = GetSrsPeriodicity (srcCi); m_srsSubframeOffset = GetSrsSubframeOffset (srcCi); m_srsConfigured = true; // a guard time is needed for the case where the SRS periodicity is changed dynamically at run time // if we use a static one, we can have a 0ms guard time m_srsStartTime = Simulator::Now () + MilliSeconds (0); NS_LOG_DEBUG (this << "" UE SRS P "" << m_srsPeriodicity << "" RNTI "" << m_rnti << "" offset "" << m_srsSubframeOffset << "" cellId "" << m_cellId << "" CI "" << srcCi); } void LteUePhy::DoSetPa (double pa) { NS_LOG_FUNCTION (this << pa); m_paLinear = pow (10,(pa/10)); } void LteUePhy::DoSetRsrpFilterCoefficient (uint8_t rsrpFilterCoefficient) { NS_LOG_FUNCTION (this << (uint16_t) (rsrpFilterCoefficient)); m_powerControl->SetRsrpFilterCoefficient (rsrpFilterCoefficient); } void LteUePhy::DoResetPhyAfterRlf () { NS_LOG_FUNCTION (this); m_downlinkSpectrumPhy->m_harqPhyModule->ClearDlHarqBuffer (m_rnti); //flush HARQ buffers m_dataInterferencePowerUpdated = false; m_rsInterferencePowerUpdated = false; m_pssReceived = false; DoReset (); } void LteUePhy::DoResetRlfParams () { NS_LOG_FUNCTION (this); InitializeRlfParams (); } void LteUePhy::DoStartInSnycDetection () { NS_LOG_FUNCTION (this); // indicates that the downlink radio link quality has to be monitored for in-sync indications m_downlinkInSync = false; } void LteUePhy::DoSetImsi (uint64_t imsi) { NS_LOG_FUNCTION (this); m_imsi = imsi; } void LteUePhy::InitializeRlfParams () { NS_LOG_FUNCTION (this); m_numOfSubframes = 0; m_sinrDbFrame = 0; m_numOfFrames = 0; m_downlinkInSync = true; } void LteUePhy::RlfDetection (double sinrDb) { NS_LOG_FUNCTION (this << sinrDb); m_sinrDbFrame += sinrDb; m_numOfSubframes++; NS_LOG_LOGIC (""No of Subframes: "" << m_numOfSubframes << "" UE synchronized: "" << m_downlinkInSync); //check for out_of_snyc indications first when UE is both DL and UL synchronized //m_downlinkInSync=true indicates that the evaluation is for out-of-sync indications if (m_downlinkInSync && m_numOfSubframes == 10) { /** * For every frame, if the downlink radio link quality(avg SINR) * is less than the threshold Qout, then the frame cannot be decoded */ if ((m_sinrDbFrame / m_numOfSubframes) < m_qOut) { m_numOfFrames++; //increment the counter if a frame cannot be decoded NS_LOG_LOGIC (""No of Frames which cannot be decoded: "" << m_numOfFrames); } else { /** * If the downlink radio link quality(avg SINR) is greater * than the threshold Qout, then the frame counter is reset * since only consecutive frames should be considered. */ NS_LOG_INFO (""Resetting frame counter at phy. Current value = "" << m_numOfFrames); m_numOfFrames = 0; // Also reset the sync indicator counter at RRC m_ueCphySapUser->ResetSyncIndicationCounter (); } m_numOfSubframes = 0; m_sinrDbFrame = 0; } /** * Once the number of consecutive frames which cannot be decoded equals * the Qout evaluation period (i.e 200ms), then an out-of-sync indication * is sent to the RRC layer */ if (m_downlinkInSync && (m_numOfFrames * 10) == m_numOfQoutEvalSf) { NS_LOG_LOGIC (""At "" << Simulator::Now ().GetMilliSeconds() << "" ms UE PHY sending out of snyc indication to UE RRC layer""); m_ueCphySapUser->NotifyOutOfSync (); m_numOfFrames = 0; } //check for in_snyc indications when T310 timer is started //m_downlinkInSync=false indicates that the evaluation is for in-sync indications if (!m_downlinkInSync && m_numOfSubframes == 10) { /** * For every frame, if the downlink radio link quality(avg SINR) * is greater than the threshold Qin, then the frame can be * successfully decoded. */ if ((m_sinrDbFrame / m_numOfSubframes) > m_qIn) { m_numOfFrames++; //increment the counter if a frame can be decoded NS_LOG_LOGIC (""No of Frames successfully decoded: "" << m_numOfFrames); } else { /** * If the downlink radio link quality(avg SINR) is less * than the threshold Qin, then the frame counter is reset * since only consecutive frames should be considered */ m_numOfFrames = 0; // Also reset the sync indicator counter at RRC m_ueCphySapUser->ResetSyncIndicationCounter (); } m_numOfSubframes = 0; m_sinrDbFrame = 0; } /** * Once the number of consecutive frames which can be decoded equals the Qin evaluation period (i.e 100ms), * then an in-sync indication is sent to the RRC layer */ if (!m_downlinkInSync && (m_numOfFrames * 10) == m_numOfQinEvalSf) { NS_LOG_LOGIC (""At "" << Simulator::Now ().GetMilliSeconds() << "" ms UE PHY sending in snyc indication to UE RRC layer""); m_ueCphySapUser->NotifyInSync (); m_numOfFrames = 0; } } void LteUePhy::SetTxMode1Gain (double gain) { SetTxModeGain (1, gain); } void LteUePhy::SetTxMode2Gain (double gain) { SetTxModeGain (2, gain); } void LteUePhy::SetTxMode3Gain (double gain) { SetTxModeGain (3, gain); } void LteUePhy::SetTxMode4Gain (double gain) { SetTxModeGain (4, gain); } void LteUePhy::SetTxMode5Gain (double gain) { SetTxModeGain (5, gain); } void LteUePhy::SetTxMode6Gain (double gain) { SetTxModeGain (6, gain); } void LteUePhy::SetTxMode7Gain (double gain) { SetTxModeGain (7, gain); } void LteUePhy::SetTxModeGain (uint8_t txMode, double gain) { NS_LOG_FUNCTION (this << gain); // convert to linear double gainLin = std::pow (10.0, (gain / 10.0)); if (m_txModeGain.size () < txMode) { m_txModeGain.resize (txMode); } std::vector temp; temp = m_txModeGain; m_txModeGain.clear (); for (uint8_t i = 0; i < temp.size (); i++) { if (i==txMode-1) { m_txModeGain.push_back (gainLin); } else { m_txModeGain.push_back (temp.at (i)); } } // forward the info to DL LteSpectrumPhy m_downlinkSpectrumPhy->SetTxModeGain (txMode, gain); } void LteUePhy::ReceiveLteDlHarqFeedback (DlInfoListElement_s m) { NS_LOG_FUNCTION (this); // generate feedback to eNB and send it through ideal PUCCH Ptr msg = Create (); msg->SetDlHarqFeedback (m); SetControlMessages (msg); } void LteUePhy::SetHarqPhyModule (Ptr harq) { m_harqPhyModule = harq; } LteUePhy::State LteUePhy::GetState () const { NS_LOG_FUNCTION (this); return m_state; } void LteUePhy::SwitchToState (State newState) { NS_LOG_FUNCTION (this << newState); State oldState = m_state; m_state = newState; NS_LOG_INFO (this << "" cellId="" << m_cellId << "" rnti="" << m_rnti << "" UePhy "" << ToString (oldState) << "" --> "" << ToString (newState)); m_stateTransitionTrace (m_cellId, m_rnti, oldState, newState); } } // namespace ns3 ",16321,True,2986.9256872838905,median "= v1.EgressNetworkPolicy {product-author} {product-version} :data-uri: :icons: :toc: macro :toc-title: :toclevels: 2 toc::[] == Description [%hardbreaks] EgressNetworkPolicy describes the current egress network policy for a Namespace. When using the 'redhat/openshift-ovs-multitenant' network plugin, traffic from a pod to an IP address outside the cluster will be checked against each EgressNetworkPolicyRule in the pod's namespace's EgressNetworkPolicy, in order. If no rule matches (or no EgressNetworkPolicy is present) then the traffic will be allowed by default. == 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:
egress:
- to:
- cidrSelector:
dnsName:
type:
++++ == Operations [[Post-oapi-v1-egressnetworkpolicies]] === Create a EgressNetworkPolicy Create an EgressNetworkPolicy ==== HTTP request ---- POST /oapi/v1/egressnetworkpolicies HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json' { ""kind"": ""EgressNetworkPolicy"", ""apiVersion"": ""v1"", ... } ---- ==== Curl request ---- $ curl -k \\ -X POST \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json' \\ https://$ENDPOINT/oapi/v1/egressnetworkpolicies <<'EOF' { ""kind"": ""EgressNetworkPolicy"", ""apiVersion"": ""v1"", ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1.EgressNetworkPolicy |=== ==== 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.EgressNetworkPolicy |201 Created|v1.EgressNetworkPolicy |202 Accepted|v1.EgressNetworkPolicy |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Post-oapi-v1-namespaces-namespace-egressnetworkpolicies]] === Create a EgressNetworkPolicy in a namespace Create an EgressNetworkPolicy ==== HTTP request ---- POST /oapi/v1/namespaces/$NAMESPACE/egressnetworkpolicies HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json' { ""kind"": ""EgressNetworkPolicy"", ""apiVersion"": ""v1"", ... } ---- ==== Curl request ---- $ curl -k \\ -X POST \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json' \\ https://$ENDPOINT/oapi/v1/namespaces/$NAMESPACE/egressnetworkpolicies <<'EOF' { ""kind"": ""EgressNetworkPolicy"", ""apiVersion"": ""v1"", ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1.EgressNetworkPolicy |=== ==== 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.EgressNetworkPolicy |201 Created|v1.EgressNetworkPolicy |202 Accepted|v1.EgressNetworkPolicy |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Get-oapi-v1-namespaces-namespace-egressnetworkpolicies-name]] === Get a EgressNetworkPolicy in a namespace Read the specified EgressNetworkPolicy ==== HTTP request ---- GET /oapi/v1/namespaces/$NAMESPACE/egressnetworkpolicies/$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/oapi/v1/namespaces/$NAMESPACE/egressnetworkpolicies/$NAME ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the EgressNetworkPolicy |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.EgressNetworkPolicy |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Get-oapi-v1-egressnetworkpolicies]] === Get all EgressNetworkPolicies List or watch objects of kind EgressNetworkPolicy ==== HTTP request ---- GET /oapi/v1/egressnetworkpolicies 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/oapi/v1/egressnetworkpolicies ---- ==== 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. This limits the duration of the call, regardless of any activity or inactivity. |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.EgressNetworkPolicyList |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf * application/json;stream=watch * application/vnd.kubernetes.protobuf;stream=watch [[Get-oapi-v1-namespaces-namespace-egressnetworkpolicies]] === Get all EgressNetworkPolicies in a namespace List or watch objects of kind EgressNetworkPolicy ==== HTTP request ---- GET /oapi/v1/namespaces/$NAMESPACE/egressnetworkpolicies 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/oapi/v1/namespaces/$NAMESPACE/egressnetworkpolicies ---- ==== 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. This limits the duration of the call, regardless of any activity or inactivity. |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.EgressNetworkPolicyList |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf * application/json;stream=watch * application/vnd.kubernetes.protobuf;stream=watch [[Get-oapi-v1-watch-namespaces-namespace-egressnetworkpolicies-name]] === Watch a EgressNetworkPolicy in a namespace Watch changes to an object of kind EgressNetworkPolicy ==== HTTP request ---- GET /oapi/v1/watch/namespaces/$NAMESPACE/egressnetworkpolicies/$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/oapi/v1/watch/namespaces/$NAMESPACE/egressnetworkpolicies/$NAME ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the EgressNetworkPolicy |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. This limits the duration of the call, regardless of any activity or inactivity. |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-oapi-v1-watch-egressnetworkpolicies]] === Watch all EgressNetworkPolicies Watch individual changes to a list of EgressNetworkPolicy ==== HTTP request ---- GET /oapi/v1/watch/egressnetworkpolicies 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/oapi/v1/watch/egressnetworkpolicies ---- ==== 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. This limits the duration of the call, regardless of any activity or inactivity. |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-oapi-v1-watch-namespaces-namespace-egressnetworkpolicies]] === Watch all EgressNetworkPolicies in a namespace Watch individual changes to a list of EgressNetworkPolicy ==== HTTP request ---- GET /oapi/v1/watch/namespaces/$NAMESPACE/egressnetworkpolicies 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/oapi/v1/watch/namespaces/$NAMESPACE/egressnetworkpolicies ---- ==== 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. This limits the duration of the call, regardless of any activity or inactivity. |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-oapi-v1-namespaces-namespace-egressnetworkpolicies-name]] === Update a EgressNetworkPolicy in a namespace Replace the specified EgressNetworkPolicy ==== HTTP request ---- PUT /oapi/v1/namespaces/$NAMESPACE/egressnetworkpolicies/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json' { ""kind"": ""EgressNetworkPolicy"", ""apiVersion"": ""v1"", ... } ---- ==== Curl request ---- $ curl -k \\ -X PUT \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json' \\ https://$ENDPOINT/oapi/v1/namespaces/$NAMESPACE/egressnetworkpolicies/$NAME <<'EOF' { ""kind"": ""EgressNetworkPolicy"", ""apiVersion"": ""v1"", ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1.EgressNetworkPolicy |=== ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the EgressNetworkPolicy |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.EgressNetworkPolicy |201 Created|v1.EgressNetworkPolicy |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Patch-oapi-v1-namespaces-namespace-egressnetworkpolicies-name]] === Patch a EgressNetworkPolicy in a namespace Partially update the specified EgressNetworkPolicy ==== HTTP request ---- PATCH /oapi/v1/namespaces/$NAMESPACE/egressnetworkpolicies/$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/oapi/v1/namespaces/$NAMESPACE/egressnetworkpolicies/$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 EgressNetworkPolicy |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.EgressNetworkPolicy |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-oapi-v1-namespaces-namespace-egressnetworkpolicies-name]] === Delete a EgressNetworkPolicy in a namespace Delete an EgressNetworkPolicy ==== HTTP request ---- DELETE /oapi/v1/namespaces/$NAMESPACE/egressnetworkpolicies/$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/oapi/v1/namespaces/$NAMESPACE/egressnetworkpolicies/$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 EgressNetworkPolicy |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-oapi-v1-namespaces-namespace-egressnetworkpolicies]] === Delete all EgressNetworkPolicies in a namespace Delete collection of EgressNetworkPolicy ==== HTTP request ---- DELETE /oapi/v1/namespaces/$NAMESPACE/egressnetworkpolicies 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/oapi/v1/namespaces/$NAMESPACE/egressnetworkpolicies ---- ==== 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. This limits the duration of the call, regardless of any activity or inactivity. |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 ",12448,False,2471.5700352491217,median "//===--- TypeCheckProtocolInference.cpp - Associated Type Inference -------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This file implements semantic analysis for protocols, in particular, checking // whether a given type conforms to a given protocol. //===----------------------------------------------------------------------===// #include ""TypeCheckProtocol.h"" #include ""DerivedConformances.h"" #include ""TypeChecker.h"" #include ""swift/AST/Decl.h"" #include ""swift/AST/GenericSignature.h"" #include ""swift/AST/ProtocolConformance.h"" #include ""swift/AST/SubstitutionMap.h"" #include ""swift/AST/TypeMatcher.h"" #include ""swift/AST/Types.h"" #include ""swift/Basic/Defer.h"" #include ""swift/ClangImporter/ClangModule.h"" #include ""llvm/ADT/TinyPtrVector.h"" #define DEBUG_TYPE ""Associated type inference"" #include ""llvm/Support/Debug.h"" using namespace swift; void InferredAssociatedTypesByWitness::dump() const { dump(llvm::errs(), 0); } void InferredAssociatedTypesByWitness::dump(llvm::raw_ostream &out, unsigned indent) const { out << ""\\n""; out.indent(indent) << ""(""; if (Witness) { Witness->dumpRef(out); } for (const auto &inferred : Inferred) { out << ""\\n""; out.indent(indent + 2); out << inferred.first->getName() << "" := "" << inferred.second.getString(); } for (const auto &inferred : NonViable) { out << ""\\n""; out.indent(indent + 2); out << std::get<0>(inferred)->getName() << "" := "" << std::get<1>(inferred).getString(); auto type = std::get<2>(inferred).getRequirement(); out << "" [failed constraint "" << type.getString() << ""]""; } out << "")""; } void InferredTypeWitnessesSolution::dump() const { llvm::errs() << ""Type Witnesses:\\n""; for (auto &typeWitness : TypeWitnesses) { llvm::errs() << "" "" << typeWitness.first->getName() << "" := ""; typeWitness.second.first->print(llvm::errs()); llvm::errs() << "" value "" << typeWitness.second.second << '\\n'; } llvm::errs() << ""Value Witnesses:\\n""; for (unsigned i : indices(ValueWitnesses)) { auto &valueWitness = ValueWitnesses[i]; llvm::errs() << i << "": "" << (Decl*)valueWitness.first << ' ' << valueWitness.first->getBaseName() << '\\n'; valueWitness.first->getDeclContext()->dumpContext(); llvm::errs() << "" for "" << (Decl*)valueWitness.second << ' ' << valueWitness.second->getBaseName() << '\\n'; valueWitness.second->getDeclContext()->dumpContext(); } } namespace { void dumpInferredAssociatedTypesByWitnesses( const InferredAssociatedTypesByWitnesses &inferred, llvm::raw_ostream &out, unsigned indent) { for (const auto &value : inferred) { value.dump(out, indent); } } void dumpInferredAssociatedTypesByWitnesses( const InferredAssociatedTypesByWitnesses &inferred) LLVM_ATTRIBUTE_USED; void dumpInferredAssociatedTypesByWitnesses( const InferredAssociatedTypesByWitnesses &inferred) { dumpInferredAssociatedTypesByWitnesses(inferred, llvm::errs(), 0); } void dumpInferredAssociatedTypes(const InferredAssociatedTypes &inferred, llvm::raw_ostream &out, unsigned indent) { for (const auto &value : inferred) { out << ""\\n""; out.indent(indent) << ""(""; value.first->dumpRef(out); dumpInferredAssociatedTypesByWitnesses(value.second, out, indent + 2); out << "")""; } out << ""\\n""; } void dumpInferredAssociatedTypes( const InferredAssociatedTypes &inferred) LLVM_ATTRIBUTE_USED; void dumpInferredAssociatedTypes(const InferredAssociatedTypes &inferred) { dumpInferredAssociatedTypes(inferred, llvm::errs(), 0); } } AssociatedTypeInference::AssociatedTypeInference( TypeChecker &tc, NormalProtocolConformance *conformance) : tc(tc), conformance(conformance), proto(conformance->getProtocol()), dc(conformance->getDeclContext()), adoptee(conformance->getType()) { } static bool associatedTypesAreSameEquivalenceClass(AssociatedTypeDecl *a, AssociatedTypeDecl *b) { if (a == b) return true; // TODO: Do a proper equivalence check here by looking for some relationship // between a and b's protocols. In practice today, it's unlikely that // two same-named associated types can currently be independent, since we // don't have anything like `@implements(P.foo)` to rename witnesses (and // we still fall back to name lookup for witnesses in more cases than we // should). if (a->getName() == b->getName()) return true; return false; } InferredAssociatedTypesByWitnesses AssociatedTypeInference::inferTypeWitnessesViaValueWitnesses( ConformanceChecker &checker, const llvm::SetVector &allUnresolved, ValueDecl *req) { // Conformances constructed by the ClangImporter should have explicit type // witnesses already. if (isa(conformance->getDeclContext()->getModuleScopeContext())) { llvm::errs() << ""Cannot infer associated types for imported conformance:\\n""; conformance->getType().dump(llvm::errs()); for (auto assocTypeDecl : allUnresolved) assocTypeDecl->dump(llvm::errs()); abort(); } InferredAssociatedTypesByWitnesses result; auto isExtensionUsableForInference = [&](ExtensionDecl *extension) -> bool { // Assume unconstrained concrete extensions we found witnesses in are // always viable. if (!extension->getExtendedType()->isAnyExistentialType()) { // TODO: When constrained extensions are a thing, we'll need an ""is // as specialized as"" kind of check here. return !extension->isConstrainedExtension(); } // The extension may not have a generic signature set up yet, as a // recursion breaker, in which case we can't yet confidently reject its // witnesses. if (!extension->getGenericSignature()) return true; // The condition here is a bit more fickle than // `isExtensionApplied`. That check would prematurely reject // extensions like `P where AssocType == T` if we're relying on a // default implementation inside the extension to infer `AssocType == T` // in the first place. Only check conformances on the `Self` type, // because those have to be explicitly declared on the type somewhere // so won't be affected by whatever answer inference comes up with. auto selfTy = extension->getSelfInterfaceType(); for (const Requirement &reqt : extension->getGenericSignature()->getRequirements()) { switch (reqt.getKind()) { case RequirementKind::Conformance: case RequirementKind::Superclass: // FIXME: This is the wrong check if (selfTy->isEqual(reqt.getFirstType()) && !tc.isSubtypeOf(conformance->getType(),reqt.getSecondType(), dc)) return false; break; case RequirementKind::Layout: case RequirementKind::SameType: break; } } return true; }; auto typeInContext = conformance->getDeclContext()->mapTypeIntoContext(conformance->getType()); for (auto witness : checker.lookupValueWitnesses(req, /*ignoringNames=*/nullptr)) { DEBUG(llvm::dbgs() << ""Inferring associated types from decl:\\n""; witness->dump(llvm::dbgs())); // If the potential witness came from an extension, and our `Self` // type can't use it regardless of what associated types we end up // inferring, skip the witness. if (auto extension = dyn_cast(witness->getDeclContext())) if (!isExtensionUsableForInference(extension)) continue; // Try to resolve the type witness via this value witness. auto witnessResult = inferTypeWitnessesViaValueWitness(req, witness); // Filter out duplicated inferred types as well as inferred types // that don't meet the requirements placed on the associated type. llvm::DenseSet> known; for (unsigned i = 0; i < witnessResult.Inferred.size(); /*nothing*/) { #define REJECT {\\ witnessResult.Inferred.erase(witnessResult.Inferred.begin() + i); \\ continue; \\ } auto &result = witnessResult.Inferred[i]; DEBUG(llvm::dbgs() << ""Considering whether "" << result.first->getName() << "" can infer to:\\n""; result.second->dump(llvm::dbgs())); // Filter out errors. if (result.second->hasError()) { DEBUG(llvm::dbgs() << ""-- has error type\\n""); REJECT; } // Filter out duplicates. if (!known.insert({result.first, result.second->getCanonicalType()}) .second) { DEBUG(llvm::dbgs() << ""-- duplicate\\n""); REJECT; } // Filter out circular possibilities, e.g. that // AssocType == S.AssocType or // AssocType == Foo. bool canInferFromOtherAssociatedType = false; bool containsTautologicalType = result.second.findIf([&](Type t) -> bool { auto dmt = t->getAs(); if (!dmt) return false; if (!associatedTypesAreSameEquivalenceClass(dmt->getAssocType(), result.first)) return false; if (!dmt->getBase()->isEqual(typeInContext)) return false; // If this associated type is same-typed to another associated type // on `Self`, then it may still be an interesting candidate if we find // an answer for that other type. auto witnessContext = witness->getDeclContext(); if (witnessContext->getAsProtocolExtensionContext() && witnessContext->getGenericSignatureOfContext()) { auto selfTy = witnessContext->getSelfInterfaceType(); auto selfAssocTy = DependentMemberType::get(selfTy, dmt->getAssocType()); for (auto &reqt : witnessContext->getGenericSignatureOfContext() ->getRequirements()) { switch (reqt.getKind()) { case RequirementKind::Conformance: case RequirementKind::Superclass: case RequirementKind::Layout: break; case RequirementKind::SameType: Type other; if (reqt.getFirstType()->isEqual(selfAssocTy)) { other = reqt.getSecondType(); } else if (reqt.getSecondType()->isEqual(selfAssocTy)) { other = reqt.getFirstType(); } else { break; } if (auto otherAssoc = other->getAs()) { if (otherAssoc->getBase()->isEqual(selfTy)) { auto otherDMT = DependentMemberType::get(dmt->getBase(), otherAssoc->getAssocType()); // We may be able to infer one associated type from the // other. result.second = result.second.transform([&](Type t) -> Type{ if (t->isEqual(dmt)) return otherDMT; return t; }); canInferFromOtherAssociatedType = true; DEBUG(llvm::dbgs() << ""++ we can same-type to:\\n""; result.second->dump(llvm::dbgs())); return false; } } break; } } } return true; }); if (containsTautologicalType) { DEBUG(llvm::dbgs() << ""-- tautological\\n""); REJECT; } // Check that the type witness doesn't contradict an // explicitly-given type witness. If it does contradict, throw out the // witness completely. if (!allUnresolved.count(result.first)) { auto existingWitness = conformance->getTypeWitness(result.first, nullptr); existingWitness = dc->mapTypeIntoContext(existingWitness); // If the deduced type contains an irreducible // DependentMemberType, that indicates a dependency // on another associated type we haven't deduced, // so we can't tell whether there's a contradiction // yet. auto newWitness = result.second->getCanonicalType(); if (!newWitness->hasTypeParameter() && !newWitness->hasDependentMember() && !existingWitness->isEqual(newWitness)) { DEBUG(llvm::dbgs() << ""** contradicts explicit type witness, "" ""rejecting inference from this decl\\n""); goto next_witness; } } // If we same-typed to another unresolved associated type, we won't // be able to check conformances yet. if (!canInferFromOtherAssociatedType) { // Check that the type witness meets the // requirements on the associated type. if (auto failed = checkTypeWitness(tc, dc, proto, result.first, result.second)) { witnessResult.NonViable.push_back( std::make_tuple(result.first,result.second,failed)); DEBUG(llvm::dbgs() << ""-- doesn't fulfill requirements\\n""); REJECT; } } DEBUG(llvm::dbgs() << ""++ seems legit\\n""); ++i; } #undef REJECT // If no inferred types remain, skip this witness. if (witnessResult.Inferred.empty() && witnessResult.NonViable.empty()) continue; // If there were any non-viable inferred associated types, don't // infer anything from this witness. if (!witnessResult.NonViable.empty()) witnessResult.Inferred.clear(); result.push_back(std::move(witnessResult)); next_witness:; } return result; } InferredAssociatedTypes AssociatedTypeInference::inferTypeWitnessesViaValueWitnesses( ConformanceChecker &checker, const llvm::SetVector &assocTypes) { InferredAssociatedTypes result; for (auto member : proto->getMembers()) { auto req = dyn_cast(member); if (!req) continue; // Infer type witnesses for associated types. if (auto assocType = dyn_cast(req)) { // If this is not one of the associated types we are trying to infer, // just continue. if (assocTypes.count(assocType) == 0) continue; auto reqInferred = inferTypeWitnessesViaAssociatedType(checker, assocTypes, assocType); if (!reqInferred.empty()) result.push_back({req, std::move(reqInferred)}); continue; } // Skip operator requirements, because they match globally and // therefore tend to cause deduction mismatches. // FIXME: If we had some basic sanity checking of Self, we might be able to // use these. if (auto func = dyn_cast(req)) { if (func->isOperator() || func->isAccessor()) continue; } // Validate the requirement. tc.validateDecl(req); if (req->isInvalid() || !req->hasValidSignature()) continue; // Check whether any of the associated types we care about are // referenced in this value requirement. bool anyAssocTypeMatches = false; for (auto assocType : checker.getReferencedAssociatedTypes(req)) { if (assocTypes.count(assocType) > 0) { anyAssocTypeMatches = true; break; } } // We cannot deduce anything from the witnesses of this // requirement; skip it. if (!anyAssocTypeMatches) continue; // Infer associated types from the potential value witnesses for // this requirement. auto reqInferred = inferTypeWitnessesViaValueWitnesses(checker, assocTypes, req); if (reqInferred.empty()) continue; result.push_back({req, std::move(reqInferred)}); } return result; } /// Map error types back to their original types. static Type mapErrorTypeToOriginal(Type type) { if (auto errorType = type->getAs()) { if (auto originalType = errorType->getOriginalType()) return originalType.transform(mapErrorTypeToOriginal); } return type; } /// Produce the type when matching a witness. static Type getWitnessTypeForMatching(TypeChecker &tc, NormalProtocolConformance *conformance, ValueDecl *witness) { if (!witness->hasInterfaceType()) tc.validateDecl(witness); if (witness->isInvalid() || !witness->hasValidSignature()) return Type(); if (!witness->getDeclContext()->isTypeContext()) { // FIXME: Could we infer from 'Self' to make these work? return witness->getInterfaceType(); } // Retrieve the set of substitutions to be applied to the witness. Type model = conformance->getDeclContext()->mapTypeIntoContext(conformance->getType()); TypeSubstitutionMap substitutions = model->getMemberSubstitutions(witness); Type type = witness->getInterfaceType()->getReferenceStorageReferent(); if (substitutions.empty()) return type; // Strip off the requirements of a generic function type. // FIXME: This doesn't actually break recursion when substitution // looks for an inferred type witness, but it makes it far less // common, because most of the recursion involves the requirements // of the generic type. if (auto genericFn = type->getAs()) { type = FunctionType::get(genericFn->getInput(), genericFn->getResult(), genericFn->getExtInfo()); } // Remap associated types that reference other protocols into this // protocol. auto proto = conformance->getProtocol(); type = type.transformRec([proto](TypeBase *type) -> Optional { if (auto depMemTy = dyn_cast(type)) { if (depMemTy->getAssocType() && depMemTy->getAssocType()->getProtocol() != proto) { for (auto member : proto->lookupDirect(depMemTy->getName())) { if (auto assocType = dyn_cast(member)) { auto origProto = depMemTy->getAssocType()->getProtocol(); if (proto->inheritsFrom(origProto)) return Type(DependentMemberType::get(depMemTy->getBase(), assocType)); } } } } return None; }); ModuleDecl *module = conformance->getDeclContext()->getParentModule(); auto resultType = type.subst(QueryTypeSubstitutionMap{substitutions}, LookUpConformanceInModule(module), SubstFlags::UseErrorType); if (!resultType->hasError()) return resultType; // Map error types with original types *back* to the original, dependent type. return resultType.transform(mapErrorTypeToOriginal); } /// Remove the 'self' type from the given type, if it's a method type. static Type removeSelfParam(ValueDecl *value, Type type) { if (auto func = dyn_cast(value)) { if (func->getDeclContext()->isTypeContext()) return type->castTo()->getResult(); } return type; } InferredAssociatedTypesByWitnesses AssociatedTypeInference::inferTypeWitnessesViaAssociatedType( ConformanceChecker &checker, const llvm::SetVector &allUnresolved, AssociatedTypeDecl *assocType) { auto &tc = checker.TC; // Form the default name _Default_Foo. Identifier defaultName; { SmallString<32> defaultNameStr; { llvm::raw_svector_ostream out(defaultNameStr); out << ""_Default_""; out << assocType->getName().str(); } defaultName = tc.Context.getIdentifier(defaultNameStr); } // Look for types with the given default name that have appropriate // @_implements attributes. InferredAssociatedTypesByWitnesses result; auto lookupOptions = defaultMemberTypeLookupOptions; lookupOptions -= NameLookupFlags::PerformConformanceCheck; for (auto candidate : tc.lookupMember(dc, adoptee, defaultName, lookupOptions)) { // We want type declarations. auto typeDecl = dyn_cast(candidate.getValueDecl()); if (!typeDecl || isa(typeDecl)) continue; // We only find these within a protocol extension. auto defaultProto = typeDecl->getDeclContext() ->getAsProtocolOrProtocolExtensionContext(); if (!defaultProto) continue; // Determine the witness type. Type witnessType = getWitnessTypeForMatching(tc, conformance, typeDecl); if (!witnessType) continue; if (auto witnessMetaType = witnessType->getAs()) witnessType = witnessMetaType->getInstanceType(); else continue; // Add this result. InferredAssociatedTypesByWitness inferred; inferred.Witness = typeDecl; inferred.Inferred.push_back({assocType, witnessType}); result.push_back(std::move(inferred)); } return result; } /// Attempt to resolve a type witness via a specific value witness. InferredAssociatedTypesByWitness AssociatedTypeInference::inferTypeWitnessesViaValueWitness(ValueDecl *req, ValueDecl *witness) { InferredAssociatedTypesByWitness inferred; inferred.Witness = witness; // Compute the requirement and witness types we'll use for matching. Type fullWitnessType = getWitnessTypeForMatching(tc, conformance, witness); if (!fullWitnessType) { return inferred; } auto setup = [&]() -> std::tuple, Type, Type> { fullWitnessType = removeSelfParam(witness, fullWitnessType); return std::make_tuple( None, removeSelfParam(req, req->getInterfaceType()), fullWitnessType); }; /// Visits a requirement type to match it to a potential witness for /// the purpose of deducing associated types. /// /// The visitor argument is the witness type. If there are any /// obvious conflicts between the structure of the two types, /// returns true. The conflict checking is fairly conservative, only /// considering rough structure. class MatchVisitor : public TypeMatcher { NormalProtocolConformance *Conformance; InferredAssociatedTypesByWitness &Inferred; public: MatchVisitor(NormalProtocolConformance *conformance, InferredAssociatedTypesByWitness &inferred) : Conformance(conformance), Inferred(inferred) { } /// Structural mismatches imply that the witness cannot match. bool mismatch(TypeBase *firstType, TypeBase *secondType, Type sugaredFirstType) { // If either type hit an error, don't stop yet. if (firstType->hasError() || secondType->hasError()) return true; // FIXME: Check whether one of the types is dependent? return false; } /// Deduce associated types from dependent member types in the witness. bool mismatch(DependentMemberType *firstDepMember, TypeBase *secondType, Type sugaredFirstType) { // If the second type is an error, don't look at it further. if (secondType->hasError()) return true; auto proto = Conformance->getProtocol(); if (auto assocType = getReferencedAssocTypeOfProtocol(firstDepMember, proto)) { Inferred.Inferred.push_back({assocType, secondType}); } // Always allow mismatches here. return true; } /// FIXME: Recheck the type of Self against the second type? bool mismatch(GenericTypeParamType *selfParamType, TypeBase *secondType, Type sugaredFirstType) { return true; } }; // Match a requirement and witness type. MatchVisitor matchVisitor(conformance, inferred); auto matchTypes = [&](Type reqType, Type witnessType) -> Optional { if (!matchVisitor.match(reqType, witnessType)) { return RequirementMatch(witness, MatchKind::TypeConflict, fullWitnessType); } return None; }; // Finalization of the checking is pretty trivial; just bundle up a // result we can look at. auto finalize = [&](bool anyRenaming, ArrayRef) -> RequirementMatch { return RequirementMatch(witness, anyRenaming ? MatchKind::RenamedMatch : MatchKind::ExactMatch, fullWitnessType); }; // Match the witness. If we don't succeed, throw away the inference // information. // FIXME: A renamed match might be useful to retain for the failure case. if (matchWitness(tc, dc, req, witness, setup, matchTypes, finalize) .Kind != MatchKind::ExactMatch) { inferred.Inferred.clear(); } return inferred; } /// Find an associated type declarations that provides a default definition. static AssociatedTypeDecl *findDefaultedAssociatedType( TypeChecker &tc, AssociatedTypeDecl *assocType) { // If this associated type has a default, we're done. tc.validateDecl(assocType); if (!assocType->getDefaultDefinitionLoc().isNull()) return assocType; // Look at overridden associated types. SmallPtrSet canonicalTypes; SmallVector results; for (auto overridden : assocType->getOverriddenDecls()) { auto overriddenDefault = findDefaultedAssociatedType(tc, overridden); if (!overriddenDefault) continue; Type overriddenType = overriddenDefault->getDefaultDefinitionLoc().getType(); assert(overriddenType); if (!overriddenType) continue; CanType key = overriddenType->mapTypeOutOfContext()->getCanonicalType(); if (canonicalTypes.insert(key).second) results.push_back(overriddenDefault); } // If there was a single result, return it. // FIXME: We could find *all* of the non-covered, defaulted associated types. return results.size() == 1 ? results.front() : nullptr; } Type AssociatedTypeInference::computeFixedTypeWitness( AssociatedTypeDecl *assocType) { // Look at all of the inherited protocols to determine whether they // require a fixed type for this associated type. Type dependentType = assocType->getDeclaredInterfaceType(); Type resultType; for (auto conformedProto : adoptee->getAnyNominal()->getAllProtocols()) { if (!conformedProto->inheritsFrom(assocType->getProtocol())) continue; auto genericSig = conformedProto->getGenericSignature(); if (!genericSig) return Type(); Type concreteType = genericSig->getConcreteType(dependentType); if (!concreteType) continue; if (!resultType) { resultType = concreteType; continue; } // FIXME: Bailing out on ambiguity. if (!resultType->isEqual(concreteType)) return Type(); } return resultType; } Type AssociatedTypeInference::computeDefaultTypeWitness( AssociatedTypeDecl *assocType) { // Go find a default definition. auto defaultedAssocType = findDefaultedAssociatedType(tc, assocType); if (!defaultedAssocType) return Type(); // If we don't have a default definition, we're done. auto selfType = proto->getSelfInterfaceType(); // Create a set of type substitutions for all known associated type. // FIXME: Base this on dependent types rather than archetypes? TypeSubstitutionMap substitutions; substitutions[proto->mapTypeIntoContext(selfType) ->castTo()] = dc->mapTypeIntoContext(adoptee); for (auto assocType : proto->getAssociatedTypeMembers()) { auto archetype = proto->mapTypeIntoContext( assocType->getDeclaredInterfaceType()) ->getAs(); if (!archetype) continue; if (conformance->hasTypeWitness(assocType)) { substitutions[archetype] = dc->mapTypeIntoContext( conformance->getTypeWitness(assocType, nullptr)); } else { auto known = typeWitnesses.begin(assocType); if (known != typeWitnesses.end()) substitutions[archetype] = known->first; else substitutions[archetype] = ErrorType::get(archetype); } } Type defaultType = defaultedAssocType->getDefaultDefinitionLoc().getType(); // FIXME: Circularity if (!defaultType) return Type(); // If the associated type came from a different protocol, map it into our // protocol's context. if (defaultedAssocType->getDeclContext() != proto) { defaultType = defaultType->mapTypeOutOfContext(); defaultType = proto->mapTypeIntoContext(defaultType); if (!defaultType) return Type(); } defaultType = defaultType.subst( QueryTypeSubstitutionMap{substitutions}, LookUpConformanceInModule(dc->getParentModule())); if (!defaultType) return Type(); if (auto failed = checkTypeWitness(tc, dc, proto, assocType, defaultType)) { // Record the failure, if we haven't seen one already. if (!failedDefaultedAssocType) { failedDefaultedAssocType = defaultedAssocType; failedDefaultedWitness = defaultType; failedDefaultedResult = failed; } return Type(); } return defaultType; } Type AssociatedTypeInference::computeDerivedTypeWitness( AssociatedTypeDecl *assocType) { if (adoptee->hasError()) return Type(); // Can we derive conformances for this protocol and adoptee? NominalTypeDecl *derivingTypeDecl = adoptee->getAnyNominal(); if (!DerivedConformance::derivesProtocolConformance(tc, derivingTypeDecl, proto)) return Type(); // Try to derive the type witness. Type derivedType = tc.deriveTypeWitness(dc, derivingTypeDecl, assocType); if (!derivedType) return Type(); // Make sure that the derived type is sane. if (checkTypeWitness(tc, dc, proto, assocType, derivedType)) { /// FIXME: Diagnose based on this. failedDerivedAssocType = assocType; failedDerivedWitness = derivedType; return Type(); } return derivedType; } Type AssociatedTypeInference::computeAbstractTypeWitness( AssociatedTypeDecl *assocType, bool allowDerived) { // We don't have a type witness for this associated type, so go // looking for more options. if (Type concreteType = computeFixedTypeWitness(assocType)) return concreteType; // If we can form a default type, do so. if (Type defaultType = computeDefaultTypeWitness(assocType)) return defaultType; // If we can derive a type witness, do so. if (allowDerived) { if (Type derivedType = computeDerivedTypeWitness(assocType)) return derivedType; } // If there is a generic parameter of the named type, use that. if (auto gpList = dc->getGenericParamsOfContext()) { GenericTypeParamDecl *foundGP = nullptr; for (auto gp : *gpList) { if (gp->getName() == assocType->getName()) { foundGP = gp; break; } } if (foundGP) return dc->mapTypeIntoContext(foundGP->getDeclaredInterfaceType()); } return Type(); } Type AssociatedTypeInference::substCurrentTypeWitnesses(Type type) { // Local function that folds dependent member types with non-dependent // bases into actual member references. std::function foldDependentMemberTypes; llvm::DenseSet recursionCheck; foldDependentMemberTypes = [&](Type type) -> Type { if (auto depMemTy = type->getAs()) { auto baseTy = depMemTy->getBase().transform(foldDependentMemberTypes); if (baseTy.isNull() || baseTy->hasTypeParameter()) return nullptr; auto assocType = depMemTy->getAssocType(); if (!assocType) return nullptr; if (!recursionCheck.insert(assocType).second) return nullptr; SWIFT_DEFER { recursionCheck.erase(assocType); }; // Try to substitute into the base type. if (Type result = depMemTy->substBaseType(dc->getParentModule(), baseTy)){ return result; } // If that failed, check whether it's because of the conformance we're // evaluating. auto localConformance = tc.conformsToProtocol( baseTy, assocType->getProtocol(), dc, ConformanceCheckFlags::SkipConditionalRequirements); if (!localConformance || localConformance->isAbstract() || (localConformance->getConcrete()->getRootNormalConformance() != conformance)) { return nullptr; } // Find the tentative type witness for this associated type. auto known = typeWitnesses.begin(assocType); if (known == typeWitnesses.end()) return nullptr; return known->first.transform(foldDependentMemberTypes); } // The presence of a generic type parameter indicates that we // cannot use this type binding. if (type->is()) { return nullptr; } return type; }; return type.transform(foldDependentMemberTypes); } /// ""Sanitize"" requirements for conformance checking, removing any requirements /// that unnecessarily refer to associated types of other protocols. static void sanitizeProtocolRequirements( ProtocolDecl *proto, ArrayRef requirements, SmallVectorImpl &sanitized) { std::function sanitizeType; sanitizeType = [&](Type outerType) { return outerType.transformRec([&] (TypeBase *type) -> Optional { if (auto depMemTy = dyn_cast(type)) { if (!depMemTy->getAssocType() || depMemTy->getAssocType()->getProtocol() != proto) { for (auto member : proto->lookupDirect(depMemTy->getName())) { if (auto assocType = dyn_cast(member)) { return Type(DependentMemberType::get( sanitizeType(depMemTy->getBase()), assocType)); } } if (depMemTy->getBase()->is()) return Type(); } } return None; }); }; for (const auto &req : requirements) { switch (req.getKind()) { case RequirementKind::Conformance: case RequirementKind::SameType: case RequirementKind::Superclass: { Type firstType = sanitizeType(req.getFirstType()); Type secondType = sanitizeType(req.getSecondType()); if (firstType && secondType) { sanitized.push_back({req.getKind(), firstType, secondType}); } break; } case RequirementKind::Layout: { Type firstType = sanitizeType(req.getFirstType()); if (firstType) { sanitized.push_back({req.getKind(), firstType, req.getLayoutConstraint()}); } break; } } } } SubstOptions AssociatedTypeInference::getSubstOptionsWithCurrentTypeWitnesses() { SubstOptions options(None); AssociatedTypeInference *self = this; options.getTentativeTypeWitness = [self](const NormalProtocolConformance *conformance, AssociatedTypeDecl *assocType) -> TypeBase * { auto thisProto = self->conformance->getProtocol(); if (conformance == self->conformance) { // Okay: we have the associated type we need. } else if (conformance->getType()->isEqual( self->conformance->getType()) && thisProto->inheritsFrom(conformance->getProtocol())) { // Find an associated type with the same name in the given // protocol. AssociatedTypeDecl *foundAssocType = nullptr; for (auto result : thisProto->lookupDirect( assocType->getName(), /*ignoreNewExtensions=*/true)) { foundAssocType = dyn_cast(result); if (foundAssocType) break; } if (!foundAssocType) return nullptr; assocType = foundAssocType; } else { return nullptr; } Type type = self->typeWitnesses.begin(assocType)->first; return type->mapTypeOutOfContext().getPointer(); }; return options; } bool AssociatedTypeInference::checkCurrentTypeWitnesses( const SmallVectorImpl> &valueWitnesses) { // Fold the dependent member types within this type. for (auto assocType : proto->getAssociatedTypeMembers()) { if (conformance->hasTypeWitness(assocType)) continue; // If the type binding does not have a type parameter, there's nothing // to do. auto known = typeWitnesses.begin(assocType); assert(known != typeWitnesses.end()); if (!known->first->hasTypeParameter() && !known->first->hasDependentMember()) continue; Type replaced = substCurrentTypeWitnesses(known->first); if (replaced.isNull()) return true; known->first = replaced; } // If we don't have a requirement signature for this protocol, bail out. // FIXME: We should never get to this point. Or we should always fail. if (!proto->isRequirementSignatureComputed()) return false; // Check any same-type requirements in the protocol's requirement signature. SubstOptions options = getSubstOptionsWithCurrentTypeWitnesses(); auto typeInContext = dc->mapTypeIntoContext(adoptee); auto substitutions = SubstitutionMap::getProtocolSubstitutions( proto, typeInContext, ProtocolConformanceRef(conformance)); SmallVector sanitizedRequirements; sanitizeProtocolRequirements(proto, proto->getRequirementSignature(), sanitizedRequirements); auto result = tc.checkGenericArguments(dc, SourceLoc(), SourceLoc(), typeInContext, { proto->getProtocolSelfType() }, sanitizedRequirements, QuerySubstitutionMap{substitutions}, TypeChecker::LookUpConformance(tc, dc), nullptr, None, nullptr, options); switch (result) { case RequirementCheckResult::Failure: case RequirementCheckResult::UnsatisfiedDependency: return true; case RequirementCheckResult::Success: case RequirementCheckResult::SubstitutionFailure: break; } // Check for extra requirements in the constrained extensions that supply // defaults. SmallPtrSet checkedExtensions; for (const auto &valueWitness : valueWitnesses) { // We only perform this additional checking for default associated types. if (!isa(valueWitness.first)) continue; auto witness = valueWitness.second; if (!witness) continue; auto ext = dyn_cast(witness->getDeclContext()); if (!ext) continue; if (!ext->isConstrainedExtension()) continue; if (!checkedExtensions.insert(ext).second) continue; if (checkConstrainedExtension(ext)) return true; } return false; } bool AssociatedTypeInference::checkConstrainedExtension(ExtensionDecl *ext) { auto typeInContext = dc->mapTypeIntoContext(adoptee); auto subs = typeInContext->getContextSubstitutions(ext); SubstOptions options = getSubstOptionsWithCurrentTypeWitnesses(); switch (tc.checkGenericArguments( dc, SourceLoc(), SourceLoc(), adoptee, ext->getGenericSignature()->getGenericParams(), ext->getGenericSignature()->getRequirements(), QueryTypeSubstitutionMap{subs}, LookUpConformanceInModule(ext->getModuleContext()), nullptr, ConformanceCheckFlags::InExpression, nullptr, options)) { case RequirementCheckResult::Success: case RequirementCheckResult::SubstitutionFailure: return false; case RequirementCheckResult::Failure: case RequirementCheckResult::UnsatisfiedDependency: return true; } } void AssociatedTypeInference::findSolutions( ArrayRef unresolvedAssocTypes, SmallVectorImpl &solutions) { SmallVector nonViableSolutions; SmallVector, 4> valueWitnesses; findSolutionsRec(unresolvedAssocTypes, solutions, nonViableSolutions, valueWitnesses, 0, 0, 0); } void AssociatedTypeInference::findSolutionsRec( ArrayRef unresolvedAssocTypes, SmallVectorImpl &solutions, SmallVectorImpl &nonViableSolutions, SmallVector, 4> &valueWitnesses, unsigned numTypeWitnesses, unsigned numValueWitnessesInProtocolExtensions, unsigned reqDepth) { typedef decltype(typeWitnesses)::ScopeTy TypeWitnessesScope; // If we hit the last requirement, record and check this solution. if (reqDepth == inferred.size()) { // Introduce a hash table scope; we may add type witnesses here. TypeWitnessesScope typeWitnessesScope(typeWitnesses); // Check for completeness of the solution for (auto assocType : unresolvedAssocTypes) { // Local function to record a missing associated type. auto recordMissing = [&] { if (!missingTypeWitness) missingTypeWitness = assocType; }; auto typeWitness = typeWitnesses.begin(assocType); if (typeWitness != typeWitnesses.end()) { // The solution contains an error. if (typeWitness->first->hasError()) { recordMissing(); return; } continue; } // Try to compute the type without the aid of a specific potential // witness. if (Type type = computeAbstractTypeWitness(assocType, /*allowDerived=*/true)) { if (type->hasError()) { recordMissing(); return; } typeWitnesses.insert(assocType, {type, reqDepth}); continue; } // The solution is incomplete. recordMissing(); return; } /// Check the current set of type witnesses. bool invalid = checkCurrentTypeWitnesses(valueWitnesses); // Determine whether there is already a solution with the same // bindings. for (const auto &solution : solutions) { bool sameSolution = true; for (const auto &existingTypeWitness : solution.TypeWitnesses) { auto typeWitness = typeWitnesses.begin(existingTypeWitness.first); if (!typeWitness->first->isEqual(existingTypeWitness.second.first)) { sameSolution = false; break; } } // We found the same solution. There is no point in recording // a new one. if (sameSolution) return; } auto &solutionList = invalid ? nonViableSolutions : solutions; solutionList.push_back(InferredTypeWitnessesSolution()); auto &solution = solutionList.back(); // Copy the type witnesses. for (auto assocType : unresolvedAssocTypes) { auto typeWitness = typeWitnesses.begin(assocType); solution.TypeWitnesses.insert({assocType, *typeWitness}); } // Copy the value witnesses. solution.ValueWitnesses = valueWitnesses; solution.NumValueWitnessesInProtocolExtensions = numValueWitnessesInProtocolExtensions; // We're done recording the solution. return; } // Iterate over the potential witnesses for this requirement, // looking for solutions involving each one. const auto &inferredReq = inferred[reqDepth]; for (const auto &witnessReq : inferredReq.second) { llvm::SaveAndRestore savedNumTypeWitnesses(numTypeWitnesses); // If we inferred a type witness via a default, try both with and without // the default. if (isa(inferredReq.first)) { // Recurse without considering this type. valueWitnesses.push_back({inferredReq.first, nullptr}); findSolutionsRec(unresolvedAssocTypes, solutions, nonViableSolutions, valueWitnesses, numTypeWitnesses, numValueWitnessesInProtocolExtensions, reqDepth + 1); valueWitnesses.pop_back(); ++numTypeWitnesses; for (const auto &typeWitness : witnessReq.Inferred) { auto known = typeWitnesses.begin(typeWitness.first); if (known != typeWitnesses.end()) continue; // Enter a new scope for the type witnesses hash table. TypeWitnessesScope typeWitnessesScope(typeWitnesses); typeWitnesses.insert(typeWitness.first, {typeWitness.second, reqDepth}); valueWitnesses.push_back({inferredReq.first, witnessReq.Witness}); findSolutionsRec(unresolvedAssocTypes, solutions, nonViableSolutions, valueWitnesses, numTypeWitnesses, numValueWitnessesInProtocolExtensions, reqDepth + 1); valueWitnesses.pop_back(); } continue; } // Enter a new scope for the type witnesses hash table. TypeWitnessesScope typeWitnessesScope(typeWitnesses); // Record this value witness, popping it when we exit the current scope. valueWitnesses.push_back({inferredReq.first, witnessReq.Witness}); if (!isa(inferredReq.first) && witnessReq.Witness->getDeclContext()->getAsProtocolExtensionContext()) ++numValueWitnessesInProtocolExtensions; SWIFT_DEFER { if (!isa(inferredReq.first) && witnessReq.Witness->getDeclContext()->getAsProtocolExtensionContext()) --numValueWitnessesInProtocolExtensions; valueWitnesses.pop_back(); }; // Introduce each of the type witnesses into the hash table. bool failed = false; for (const auto &typeWitness : witnessReq.Inferred) { // If we've seen a type witness for this associated type that // conflicts, there is no solution. auto known = typeWitnesses.begin(typeWitness.first); if (known != typeWitnesses.end()) { // Don't overwrite a defaulted associated type witness. if (isa(valueWitnesses[known->second].second)) continue; // If witnesses for two different requirements inferred the same // type, we're okay. if (known->first->isEqual(typeWitness.second)) continue; // If one has a type parameter remaining but the other does not, // drop the one with the type parameter. if ((known->first->hasTypeParameter() || known->first->hasDependentMember()) != (typeWitness.second->hasTypeParameter() || typeWitness.second->hasDependentMember())) { if (typeWitness.second->hasTypeParameter() || typeWitness.second->hasDependentMember()) continue; known->first = typeWitness.second; continue; } if (!typeWitnessConflict || numTypeWitnesses > numTypeWitnessesBeforeConflict) { typeWitnessConflict = {typeWitness.first, typeWitness.second, inferredReq.first, witnessReq.Witness, known->first, valueWitnesses[known->second].first, valueWitnesses[known->second].second}; numTypeWitnessesBeforeConflict = numTypeWitnesses; } failed = true; break; } // Record the type witness. ++numTypeWitnesses; typeWitnesses.insert(typeWitness.first, {typeWitness.second, reqDepth}); } if (failed) continue; // Recurse findSolutionsRec(unresolvedAssocTypes, solutions, nonViableSolutions, valueWitnesses, numTypeWitnesses, numValueWitnessesInProtocolExtensions, reqDepth + 1); } } static Comparison compareDeclsForInference(TypeChecker &TC, DeclContext *DC, ValueDecl *decl1, ValueDecl *decl2) { // TC.compareDeclarations assumes that it's comparing two decls that // apply equally well to a call site. We haven't yet inferred the // associated types for a type, so the ranking algorithm used by // compareDeclarations to score protocol extensions is inappropriate, // since we may have potential witnesses from extensions with mutually // exclusive associated type constraints, and compareDeclarations will // consider these unordered since neither extension's generic signature // is a superset of the other. // If one of the declarations is null, it implies that we're working with // a skipped associated type default. Prefer that default to something // that came from a protocol extension. if (!decl1 || !decl2) { if (!decl1 && decl2 && decl2->getDeclContext()->getAsProtocolExtensionContext()) return Comparison::Worse; if (!decl2 && decl1 && decl1->getDeclContext()->getAsProtocolExtensionContext()) return Comparison::Better; return Comparison::Unordered; } // If the witnesses come from the same decl context, score normally. auto dc1 = decl1->getDeclContext(); auto dc2 = decl2->getDeclContext(); if (dc1 == dc2) return TC.compareDeclarations(DC, decl1, decl2); auto isProtocolExt1 = (bool)dc1->getAsProtocolExtensionContext(); auto isProtocolExt2 = (bool)dc2->getAsProtocolExtensionContext(); // If one witness comes from a protocol extension, favor the one // from a concrete context. if (isProtocolExt1 != isProtocolExt2) { return isProtocolExt1 ? Comparison::Worse : Comparison::Better; } // If both witnesses came from concrete contexts, score normally. // Associated type inference shouldn't impact the result. // FIXME: It could, if someone constrained to ConcreteType.AssocType... if (!isProtocolExt1) return TC.compareDeclarations(DC, decl1, decl2); // Compare protocol extensions by which protocols they require Self to // conform to. If one extension requires a superset of the other's // constraints, it wins. auto sig1 = dc1->getGenericSignatureOfContext(); auto sig2 = dc2->getGenericSignatureOfContext(); // FIXME: Extensions sometimes have null generic signatures while // checking the standard library... if (!sig1 || !sig2) return TC.compareDeclarations(DC, decl1, decl2); auto selfParam = GenericTypeParamType::get(0, 0, TC.Context); // Collect the protocols required by extension 1. Type class1; SmallPtrSet protos1; std::function insertProtocol; insertProtocol = [&](ProtocolDecl *p) { if (!protos1.insert(p).second) return; for (auto parent : p->getInheritedProtocols()) insertProtocol(parent); }; for (auto &reqt : sig1->getRequirements()) { if (!reqt.getFirstType()->isEqual(selfParam)) continue; switch (reqt.getKind()) { case RequirementKind::Conformance: { auto *proto = reqt.getSecondType()->castTo()->getDecl(); insertProtocol(proto); break; } case RequirementKind::Superclass: class1 = reqt.getSecondType(); break; case RequirementKind::SameType: case RequirementKind::Layout: break; } } // Compare with the protocols required by extension 2. Type class2; SmallPtrSet protos2; bool protos2AreSubsetOf1 = true; std::function removeProtocol; removeProtocol = [&](ProtocolDecl *p) { if (!protos2.insert(p).second) return; protos2AreSubsetOf1 &= protos1.erase(p); for (auto parent : p->getInheritedProtocols()) removeProtocol(parent); }; for (auto &reqt : sig2->getRequirements()) { if (!reqt.getFirstType()->isEqual(selfParam)) continue; switch (reqt.getKind()) { case RequirementKind::Conformance: { auto *proto = reqt.getSecondType()->castTo()->getDecl(); removeProtocol(proto); break; } case RequirementKind::Superclass: class2 = reqt.getSecondType(); break; case RequirementKind::SameType: case RequirementKind::Layout: break; } } auto isClassConstraintAsStrict = [&](Type t1, Type t2) -> bool { if (!t1) return !t2; if (!t2) return true; return TC.isSubclassOf(t1, t2, DC); }; bool protos1AreSubsetOf2 = protos1.empty(); // If the second extension requires strictly more protocols than the // first, it's better. if (protos1AreSubsetOf2 > protos2AreSubsetOf1 && isClassConstraintAsStrict(class2, class1)) { return Comparison::Worse; // If the first extension requires strictly more protocols than the // second, it's better. } else if (protos2AreSubsetOf1 > protos1AreSubsetOf2 && isClassConstraintAsStrict(class1, class2)) { return Comparison::Better; } // If they require the same set of protocols, or non-overlapping // sets, judge them normally. return TC.compareDeclarations(DC, decl1, decl2); } bool AssociatedTypeInference::isBetterSolution( const InferredTypeWitnessesSolution &first, const InferredTypeWitnessesSolution &second) { assert(first.ValueWitnesses.size() == second.ValueWitnesses.size()); bool firstBetter = false; bool secondBetter = false; for (unsigned i = 0, n = first.ValueWitnesses.size(); i != n; ++i) { assert(first.ValueWitnesses[i].first == second.ValueWitnesses[i].first); auto firstWitness = first.ValueWitnesses[i].second; auto secondWitness = second.ValueWitnesses[i].second; if (firstWitness == secondWitness) continue; switch (compareDeclsForInference(tc, dc, firstWitness, secondWitness)) { case Comparison::Better: if (secondBetter) return false; firstBetter = true; break; case Comparison::Worse: if (firstBetter) return false; secondBetter = true; break; case Comparison::Unordered: break; } } return firstBetter; } bool AssociatedTypeInference::findBestSolution( SmallVectorImpl &solutions) { if (solutions.empty()) return true; if (solutions.size() == 1) return false; // Find the smallest number of value witnesses found in protocol extensions. // FIXME: This is a silly heuristic that should go away. unsigned bestNumValueWitnessesInProtocolExtensions = solutions.front().NumValueWitnessesInProtocolExtensions; for (unsigned i = 1, n = solutions.size(); i != n; ++i) { bestNumValueWitnessesInProtocolExtensions = std::min(bestNumValueWitnessesInProtocolExtensions, solutions[i].NumValueWitnessesInProtocolExtensions); } // Erase any solutions with more value witnesses in protocol // extensions than the best. solutions.erase( std::remove_if(solutions.begin(), solutions.end(), [&](const InferredTypeWitnessesSolution &solution) { return solution.NumValueWitnessesInProtocolExtensions > bestNumValueWitnessesInProtocolExtensions; }), solutions.end()); // If we're down to one solution, success! if (solutions.size() == 1) return false; // Find a solution that's at least as good as the solutions that follow it. unsigned bestIdx = 0; for (unsigned i = 1, n = solutions.size(); i != n; ++i) { if (isBetterSolution(solutions[i], solutions[bestIdx])) bestIdx = i; } // Make sure that solution is better than any of the other solutions. bool ambiguous = false; for (unsigned i = 1, n = solutions.size(); i != n; ++i) { if (i != bestIdx && !isBetterSolution(solutions[bestIdx], solutions[i])) { ambiguous = true; break; } } // If the result was ambiguous, fail. if (ambiguous) { assert(solutions.size() != 1 && ""should have succeeded somewhere above?""); return true; } // Keep the best solution, erasing all others. if (bestIdx != 0) solutions[0] = std::move(solutions[bestIdx]); solutions.erase(solutions.begin() + 1, solutions.end()); return false; } namespace { /// A failed type witness binding. struct FailedTypeWitness { /// The value requirement that triggered inference. ValueDecl *Requirement; /// The corresponding value witness from which the type witness /// was inferred. ValueDecl *Witness; /// The actual type witness that was inferred. Type TypeWitness; /// The failed type witness result. CheckTypeWitnessResult Result; }; } // end anonymous namespace bool AssociatedTypeInference::diagnoseNoSolutions( ArrayRef unresolvedAssocTypes, ConformanceChecker &checker) { // If a defaulted type witness failed, diagnose it. if (failedDefaultedAssocType) { auto failedDefaultedAssocType = this->failedDefaultedAssocType; auto failedDefaultedWitness = this->failedDefaultedWitness; auto failedDefaultedResult = this->failedDefaultedResult; checker.diagnoseOrDefer(failedDefaultedAssocType, true, [failedDefaultedAssocType, failedDefaultedWitness, failedDefaultedResult](NormalProtocolConformance *conformance) { auto proto = conformance->getProtocol(); auto &diags = proto->getASTContext().Diags; diags.diagnose(failedDefaultedAssocType, diag::default_associated_type_req_fail, failedDefaultedWitness, failedDefaultedAssocType->getFullName(), proto->getDeclaredType(), failedDefaultedResult.getRequirement(), failedDefaultedResult.isConformanceRequirement()); }); return true; } // Form a mapping from associated type declarations to failed type // witnesses. llvm::DenseMap> failedTypeWitnesses; for (const auto &inferredReq : inferred) { for (const auto &inferredWitness : inferredReq.second) { for (const auto &nonViable : inferredWitness.NonViable) { failedTypeWitnesses[std::get<0>(nonViable)] .push_back({inferredReq.first, inferredWitness.Witness, std::get<1>(nonViable), std::get<2>(nonViable)}); } } } // Local function to attempt to diagnose potential type witnesses // that failed requirements. auto tryDiagnoseTypeWitness = [&](AssociatedTypeDecl *assocType) -> bool { auto known = failedTypeWitnesses.find(assocType); if (known == failedTypeWitnesses.end()) return false; auto failedSet = std::move(known->second); checker.diagnoseOrDefer(assocType, true, [assocType, failedSet](NormalProtocolConformance *conformance) { auto proto = conformance->getProtocol(); auto &diags = proto->getASTContext().Diags; diags.diagnose(assocType, diag::bad_associated_type_deduction, assocType->getFullName(), proto->getFullName()); for (const auto &failed : failedSet) { diags.diagnose(failed.Witness, diag::associated_type_deduction_witness_failed, failed.Requirement->getFullName(), failed.TypeWitness, failed.Result.getRequirement(), failed.Result.isConformanceRequirement()); } }); return true; }; // Try to diagnose the first missing type witness we encountered. if (missingTypeWitness && tryDiagnoseTypeWitness(missingTypeWitness)) return true; // Failing that, try to diagnose any type witness that failed a // requirement. for (auto assocType : unresolvedAssocTypes) { if (tryDiagnoseTypeWitness(assocType)) return true; } // If we saw a conflict, complain about it. if (typeWitnessConflict) { auto typeWitnessConflict = this->typeWitnessConflict; checker.diagnoseOrDefer(typeWitnessConflict->AssocType, true, [typeWitnessConflict](NormalProtocolConformance *conformance) { auto &diags = conformance->getDeclContext()->getASTContext().Diags; diags.diagnose(typeWitnessConflict->AssocType, diag::ambiguous_associated_type_deduction, typeWitnessConflict->AssocType->getFullName(), typeWitnessConflict->FirstType, typeWitnessConflict->SecondType); diags.diagnose(typeWitnessConflict->FirstWitness, diag::associated_type_deduction_witness, typeWitnessConflict->FirstRequirement->getFullName(), typeWitnessConflict->FirstType); diags.diagnose(typeWitnessConflict->SecondWitness, diag::associated_type_deduction_witness, typeWitnessConflict->SecondRequirement->getFullName(), typeWitnessConflict->SecondType); }); return true; } return false; } bool AssociatedTypeInference::diagnoseAmbiguousSolutions( ArrayRef unresolvedAssocTypes, ConformanceChecker &checker, SmallVectorImpl &solutions) { for (auto assocType : unresolvedAssocTypes) { // Find two types that conflict. auto &firstSolution = solutions.front(); // Local function to retrieve the value witness for the current associated // type within the given solution. auto getValueWitness = [&](InferredTypeWitnessesSolution &solution) { unsigned witnessIdx = solution.TypeWitnesses[assocType].second; if (witnessIdx < solution.ValueWitnesses.size()) return solution.ValueWitnesses[witnessIdx]; return std::pair(nullptr, nullptr); }; Type firstType = firstSolution.TypeWitnesses[assocType].first; // Extract the value witness used to deduce this associated type, if any. auto firstMatch = getValueWitness(firstSolution); Type secondType; std::pair secondMatch; for (auto &solution : solutions) { Type typeWitness = solution.TypeWitnesses[assocType].first; if (!typeWitness->isEqual(firstType)) { secondType = typeWitness; secondMatch = getValueWitness(solution); break; } } if (!secondType) continue; // We found an ambiguity. diagnose it. checker.diagnoseOrDefer(assocType, true, [assocType, firstType, firstMatch, secondType, secondMatch]( NormalProtocolConformance *conformance) { auto &diags = assocType->getASTContext().Diags; diags.diagnose(assocType, diag::ambiguous_associated_type_deduction, assocType->getFullName(), firstType, secondType); auto diagnoseWitness = [&](std::pair match, Type type){ // If we have a requirement/witness pair, diagnose it. if (match.first && match.second) { diags.diagnose(match.second, diag::associated_type_deduction_witness, match.first->getFullName(), type); return; } // Otherwise, we have a default. diags.diagnose(assocType, diag::associated_type_deduction_default, type) .highlight(assocType->getDefaultDefinitionLoc().getSourceRange()); }; diagnoseWitness(firstMatch, firstType); diagnoseWitness(secondMatch, secondType); }); return true; } return false; } auto AssociatedTypeInference::solve(ConformanceChecker &checker) -> Optional { // Track when we are checking type witnesses. ProtocolConformanceState initialState = conformance->getState(); conformance->setState(ProtocolConformanceState::CheckingTypeWitnesses); SWIFT_DEFER { conformance->setState(initialState); }; // Try to resolve type witnesses via name lookup. llvm::SetVector unresolvedAssocTypes; for (auto assocType : proto->getAssociatedTypeMembers()) { // If we already have a type witness, do nothing. if (conformance->hasTypeWitness(assocType)) continue; // Try to resolve this type witness via name lookup, which is the // most direct mechanism, overriding all others. switch (checker.resolveTypeWitnessViaLookup(assocType)) { case ResolveWitnessResult::Success: // Success. Move on to the next. continue; case ResolveWitnessResult::ExplicitFailed: continue; case ResolveWitnessResult::Missing: // Note that we haven't resolved this associated type yet. unresolvedAssocTypes.insert(assocType); break; } } // Result variable to use for returns so that we get NRVO. Optional result; result = { }; // If we resolved everything, we're done. if (unresolvedAssocTypes.empty()) return result; // Infer potential type witnesses from value witnesses. inferred = inferTypeWitnessesViaValueWitnesses(checker, unresolvedAssocTypes); DEBUG(llvm::dbgs() << ""Candidates for inference:\\n""; dumpInferredAssociatedTypes(inferred)); // Compute the set of solutions. SmallVector solutions; findSolutions(unresolvedAssocTypes.getArrayRef(), solutions); // Go make sure that type declarations that would act as witnesses // did not get injected while we were performing checks above. This // can happen when two associated types in different protocols have // the same name, and validating a declaration (above) triggers the // type-witness generation for that second protocol, introducing a // new type declaration. // FIXME: This is ridiculous. for (auto assocType : unresolvedAssocTypes) { switch (checker.resolveTypeWitnessViaLookup(assocType)) { case ResolveWitnessResult::Success: case ResolveWitnessResult::ExplicitFailed: // A declaration that can become a witness has shown up. Go // perform the resolution again now that we have more // information. return solve(checker); case ResolveWitnessResult::Missing: // The type witness is still missing. Keep going. break; } } // Find the best solution. if (!findBestSolution(solutions)) { assert(solutions.size() == 1 && ""Not a unique best solution?""); // Form the resulting solution. auto &typeWitnesses = solutions.front().TypeWitnesses; for (auto assocType : unresolvedAssocTypes) { assert(typeWitnesses.count(assocType) == 1 && ""missing witness""); auto replacement = typeWitnesses[assocType].first; // FIXME: We can end up here with dependent types that were not folded // away for some reason. if (replacement->hasDependentMember()) return None; if (replacement->hasArchetype()) replacement = replacement->mapTypeOutOfContext(); result->push_back({assocType, replacement}); } return result; } // Diagnose the complete lack of solutions. if (solutions.empty() && diagnoseNoSolutions(unresolvedAssocTypes.getArrayRef(), checker)) return None; // Diagnose ambiguous solutions. if (!solutions.empty() && diagnoseAmbiguousSolutions(unresolvedAssocTypes.getArrayRef(), checker, solutions)) return None; // Save the missing type witnesses for later diagnosis. checker.GlobalMissingWitnesses.insert(unresolvedAssocTypes.begin(), unresolvedAssocTypes.end()); return None; } void ConformanceChecker::resolveTypeWitnesses() { SWIFT_DEFER { // Resolution attempts to have the witnesses be correct by construction, but // this isn't guaranteed, so let's double check. ensureRequirementsAreSatisfied(/*failUnsubstituted=*/false); }; // Attempt to infer associated type witnesses. AssociatedTypeInference inference(TC, Conformance); if (auto inferred = inference.solve(*this)) { for (const auto &inferredWitness : *inferred) { recordTypeWitness(inferredWitness.first, inferredWitness.second, /*typeDecl=*/nullptr, /*performRedeclarationCheck=*/true); } ensureRequirementsAreSatisfied(/*failUnsubstituted=*/false); return; } // Conformance failed. Record errors for each of the witnesses. Conformance->setInvalid(); // We're going to produce an error below. Mark each unresolved // associated type witness as erroneous. for (auto assocType : Proto->getAssociatedTypeMembers()) { // If we already have a type witness, do nothing. if (Conformance->hasTypeWitness(assocType)) continue; recordTypeWitness(assocType, ErrorType::get(TC.Context), nullptr, true); } } void ConformanceChecker::resolveSingleTypeWitness( AssociatedTypeDecl *assocType) { // Ensure we diagnose if the witness is missing. SWIFT_DEFER { diagnoseMissingWitnesses(MissingWitnessDiagnosisKind::ErrorFixIt); }; switch (resolveTypeWitnessViaLookup(assocType)) { case ResolveWitnessResult::Success: case ResolveWitnessResult::ExplicitFailed: // We resolved this type witness one way or another. return; case ResolveWitnessResult::Missing: // The type witness is still missing. Resolve all of the type witnesses. resolveTypeWitnesses(); return; } } void ConformanceChecker::resolveSingleWitness(ValueDecl *requirement) { assert(!isa(requirement) && ""Not a value witness""); assert(!Conformance->hasWitness(requirement) && ""Already resolved""); // Note that we're resolving this witness. assert(ResolvingWitnesses.count(requirement) == 0 && ""Currently resolving""); ResolvingWitnesses.insert(requirement); SWIFT_DEFER { ResolvingWitnesses.erase(requirement); }; // Make sure we've validated the requirement. if (!requirement->hasInterfaceType()) TC.validateDecl(requirement); if (requirement->isInvalid() || !requirement->hasValidSignature()) { Conformance->setInvalid(); return; } if (!requirement->isProtocolRequirement()) return; // Resolve all associated types before trying to resolve this witness. resolveTypeWitnesses(); // If any of the type witnesses was erroneous, don't bother to check // this value witness: it will fail. for (auto assocType : getReferencedAssociatedTypes(requirement)) { if (Conformance->getTypeWitness(assocType, nullptr)->hasError()) { Conformance->setInvalid(); return; } } // Try to resolve the witness via explicit definitions. switch (resolveWitnessViaLookup(requirement)) { case ResolveWitnessResult::Success: return; case ResolveWitnessResult::ExplicitFailed: Conformance->setInvalid(); recordInvalidWitness(requirement); return; case ResolveWitnessResult::Missing: // Continue trying below. break; } // Try to resolve the witness via derivation. switch (resolveWitnessViaDerivation(requirement)) { case ResolveWitnessResult::Success: return; case ResolveWitnessResult::ExplicitFailed: Conformance->setInvalid(); recordInvalidWitness(requirement); return; case ResolveWitnessResult::Missing: // Continue trying below. break; } // Try to resolve the witness via defaults. switch (resolveWitnessViaDefault(requirement)) { case ResolveWitnessResult::Success: return; case ResolveWitnessResult::ExplicitFailed: Conformance->setInvalid(); recordInvalidWitness(requirement); return; case ResolveWitnessResult::Missing: llvm_unreachable(""Should have failed""); break; } } ",16185,True,2951.5778551293843,median "//============================================================================== // Copyright (c) 2015-2021 Advanced Micro Devices, Inc. All rights reserved. /// @author AMD Developer Tools Team /// @file /// @brief PublicCounterDefinitions for GL GFX103 for testing. //============================================================================== // *** Note, this is an auto-generated file. Do not edit. Execute PublicCounterCompiler to rebuild. #include ""auto_generated/gpu_perf_api_unit_tests/counters/public_derived_counters_gl_gfx103.h"" const GpaCounterDesc kGlGfx103PublicCounters[kGlGfx103PublicCounterCount] = { {""GPUTime"", ""Timing"", ""Time this API command took to execute on the GPU in nanoseconds from the time the previous command reached the bottom of the pipeline (BOP) to the time this command reaches the bottom of the pipeline (BOP). Does not include time that draw calls are processed in parallel."", ""0,TS_FREQ,/,(1000000000),*"", 1, kGpaDataTypeFloat64, kGpaUsageTypeNanoseconds, {0xcbd338f2, 0xde6c, 0x7b14, {0x92, 0xad, 0xba, 0x72, 0x4c, 0xa2, 0xe5, 0x01}}}, {""GPUBusy"", ""Timing"", ""The percentage of time the GPU command processor was busy."", ""0,1,/,(100),*,(100),min"", 2, kGpaDataTypeFloat64, kGpaUsageTypePercentage, {0xb1ba5363, 0x1abc, 0xfe66, {0x2f, 0xdd, 0x1f, 0xe6, 0xee, 0x89, 0x89, 0xa0}}}, {""GPUBusyCycles"", ""Timing"", ""Number of GPU cycles that the GPU command processor was busy."", ""0"", 1, kGpaDataTypeFloat64, kGpaUsageTypeCycles, {0x451cb045, 0x23af, 0xac44, {0x46, 0x03, 0xd5, 0x83, 0x2f, 0xa0, 0x41, 0xd9}}}, {""PSBusy"", ""Timing"", ""The percentage of time the ShaderUnit has pixel shader work to do."", ""(0),0,1,ifnotzero,(0),2,3,ifnotzero,(0),4,5,ifnotzero,(0),6,7,ifnotzero,max4,8,/,(100),*,(100),min"", 9, kGpaDataTypeFloat64, kGpaUsageTypePercentage, {0x7e772beb, 0xd82c, 0xbd9a, {0xae, 0xd0, 0xfe, 0x50, 0x4d, 0x41, 0x6c, 0xe5}}}, {""PSBusyCycles"", ""Timing"", ""Number of GPU cycles that the ShaderUnit has pixel shader work to do."", ""(0),0,1,ifnotzero,(0),2,3,ifnotzero,(0),4,5,ifnotzero,(0),6,7,ifnotzero,max4"", 8, kGpaDataTypeFloat64, kGpaUsageTypeCycles, {0xb58bea04, 0xce8e, 0x2984, {0x80, 0xf4, 0x8a, 0xba, 0x7d, 0x4c, 0x81, 0x7b}}}, {""PSTime"", ""Timing"", ""Time pixel shaders are busy in nanoseconds."", ""(0),1,2,ifnotzero,(0),3,4,ifnotzero,(0),5,6,ifnotzero,(0),7,8,ifnotzero,max4,9,/,(1),min,0,TS_FREQ,/,(1000000000),*,*"", 10, kGpaDataTypeFloat64, kGpaUsageTypeNanoseconds, {0xedca7694, 0x7416, 0xe8a6, {0x0c, 0x5a, 0x63, 0xa5, 0xad, 0x5f, 0x3d, 0x74}}}, {""CSBusy"", ""Timing"", ""The percentage of time the ShaderUnit has compute shader work to do."", ""(0),0,1,ifnotzero,(0),2,3,ifnotzero,max,4,/,(100),*,(100),min"", 5, kGpaDataTypeFloat64, kGpaUsageTypePercentage, {0x493fdd90, 0x8d2b, 0xa055, {0x5e, 0x4e, 0x2d, 0x29, 0xc3, 0x39, 0x6b, 0x8c}}}, {""CSBusyCycles"", ""Timing"", ""Number of GPU cycles that the ShaderUnit has compute shader work to do."", ""(0),0,1,ifnotzero,(0),2,3,ifnotzero,max"", 4, kGpaDataTypeFloat64, kGpaUsageTypeCycles, {0x39bcf1b8, 0xf6b2, 0x4c37, {0xf9, 0xaf, 0x0a, 0x2b, 0xb5, 0x95, 0x12, 0xf9}}}, {""CSTime"", ""Timing"", ""Time compute shaders are busy in nanoseconds."", ""(0),1,2,ifnotzero,(0),3,4,ifnotzero,max,5,/,(1),min,0,TS_FREQ,/,(1000000000),*,*"", 6, kGpaDataTypeFloat64, kGpaUsageTypeNanoseconds, {0xdbc24916, 0xecb2, 0x7eef, {0x8d, 0x63, 0x7a, 0xfa, 0xda, 0xaa, 0xb6, 0xbc}}}, {""PrimitiveAssemblyBusy"", ""Timing"", ""The percentage of GPUTime that primitive assembly (clipping and culling) is busy. High values may be caused by having many small primitives; mid to low values may indicate pixel shader or output buffer bottleneck."", ""0,1,-,2,3,+,4,+,5,(2),*,+,SU_CLOCKS_PRIM,*,-,NUM_PRIM_PIPES,/,(0),max,6,/,(100),*,(100),min"", 7, kGpaDataTypeFloat64, kGpaUsageTypePercentage, {0x54ac5640, 0xc4d7, 0x95e2, {0x20, 0xe0, 0x6a, 0x9f, 0xdf, 0xc0, 0x73, 0x33}}}, {""PrimitiveAssemblyBusyCycles"", ""Timing"", ""Number of GPU cycles the primitive assembly (clipping and culling) is busy. High values may be caused by having many small primitives; mid to low values may indicate pixel shader or output buffer bottleneck."", ""0,1,-,2,3,+,4,+,5,(2),*,+,SU_CLOCKS_PRIM,*,-,NUM_PRIM_PIPES,/,(0),max"", 6, kGpaDataTypeFloat64, kGpaUsageTypeCycles, {0x99777f2d, 0x9626, 0xc78a, {0xa9, 0x7c, 0xc4, 0x50, 0x5e, 0xba, 0x1e, 0x5f}}}, {""CulledPrims"", ""PrimitiveAssembly"", ""The number of culled primitives. Typical reasons include scissor, the primitive having zero area, and back or front face culling."", ""0,1,+,2,+,3,+,4,+"", 5, kGpaDataTypeFloat64, kGpaUsageTypeItems, {0x589bdf55, 0x9192, 0x280a, {0x41, 0xc3, 0x58, 0x4b, 0xc9, 0x4f, 0x25, 0x62}}}, {""ClippedPrims"", ""PrimitiveAssembly"", ""The number of primitives that required one or more clipping operations due to intersecting the view volume or user clip planes."", ""0"", 1, kGpaDataTypeFloat64, kGpaUsageTypeItems, {0x5ef6f9d5, 0x155e, 0x5baa, {0x16, 0x3f, 0x83, 0x59, 0xd9, 0xea, 0x9b, 0xbf}}}, {""PAStalledOnRasterizer"", ""PrimitiveAssembly"", ""Percentage of GPUTime that primitive assembly waits for rasterization to be ready to accept data. This roughly indicates for what percentage of time the pipeline is bottlenecked by pixel operations."", ""0,NUM_PRIM_PIPES,/,1,/,(100),*"", 2, kGpaDataTypeFloat64, kGpaUsageTypePercentage, {0x6f9f416b, 0x53c1, 0x0457, {0xf8, 0x8c, 0x7b, 0x6b, 0xa8, 0x97, 0x39, 0x74}}}, {""PAStalledOnRasterizerCycles"", ""PrimitiveAssembly"", ""Number of GPU cycles the primitive assembly waits for rasterization to be ready to accept data. Indicates the number of GPU cycles the pipeline is bottlenecked by pixel operations."", ""0,NUM_PRIM_PIPES,/"", 1, kGpaDataTypeFloat64, kGpaUsageTypeCycles, {0x7a8c492a, 0xc566, 0x9328, {0x68, 0x05, 0x76, 0x0d, 0xbf, 0xf5, 0xc0, 0xf2}}}, {""PSPixelsOut"", ""PixelShader"", ""Pixels exported from shader to color buffers. Does not include killed or alpha tested pixels; if there are multiple render targets, each render target receives one export, so this will be 2 for 1 pixel written to two RTs."", ""0,1,2,3,sum4"", 4, kGpaDataTypeFloat64, kGpaUsageTypeItems, {0x24cba16c, 0xbaa6, 0x6ecd, {0x95, 0xad, 0x92, 0xec, 0xb1, 0x33, 0x8d, 0xa1}}}, {""PSExportStalls"", ""PixelShader"", ""Pixel shader output stalls. Percentage of GPUBusy. Should be zero for PS or further upstream limited cases; if not zero, indicates a bottleneck in late Z testing or in the color buffer."", ""0,1,2,3,max4,4,/,NUM_SHADER_ARRAYS,/,(100),*"", 5, kGpaDataTypeFloat64, kGpaUsageTypePercentage, {0x9b4f466c, 0xff97, 0x22bb, {0x55, 0x7d, 0x84, 0xd3, 0xc4, 0xc5, 0x18, 0x95}}}, {""PSExportStallsCycles"", ""PixelShader"", ""Number of GPU cycles the pixel shader output stalls. Should be zero for PS or further upstream limited cases; if not zero, indicates a bottleneck in late Z testing or in the color buffer."", ""0,1,max,2,max,3,max,NUM_SHADER_ARRAYS,/"", 4, kGpaDataTypeFloat64, kGpaUsageTypeCycles, {0x47c72aad, 0x64e6, 0x0864, {0xd5, 0x33, 0xd8, 0xe0, 0xbc, 0x27, 0xc1, 0x56}}}, {""CSThreadGroups"", ""ComputeShader"", ""Total number of thread groups."", ""0,1,+"", 2, kGpaDataTypeFloat64, kGpaUsageTypeItems, {0x8ce3fc80, 0x56b2, 0x97f9, {0x8e, 0x70, 0x2e, 0x8c, 0x74, 0x7c, 0xea, 0x68}}}, {""CSWavefronts"", ""ComputeShader"", ""The total number of wavefronts used for the CS."", ""0"", 1, kGpaDataTypeFloat64, kGpaUsageTypeItems, {0x42379c6e, 0x369b, 0xc237, {0x8b, 0x25, 0xcd, 0xb9, 0xcd, 0xc6, 0x5c, 0x4d}}}, {""CSThreads"", ""ComputeShader"", ""The number of CS threads processed by the hardware."", ""0"", 1, kGpaDataTypeFloat64, kGpaUsageTypeItems, {0x7a648013, 0x6eac, 0x2665, {0xac, 0x36, 0x13, 0xc6, 0xf4, 0xac, 0x9c, 0x26}}}, {""CSThreadGroupSize"", ""ComputeShader"", ""The number of CS threads within each thread group."", ""(0),0,1,2,+,/,1,2,+,ifnotzero"", 3, kGpaDataTypeFloat64, kGpaUsageTypeItems, {0x8c65008a, 0x9957, 0x7ca6, {0x41, 0x99, 0xf6, 0xfe, 0x94, 0x04, 0x20, 0xf6}}}, {""CSMemUnitBusy"", ""ComputeShader"", ""The percentage of GPUTime the memory unit is active. The result includes the stall time (MemUnitStalled). This is measured with all extra fetches and writes and any cache or memory effects taken into account. Value range: 0% to 100% (fetch-bound)."", ""(0),0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,max16,16,/,NUM_SHADER_ARRAYS,/,(100),*,17,18,+,ifnotzero"", 19, kGpaDataTypeFloat64, kGpaUsageTypePercentage, {0x42ab96e1, 0x0a24, 0x96c8, {0xc4, 0xff, 0x09, 0x8f, 0xa2, 0x67, 0xd7, 0x8e}}}, {""CSMemUnitBusyCycles"", ""ComputeShader"", ""Number of GPU cycles the memory unit is active. The result includes the stall time (MemUnitStalled). This is measured with all extra fetches and writes and any cache or memory effects taken into account."", ""(0),0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,max16,NUM_SHADER_ARRAYS,/,16,17,+,ifnotzero"", 18, kGpaDataTypeFloat64, kGpaUsageTypeCycles, {0x39d5687f, 0xc727, 0x7c0c, {0xaf, 0x82, 0xbb, 0x71, 0x1d, 0x38, 0x97, 0xed}}}, {""CSMemUnitStalled"", ""ComputeShader"", ""The percentage of GPUTime the memory unit is stalled. Try reducing the number or size of fetches and writes if possible. Value range: 0% (optimal) to 100% (bad)."", ""(0),0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,max16,16,/,NUM_SHADER_ARRAYS,/,(100),*,17,18,+,ifnotzero"", 19, kGpaDataTypeFloat64, kGpaUsageTypePercentage, {0xf18e8679, 0x1511, 0xd533, {0xd9, 0xee, 0x43, 0x65, 0x19, 0x7f, 0x7d, 0x0c}}}, {""CSMemUnitStalledCycles"", ""ComputeShader"", ""Number of GPU cycles the memory unit is stalled. Try reducing the number or size of fetches and writes if possible."", ""(0),0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,max16,NUM_SHADER_ARRAYS,/,16,17,+,ifnotzero"", 18, kGpaDataTypeFloat64, kGpaUsageTypeCycles, {0x51991c84, 0xed2b, 0xbf31, {0xc4, 0xab, 0x8f, 0x8e, 0x9e, 0xb8, 0xf2, 0x9f}}}, {""CSWriteUnitStalled"", ""ComputeShader"", ""The percentage of GPUTime the write unit is stalled."", ""(0),0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,max16,16,/,(100),*,17,18,+,ifnotzero"", 19, kGpaDataTypeFloat64, kGpaUsageTypePercentage, {0x55118f7a, 0x8f92, 0x726f, {0x78, 0xc6, 0x40, 0x7f, 0x68, 0x9a, 0x2e, 0xb4}}}, {""CSWriteUnitStalledCycles"", ""ComputeShader"", ""Number of GPU cycles the write unit is stalled."", ""(0),0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,max16,16,17,+,ifnotzero"", 18, kGpaDataTypeFloat64, kGpaUsageTypeCycles, {0xbe164c60, 0x5e48, 0xacac, {0x96, 0x22, 0x29, 0x61, 0x6d, 0x09, 0xaa, 0x9a}}}, {""CSGDSInsts"", ""ComputeShader"", ""The average number of GDS read or GDS write instructions executed per work item (affected by flow control)."", ""(0),0,1,/,1,ifnotzero"", 2, kGpaDataTypeFloat64, kGpaUsageTypeItems, {0x2a867f3e, 0x4a37, 0xad16, {0x55, 0xd1, 0xf0, 0x3d, 0x74, 0x70, 0x78, 0x19}}}, {""CSLDSInsts"", ""ComputeShader"", ""The average number of LDS read/write instructions executed per work-item (affected by flow control)."", ""(0),0,1,/,1,ifnotzero"", 2, kGpaDataTypeFloat64, kGpaUsageTypeItems, {0x61b0b351, 0x7e06, 0xef8e, {0xa8, 0xe0, 0x7a, 0x9e, 0x32, 0x00, 0xa8, 0x36}}}, {""CSALUStalledByLDS"", ""ComputeShader"", ""The percentage of GPUTime ALU units are stalled by the LDS input queue being full or the output queue being not ready. If there are LDS bank conflicts, reduce them. Otherwise, try reducing the number of LDS accesses if possible. Value range: 0% (optimal) to 100% (bad)."", ""(0),0,1,/,2,/,NUM_SHADER_ENGINES,/,(100),*,1,ifnotzero"", 3, kGpaDataTypeFloat64, kGpaUsageTypePercentage, {0x6dc4f1c2, 0xbad0, 0xc9ff, {0x15, 0x6e, 0x88, 0x3b, 0x31, 0x9a, 0x75, 0x2a}}}, {""CSALUStalledByLDSCycles"", ""ComputeShader"", ""Number of GPU cycles the ALU units are stalled by the LDS input queue being full or the output queue being not ready. If there are LDS bank conflicts, reduce them. Otherwise, try reducing the number of LDS accesses if possible."", ""0,NUM_SHADER_ENGINES,/"", 1, kGpaDataTypeFloat64, kGpaUsageTypeCycles, {0x8f3d5f25, 0x2159, 0x0374, {0xfa, 0xfe, 0xe2, 0x6a, 0x77, 0x99, 0xb6, 0xc8}}}, {""CSLDSBankConflict"", ""ComputeShader"", ""The percentage of GPUTime LDS is stalled by bank conflicts. Value range: 0% (optimal) to 100% (bad)."", ""0,1,/,NUM_SIMDS,/,(100),*"", 2, kGpaDataTypeFloat64, kGpaUsageTypePercentage, {0x1065ee10, 0x2e41, 0xea41, {0x1e, 0xb3, 0xb6, 0x1b, 0x49, 0x17, 0x52, 0xf4}}}, {""CSLDSBankConflictCycles"", ""ComputeShader"", ""Number of GPU cycles the LDS is stalled by bank conflicts. Value range: 0 (optimal) to GPUBusyCycles (bad)."", ""0,NUM_SIMDS,/"", 1, kGpaDataTypeFloat64, kGpaUsageTypeCycles, {0x1fd1adf3, 0xc51e, 0x94fd, {0x08, 0x3e, 0xc4, 0x82, 0xa0, 0xa0, 0x80, 0x9e}}}, {""TexUnitBusy"", ""Timing"", ""The percentage of GPUTime the texture unit is active. This is measured with all extra fetches and any cache or memory effects taken into account."", ""0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,max16,16,/,NUM_SHADER_ARRAYS,/,(100),*"", 17, kGpaDataTypeFloat64, kGpaUsageTypePercentage, {0x36afb8d9, 0x42fc, 0xaafe, {0x66, 0xc5, 0x44, 0x95, 0x42, 0x15, 0x3b, 0x2c}}}, {""TexUnitBusyCycles"", ""Timing"", ""Number of GPU cycles the texture unit is active. This is measured with all extra fetches and any cache or memory effects taken into account."", ""0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,max16,NUM_SHADER_ARRAYS,/"", 16, kGpaDataTypeFloat64, kGpaUsageTypeCycles, {0xc68761f2, 0x248c, 0x4f39, {0x65, 0x28, 0xc3, 0x08, 0xb1, 0xc0, 0x80, 0x7c}}}, {""TexAveAnisotropy"", ""TextureUnit"", ""The average degree of anisotropy applied. A number between 1 and 16. The anisotropic filtering algorithm only applies samples where they are required (e.g. there will be no extra anisotropic samples if the view vector is perpendicular to the surface) so this can be much lower than the requested anisotropy."", ""0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,sum16,(2),16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,sum16,*,+,(4),32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,sum16,*,+,(6),48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,sum16,*,+,(8),64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,sum16,*,+,(10),80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,sum16,*,+,(12),96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,sum16,*,+,(14),112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,sum16,*,+,(16),128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,sum16,*,+,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,sum16,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,sum16,+,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,sum16,+,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,sum16,+,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,sum16,+,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,sum16,+,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,sum16,+,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,sum16,+,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,sum16,+,/"", 144, kGpaDataTypeFloat64, kGpaUsageTypeItems, {0x7ca2a2b9, 0xa4eb, 0xce23, {0xd1, 0x63, 0x59, 0x14, 0x7e, 0x67, 0x23, 0x96}}}, {""DepthStencilTestBusy"", ""Timing"", ""Percentage of time GPU spent performing depth and stencil tests relative to GPUBusy."", ""0,1,max,2,max,3,max,4,/,NUM_SHADER_ENGINES,/,(100),*"", 5, kGpaDataTypeFloat64, kGpaUsageTypePercentage, {0x6834fb52, 0x42e8, 0xbb50, {0xfd, 0x48, 0xec, 0x2f, 0x29, 0x04, 0xe7, 0xe0}}}, {""DepthStencilTestBusyCount"", ""Timing"", ""Number of GPU cycles spent performing depth and stencil tests."", ""0,1,max,2,max,3,max,NUM_SHADER_ENGINES,/"", 4, kGpaDataTypeFloat64, kGpaUsageTypeCycles, {0xe02860fa, 0xc7bd, 0x90ea, {0x21, 0x49, 0x69, 0xb4, 0xe9, 0x8a, 0x63, 0x6c}}}, {""HiZTilesAccepted"", ""DepthAndStencil"", ""Percentage of tiles accepted by HiZ and will be rendered to the depth or color buffers."", ""4,5,6,7,sum4,0,1,2,3,sum4,-,(0),max,4,5,6,7,sum4,/,(100),*"", 8, kGpaDataTypeFloat64, kGpaUsageTypePercentage, {0x56176f45, 0xd7ff, 0x813d, {0x4f, 0x05, 0x3b, 0x2f, 0x04, 0x60, 0x67, 0xe7}}}, {""HiZTilesAcceptedCount"", ""DepthAndStencil"", ""Count of tiles accepted by HiZ and will be rendered to the depth or color buffers."", ""0,1,2,3,sum4,4,5,6,7,sum4,-,(0),max"", 8, kGpaDataTypeFloat64, kGpaUsageTypeItems, {0x95d4e3f6, 0xb2f0, 0xf26e, {0x84, 0x23, 0xaa, 0xcd, 0xfa, 0xf7, 0x9e, 0xa3}}}, {""HiZTilesRejectedCount"", ""DepthAndStencil"", ""Count of tiles not accepted by HiZ."", ""0,1,2,3,sum4"", 4, kGpaDataTypeFloat64, kGpaUsageTypeItems, {0x156ba142, 0x7eeb, 0xaa6e, {0xa0, 0x0a, 0xf8, 0xae, 0xa4, 0xe4, 0x1e, 0x0b}}}, {""PreZTilesDetailCulled"", ""DepthAndStencil"", ""Percentage of tiles rejected because the associated prim had no contributing area."", ""4,5,6,7,sum4,0,1,2,3,sum4,/,(100),*"", 8, kGpaDataTypeFloat64, kGpaUsageTypePercentage, {0xcad7f54d, 0xa044, 0x7574, {0xc4, 0x72, 0x6f, 0x20, 0x65, 0xcb, 0xee, 0xac}}}, {""PreZTilesDetailCulledCount"", ""DepthAndStencil"", ""Count of tiles rejected because the associated primitive had no contributing area."", ""0,1,2,3,sum4"", 4, kGpaDataTypeFloat64, kGpaUsageTypeItems, {0x49262c8a, 0xb1e6, 0x90dd, {0xf0, 0x96, 0x0f, 0xc4, 0x92, 0x17, 0x15, 0xe9}}}, {""PreZTilesDetailSurvivingCount"", ""DepthAndStencil"", ""Count of tiles surviving because the associated primitive had contributing area."", ""0,1,2,3,sum4"", 4, kGpaDataTypeFloat64, kGpaUsageTypeItems, {0xf803eaa4, 0xbbed, 0xbd39, {0x77, 0x5f, 0xa6, 0x4d, 0xf9, 0x2e, 0x2c, 0x08}}}, {""HiZQuadsCulled"", ""DepthAndStencil"", ""Percentage of quads that did not have to continue on in the pipeline after HiZ. They may be written directly to the depth buffer, or culled completely. Consistently low values here may suggest that the Z-range is not being fully utilized."", ""0,1,2,3,4,5,6,7,sum8,8,9,10,11,12,13,14,15,sum8,-,(0),max,0,1,2,3,4,5,6,7,sum8,/,(100),*"", 16, kGpaDataTypeFloat64, kGpaUsageTypePercentage, {0xfa0e319b, 0x5573, 0x6d34, {0x5b, 0xab, 0x90, 0x47, 0x69, 0x92, 0x50, 0x36}}}, {""HiZQuadsCulledCount"", ""DepthAndStencil"", ""Count of quads that did not have to continue on in the pipeline after HiZ. They may be written directly to the depth buffer, or culled completely. Consistently low values here may suggest that the Z-range is not being fully utilized."", ""0,1,2,3,4,5,6,7,sum8,8,9,10,11,12,13,14,15,sum8,-,(0),max"", 16, kGpaDataTypeFloat64, kGpaUsageTypeItems, {0x73b0b39d, 0x6df2, 0x3e24, {0x0b, 0x5c, 0x7c, 0xb0, 0xac, 0x8b, 0x6f, 0x39}}}, {""HiZQuadsAcceptedCount"", ""DepthAndStencil"", ""Count of quads that did continue on in the pipeline after HiZ."", ""0,1,2,3,4,5,6,7,sum8"", 8, kGpaDataTypeFloat64, kGpaUsageTypeItems, {0x59049ad9, 0x42b5, 0xc7cb, {0x36, 0x16, 0x6a, 0x8f, 0x6a, 0x8e, 0x48, 0x94}}}, {""PreZQuadsCulled"", ""DepthAndStencil"", ""Percentage of quads rejected based on the detailZ and earlyZ tests."", ""0,1,2,3,4,5,6,7,sum8,8,9,+,-,(0),max,10,11,12,13,14,15,16,17,sum8,/,(100),*"", 18, kGpaDataTypeFloat64, kGpaUsageTypePercentage, {0x4e77547b, 0xec55, 0x5663, {0xf0, 0x34, 0xaf, 0x59, 0xbe, 0x66, 0xd7, 0x7d}}}, {""PreZQuadsCulledCount"", ""DepthAndStencil"", ""Count of quads rejected based on the detailZ and earlyZ tests."", ""0,1,2,3,4,5,6,7,sum8,8,9,sum2,-,(0),max"", 10, kGpaDataTypeFloat64, kGpaUsageTypeItems, {0x1bf169e6, 0x9304, 0x834e, {0xdf, 0x5f, 0x0c, 0x44, 0xd7, 0x89, 0x0a, 0x08}}}, {""PreZQuadsSurvivingCount"", ""DepthAndStencil"", ""Count of quads surviving detailZ and earlyZ tests."", ""0,1,sum2"", 2, kGpaDataTypeFloat64, kGpaUsageTypeItems, {0x50e25e51, 0x3713, 0x89cb, {0x7f, 0x92, 0x55, 0x9c, 0xde, 0x5e, 0x55, 0x32}}}, {""PostZQuads"", ""DepthAndStencil"", ""Percentage of quads for which the pixel shader will run and may be postZ tested."", ""0,1,+,2,3,4,5,6,7,8,9,sum8,/,(100),*,(100),min"", 10, kGpaDataTypeFloat64, kGpaUsageTypePercentage, {0x58f0d34b, 0xeeb8, 0xe8db, {0xab, 0xce, 0xcb, 0x72, 0x58, 0x41, 0x44, 0xbe}}}, {""PostZQuadCount"", ""DepthAndStencil"", ""Count of quads for which the pixel shader will run and may be postZ tested."", ""0,1,+"", 2, kGpaDataTypeFloat64, kGpaUsageTypeItems, {0x08404526, 0xce35, 0x939b, {0x34, 0xc8, 0xa7, 0xa3, 0x5a, 0x0f, 0xf4, 0xd6}}}, {""PreZSamplesPassing"", ""DepthAndStencil"", ""Number of samples tested for Z before shading and passed."", ""0,1,2,3,sum4"", 4, kGpaDataTypeFloat64, kGpaUsageTypeItems, {0x3bfe6c4d, 0x7422, 0xca03, {0x7e, 0xa5, 0xe6, 0x7f, 0xf1, 0xa0, 0x01, 0x36}}}, {""PreZSamplesFailingS"", ""DepthAndStencil"", ""Number of samples tested for Z before shading and failed stencil test."", ""0,1,2,3,sum4"", 4, kGpaDataTypeFloat64, kGpaUsageTypeItems, {0xdf7f705e, 0x5162, 0xd3b5, {0xda, 0x8b, 0x63, 0x46, 0x6c, 0xf9, 0xc4, 0xe5}}}, {""PreZSamplesFailingZ"", ""DepthAndStencil"", ""Number of samples tested for Z before shading and failed Z test."", ""0,1,2,3,sum4"", 4, kGpaDataTypeFloat64, kGpaUsageTypeItems, {0x4484e950, 0xf7a4, 0x3800, {0xbc, 0x74, 0x78, 0xdd, 0x29, 0x7f, 0x01, 0x7e}}}, {""PostZSamplesPassing"", ""DepthAndStencil"", ""Number of samples tested for Z after shading and passed."", ""0,1,2,3,sum4"", 4, kGpaDataTypeFloat64, kGpaUsageTypeItems, {0x4995d5d6, 0x2330, 0xb986, {0x50, 0x8b, 0xfa, 0xe2, 0x48, 0x56, 0xf4, 0x4c}}}, {""PostZSamplesFailingS"", ""DepthAndStencil"", ""Number of samples tested for Z after shading and failed stencil test."", ""0,1,2,3,sum4"", 4, kGpaDataTypeFloat64, kGpaUsageTypeItems, {0xae558af4, 0xf4be, 0x3dd4, {0x73, 0x16, 0xb2, 0xc4, 0xdc, 0xf0, 0xde, 0xf8}}}, {""PostZSamplesFailingZ"", ""DepthAndStencil"", ""Number of samples tested for Z after shading and failed Z test."", ""0,1,2,3,sum4"", 4, kGpaDataTypeFloat64, kGpaUsageTypeItems, {0xb3684c94, 0x814a, 0xc695, {0xc8, 0x5d, 0xa5, 0xb6, 0xab, 0x79, 0x8b, 0x35}}}, {""ZUnitStalled"", ""DepthAndStencil"", ""The percentage of GPUTime the depth buffer spends waiting for the color buffer to be ready to accept data. High figures here indicate a bottleneck in color buffer operations."", ""0,1,max,2,max,3,max,4,/,NUM_SHADER_ENGINES,/,(100),*"", 5, kGpaDataTypeFloat64, kGpaUsageTypePercentage, {0x5e86c3ad, 0x1726, 0x3157, {0x1d, 0x01, 0x7e, 0xd1, 0x88, 0xbf, 0x85, 0x4d}}}, {""ZUnitStalledCycles"", ""DepthAndStencil"", ""Number of GPU cycles the depth buffer spends waiting for the color buffer to be ready to accept data. Larger numbers indicate a bottleneck in color buffer operations."", ""0,1,max,2,max,3,max,NUM_SHADER_ENGINES,/"", 4, kGpaDataTypeFloat64, kGpaUsageTypeCycles, {0x4351fa7f, 0x6737, 0x2c3e, {0x3f, 0xfb, 0xb3, 0xad, 0xdb, 0xdc, 0xee, 0xdd}}}, {""DBMemRead"", ""DepthAndStencil"", ""Number of bytes read from the depth buffer."", ""0,1,2,3,sum4,(256),*,4,5,6,7,sum4,(32),*,+"", 8, kGpaDataTypeFloat64, kGpaUsageTypeBytes, {0xdcdb4ee7, 0xbd50, 0x00f7, {0xc0, 0x28, 0x9e, 0x5f, 0x4c, 0xe8, 0x88, 0xc0}}}, {""DBMemWritten"", ""DepthAndStencil"", ""Number of bytes written to the depth buffer."", ""0,1,2,3,sum4,(32),*,4,5,6,7,sum4,(32),*,+"", 8, kGpaDataTypeFloat64, kGpaUsageTypeBytes, {0xde5717f8, 0x8a49, 0xee44, {0x46, 0x45, 0x10, 0xde, 0x51, 0xb3, 0x7d, 0xcf}}}, {""CBMemRead"", ""ColorBuffer"", ""Number of bytes read from the color buffer."", ""0,1,2,3,sum4,(32),*"", 4, kGpaDataTypeFloat64, kGpaUsageTypeBytes, {0x84b531d8, 0xa1f8, 0x7f49, {0x7c, 0x27, 0x7b, 0xc9, 0x78, 0x01, 0xf1, 0xe6}}}, {""CBColorAndMaskRead"", ""ColorBuffer"", ""Total number of bytes read from the color and mask buffers."", ""0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,sum16,(32),*"", 16, kGpaDataTypeFloat64, kGpaUsageTypeBytes, {0xda41660e, 0xeb6f, 0x32ec, {0x8a, 0x64, 0xb3, 0x2c, 0xa1, 0x7b, 0xd7, 0xeb}}}, {""CBMemWritten"", ""ColorBuffer"", ""Number of bytes written to the color buffer."", ""0,1,2,3,sum4,(32),*"", 4, kGpaDataTypeFloat64, kGpaUsageTypeBytes, {0x550f8ff8, 0x60b6, 0xa6bf, {0x87, 0xd0, 0x25, 0xac, 0x9e, 0x87, 0xde, 0x70}}}, {""CBColorAndMaskWritten"", ""ColorBuffer"", ""Total number of bytes written to the color and mask buffers."", ""0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,sum16,(32),*"", 16, kGpaDataTypeFloat64, kGpaUsageTypeBytes, {0x29a04b69, 0x8f5f, 0xb770, {0xa0, 0xf2, 0x34, 0x53, 0xe2, 0xc9, 0x9e, 0x49}}}, {""CBSlowPixelPct"", ""ColorBuffer"", ""Percentage of pixels written to the color buffer using a half-rate or quarter-rate format."", ""0,1,2,3,sum4,4,5,6,7,sum4,/,(100),*,(100),min"", 8, kGpaDataTypeFloat64, kGpaUsageTypePercentage, {0x5775943f, 0x0313, 0x7e52, {0x96, 0x38, 0xb2, 0x4a, 0x44, 0x91, 0x97, 0xbc}}}, {""CBSlowPixelCount"", ""ColorBuffer"", ""Number of pixels written to the color buffer using a half-rate or quarter-rate format."", ""0,1,2,3,sum4"", 4, kGpaDataTypeFloat64, kGpaUsageTypeItems, {0x47eacbb0, 0x28c8, 0x22b4, {0x5c, 0x69, 0xc0, 0x0d, 0x58, 0x13, 0xbb, 0x1c}}}, {""L0CacheHit"", ""MemoryCache"", ""The percentage of read requests that hit the data in the L0 cache. The L0 cache contains vector data, which is data that may vary in each thread across the wavefront. Each request is 128 bytes in size. Value range: 0% (no hit) to 100% (optimal)."", ""(0),(1),16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,sum16,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,sum16,/,-,(100),*,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,sum16,ifnotzero"", 32, kGpaDataTypeFloat64, kGpaUsageTypePercentage, {0x286c786e, 0x9a42, 0x3371, {0x9d, 0xea, 0xdd, 0x54, 0xe6, 0xe6, 0x12, 0xe9}}}, {""L0CacheRequestCount"", ""MemoryCache"", ""The number of read requests made to the L0 cache. The L0 cache contains vector data, which is data that may vary in each thread across the wavefront. Each request is 128 bytes in size."", ""0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,sum16"", 16, kGpaDataTypeFloat64, kGpaUsageTypeItems, {0x74983cae, 0xee57, 0x2e1b, {0xd9, 0x90, 0x51, 0x28, 0xfe, 0xf8, 0x4e, 0x1f}}}, {""L0CacheHitCount"", ""MemoryCache"", ""The number of read requests which result in a cache hit from the L0 cache. The L0 cache contains vector data, which is data that may vary in each thread across the wavefront. Each request is 128 bytes in size."", ""0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,sum16,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,sum16,-"", 32, kGpaDataTypeFloat64, kGpaUsageTypeItems, {0xc0de7338, 0x069b, 0xc5ba, {0xea, 0xd3, 0xc6, 0x5e, 0x03, 0x0c, 0xd2, 0xac}}}, {""L0CacheMissCount"", ""MemoryCache"", ""The number of read requests which result in a cache miss from the L0 cache. The L0 cache contains vector data, which is data that may vary in each thread across the wavefront. Each request is 128 bytes in size."", ""0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,sum16"", 16, kGpaDataTypeFloat64, kGpaUsageTypeItems, {0xa2f08766, 0xea1b, 0x6eae, {0x6e, 0xaf, 0xfa, 0xa0, 0x41, 0x25, 0xd3, 0xe6}}}, {""L1CacheHit"", ""MemoryCache"", ""The percentage of read or write requests that hit the data in the L1 cache. The L1 cache is shared across all WGPs in a single shader engine. Each request is 128 bytes in size. Value range: 0% (no hit) to 100% (optimal)."", ""(0),(1),1,0,/,-,(100),*,0,ifnotzero"", 2, kGpaDataTypeFloat64, kGpaUsageTypePercentage, {0x5a34915a, 0x24b8, 0x8baf, {0x2b, 0xf8, 0x58, 0x78, 0xe7, 0x89, 0x4a, 0xe3}}}, {""L1CacheRequestCount"", ""MemoryCache"", ""The number of read or write requests made to the L1 cache. The L1 cache is shared across all WGPs in a single shader engine. Each request is 128 bytes in size."", ""0"", 1, kGpaDataTypeFloat64, kGpaUsageTypeItems, {0x29c76c67, 0x4611, 0x205d, {0x0b, 0x88, 0xd0, 0x86, 0x68, 0xdf, 0x03, 0xc5}}}, {""L1CacheHitCount"", ""MemoryCache"", ""The number of read or write requests which result in a cache hit from the L1 cache. The L1 cache is shared across all WGPs in a single shader engine. Each request is 128 bytes in size."", ""0,1,-"", 2, kGpaDataTypeFloat64, kGpaUsageTypeItems, {0x1ae150c3, 0xf2d0, 0x82c6, {0xa5, 0x1b, 0xa7, 0x7f, 0xd8, 0xd5, 0xfc, 0x33}}}, {""L1CacheMissCount"", ""MemoryCache"", ""The number of read or write requests which result in a cache miss from the L1 cache. The L1 cache is shared across all WGPs in a single shader engine. Each request is 128 bytes in size."", ""0"", 1, kGpaDataTypeFloat64, kGpaUsageTypeItems, {0x71bfec6d, 0x257b, 0x849d, {0xe2, 0x12, 0xcd, 0xf5, 0xc1, 0xb1, 0xde, 0x65}}}, {""L2CacheHit"", ""MemoryCache"", ""The percentage of read or write requests that hit the data in the L2 cache. The L2 cache is shared by many blocks across the GPU, including the Command Processor, Geometry Engine, all WGPs, all Render Backends, and others. Each request is 128 bytes in size. Value range: 0% (no hit) to 100% (optimal)."", ""(0),(1),16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,sum16,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,sum16,/,-,(100),*,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,sum16,ifnotzero"", 32, kGpaDataTypeFloat64, kGpaUsageTypePercentage, {0x47694e4d, 0x6ce6, 0xf387, {0x08, 0x0d, 0xb1, 0xf3, 0xd0, 0x0b, 0x73, 0xac}}}, {""L2CacheMiss"", ""MemoryCache"", ""The percentage of read or write requests that miss the data in the L2 cache. The L2 cache is shared by many blocks across the GPU, including the Command Processor, Geometry Engine, all WGPs, all Render Backends, and others. Each request is 128 bytes in size. Value range: 0% (optimal) to 100% (all miss)."", ""0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,sum16,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,sum16,/,(100),*"", 32, kGpaDataTypeFloat64, kGpaUsageTypePercentage, {0x8aee5458, 0xa58e, 0x11b6, {0x51, 0x31, 0x7f, 0x19, 0xed, 0x07, 0x01, 0x17}}}, {""L2CacheRequestCount"", ""MemoryCache"", ""The number of read or write requests made to the L2 cache. The L2 cache is shared by many blocks across the GPU, including the Command Processor, Geometry Engine, all WGPs, all Render Backends, and others. Each request is 128 bytes in size."", ""0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,sum16"", 16, kGpaDataTypeFloat64, kGpaUsageTypeItems, {0x21e9219c, 0xe725, 0x0d96, {0x06, 0xb1, 0xb2, 0x16, 0x98, 0xb7, 0x36, 0xb2}}}, {""L2CacheHitCount"", ""MemoryCache"", ""The number of read or write requests which result in a cache hit from the L2 cache. The L2 cache is shared by many blocks across the GPU, including the Command Processor, Geometry Engine, all WGPs, all Render Backends, and others. Each request is 128 bytes in size."", ""0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,sum16,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,sum16,-"", 32, kGpaDataTypeFloat64, kGpaUsageTypeItems, {0x29ddcb92, 0xd3dd, 0x951b, {0x1b, 0x23, 0xef, 0xe5, 0x2e, 0x4e, 0xee, 0xe4}}}, {""L2CacheMissCount"", ""MemoryCache"", ""The number of read or write requests which result in a cache miss from the L2 cache. The L2 cache is shared by many blocks across the GPU, including the Command Processor, Geometry Engine, all WGPs, all Render Backends, and others. Each request is 128 bytes in size."", ""0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,sum16"", 16, kGpaDataTypeFloat64, kGpaUsageTypeItems, {0x376eec7b, 0xab25, 0x9012, {0x06, 0xb5, 0x63, 0x29, 0x1a, 0x17, 0xfd, 0x47}}}, {""FetchSize"", ""GlobalMemory"", ""The total bytes fetched from the video memory. This is measured with all extra fetches and any cache or memory effects taken into account."", ""0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,sum16,(32),*,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,sum16,(64),*,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,sum16,(96),*,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,sum16,(128),*,sum4"", 64, kGpaDataTypeFloat64, kGpaUsageTypeBytes, {0x664bb3ef, 0x6eca, 0x86b1, {0x1e, 0x2d, 0x30, 0xcb, 0x89, 0x7b, 0x5f, 0xa9}}}, {""WriteSize"", ""GlobalMemory"", ""The total bytes written to the video memory. This is measured with all extra fetches and any cache or memory effects taken into account."", ""0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,sum16,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,sum16,-,(32),*,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,sum16,(64),*,+"", 32, kGpaDataTypeFloat64, kGpaUsageTypeBytes, {0xf96f2c16, 0xb1b4, 0x4ec4, {0x22, 0x9c, 0xfc, 0x82, 0xe6, 0xf8, 0x0a, 0x82}}}, {""MemUnitBusy"", ""GlobalMemory"", ""The percentage of GPUTime the memory unit is active. The result includes the stall time (MemUnitStalled). This is measured with all extra fetches and writes and any cache or memory effects taken into account. Value range: 0% to 100% (fetch-bound)."", ""0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,max16,16,/,NUM_SHADER_ARRAYS,/,(100),*"", 17, kGpaDataTypeFloat64, kGpaUsageTypePercentage, {0xa1efa380, 0x4a72, 0xe066, {0xe0, 0x6a, 0x2a, 0xb7, 0x1a, 0x48, 0x85, 0x21}}}, {""MemUnitBusyCycles"", ""GlobalMemory"", ""Number of GPU cycles the memory unit is active. The result includes the stall time (MemUnitStalledCycles). This is measured with all extra fetches and writes and any cache or memory effects taken into account."", ""0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,max16"", 16, kGpaDataTypeFloat64, kGpaUsageTypeCycles, {0x168f077c, 0x4797, 0xb2f5, {0x71, 0x7f, 0x10, 0x5c, 0x72, 0x52, 0x66, 0xc8}}}, {""MemUnitStalled"", ""GlobalMemory"", ""The percentage of GPUTime the memory unit is stalled. Try reducing the number or size of fetches and writes if possible. Value range: 0% (optimal) to 100% (bad)."", ""0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,max16,16,/,NUM_SHADER_ARRAYS,/,(100),*"", 17, kGpaDataTypeFloat64, kGpaUsageTypePercentage, {0x465ba54f, 0xd250, 0x1453, {0x79, 0x0a, 0x73, 0x1b, 0x10, 0xd2, 0x30, 0xb1}}}, {""MemUnitStalledCycles"", ""GlobalMemory"", ""Number of GPU cycles the memory unit is stalled."", ""0,1,2,3,4,5,6,7,8,9,max10"", 10, kGpaDataTypeFloat64, kGpaUsageTypeCycles, {0x2745659a, 0x0e40, 0xbace, {0x3b, 0x9b, 0x86, 0xa5, 0x4f, 0x8e, 0x46, 0x23}}}, {""WriteUnitStalled"", ""GlobalMemory"", ""The percentage of GPUTime the Write unit is stalled. Value range: 0% to 100% (bad)."", ""0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,max16,16,/,(100),*"", 17, kGpaDataTypeFloat64, kGpaUsageTypePercentage, {0x594ad3ce, 0xd1ec, 0x10fc, {0x7d, 0x59, 0x25, 0x73, 0x8e, 0x39, 0x7d, 0x72}}}, {""WriteUnitStalledCycles"", ""GlobalMemory"", ""Number of GPU cycles the Write unit is stalled."", ""0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,max16"", 16, kGpaDataTypeFloat64, kGpaUsageTypeCycles, {0xede3305e, 0xabd4, 0xd6bf, {0x6b, 0x00, 0xff, 0xc5, 0x7a, 0x29, 0xfc, 0xe3}}}, }; ",16207,True,4646.643059297393,median "open util/ordering [State] as ord pred test4 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Grain0: Grain {some disj Farmer0, Fox0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 no Chicken Grain = Grain0 Object = Farmer0 + Fox0 + Grain0 no eats State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State3->Fox0 far = State1->Farmer0 + State1->Grain0 + State2->Grain0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}} } run test4 for 4 expect 0 pred test38 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Grain0,Grain0,Fox0 + Grain0,Farmer0 + Fox0 + Grain0] }}}}}} } run test38 for 4 expect 1 pred test51 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Farmer0 + State1->Fox0 + State1->Chicken0 + State1->Grain0 + State2->Fox0 + State2->Grain0 + State3->Farmer0 + State3->Fox0 + State3->Grain0 far = State2->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test51 for 4 expect 0 pred test9 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Grain0,Fox0 + Grain0,none,Farmer0] }}}}}} } run test9 for 4 expect 1 pred test28 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Chicken0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State1->Chicken0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Chicken0,Fox0 + Grain0,Chicken0] }}}}}} } run test28 for 4 expect 0 pred test46 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State1->Chicken0 + State2->Chicken0 + State3->Farmer0 + State3->Chicken0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 solvePuzzle[] }}}}}} } run test46 for 4 expect 0 pred test33 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0,Chicken0,none,Farmer0 + Fox0] }}}}}} } run test33 for 4 expect 1 pred test14 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Grain0,Fox0 + Grain0,Grain0,Fox0 + Chicken0] }}}}}} } run test14 for 4 expect 0 pred test27 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Chicken0 + Grain0,Grain0,Chicken0 + Grain0,Farmer0 + Chicken0 + Grain0] }}}}}} } run test27 for 4 expect 1 pred test52 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State0->Chicken0 + State0->Grain0 + State1->Farmer0 + State1->Chicken0 + State1->Grain0 + State2->Chicken0 + State3->Farmer0 + State3->Chicken0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test52 for 4 expect 0 pred test30 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Chicken0,Fox0 + Chicken0 + Grain0,Farmer0 + Fox0 + Chicken0 + Grain0] }}}}}} } run test30 for 4 expect 1 pred test12 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Farmer0,none,Farmer0] }}}}}} } run test12 for 4 expect 0 pred test43 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0,Fox0,none,Farmer0 + Chicken0] }}}}}} } run test43 for 4 expect 1 pred test8 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Farmer0,Grain0,Fox0 + Chicken0] }}}}}} } run test8 for 4 expect 0 pred test31 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Chicken0 + Grain0,Chicken0,none,Farmer0 + Grain0] }}}}}} } run test31 for 4 expect 1 pred test6 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Chicken0 + State2->Farmer0 + State2->Chicken0 far = State1->Farmer0 + State1->Fox0 + State2->Fox0 + State3->Farmer0 + State3->Fox0 + State3->Chicken0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test6 for 4 expect 1 pred test25 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Chicken0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State1->Chicken0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Farmer0,Grain0,Fox0 + Chicken0] }}}}}} } run test25 for 4 expect 0 pred test29 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Grain0,Fox0,none,Farmer0 + Grain0] }}}}}} } run test29 for 4 expect 1 pred test40 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Chicken0,none,Farmer0 + Fox0] }}}}}} } run test40 for 4 expect 1 pred test32 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Chicken0 + Grain0,Chicken0,none,Farmer0 + Grain0] }}}}}} } run test32 for 4 expect 1 pred test24 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Chicken0,none,none,Farmer0 + Grain0] }}}}}} } run test24 for 4 expect 0 pred test54 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Chicken0 + State2->Grain0 + State3->Fox0 + State3->Chicken0 far = State1->Farmer0 + State2->Fox0 + State2->Chicken0 + State2->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test54 for 4 expect 0 pred test22 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State1->Chicken0 + State2->Chicken0 + State3->Farmer0 + State3->Chicken0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Grain0,Fox0 + Grain0,Fox0 + Chicken0 + Grain0,none] }}}}}} } run test22 for 4 expect 0 pred test2 { some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { no Farmer Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Chicken0 far = State1->Fox0 + State2->Fox0 + State2->Chicken0 + State3->Fox0 + State3->Chicken0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}} } run test2 for 4 expect 0 pred test10 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Grain0,Fox0 + Grain0,none,Farmer0] }}}}}} } run test10 for 4 expect 1 pred test42 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Fox0 + Grain0,Fox0 + Grain0,Farmer0 + Fox0] }}}}}} } run test42 for 4 expect 0 pred test26 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Chicken0 + State2->Farmer0 + State2->Fox0 + State2->Chicken0 + State3->Fox0 far = State1->Farmer0 + State1->Fox0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Chicken0 + Grain0,Grain0,Fox0 + Chicken0 + Grain0,Farmer0 + Fox0 + Chicken0 + Grain0] }}}}}} } run test26 for 4 expect 1 pred test41 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Fox0 + Grain0,none,Farmer0 + Chicken0] }}}}}} } run test41 for 4 expect 1 ",8116,True,3162.654241293577,median "// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include ""base/bind.h"" #include ""base/files/file_path.h"" #include ""base/files/file_util.h"" #include ""base/files/scoped_temp_dir.h"" #include ""base/json/json_reader.h"" #include ""base/message_loop/message_loop.h"" #include ""base/run_loop.h"" #include ""base/strings/string_number_conversions.h"" #include ""base/values.h"" #include ""google_apis/drive/drive_api_parser.h"" #include ""google_apis/drive/drive_api_requests.h"" #include ""google_apis/drive/drive_api_url_generator.h"" #include ""google_apis/drive/dummy_auth_service.h"" #include ""google_apis/drive/request_sender.h"" #include ""google_apis/drive/test_util.h"" #include ""net/test/embedded_test_server/embedded_test_server.h"" #include ""net/test/embedded_test_server/http_request.h"" #include ""net/test/embedded_test_server/http_response.h"" #include ""net/url_request/url_request_test_util.h"" #include ""testing/gtest/include/gtest/gtest.h"" namespace google_apis { namespace { const char kTestETag[] = ""test_etag""; const char kTestUserAgent[] = ""test-user-agent""; const char kTestChildrenResponse[] = ""{\\n"" ""\\""kind\\"": \\""drive#childReference\\"",\\n"" ""\\""id\\"": \\""resource_id\\"",\\n"" ""\\""selfLink\\"": \\""self_link\\"",\\n"" ""\\""childLink\\"": \\""child_link\\"",\\n"" ""}\\n""; const char kTestPermissionResponse[] = ""{\\n"" ""\\""kind\\"": \\""drive#permission\\"",\\n"" ""\\""id\\"": \\""resource_id\\"",\\n"" ""\\""selfLink\\"": \\""self_link\\"",\\n"" ""}\\n""; const char kTestUploadExistingFilePath[] = ""/upload/existingfile/path""; const char kTestUploadNewFilePath[] = ""/upload/newfile/path""; const char kTestDownloadPathPrefix[] = ""/download/""; // Used as a GetContentCallback. void AppendContent(std::string* out, GDataErrorCode error, scoped_ptr content) { EXPECT_EQ(HTTP_SUCCESS, error); out->append(*content); } } // namespace class DriveApiRequestsTest : public testing::Test { public: DriveApiRequestsTest() { } virtual void SetUp() OVERRIDE { request_context_getter_ = new net::TestURLRequestContextGetter( message_loop_.message_loop_proxy()); request_sender_.reset(new RequestSender(new DummyAuthService, request_context_getter_.get(), message_loop_.message_loop_proxy(), kTestUserAgent)); ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); ASSERT_TRUE(test_server_.InitializeAndWaitUntilReady()); test_server_.RegisterRequestHandler( base::Bind(&DriveApiRequestsTest::HandleChildrenDeleteRequest, base::Unretained(this))); test_server_.RegisterRequestHandler( base::Bind(&DriveApiRequestsTest::HandleDataFileRequest, base::Unretained(this))); test_server_.RegisterRequestHandler( base::Bind(&DriveApiRequestsTest::HandleDeleteRequest, base::Unretained(this))); test_server_.RegisterRequestHandler( base::Bind(&DriveApiRequestsTest::HandlePreconditionFailedRequest, base::Unretained(this))); test_server_.RegisterRequestHandler( base::Bind(&DriveApiRequestsTest::HandleResumeUploadRequest, base::Unretained(this))); test_server_.RegisterRequestHandler( base::Bind(&DriveApiRequestsTest::HandleInitiateUploadRequest, base::Unretained(this))); test_server_.RegisterRequestHandler( base::Bind(&DriveApiRequestsTest::HandleContentResponse, base::Unretained(this))); test_server_.RegisterRequestHandler( base::Bind(&DriveApiRequestsTest::HandleDownloadRequest, base::Unretained(this))); GURL test_base_url = test_util::GetBaseUrlForTesting(test_server_.port()); url_generator_.reset(new DriveApiUrlGenerator( test_base_url, test_base_url.Resolve(kTestDownloadPathPrefix))); // Reset the server's expected behavior just in case. ResetExpectedResponse(); received_bytes_ = 0; content_length_ = 0; } base::MessageLoopForIO message_loop_; // Test server needs IO thread. net::test_server::EmbeddedTestServer test_server_; scoped_ptr request_sender_; scoped_ptr url_generator_; scoped_refptr request_context_getter_; base::ScopedTempDir temp_dir_; // This is a path to the file which contains expected response from // the server. See also HandleDataFileRequest below. base::FilePath expected_data_file_path_; // This is a path string in the expected response header from the server // for initiating file uploading. std::string expected_upload_path_; // This is a path to the file which contains expected response for // PRECONDITION_FAILED response. base::FilePath expected_precondition_failed_file_path_; // These are content and its type in the expected response from the server. // See also HandleContentResponse below. std::string expected_content_type_; std::string expected_content_; // The incoming HTTP request is saved so tests can verify the request // parameters like HTTP method (ex. some requests should use DELETE // instead of GET). net::test_server::HttpRequest http_request_; private: void ResetExpectedResponse() { expected_data_file_path_.clear(); expected_upload_path_.clear(); expected_content_type_.clear(); expected_content_.clear(); } // For ""Children: delete"" request, the server will return ""204 No Content"" // response meaning ""success"". scoped_ptr HandleChildrenDeleteRequest( const net::test_server::HttpRequest& request) { if (request.method != net::test_server::METHOD_DELETE || request.relative_url.find(""/children/"") == string::npos) { // The request is not the ""Children: delete"" request. Delegate the // processing to the next handler. return scoped_ptr(); } http_request_ = request; // Return the response with just ""204 No Content"" status code. scoped_ptr http_response( new net::test_server::BasicHttpResponse); http_response->set_code(net::HTTP_NO_CONTENT); return http_response.PassAs(); } // Reads the data file of |expected_data_file_path_| and returns its content // for the request. // To use this method, it is necessary to set |expected_data_file_path_| // to the appropriate file path before sending the request to the server. scoped_ptr HandleDataFileRequest( const net::test_server::HttpRequest& request) { if (expected_data_file_path_.empty()) { // The file is not specified. Delegate the processing to the next // handler. return scoped_ptr(); } http_request_ = request; // Return the response from the data file. return test_util::CreateHttpResponseFromFile( expected_data_file_path_).PassAs(); } // Deletes the resource and returns no content with HTTP_NO_CONTENT status // code. scoped_ptr HandleDeleteRequest( const net::test_server::HttpRequest& request) { if (request.method != net::test_server::METHOD_DELETE || request.relative_url.find(""/files/"") == string::npos) { // The file is not file deletion request. Delegate the processing to the // next handler. return scoped_ptr(); } http_request_ = request; scoped_ptr response( new net::test_server::BasicHttpResponse); response->set_code(net::HTTP_NO_CONTENT); return response.PassAs(); } // Returns PRECONDITION_FAILED response for ETag mismatching with error JSON // content specified by |expected_precondition_failed_file_path_|. // To use this method, it is necessary to set the variable to the appropriate // file path before sending the request to the server. scoped_ptr HandlePreconditionFailedRequest( const net::test_server::HttpRequest& request) { if (expected_precondition_failed_file_path_.empty()) { // The file is not specified. Delegate the process to the next handler. return scoped_ptr(); } http_request_ = request; scoped_ptr response( new net::test_server::BasicHttpResponse); response->set_code(net::HTTP_PRECONDITION_FAILED); std::string content; if (base::ReadFileToString(expected_precondition_failed_file_path_, &content)) { response->set_content(content); response->set_content_type(""application/json""); } return response.PassAs(); } // Returns the response based on set expected upload url. // The response contains the url in its ""Location: "" header. Also, it doesn't // have any content. // To use this method, it is necessary to set |expected_upload_path_| // to the string representation of the url to be returned. scoped_ptr HandleInitiateUploadRequest( const net::test_server::HttpRequest& request) { if (request.relative_url == expected_upload_path_ || expected_upload_path_.empty()) { // The request is for resume uploading or the expected upload url is not // set. Delegate the processing to the next handler. return scoped_ptr(); } http_request_ = request; scoped_ptr response( new net::test_server::BasicHttpResponse); // Check if the X-Upload-Content-Length is present. If yes, store the // length of the file. std::map::const_iterator found = request.headers.find(""X-Upload-Content-Length""); if (found == request.headers.end() || !base::StringToInt64(found->second, &content_length_)) { return scoped_ptr(); } received_bytes_ = 0; response->set_code(net::HTTP_OK); response->AddCustomHeader( ""Location"", test_server_.base_url().Resolve(expected_upload_path_).spec()); return response.PassAs(); } scoped_ptr HandleResumeUploadRequest( const net::test_server::HttpRequest& request) { if (request.relative_url != expected_upload_path_) { // The request path is different from the expected path for uploading. // Delegate the processing to the next handler. return scoped_ptr(); } http_request_ = request; if (!request.content.empty()) { std::map::const_iterator iter = request.headers.find(""Content-Range""); if (iter == request.headers.end()) { // The range must be set. return scoped_ptr(); } int64 length = 0; int64 start_position = 0; int64 end_position = 0; if (!test_util::ParseContentRangeHeader( iter->second, &start_position, &end_position, &length)) { // Invalid ""Content-Range"" value. return scoped_ptr(); } EXPECT_EQ(start_position, received_bytes_); EXPECT_EQ(length, content_length_); // end_position is inclusive, but so +1 to change the range to byte size. received_bytes_ = end_position + 1; } if (received_bytes_ < content_length_) { scoped_ptr response( new net::test_server::BasicHttpResponse); // Set RESUME INCOMPLETE (308) status code. response->set_code(static_cast(308)); // Add Range header to the response, based on the values of // Content-Range header in the request. // The header is annotated only when at least one byte is received. if (received_bytes_ > 0) { response->AddCustomHeader( ""Range"", ""bytes=0-"" + base::Int64ToString(received_bytes_ - 1)); } return response.PassAs(); } // All bytes are received. Return the ""success"" response with the file's // (dummy) metadata. scoped_ptr response = test_util::CreateHttpResponseFromFile( test_util::GetTestFilePath(""drive/file_entry.json"")); // The response code is CREATED if it is new file uploading. if (http_request_.relative_url == kTestUploadNewFilePath) { response->set_code(net::HTTP_CREATED); } return response.PassAs(); } // Returns the response based on set expected content and its type. // To use this method, both |expected_content_type_| and |expected_content_| // must be set in advance. scoped_ptr HandleContentResponse( const net::test_server::HttpRequest& request) { if (expected_content_type_.empty() || expected_content_.empty()) { // Expected content is not set. Delegate the processing to the next // handler. return scoped_ptr(); } http_request_ = request; scoped_ptr response( new net::test_server::BasicHttpResponse); response->set_code(net::HTTP_OK); response->set_content_type(expected_content_type_); response->set_content(expected_content_); return response.PassAs(); } // Handles a request for downloading a file. scoped_ptr HandleDownloadRequest( const net::test_server::HttpRequest& request) { http_request_ = request; const GURL absolute_url = test_server_.GetURL(request.relative_url); std::string id; if (!test_util::RemovePrefix(absolute_url.path(), kTestDownloadPathPrefix, &id)) { return scoped_ptr(); } // For testing, returns a text with |id| repeated 3 times. scoped_ptr response( new net::test_server::BasicHttpResponse); response->set_code(net::HTTP_OK); response->set_content(id + id + id); response->set_content_type(""text/plain""); return response.PassAs(); } // These are for the current upload file status. int64 received_bytes_; int64 content_length_; }; TEST_F(DriveApiRequestsTest, DriveApiDataRequest_Fields) { // Make sure that ""fields"" query param is supported by using its subclass, // AboutGetRequest. // Set an expected data file containing valid result. expected_data_file_path_ = test_util::GetTestFilePath( ""drive/about.json""); GDataErrorCode error = GDATA_OTHER_ERROR; scoped_ptr about_resource; { base::RunLoop run_loop; drive::AboutGetRequest* request = new drive::AboutGetRequest( request_sender_.get(), *url_generator_, test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&error, &about_resource))); request->set_fields( ""kind,quotaBytesTotal,quotaBytesUsed,largestChangeId,rootFolderId""); request_sender_->StartRequestWithRetry(request); run_loop.Run(); } EXPECT_EQ(HTTP_SUCCESS, error); EXPECT_EQ(net::test_server::METHOD_GET, http_request_.method); EXPECT_EQ(""/drive/v2/about?"" ""fields=kind%2CquotaBytesTotal%2CquotaBytesUsed%2C"" ""largestChangeId%2CrootFolderId"", http_request_.relative_url); scoped_ptr expected( AboutResource::CreateFrom( *test_util::LoadJSONFile(""drive/about.json""))); ASSERT_TRUE(about_resource.get()); EXPECT_EQ(expected->largest_change_id(), about_resource->largest_change_id()); EXPECT_EQ(expected->quota_bytes_total(), about_resource->quota_bytes_total()); EXPECT_EQ(expected->quota_bytes_used(), about_resource->quota_bytes_used()); EXPECT_EQ(expected->root_folder_id(), about_resource->root_folder_id()); } TEST_F(DriveApiRequestsTest, FilesInsertRequest) { const base::Time::Exploded kModifiedDate = {2012, 7, 0, 19, 15, 59, 13, 123}; const base::Time::Exploded kLastViewedByMeDate = {2013, 7, 0, 19, 15, 59, 13, 123}; // Set an expected data file containing the directory's entry data. expected_data_file_path_ = test_util::GetTestFilePath(""drive/directory_entry.json""); GDataErrorCode error = GDATA_OTHER_ERROR; scoped_ptr file_resource; // Create ""new directory"" in the root directory. { base::RunLoop run_loop; drive::FilesInsertRequest* request = new drive::FilesInsertRequest( request_sender_.get(), *url_generator_, test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&error, &file_resource))); request->set_last_viewed_by_me_date( base::Time::FromUTCExploded(kLastViewedByMeDate)); request->set_mime_type(""application/vnd.google-apps.folder""); request->set_modified_date(base::Time::FromUTCExploded(kModifiedDate)); request->add_parent(""root""); request->set_title(""new directory""); request_sender_->StartRequestWithRetry(request); run_loop.Run(); } EXPECT_EQ(HTTP_SUCCESS, error); EXPECT_EQ(net::test_server::METHOD_POST, http_request_.method); EXPECT_EQ(""/drive/v2/files"", http_request_.relative_url); EXPECT_EQ(""application/json"", http_request_.headers[""Content-Type""]); EXPECT_TRUE(http_request_.has_content); EXPECT_EQ(""{\\""lastViewedByMeDate\\"":\\""2013-07-19T15:59:13.123Z\\"","" ""\\""mimeType\\"":\\""application/vnd.google-apps.folder\\"","" ""\\""modifiedDate\\"":\\""2012-07-19T15:59:13.123Z\\"","" ""\\""parents\\"":[{\\""id\\"":\\""root\\""}],"" ""\\""title\\"":\\""new directory\\""}"", http_request_.content); scoped_ptr expected( FileResource::CreateFrom( *test_util::LoadJSONFile(""drive/directory_entry.json""))); // Sanity check. ASSERT_TRUE(file_resource.get()); EXPECT_EQ(expected->file_id(), file_resource->file_id()); EXPECT_EQ(expected->title(), file_resource->title()); EXPECT_EQ(expected->mime_type(), file_resource->mime_type()); EXPECT_EQ(expected->parents().size(), file_resource->parents().size()); } TEST_F(DriveApiRequestsTest, FilesPatchRequest) { const base::Time::Exploded kModifiedDate = {2012, 7, 0, 19, 15, 59, 13, 123}; const base::Time::Exploded kLastViewedByMeDate = {2013, 7, 0, 19, 15, 59, 13, 123}; // Set an expected data file containing valid result. expected_data_file_path_ = test_util::GetTestFilePath(""drive/file_entry.json""); GDataErrorCode error = GDATA_OTHER_ERROR; scoped_ptr file_resource; { base::RunLoop run_loop; drive::FilesPatchRequest* request = new drive::FilesPatchRequest( request_sender_.get(), *url_generator_, test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&error, &file_resource))); request->set_file_id(""resource_id""); request->set_set_modified_date(true); request->set_update_viewed_date(false); request->set_title(""new title""); request->set_modified_date(base::Time::FromUTCExploded(kModifiedDate)); request->set_last_viewed_by_me_date( base::Time::FromUTCExploded(kLastViewedByMeDate)); request->add_parent(""parent_resource_id""); request_sender_->StartRequestWithRetry(request); run_loop.Run(); } EXPECT_EQ(HTTP_SUCCESS, error); EXPECT_EQ(net::test_server::METHOD_PATCH, http_request_.method); EXPECT_EQ(""/drive/v2/files/resource_id"" ""?setModifiedDate=true&updateViewedDate=false"", http_request_.relative_url); EXPECT_EQ(""application/json"", http_request_.headers[""Content-Type""]); EXPECT_TRUE(http_request_.has_content); EXPECT_EQ(""{\\""lastViewedByMeDate\\"":\\""2013-07-19T15:59:13.123Z\\"","" ""\\""modifiedDate\\"":\\""2012-07-19T15:59:13.123Z\\"","" ""\\""parents\\"":[{\\""id\\"":\\""parent_resource_id\\""}],"" ""\\""title\\"":\\""new title\\""}"", http_request_.content); EXPECT_TRUE(file_resource); } TEST_F(DriveApiRequestsTest, AboutGetRequest_ValidJson) { // Set an expected data file containing valid result. expected_data_file_path_ = test_util::GetTestFilePath( ""drive/about.json""); GDataErrorCode error = GDATA_OTHER_ERROR; scoped_ptr about_resource; { base::RunLoop run_loop; drive::AboutGetRequest* request = new drive::AboutGetRequest( request_sender_.get(), *url_generator_, test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&error, &about_resource))); request_sender_->StartRequestWithRetry(request); run_loop.Run(); } EXPECT_EQ(HTTP_SUCCESS, error); EXPECT_EQ(net::test_server::METHOD_GET, http_request_.method); EXPECT_EQ(""/drive/v2/about"", http_request_.relative_url); scoped_ptr expected( AboutResource::CreateFrom( *test_util::LoadJSONFile(""drive/about.json""))); ASSERT_TRUE(about_resource.get()); EXPECT_EQ(expected->largest_change_id(), about_resource->largest_change_id()); EXPECT_EQ(expected->quota_bytes_total(), about_resource->quota_bytes_total()); EXPECT_EQ(expected->quota_bytes_used(), about_resource->quota_bytes_used()); EXPECT_EQ(expected->root_folder_id(), about_resource->root_folder_id()); } TEST_F(DriveApiRequestsTest, AboutGetRequest_InvalidJson) { // Set an expected data file containing invalid result. expected_data_file_path_ = test_util::GetTestFilePath( ""gdata/testfile.txt""); GDataErrorCode error = GDATA_OTHER_ERROR; scoped_ptr about_resource; { base::RunLoop run_loop; drive::AboutGetRequest* request = new drive::AboutGetRequest( request_sender_.get(), *url_generator_, test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&error, &about_resource))); request_sender_->StartRequestWithRetry(request); run_loop.Run(); } // ""parse error"" should be returned, and the about resource should be NULL. EXPECT_EQ(GDATA_PARSE_ERROR, error); EXPECT_EQ(net::test_server::METHOD_GET, http_request_.method); EXPECT_EQ(""/drive/v2/about"", http_request_.relative_url); EXPECT_FALSE(about_resource); } TEST_F(DriveApiRequestsTest, AppsListRequest) { // Set an expected data file containing valid result. expected_data_file_path_ = test_util::GetTestFilePath( ""drive/applist.json""); GDataErrorCode error = GDATA_OTHER_ERROR; scoped_ptr app_list; { base::RunLoop run_loop; drive::AppsListRequest* request = new drive::AppsListRequest( request_sender_.get(), *url_generator_, false, // use_internal_endpoint test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&error, &app_list))); request_sender_->StartRequestWithRetry(request); run_loop.Run(); } EXPECT_EQ(HTTP_SUCCESS, error); EXPECT_EQ(net::test_server::METHOD_GET, http_request_.method); EXPECT_EQ(""/drive/v2/apps"", http_request_.relative_url); EXPECT_TRUE(app_list); } TEST_F(DriveApiRequestsTest, ChangesListRequest) { // Set an expected data file containing valid result. expected_data_file_path_ = test_util::GetTestFilePath( ""drive/changelist.json""); GDataErrorCode error = GDATA_OTHER_ERROR; scoped_ptr result; { base::RunLoop run_loop; drive::ChangesListRequest* request = new drive::ChangesListRequest( request_sender_.get(), *url_generator_, test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&error, &result))); request->set_include_deleted(true); request->set_start_change_id(100); request->set_max_results(500); request_sender_->StartRequestWithRetry(request); run_loop.Run(); } EXPECT_EQ(HTTP_SUCCESS, error); EXPECT_EQ(net::test_server::METHOD_GET, http_request_.method); EXPECT_EQ(""/drive/v2/changes?maxResults=500&startChangeId=100"", http_request_.relative_url); EXPECT_TRUE(result); } TEST_F(DriveApiRequestsTest, ChangesListNextPageRequest) { // Set an expected data file containing valid result. expected_data_file_path_ = test_util::GetTestFilePath( ""drive/changelist.json""); GDataErrorCode error = GDATA_OTHER_ERROR; scoped_ptr result; { base::RunLoop run_loop; drive::ChangesListNextPageRequest* request = new drive::ChangesListNextPageRequest( request_sender_.get(), test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&error, &result))); request->set_next_link(test_server_.GetURL(""/continue/get/change/list"")); request_sender_->StartRequestWithRetry(request); run_loop.Run(); } EXPECT_EQ(HTTP_SUCCESS, error); EXPECT_EQ(net::test_server::METHOD_GET, http_request_.method); EXPECT_EQ(""/continue/get/change/list"", http_request_.relative_url); EXPECT_TRUE(result); } TEST_F(DriveApiRequestsTest, FilesCopyRequest) { const base::Time::Exploded kModifiedDate = {2012, 7, 0, 19, 15, 59, 13, 123}; // Set an expected data file containing the dummy file entry data. // It'd be returned if we copy a file. expected_data_file_path_ = test_util::GetTestFilePath(""drive/file_entry.json""); GDataErrorCode error = GDATA_OTHER_ERROR; scoped_ptr file_resource; // Copy the file to a new file named ""new title"". { base::RunLoop run_loop; drive::FilesCopyRequest* request = new drive::FilesCopyRequest( request_sender_.get(), *url_generator_, test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&error, &file_resource))); request->set_file_id(""resource_id""); request->set_modified_date(base::Time::FromUTCExploded(kModifiedDate)); request->add_parent(""parent_resource_id""); request->set_title(""new title""); request_sender_->StartRequestWithRetry(request); run_loop.Run(); } EXPECT_EQ(HTTP_SUCCESS, error); EXPECT_EQ(net::test_server::METHOD_POST, http_request_.method); EXPECT_EQ(""/drive/v2/files/resource_id/copy"", http_request_.relative_url); EXPECT_EQ(""application/json"", http_request_.headers[""Content-Type""]); EXPECT_TRUE(http_request_.has_content); EXPECT_EQ( ""{\\""modifiedDate\\"":\\""2012-07-19T15:59:13.123Z\\"","" ""\\""parents\\"":[{\\""id\\"":\\""parent_resource_id\\""}],\\""title\\"":\\""new title\\""}"", http_request_.content); EXPECT_TRUE(file_resource); } TEST_F(DriveApiRequestsTest, FilesCopyRequest_EmptyParentResourceId) { // Set an expected data file containing the dummy file entry data. // It'd be returned if we copy a file. expected_data_file_path_ = test_util::GetTestFilePath(""drive/file_entry.json""); GDataErrorCode error = GDATA_OTHER_ERROR; scoped_ptr file_resource; // Copy the file to a new file named ""new title"". { base::RunLoop run_loop; drive::FilesCopyRequest* request = new drive::FilesCopyRequest( request_sender_.get(), *url_generator_, test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&error, &file_resource))); request->set_file_id(""resource_id""); request->set_title(""new title""); request_sender_->StartRequestWithRetry(request); run_loop.Run(); } EXPECT_EQ(HTTP_SUCCESS, error); EXPECT_EQ(net::test_server::METHOD_POST, http_request_.method); EXPECT_EQ(""/drive/v2/files/resource_id/copy"", http_request_.relative_url); EXPECT_EQ(""application/json"", http_request_.headers[""Content-Type""]); EXPECT_TRUE(http_request_.has_content); EXPECT_EQ(""{\\""title\\"":\\""new title\\""}"", http_request_.content); EXPECT_TRUE(file_resource); } TEST_F(DriveApiRequestsTest, FilesListRequest) { // Set an expected data file containing valid result. expected_data_file_path_ = test_util::GetTestFilePath( ""drive/filelist.json""); GDataErrorCode error = GDATA_OTHER_ERROR; scoped_ptr result; { base::RunLoop run_loop; drive::FilesListRequest* request = new drive::FilesListRequest( request_sender_.get(), *url_generator_, test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&error, &result))); request->set_max_results(50); request->set_q(""\\""abcde\\"" in parents""); request_sender_->StartRequestWithRetry(request); run_loop.Run(); } EXPECT_EQ(HTTP_SUCCESS, error); EXPECT_EQ(net::test_server::METHOD_GET, http_request_.method); EXPECT_EQ(""/drive/v2/files?maxResults=50&q=%22abcde%22+in+parents"", http_request_.relative_url); EXPECT_TRUE(result); } TEST_F(DriveApiRequestsTest, FilesListNextPageRequest) { // Set an expected data file containing valid result. expected_data_file_path_ = test_util::GetTestFilePath( ""drive/filelist.json""); GDataErrorCode error = GDATA_OTHER_ERROR; scoped_ptr result; { base::RunLoop run_loop; drive::FilesListNextPageRequest* request = new drive::FilesListNextPageRequest( request_sender_.get(), test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&error, &result))); request->set_next_link(test_server_.GetURL(""/continue/get/file/list"")); request_sender_->StartRequestWithRetry(request); run_loop.Run(); } EXPECT_EQ(HTTP_SUCCESS, error); EXPECT_EQ(net::test_server::METHOD_GET, http_request_.method); EXPECT_EQ(""/continue/get/file/list"", http_request_.relative_url); EXPECT_TRUE(result); } TEST_F(DriveApiRequestsTest, FilesDeleteRequest) { GDataErrorCode error = GDATA_OTHER_ERROR; // Delete a resource with the given resource id. { base::RunLoop run_loop; drive::FilesDeleteRequest* request = new drive::FilesDeleteRequest( request_sender_.get(), *url_generator_, test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&error))); request->set_file_id(""resource_id""); request->set_etag(kTestETag); request_sender_->StartRequestWithRetry(request); run_loop.Run(); } EXPECT_EQ(HTTP_NO_CONTENT, error); EXPECT_EQ(net::test_server::METHOD_DELETE, http_request_.method); EXPECT_EQ(kTestETag, http_request_.headers[""If-Match""]); EXPECT_EQ(""/drive/v2/files/resource_id"", http_request_.relative_url); EXPECT_FALSE(http_request_.has_content); } TEST_F(DriveApiRequestsTest, FilesTrashRequest) { // Set data for the expected result. Directory entry should be returned // if the trashing entry is a directory, so using it here should be fine. expected_data_file_path_ = test_util::GetTestFilePath(""drive/directory_entry.json""); GDataErrorCode error = GDATA_OTHER_ERROR; scoped_ptr file_resource; // Trash a resource with the given resource id. { base::RunLoop run_loop; drive::FilesTrashRequest* request = new drive::FilesTrashRequest( request_sender_.get(), *url_generator_, test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&error, &file_resource))); request->set_file_id(""resource_id""); request_sender_->StartRequestWithRetry(request); run_loop.Run(); } EXPECT_EQ(HTTP_SUCCESS, error); EXPECT_EQ(net::test_server::METHOD_POST, http_request_.method); EXPECT_EQ(""/drive/v2/files/resource_id/trash"", http_request_.relative_url); EXPECT_TRUE(http_request_.has_content); EXPECT_TRUE(http_request_.content.empty()); } TEST_F(DriveApiRequestsTest, ChildrenInsertRequest) { // Set an expected data file containing the children entry. expected_content_type_ = ""application/json""; expected_content_ = kTestChildrenResponse; GDataErrorCode error = GDATA_OTHER_ERROR; // Add a resource with ""resource_id"" to a directory with // ""parent_resource_id"". { base::RunLoop run_loop; drive::ChildrenInsertRequest* request = new drive::ChildrenInsertRequest( request_sender_.get(), *url_generator_, test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&error))); request->set_folder_id(""parent_resource_id""); request->set_id(""resource_id""); request_sender_->StartRequestWithRetry(request); run_loop.Run(); } EXPECT_EQ(HTTP_SUCCESS, error); EXPECT_EQ(net::test_server::METHOD_POST, http_request_.method); EXPECT_EQ(""/drive/v2/files/parent_resource_id/children"", http_request_.relative_url); EXPECT_EQ(""application/json"", http_request_.headers[""Content-Type""]); EXPECT_TRUE(http_request_.has_content); EXPECT_EQ(""{\\""id\\"":\\""resource_id\\""}"", http_request_.content); } TEST_F(DriveApiRequestsTest, ChildrenDeleteRequest) { GDataErrorCode error = GDATA_OTHER_ERROR; // Remove a resource with ""resource_id"" from a directory with // ""parent_resource_id"". { base::RunLoop run_loop; drive::ChildrenDeleteRequest* request = new drive::ChildrenDeleteRequest( request_sender_.get(), *url_generator_, test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&error))); request->set_child_id(""resource_id""); request->set_folder_id(""parent_resource_id""); request_sender_->StartRequestWithRetry(request); run_loop.Run(); } EXPECT_EQ(HTTP_NO_CONTENT, error); EXPECT_EQ(net::test_server::METHOD_DELETE, http_request_.method); EXPECT_EQ(""/drive/v2/files/parent_resource_id/children/resource_id"", http_request_.relative_url); EXPECT_FALSE(http_request_.has_content); } TEST_F(DriveApiRequestsTest, UploadNewFileRequest) { // Set an expected url for uploading. expected_upload_path_ = kTestUploadNewFilePath; const char kTestContentType[] = ""text/plain""; const std::string kTestContent(100, 'a'); const base::FilePath kTestFilePath = temp_dir_.path().AppendASCII(""upload_file.txt""); ASSERT_TRUE(test_util::WriteStringToFile(kTestFilePath, kTestContent)); GDataErrorCode error = GDATA_OTHER_ERROR; GURL upload_url; // Initiate uploading a new file to the directory with // ""parent_resource_id"". { base::RunLoop run_loop; drive::InitiateUploadNewFileRequest* request = new drive::InitiateUploadNewFileRequest( request_sender_.get(), *url_generator_, kTestContentType, kTestContent.size(), ""parent_resource_id"", // The resource id of the parent directory. ""new file title"", // The title of the file being uploaded. test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&error, &upload_url))); request_sender_->StartRequestWithRetry(request); run_loop.Run(); } EXPECT_EQ(HTTP_SUCCESS, error); EXPECT_EQ(kTestUploadNewFilePath, upload_url.path()); EXPECT_EQ(kTestContentType, http_request_.headers[""X-Upload-Content-Type""]); EXPECT_EQ(base::Int64ToString(kTestContent.size()), http_request_.headers[""X-Upload-Content-Length""]); EXPECT_EQ(net::test_server::METHOD_POST, http_request_.method); EXPECT_EQ(""/upload/drive/v2/files?uploadType=resumable"", http_request_.relative_url); EXPECT_EQ(""application/json"", http_request_.headers[""Content-Type""]); EXPECT_TRUE(http_request_.has_content); EXPECT_EQ(""{\\""parents\\"":[{"" ""\\""id\\"":\\""parent_resource_id\\"","" ""\\""kind\\"":\\""drive#fileLink\\"""" ""}],"" ""\\""title\\"":\\""new file title\\""}"", http_request_.content); // Upload the content to the upload URL. UploadRangeResponse response; scoped_ptr new_entry; { base::RunLoop run_loop; drive::ResumeUploadRequest* resume_request = new drive::ResumeUploadRequest( request_sender_.get(), upload_url, 0, // start_position kTestContent.size(), // end_position (exclusive) kTestContent.size(), // content_length, kTestContentType, kTestFilePath, test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&response, &new_entry)), ProgressCallback()); request_sender_->StartRequestWithRetry(resume_request); run_loop.Run(); } // METHOD_PUT should be used to upload data. EXPECT_EQ(net::test_server::METHOD_PUT, http_request_.method); // Request should go to the upload URL. EXPECT_EQ(upload_url.path(), http_request_.relative_url); // Content-Range header should be added. EXPECT_EQ(""bytes 0-"" + base::Int64ToString(kTestContent.size() - 1) + ""/"" + base::Int64ToString(kTestContent.size()), http_request_.headers[""Content-Range""]); // The upload content should be set in the HTTP request. EXPECT_TRUE(http_request_.has_content); EXPECT_EQ(kTestContent, http_request_.content); // Check the response. EXPECT_EQ(HTTP_CREATED, response.code); // Because it's a new file // The start and end positions should be set to -1, if an upload is complete. EXPECT_EQ(-1, response.start_position_received); EXPECT_EQ(-1, response.end_position_received); } TEST_F(DriveApiRequestsTest, UploadNewEmptyFileRequest) { // Set an expected url for uploading. expected_upload_path_ = kTestUploadNewFilePath; const char kTestContentType[] = ""text/plain""; const char kTestContent[] = """"; const base::FilePath kTestFilePath = temp_dir_.path().AppendASCII(""empty_file.txt""); ASSERT_TRUE(test_util::WriteStringToFile(kTestFilePath, kTestContent)); GDataErrorCode error = GDATA_OTHER_ERROR; GURL upload_url; // Initiate uploading a new file to the directory with ""parent_resource_id"". { base::RunLoop run_loop; drive::InitiateUploadNewFileRequest* request = new drive::InitiateUploadNewFileRequest( request_sender_.get(), *url_generator_, kTestContentType, 0, ""parent_resource_id"", // The resource id of the parent directory. ""new file title"", // The title of the file being uploaded. test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&error, &upload_url))); request_sender_->StartRequestWithRetry(request); run_loop.Run(); } EXPECT_EQ(HTTP_SUCCESS, error); EXPECT_EQ(kTestUploadNewFilePath, upload_url.path()); EXPECT_EQ(kTestContentType, http_request_.headers[""X-Upload-Content-Type""]); EXPECT_EQ(""0"", http_request_.headers[""X-Upload-Content-Length""]); EXPECT_EQ(net::test_server::METHOD_POST, http_request_.method); EXPECT_EQ(""/upload/drive/v2/files?uploadType=resumable"", http_request_.relative_url); EXPECT_EQ(""application/json"", http_request_.headers[""Content-Type""]); EXPECT_TRUE(http_request_.has_content); EXPECT_EQ(""{\\""parents\\"":[{"" ""\\""id\\"":\\""parent_resource_id\\"","" ""\\""kind\\"":\\""drive#fileLink\\"""" ""}],"" ""\\""title\\"":\\""new file title\\""}"", http_request_.content); // Upload the content to the upload URL. UploadRangeResponse response; scoped_ptr new_entry; { base::RunLoop run_loop; drive::ResumeUploadRequest* resume_request = new drive::ResumeUploadRequest( request_sender_.get(), upload_url, 0, // start_position 0, // end_position (exclusive) 0, // content_length, kTestContentType, kTestFilePath, test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&response, &new_entry)), ProgressCallback()); request_sender_->StartRequestWithRetry(resume_request); run_loop.Run(); } // METHOD_PUT should be used to upload data. EXPECT_EQ(net::test_server::METHOD_PUT, http_request_.method); // Request should go to the upload URL. EXPECT_EQ(upload_url.path(), http_request_.relative_url); // Content-Range header should NOT be added. EXPECT_EQ(0U, http_request_.headers.count(""Content-Range"")); // The upload content should be set in the HTTP request. EXPECT_TRUE(http_request_.has_content); EXPECT_EQ(kTestContent, http_request_.content); // Check the response. EXPECT_EQ(HTTP_CREATED, response.code); // Because it's a new file // The start and end positions should be set to -1, if an upload is complete. EXPECT_EQ(-1, response.start_position_received); EXPECT_EQ(-1, response.end_position_received); } TEST_F(DriveApiRequestsTest, UploadNewLargeFileRequest) { // Set an expected url for uploading. expected_upload_path_ = kTestUploadNewFilePath; const char kTestContentType[] = ""text/plain""; const size_t kNumChunkBytes = 10; // Num bytes in a chunk. const std::string kTestContent(100, 'a'); const base::FilePath kTestFilePath = temp_dir_.path().AppendASCII(""upload_file.txt""); ASSERT_TRUE(test_util::WriteStringToFile(kTestFilePath, kTestContent)); GDataErrorCode error = GDATA_OTHER_ERROR; GURL upload_url; // Initiate uploading a new file to the directory with ""parent_resource_id"". { base::RunLoop run_loop; drive::InitiateUploadNewFileRequest* request = new drive::InitiateUploadNewFileRequest( request_sender_.get(), *url_generator_, kTestContentType, kTestContent.size(), ""parent_resource_id"", // The resource id of the parent directory. ""new file title"", // The title of the file being uploaded. test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&error, &upload_url))); request_sender_->StartRequestWithRetry(request); run_loop.Run(); } EXPECT_EQ(HTTP_SUCCESS, error); EXPECT_EQ(kTestUploadNewFilePath, upload_url.path()); EXPECT_EQ(kTestContentType, http_request_.headers[""X-Upload-Content-Type""]); EXPECT_EQ(base::Int64ToString(kTestContent.size()), http_request_.headers[""X-Upload-Content-Length""]); EXPECT_EQ(net::test_server::METHOD_POST, http_request_.method); EXPECT_EQ(""/upload/drive/v2/files?uploadType=resumable"", http_request_.relative_url); EXPECT_EQ(""application/json"", http_request_.headers[""Content-Type""]); EXPECT_TRUE(http_request_.has_content); EXPECT_EQ(""{\\""parents\\"":[{"" ""\\""id\\"":\\""parent_resource_id\\"","" ""\\""kind\\"":\\""drive#fileLink\\"""" ""}],"" ""\\""title\\"":\\""new file title\\""}"", http_request_.content); // Before sending any data, check the current status. // This is an edge case test for GetUploadStatusRequest. { UploadRangeResponse response; scoped_ptr new_entry; // Check the response by GetUploadStatusRequest. { base::RunLoop run_loop; drive::GetUploadStatusRequest* get_upload_status_request = new drive::GetUploadStatusRequest( request_sender_.get(), upload_url, kTestContent.size(), test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&response, &new_entry))); request_sender_->StartRequestWithRetry(get_upload_status_request); run_loop.Run(); } // METHOD_PUT should be used to upload data. EXPECT_EQ(net::test_server::METHOD_PUT, http_request_.method); // Request should go to the upload URL. EXPECT_EQ(upload_url.path(), http_request_.relative_url); // Content-Range header should be added. EXPECT_EQ(""bytes */"" + base::Int64ToString(kTestContent.size()), http_request_.headers[""Content-Range""]); EXPECT_TRUE(http_request_.has_content); EXPECT_TRUE(http_request_.content.empty()); // Check the response. EXPECT_EQ(HTTP_RESUME_INCOMPLETE, response.code); EXPECT_EQ(0, response.start_position_received); EXPECT_EQ(0, response.end_position_received); } // Upload the content to the upload URL. for (size_t start_position = 0; start_position < kTestContent.size(); start_position += kNumChunkBytes) { const std::string payload = kTestContent.substr( start_position, std::min(kNumChunkBytes, kTestContent.size() - start_position)); const size_t end_position = start_position + payload.size(); UploadRangeResponse response; scoped_ptr new_entry; { base::RunLoop run_loop; drive::ResumeUploadRequest* resume_request = new drive::ResumeUploadRequest( request_sender_.get(), upload_url, start_position, end_position, kTestContent.size(), // content_length, kTestContentType, kTestFilePath, test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&response, &new_entry)), ProgressCallback()); request_sender_->StartRequestWithRetry(resume_request); run_loop.Run(); } // METHOD_PUT should be used to upload data. EXPECT_EQ(net::test_server::METHOD_PUT, http_request_.method); // Request should go to the upload URL. EXPECT_EQ(upload_url.path(), http_request_.relative_url); // Content-Range header should be added. EXPECT_EQ(""bytes "" + base::Int64ToString(start_position) + ""-"" + base::Int64ToString(end_position - 1) + ""/"" + base::Int64ToString(kTestContent.size()), http_request_.headers[""Content-Range""]); // The upload content should be set in the HTTP request. EXPECT_TRUE(http_request_.has_content); EXPECT_EQ(payload, http_request_.content); if (end_position == kTestContent.size()) { // Check the response. EXPECT_EQ(HTTP_CREATED, response.code); // Because it's a new file // The start and end positions should be set to -1, if an upload is // complete. EXPECT_EQ(-1, response.start_position_received); EXPECT_EQ(-1, response.end_position_received); break; } // Check the response. EXPECT_EQ(HTTP_RESUME_INCOMPLETE, response.code); EXPECT_EQ(0, response.start_position_received); EXPECT_EQ(static_cast(end_position), response.end_position_received); // Check the response by GetUploadStatusRequest. { base::RunLoop run_loop; drive::GetUploadStatusRequest* get_upload_status_request = new drive::GetUploadStatusRequest( request_sender_.get(), upload_url, kTestContent.size(), test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&response, &new_entry))); request_sender_->StartRequestWithRetry(get_upload_status_request); run_loop.Run(); } // METHOD_PUT should be used to upload data. EXPECT_EQ(net::test_server::METHOD_PUT, http_request_.method); // Request should go to the upload URL. EXPECT_EQ(upload_url.path(), http_request_.relative_url); // Content-Range header should be added. EXPECT_EQ(""bytes */"" + base::Int64ToString(kTestContent.size()), http_request_.headers[""Content-Range""]); EXPECT_TRUE(http_request_.has_content); EXPECT_TRUE(http_request_.content.empty()); // Check the response. EXPECT_EQ(HTTP_RESUME_INCOMPLETE, response.code); EXPECT_EQ(0, response.start_position_received); EXPECT_EQ(static_cast(end_position), response.end_position_received); } } TEST_F(DriveApiRequestsTest, UploadNewFileWithMetadataRequest) { const base::Time::Exploded kModifiedDate = {2012, 7, 0, 19, 15, 59, 13, 123}; const base::Time::Exploded kLastViewedByMeDate = {2013, 7, 0, 19, 15, 59, 13, 123}; // Set an expected url for uploading. expected_upload_path_ = kTestUploadNewFilePath; const char kTestContentType[] = ""text/plain""; const std::string kTestContent(100, 'a'); GDataErrorCode error = GDATA_OTHER_ERROR; GURL upload_url; // Initiate uploading a new file to the directory with ""parent_resource_id"". { base::RunLoop run_loop; drive::InitiateUploadNewFileRequest* request = new drive::InitiateUploadNewFileRequest( request_sender_.get(), *url_generator_, kTestContentType, kTestContent.size(), ""parent_resource_id"", // The resource id of the parent directory. ""new file title"", // The title of the file being uploaded. test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&error, &upload_url))); request->set_modified_date(base::Time::FromUTCExploded(kModifiedDate)); request->set_last_viewed_by_me_date( base::Time::FromUTCExploded(kLastViewedByMeDate)); request_sender_->StartRequestWithRetry(request); run_loop.Run(); } EXPECT_EQ(HTTP_SUCCESS, error); EXPECT_EQ(kTestUploadNewFilePath, upload_url.path()); EXPECT_EQ(kTestContentType, http_request_.headers[""X-Upload-Content-Type""]); EXPECT_EQ(base::Int64ToString(kTestContent.size()), http_request_.headers[""X-Upload-Content-Length""]); EXPECT_EQ(net::test_server::METHOD_POST, http_request_.method); EXPECT_EQ(""/upload/drive/v2/files?uploadType=resumable&setModifiedDate=true"", http_request_.relative_url); EXPECT_EQ(""application/json"", http_request_.headers[""Content-Type""]); EXPECT_TRUE(http_request_.has_content); EXPECT_EQ(""{\\""lastViewedByMeDate\\"":\\""2013-07-19T15:59:13.123Z\\"","" ""\\""modifiedDate\\"":\\""2012-07-19T15:59:13.123Z\\"","" ""\\""parents\\"":[{\\""id\\"":\\""parent_resource_id\\"","" ""\\""kind\\"":\\""drive#fileLink\\""}],"" ""\\""title\\"":\\""new file title\\""}"", http_request_.content); } TEST_F(DriveApiRequestsTest, UploadExistingFileRequest) { // Set an expected url for uploading. expected_upload_path_ = kTestUploadExistingFilePath; const char kTestContentType[] = ""text/plain""; const std::string kTestContent(100, 'a'); const base::FilePath kTestFilePath = temp_dir_.path().AppendASCII(""upload_file.txt""); ASSERT_TRUE(test_util::WriteStringToFile(kTestFilePath, kTestContent)); GDataErrorCode error = GDATA_OTHER_ERROR; GURL upload_url; // Initiate uploading a new file to the directory with ""parent_resource_id"". { base::RunLoop run_loop; drive::InitiateUploadExistingFileRequest* request = new drive::InitiateUploadExistingFileRequest( request_sender_.get(), *url_generator_, kTestContentType, kTestContent.size(), ""resource_id"", // The resource id of the file to be overwritten. std::string(), // No etag. test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&error, &upload_url))); request_sender_->StartRequestWithRetry(request); run_loop.Run(); } EXPECT_EQ(HTTP_SUCCESS, error); EXPECT_EQ(kTestUploadExistingFilePath, upload_url.path()); EXPECT_EQ(kTestContentType, http_request_.headers[""X-Upload-Content-Type""]); EXPECT_EQ(base::Int64ToString(kTestContent.size()), http_request_.headers[""X-Upload-Content-Length""]); EXPECT_EQ(""*"", http_request_.headers[""If-Match""]); EXPECT_EQ(net::test_server::METHOD_PUT, http_request_.method); EXPECT_EQ(""/upload/drive/v2/files/resource_id?uploadType=resumable"", http_request_.relative_url); EXPECT_TRUE(http_request_.has_content); EXPECT_TRUE(http_request_.content.empty()); // Upload the content to the upload URL. UploadRangeResponse response; scoped_ptr new_entry; { base::RunLoop run_loop; drive::ResumeUploadRequest* resume_request = new drive::ResumeUploadRequest( request_sender_.get(), upload_url, 0, // start_position kTestContent.size(), // end_position (exclusive) kTestContent.size(), // content_length, kTestContentType, kTestFilePath, test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&response, &new_entry)), ProgressCallback()); request_sender_->StartRequestWithRetry(resume_request); run_loop.Run(); } // METHOD_PUT should be used to upload data. EXPECT_EQ(net::test_server::METHOD_PUT, http_request_.method); // Request should go to the upload URL. EXPECT_EQ(upload_url.path(), http_request_.relative_url); // Content-Range header should be added. EXPECT_EQ(""bytes 0-"" + base::Int64ToString(kTestContent.size() - 1) + ""/"" + base::Int64ToString(kTestContent.size()), http_request_.headers[""Content-Range""]); // The upload content should be set in the HTTP request. EXPECT_TRUE(http_request_.has_content); EXPECT_EQ(kTestContent, http_request_.content); // Check the response. EXPECT_EQ(HTTP_SUCCESS, response.code); // Because it's an existing file // The start and end positions should be set to -1, if an upload is complete. EXPECT_EQ(-1, response.start_position_received); EXPECT_EQ(-1, response.end_position_received); } TEST_F(DriveApiRequestsTest, UploadExistingFileRequestWithETag) { // Set an expected url for uploading. expected_upload_path_ = kTestUploadExistingFilePath; const char kTestContentType[] = ""text/plain""; const std::string kTestContent(100, 'a'); const base::FilePath kTestFilePath = temp_dir_.path().AppendASCII(""upload_file.txt""); ASSERT_TRUE(test_util::WriteStringToFile(kTestFilePath, kTestContent)); GDataErrorCode error = GDATA_OTHER_ERROR; GURL upload_url; // Initiate uploading a new file to the directory with ""parent_resource_id"". { base::RunLoop run_loop; drive::InitiateUploadExistingFileRequest* request = new drive::InitiateUploadExistingFileRequest( request_sender_.get(), *url_generator_, kTestContentType, kTestContent.size(), ""resource_id"", // The resource id of the file to be overwritten. kTestETag, test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&error, &upload_url))); request_sender_->StartRequestWithRetry(request); run_loop.Run(); } EXPECT_EQ(HTTP_SUCCESS, error); EXPECT_EQ(kTestUploadExistingFilePath, upload_url.path()); EXPECT_EQ(kTestContentType, http_request_.headers[""X-Upload-Content-Type""]); EXPECT_EQ(base::Int64ToString(kTestContent.size()), http_request_.headers[""X-Upload-Content-Length""]); EXPECT_EQ(kTestETag, http_request_.headers[""If-Match""]); EXPECT_EQ(net::test_server::METHOD_PUT, http_request_.method); EXPECT_EQ(""/upload/drive/v2/files/resource_id?uploadType=resumable"", http_request_.relative_url); EXPECT_TRUE(http_request_.has_content); EXPECT_TRUE(http_request_.content.empty()); // Upload the content to the upload URL. UploadRangeResponse response; scoped_ptr new_entry; { base::RunLoop run_loop; drive::ResumeUploadRequest* resume_request = new drive::ResumeUploadRequest( request_sender_.get(), upload_url, 0, // start_position kTestContent.size(), // end_position (exclusive) kTestContent.size(), // content_length, kTestContentType, kTestFilePath, test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&response, &new_entry)), ProgressCallback()); request_sender_->StartRequestWithRetry(resume_request); run_loop.Run(); } // METHOD_PUT should be used to upload data. EXPECT_EQ(net::test_server::METHOD_PUT, http_request_.method); // Request should go to the upload URL. EXPECT_EQ(upload_url.path(), http_request_.relative_url); // Content-Range header should be added. EXPECT_EQ(""bytes 0-"" + base::Int64ToString(kTestContent.size() - 1) + ""/"" + base::Int64ToString(kTestContent.size()), http_request_.headers[""Content-Range""]); // The upload content should be set in the HTTP request. EXPECT_TRUE(http_request_.has_content); EXPECT_EQ(kTestContent, http_request_.content); // Check the response. EXPECT_EQ(HTTP_SUCCESS, response.code); // Because it's an existing file // The start and end positions should be set to -1, if an upload is complete. EXPECT_EQ(-1, response.start_position_received); EXPECT_EQ(-1, response.end_position_received); } TEST_F(DriveApiRequestsTest, UploadExistingFileRequestWithETagConflicting) { // Set an expected url for uploading. expected_upload_path_ = kTestUploadExistingFilePath; // If it turned out that the etag is conflicting, PRECONDITION_FAILED should // be returned. expected_precondition_failed_file_path_ = test_util::GetTestFilePath(""drive/error.json""); const char kTestContentType[] = ""text/plain""; const std::string kTestContent(100, 'a'); GDataErrorCode error = GDATA_OTHER_ERROR; GURL upload_url; // Initiate uploading a new file to the directory with ""parent_resource_id"". { base::RunLoop run_loop; drive::InitiateUploadExistingFileRequest* request = new drive::InitiateUploadExistingFileRequest( request_sender_.get(), *url_generator_, kTestContentType, kTestContent.size(), ""resource_id"", // The resource id of the file to be overwritten. ""Conflicting-etag"", test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&error, &upload_url))); request_sender_->StartRequestWithRetry(request); run_loop.Run(); } EXPECT_EQ(HTTP_PRECONDITION, error); EXPECT_EQ(kTestContentType, http_request_.headers[""X-Upload-Content-Type""]); EXPECT_EQ(base::Int64ToString(kTestContent.size()), http_request_.headers[""X-Upload-Content-Length""]); EXPECT_EQ(""Conflicting-etag"", http_request_.headers[""If-Match""]); EXPECT_EQ(net::test_server::METHOD_PUT, http_request_.method); EXPECT_EQ(""/upload/drive/v2/files/resource_id?uploadType=resumable"", http_request_.relative_url); EXPECT_TRUE(http_request_.has_content); EXPECT_TRUE(http_request_.content.empty()); } TEST_F(DriveApiRequestsTest, UploadExistingFileRequestWithETagConflictOnResumeUpload) { // Set an expected url for uploading. expected_upload_path_ = kTestUploadExistingFilePath; const char kTestContentType[] = ""text/plain""; const std::string kTestContent(100, 'a'); const base::FilePath kTestFilePath = temp_dir_.path().AppendASCII(""upload_file.txt""); ASSERT_TRUE(test_util::WriteStringToFile(kTestFilePath, kTestContent)); GDataErrorCode error = GDATA_OTHER_ERROR; GURL upload_url; // Initiate uploading a new file to the directory with ""parent_resource_id"". { base::RunLoop run_loop; drive::InitiateUploadExistingFileRequest* request = new drive::InitiateUploadExistingFileRequest( request_sender_.get(), *url_generator_, kTestContentType, kTestContent.size(), ""resource_id"", // The resource id of the file to be overwritten. kTestETag, test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&error, &upload_url))); request_sender_->StartRequestWithRetry(request); run_loop.Run(); } EXPECT_EQ(HTTP_SUCCESS, error); EXPECT_EQ(kTestUploadExistingFilePath, upload_url.path()); EXPECT_EQ(kTestContentType, http_request_.headers[""X-Upload-Content-Type""]); EXPECT_EQ(base::Int64ToString(kTestContent.size()), http_request_.headers[""X-Upload-Content-Length""]); EXPECT_EQ(kTestETag, http_request_.headers[""If-Match""]); EXPECT_EQ(net::test_server::METHOD_PUT, http_request_.method); EXPECT_EQ(""/upload/drive/v2/files/resource_id?uploadType=resumable"", http_request_.relative_url); EXPECT_TRUE(http_request_.has_content); EXPECT_TRUE(http_request_.content.empty()); // Set PRECONDITION_FAILED to the server. This is the emulation of the // confliction during uploading. expected_precondition_failed_file_path_ = test_util::GetTestFilePath(""drive/error.json""); // Upload the content to the upload URL. UploadRangeResponse response; scoped_ptr new_entry; { base::RunLoop run_loop; drive::ResumeUploadRequest* resume_request = new drive::ResumeUploadRequest( request_sender_.get(), upload_url, 0, // start_position kTestContent.size(), // end_position (exclusive) kTestContent.size(), // content_length, kTestContentType, kTestFilePath, test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&response, &new_entry)), ProgressCallback()); request_sender_->StartRequestWithRetry(resume_request); run_loop.Run(); } // METHOD_PUT should be used to upload data. EXPECT_EQ(net::test_server::METHOD_PUT, http_request_.method); // Request should go to the upload URL. EXPECT_EQ(upload_url.path(), http_request_.relative_url); // Content-Range header should be added. EXPECT_EQ(""bytes 0-"" + base::Int64ToString(kTestContent.size() - 1) + ""/"" + base::Int64ToString(kTestContent.size()), http_request_.headers[""Content-Range""]); // The upload content should be set in the HTTP request. EXPECT_TRUE(http_request_.has_content); EXPECT_EQ(kTestContent, http_request_.content); // Check the response. EXPECT_EQ(HTTP_PRECONDITION, response.code); // The start and end positions should be set to -1 for error. EXPECT_EQ(-1, response.start_position_received); EXPECT_EQ(-1, response.end_position_received); // New entry should be NULL. EXPECT_FALSE(new_entry.get()); } TEST_F(DriveApiRequestsTest, UploadExistingFileWithMetadataRequest) { const base::Time::Exploded kModifiedDate = {2012, 7, 0, 19, 15, 59, 13, 123}; const base::Time::Exploded kLastViewedByMeDate = {2013, 7, 0, 19, 15, 59, 13, 123}; // Set an expected url for uploading. expected_upload_path_ = kTestUploadExistingFilePath; const char kTestContentType[] = ""text/plain""; const std::string kTestContent(100, 'a'); GDataErrorCode error = GDATA_OTHER_ERROR; GURL upload_url; // Initiate uploading a new file to the directory with ""parent_resource_id"". { base::RunLoop run_loop; drive::InitiateUploadExistingFileRequest* request = new drive::InitiateUploadExistingFileRequest( request_sender_.get(), *url_generator_, kTestContentType, kTestContent.size(), ""resource_id"", // The resource id of the file to be overwritten. kTestETag, test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&error, &upload_url))); request->set_parent_resource_id(""new_parent_resource_id""); request->set_title(""new file title""); request->set_modified_date(base::Time::FromUTCExploded(kModifiedDate)); request->set_last_viewed_by_me_date( base::Time::FromUTCExploded(kLastViewedByMeDate)); request_sender_->StartRequestWithRetry(request); run_loop.Run(); } EXPECT_EQ(HTTP_SUCCESS, error); EXPECT_EQ(kTestUploadExistingFilePath, upload_url.path()); EXPECT_EQ(kTestContentType, http_request_.headers[""X-Upload-Content-Type""]); EXPECT_EQ(base::Int64ToString(kTestContent.size()), http_request_.headers[""X-Upload-Content-Length""]); EXPECT_EQ(kTestETag, http_request_.headers[""If-Match""]); EXPECT_EQ(net::test_server::METHOD_PUT, http_request_.method); EXPECT_EQ(""/upload/drive/v2/files/resource_id?"" ""uploadType=resumable&setModifiedDate=true"", http_request_.relative_url); EXPECT_EQ(""application/json"", http_request_.headers[""Content-Type""]); EXPECT_TRUE(http_request_.has_content); EXPECT_EQ(""{\\""lastViewedByMeDate\\"":\\""2013-07-19T15:59:13.123Z\\"","" ""\\""modifiedDate\\"":\\""2012-07-19T15:59:13.123Z\\"","" ""\\""parents\\"":[{\\""id\\"":\\""new_parent_resource_id\\"","" ""\\""kind\\"":\\""drive#fileLink\\""}],"" ""\\""title\\"":\\""new file title\\""}"", http_request_.content); } TEST_F(DriveApiRequestsTest, DownloadFileRequest) { const base::FilePath kDownloadedFilePath = temp_dir_.path().AppendASCII(""cache_file""); const std::string kTestId(""dummyId""); GDataErrorCode result_code = GDATA_OTHER_ERROR; base::FilePath temp_file; { base::RunLoop run_loop; drive::DownloadFileRequest* request = new drive::DownloadFileRequest( request_sender_.get(), *url_generator_, kTestId, kDownloadedFilePath, test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&result_code, &temp_file)), GetContentCallback(), ProgressCallback()); request_sender_->StartRequestWithRetry(request); run_loop.Run(); } std::string contents; base::ReadFileToString(temp_file, &contents); base::DeleteFile(temp_file, false); EXPECT_EQ(HTTP_SUCCESS, result_code); EXPECT_EQ(net::test_server::METHOD_GET, http_request_.method); EXPECT_EQ(kTestDownloadPathPrefix + kTestId, http_request_.relative_url); EXPECT_EQ(kDownloadedFilePath, temp_file); const std::string expected_contents = kTestId + kTestId + kTestId; EXPECT_EQ(expected_contents, contents); } TEST_F(DriveApiRequestsTest, DownloadFileRequest_GetContentCallback) { const base::FilePath kDownloadedFilePath = temp_dir_.path().AppendASCII(""cache_file""); const std::string kTestId(""dummyId""); GDataErrorCode result_code = GDATA_OTHER_ERROR; base::FilePath temp_file; std::string contents; { base::RunLoop run_loop; drive::DownloadFileRequest* request = new drive::DownloadFileRequest( request_sender_.get(), *url_generator_, kTestId, kDownloadedFilePath, test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&result_code, &temp_file)), base::Bind(&AppendContent, &contents), ProgressCallback()); request_sender_->StartRequestWithRetry(request); run_loop.Run(); } base::DeleteFile(temp_file, false); EXPECT_EQ(HTTP_SUCCESS, result_code); EXPECT_EQ(net::test_server::METHOD_GET, http_request_.method); EXPECT_EQ(kTestDownloadPathPrefix + kTestId, http_request_.relative_url); EXPECT_EQ(kDownloadedFilePath, temp_file); const std::string expected_contents = kTestId + kTestId + kTestId; EXPECT_EQ(expected_contents, contents); } TEST_F(DriveApiRequestsTest, PermissionsInsertRequest) { expected_content_type_ = ""application/json""; expected_content_ = kTestPermissionResponse; GDataErrorCode error = GDATA_OTHER_ERROR; // Add comment permission to the user ""user@example.com"". { base::RunLoop run_loop; drive::PermissionsInsertRequest* request = new drive::PermissionsInsertRequest( request_sender_.get(), *url_generator_, test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&error))); request->set_id(""resource_id""); request->set_role(drive::PERMISSION_ROLE_COMMENTER); request->set_type(drive::PERMISSION_TYPE_USER); request->set_value(""user@example.com""); request_sender_->StartRequestWithRetry(request); run_loop.Run(); } EXPECT_EQ(HTTP_SUCCESS, error); EXPECT_EQ(net::test_server::METHOD_POST, http_request_.method); EXPECT_EQ(""/drive/v2/files/resource_id/permissions"", http_request_.relative_url); EXPECT_EQ(""application/json"", http_request_.headers[""Content-Type""]); scoped_ptr expected(base::JSONReader::Read( ""{\\""additionalRoles\\"":[\\""commenter\\""], \\""role\\"":\\""reader\\"", "" ""\\""type\\"":\\""user\\"",\\""value\\"":\\""user@example.com\\""}"")); ASSERT_TRUE(expected); scoped_ptr result(base::JSONReader::Read(http_request_.content)); EXPECT_TRUE(http_request_.has_content); EXPECT_TRUE(base::Value::Equals(expected.get(), result.get())); // Add ""can edit"" permission to users in ""example.com"". error = GDATA_OTHER_ERROR; { base::RunLoop run_loop; drive::PermissionsInsertRequest* request = new drive::PermissionsInsertRequest( request_sender_.get(), *url_generator_, test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&error))); request->set_id(""resource_id2""); request->set_role(drive::PERMISSION_ROLE_WRITER); request->set_type(drive::PERMISSION_TYPE_DOMAIN); request->set_value(""example.com""); request_sender_->StartRequestWithRetry(request); run_loop.Run(); } EXPECT_EQ(HTTP_SUCCESS, error); EXPECT_EQ(net::test_server::METHOD_POST, http_request_.method); EXPECT_EQ(""/drive/v2/files/resource_id2/permissions"", http_request_.relative_url); EXPECT_EQ(""application/json"", http_request_.headers[""Content-Type""]); expected.reset(base::JSONReader::Read( ""{\\""role\\"":\\""writer\\"", \\""type\\"":\\""domain\\"",\\""value\\"":\\""example.com\\""}"")); ASSERT_TRUE(expected); result.reset(base::JSONReader::Read(http_request_.content)); EXPECT_TRUE(http_request_.has_content); EXPECT_TRUE(base::Value::Equals(expected.get(), result.get())); } } // namespace google_apis ",16285,True,3531.9009584476175,median "pred test85 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node0->Node1 + Node2->Node0 right = Node2->Node1 elem = Node0->7 + Node1->6 + Node2->5 }} } run test85 for 4 expect 0 pred test14 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node0->Node1 right = Node2->Node0 elem = Node0->7 + Node1->0 + Node2->-5 Sorted[] }} } run test14 for 4 expect 1 pred test87 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node0->Node1 + Node2->Node2 right = Node2->Node0 elem = Node0->7 + Node1->6 + Node2->4 }} } run test87 for 4 expect 0 pred test22 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 left = Node1->Node0 no right elem = Node0->1 + Node1->4 Sorted[] }} } run test22 for 4 expect 1 pred test21 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 left = Node1->Node0 no right elem = Node0->3 + Node1->2 Sorted[] }} } run test21 for 4 expect 0 pred test96 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 left = Node1->Node0 no right elem = Node0->7 + Node1->5 }} } run test96 for 4 expect 1 pred test71 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 left = Node1->Node0 no right elem = Node0->7 + Node1->-4 RepOk[] }} } run test71 for 4 expect 0 pred test43 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2, Node3: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node3 Node = Node0 + Node1 + Node2 + Node3 no left right = Node1->Node2 + Node2->Node0 + Node3->Node1 elem = Node0->7 + Node1->3 + Node2->2 + Node3->-2 Sorted[] }} } run test43 for 4 expect 0 pred test93 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node0->Node2 right = Node0->Node1 + Node2->Node0 elem = Node0->7 + Node1->5 + Node2->5 }} } run test93 for 4 expect 0 pred test88 { some disj BinaryTree0: BinaryTree {some disj Node0: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node0 Node = Node0 no left no right elem = Node0->-1 }} } run test88 for 4 expect 1 pred test106 { some disj BinaryTree0: BinaryTree {some disj Node0: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node0 Node = Node0 no left no right elem = Node0->-5 }} } run test106 for 4 expect 1 pred test48 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 no left right = Node1->Node0 elem = Node0->-7 + Node1->-8 HasAtMostOneChild[Node1] }} } run test48 for 4 expect 1 pred test7 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node0->Node1 + Node2->Node0 no right elem = Node0->7 + Node1->3 + Node2->2 }} } run test7 for 4 expect 1 pred test80 { some disj BinaryTree0: BinaryTree {some disj Node0: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node0 Node = Node0 left = Node0->Node0 no right elem = Node0->1 }} } run test80 for 4 expect 0 pred test104 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 no left right = Node1->Node0 + Node2->Node1 elem = Node0->5 + Node1->5 + Node2->-1 }} } run test104 for 4 expect 1 pred test9 { some disj BinaryTree0: BinaryTree {some disj Node0: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node0 Node = Node0 no left no right no elem }} } run test9 for 4 expect 0 pred test46 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node2->Node0 right = Node2->Node1 elem = Node0->1 + Node1->-2 + Node2->-1 HasAtMostOneChild[Node2] }} } run test46 for 4 expect 0 pred test41 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node0->Node1 right = Node2->Node0 elem = Node0->-5 + Node1->-8 + Node2->-8 Sorted[] }} } run test41 for 4 expect 0 pred test45 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 no left right = Node1->Node0 elem = Node0->5 + Node1->5 Sorted[] }} } run test45 for 4 expect 0 pred test74 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2, Node3: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node3 Node = Node0 + Node1 + Node2 + Node3 left = Node0->Node2 right = Node2->Node1 + Node3->Node0 elem = Node0->7 + Node1->5 + Node2->4 + Node3->2 RepOk[] }} } run test74 for 4 expect 0 pred test34 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 no left right = Node1->Node0 elem = Node0->-7 + Node1->-8 Sorted[] }} } run test34 for 4 expect 1 pred test28 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node1->Node0 right = Node2->Node1 elem = Node0->7 + Node1->7 + Node2->-2 Sorted[] }} } run test28 for 4 expect 0 pred test2 { some disj BinaryTree0, BinaryTree1: BinaryTree {some disj Node0, Node1, Node2, Node3: Node { BinaryTree = BinaryTree0 + BinaryTree1 root = BinaryTree1->Node3 Node = Node0 + Node1 + Node2 + Node3 left = Node1->Node0 + Node3->Node1 right = Node3->Node2 elem = Node0->6 + Node1->5 + Node2->1 + Node3->-8 }} } run test2 for 4 expect 0 pred test23 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 left = Node1->Node0 no right elem = Node0->0 + Node1->-2 Sorted[] }} } run test23 for 4 expect 0 pred test36 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 no left right = Node1->Node0 elem = Node0->0 + Node1->-4 Sorted[] }} } run test36 for 4 expect 1 pred test25 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node2->Node1 right = Node1->Node0 elem = Node0->-3 + Node1->-7 + Node2->-3 Sorted[] }} } run test25 for 4 expect 0 pred test59 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2, Node3: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node3 Node = Node0 + Node1 + Node2 + Node3 left = Node2->Node1 + Node3->Node2 right = Node3->Node0 elem = Node0->7 + Node1->3 + Node2->0 + Node3->-5 Balanced[] }} } run test59 for 4 expect 1 pred test55 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 + Node2 left = Node2->Node0 right = Node1->Node2 elem = Node0->2 + Node1->-8 + Node2->7 HasAtMostOneChild[Node2] }} } run test55 for 4 expect 1 pred test17 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 no left right = Node1->Node0 elem = Node0->-3 + Node1->-1 Sorted[] }} } run test17 for 4 expect 0 pred test62 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2, Node3: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node3 Node = Node0 + Node1 + Node2 + Node3 left = Node2->Node1 + Node3->Node2 right = Node3->Node0 elem = Node0->4 + Node1->4 + Node2->4 + Node3->0 Balanced[] }} } run test62 for 4 expect 1 pred test1 { no BinaryTree no root no Node no left no right no elem } run test1 for 4 expect 0 pred test102 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node1->Node0 + Node2->Node1 no right elem = Node0->5 + Node1->5 + Node2->-1 }} } run test102 for 4 expect 1 pred test8 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node1->Node0 + Node2->Node1 no right elem = Node0->-7 + Node0->-6 + Node0->-5 + Node0->-4 + Node0->-3 + Node0->-2 + Node0->-1 + Node0->0 + Node0->1 + Node0->2 + Node0->3 + Node0->4 + Node0->5 + Node0->6 + Node0->7 + Node1->-8 + Node1->7 + Node2->-7 + Node2->-6 + Node2->-5 + Node2->-4 + Node2->-3 + Node2->-2 + Node2->-1 + Node2->0 + Node2->1 + Node2->2 + Node2->3 + Node2->4 + Node2->5 + Node2->6 + Node2->7 }} } run test8 for 4 expect 0 pred test64 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2, Node3: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node3 Node = Node0 + Node1 + Node2 + Node3 left = Node2->Node1 + Node3->Node2 right = Node3->Node0 elem = Node0->7 + Node1->0 + Node2->-2 + Node3->-5 Balanced[] }} } run test64 for 4 expect 1 pred test57 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node0->Node1 + Node2->Node0 no right elem = Node0->7 + Node1->1 + Node2->-6 Balanced[] }} } run test57 for 4 expect 0 pred test47 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 no left right = Node1->Node0 elem = Node0->-8 + Node1->5 HasAtMostOneChild[Node1] }} } run test47 for 4 expect 1 pred test20 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 left = Node1->Node0 no right elem = Node0->-7 + Node1->-4 Sorted[] }} } run test20 for 4 expect 1 pred test39 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 no left right = Node1->Node0 elem = Node0->-3 + Node1->-2 Sorted[] }} } run test39 for 4 expect 0 pred test72 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node2->Node1 right = Node2->Node0 elem = Node0->3 + Node1->3 + Node2->2 RepOk[] }} } run test72 for 4 expect 0 pred test11 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 left = Node1->Node0 no right elem = Node0->4 + Node1->4 Sorted[] }} } run test11 for 4 expect 0 pred test4 { some disj BinaryTree0: BinaryTree { BinaryTree = BinaryTree0 no root no Node no left no right no elem } } run test4 for 4 expect 1 pred test77 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node0 Node = Node0 + Node1 no left right = Node0->Node1 elem = Node0->7 + Node1->6 Depth[Node1] = 2 }} } run test77 for 4 expect 1 pred test35 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 no left right = Node1->Node0 elem = Node0->0 + Node1->2 Sorted[] }} } run test35 for 4 expect 0 pred test84 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 left = Node1->Node1 right = Node1->Node0 elem = Node0->-4 + Node1->-5 }} } run test84 for 4 expect 0 pred test42 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 no left right = Node1->Node0 elem = Node0->7 + Node1->6 Sorted[] }} } run test42 for 4 expect 1 pred test3 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node0 + BinaryTree0->Node1 Node = Node0 + Node1 left = Node0->Node1 no right elem = Node0->7 + Node1->6 }} } run test3 for 4 expect 0 pred test78 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 left = Node1->Node0 no right elem = Node0->7 + Node1->6 Depth[Node1] = 1 }} } run test78 for 4 expect 1 pred test49 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 left = Node1->Node0 no right elem = Node0->-5 + Node1->-4 HasAtMostOneChild[Node1] }} } run test49 for 4 expect 1 pred test12 { some disj BinaryTree0: BinaryTree {some disj Node0: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node0 Node = Node0 no left no right elem = Node0->-1 Sorted[] }} } run test12 for 4 expect 1 pred test32 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 left = Node1->Node0 no right elem = Node0->-8 + Node1->-7 Sorted[] }} } run test32 for 4 expect 1 pred test94 { some disj BinaryTree0: BinaryTree {some disj Node0: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node0 Node = Node0 no left no right elem = Node0->-4 }} } run test94 for 4 expect 1 pred test73 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2, Node3: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node3 Node = Node0 + Node1 + Node2 + Node3 left = Node2->Node1 + Node3->Node2 right = Node3->Node0 elem = Node0->7 + Node1->5 + Node2->5 + Node3->4 RepOk[] }} } run test73 for 4 expect 0 pred test37 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2, Node3: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node3 Node = Node0 + Node1 + Node2 + Node3 no left right = Node0->Node1 + Node2->Node0 + Node3->Node2 elem = Node0->6 + Node1->6 + Node2->4 + Node3->-4 Sorted[] }} } run test37 for 4 expect 0 pred test97 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node2->Node0 right = Node2->Node1 elem = Node0->7 + Node1->6 + Node2->2 }} } run test97 for 4 expect 1 pred test98 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node2->Node1 right = Node1->Node0 + Node2->Node0 elem = Node0->7 + Node1->7 + Node2->4 }} } run test98 for 4 expect 0 pred test44 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 no left right = Node1->Node0 elem = Node0->1 + Node1->1 Sorted[] }} } run test44 for 4 expect 0 pred test65 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2, Node3: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node3 Node = Node0 + Node1 + Node2 + Node3 left = Node2->Node1 + Node3->Node2 right = Node3->Node0 elem = Node0->7 + Node1->-6 + Node2->-7 + Node3->-8 Balanced[] }} } run test65 for 4 expect 1 pred test107 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 left = Node1->Node0 no right elem = Node0->7 + Node1->1 }} } run test107 for 4 expect 1 pred test30 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 left = Node1->Node0 no right elem = Node0->2 + Node1->2 Sorted[] }} } run test30 for 4 expect 0 pred test109 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node0->Node1 right = Node0->Node1 + Node2->Node0 elem = Node0->7 + Node1->6 + Node2->3 }} } run test109 for 4 expect 0 pred test86 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node2->Node0 right = Node0->Node1 + Node2->Node0 elem = Node0->-6 + Node1->-7 + Node2->-8 }} } run test86 for 4 expect 0 pred test103 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 left = Node1->Node0 no right elem = Node0->7 + Node1->0 }} } run test103 for 4 expect 1 pred test38 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 no left right = Node1->Node0 elem = Node0->-2 + Node1->-3 Sorted[] }} } run test38 for 4 expect 1 pred test105 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node2->Node0 right = Node0->Node1 + Node2->Node0 elem = Node0->7 + Node1->6 + Node2->5 }} } run test105 for 4 expect 0 pred test101 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 no left right = Node1->Node0 elem = Node0->7 + Node1->0 }} } run test101 for 4 expect 1 pred test99 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node2->Node0 right = Node1->Node0 + Node2->Node1 elem = Node0->7 + Node1->6 + Node2->6 }} } run test99 for 4 expect 0 pred test56 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node2->Node1 right = Node1->Node0 elem = Node0->7 + Node1->7 + Node2->6 HasAtMostOneChild[Node2] }} } run test56 for 4 expect 1 pred test58 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2, Node3: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node3 Node = Node0 + Node1 + Node2 + Node3 left = Node2->Node1 + Node3->Node2 right = Node3->Node0 elem = Node0->7 + Node1->6 + Node2->-7 + Node3->-8 Balanced[] }} } run test58 for 4 expect 1 pred test13 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 left = Node1->Node0 no right elem = Node0->3 + Node1->0 Sorted[] }} } run test13 for 4 expect 0 pred test90 { some disj BinaryTree0: BinaryTree {some disj Node0: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node0 Node = Node0 no left right = Node0->Node0 elem = Node0->-6 }} } run test90 for 4 expect 0 pred test54 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 left = Node1->Node0 no right elem = Node0->-6 + Node1->-5 HasAtMostOneChild[Node1] }} } run test54 for 4 expect 1 pred test16 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 left = Node1->Node0 no right elem = Node0->5 + Node1->0 Sorted[] }} } run test16 for 4 expect 0 pred test61 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2, Node3: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node3 Node = Node0 + Node1 + Node2 + Node3 left = Node2->Node1 + Node3->Node2 right = Node3->Node0 elem = Node0->7 + Node1->-2 + Node2->-4 + Node3->-5 Balanced[] }} } run test61 for 4 expect 1 pred test100 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node2->Node0 right = Node1->Node0 + Node2->Node1 elem = Node0->7 + Node1->6 + Node2->5 }} } run test100 for 4 expect 0 pred test110 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node1->Node0 + Node2->Node1 right = Node2->Node1 elem = Node0->7 + Node1->7 + Node2->-2 }} } run test110 for 4 expect 0 pred test81 { some disj BinaryTree0: BinaryTree {some disj Node0: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node0 Node = Node0 no left right = Node0->Node0 elem = Node0->-1 }} } run test81 for 4 expect 0 pred test83 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 left = Node1->Node1 right = Node1->Node0 elem = Node0->-5 + Node1->-6 }} } run test83 for 4 expect 0 pred test63 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2, Node3: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node3 Node = Node0 + Node1 + Node2 + Node3 left = Node2->Node1 + Node3->Node2 right = Node3->Node0 elem = Node0->7 + Node1->7 + Node2->3 + Node3->-6 Balanced[] }} } run test63 for 4 expect 1 pred test76 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 no left right = Node1->Node0 elem = Node0->-5 + Node1->6 Depth[Node1] = 1 }} } run test76 for 4 expect 1 pred test68 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2, Node3: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node3 Node = Node0 + Node1 + Node2 + Node3 left = Node2->Node1 + Node3->Node2 right = Node3->Node0 elem = Node0->6 + Node1->3 + Node2->-7 + Node3->-8 Balanced[] }} } run test68 for 4 expect 1 pred test26 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 left = Node1->Node0 no right elem = Node0->4 + Node1->5 Sorted[] }} } run test26 for 4 expect 1 pred test51 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 + Node2 left = Node1->Node2 right = Node2->Node0 elem = Node0->7 + Node1->-8 + Node2->3 HasAtMostOneChild[Node2] }} } run test51 for 4 expect 1 pred test82 { some disj BinaryTree0: BinaryTree {some disj Node0: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node0 Node = Node0 no left right = Node0->Node0 elem = Node0->-2 }} } run test82 for 4 expect 0 pred test31 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 left = Node1->Node0 no right elem = Node0->6 + Node1->-8 Sorted[] }} } run test31 for 4 expect 0 pred test5 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 no left right = Node1->Node0 elem = Node0->7 + Node1->6 }} } run test5 for 4 expect 1 pred test108 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 left = Node1->Node0 no right elem = Node0->7 + Node1->4 }} } run test108 for 4 expect 1 pred test67 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2, Node3: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node3 Node = Node0 + Node1 + Node2 + Node3 left = Node2->Node1 + Node3->Node2 right = Node3->Node0 elem = Node0->7 + Node1->7 + Node2->7 + Node3->6 Balanced[] }} } run test67 for 4 expect 1 pred test50 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node2->Node0 right = Node2->Node1 elem = Node0->1 + Node1->-7 + Node2->-6 HasAtMostOneChild[Node2] }} } run test50 for 4 expect 0 ",8416,True,3067.789917720525,median "/*========================================================================= Program: Image Guided Surgery Software Toolkit Module: igstkTrackerController.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) ISC Insight Software Consortium. All rights reserved. See IGSTKCopyright.txt or http://www.igstk.org/copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include ""igstkTrackerController.h"" #include ""igstkTrackerConfiguration.h"" #include ""itksys/SystemTools.hxx"" #include ""itksys/Directory.hxx"" #include ""igstkPolarisTracker.h"" #include ""igstkAuroraTracker.h"" #include ""igstkAscensionTracker.h"" #ifdef IGSTK_USE_MicronTracker #include ""igstkMicronTracker.h"" #endif #ifdef IGSTK_USE_Ascension3DGTracker #include ""igstkAscension3DGTracker.h"" #endif namespace igstk { TrackerController::TrackerController() : m_StateMachine( this ) { //create error observer this->m_ErrorObserver = ErrorObserver::New(); //create observer for the tracker update status events this->m_TrackerUpdateStatusObserver = TrackerUpdateObserver::New(); this->m_TrackerUpdateStatusObserver->SetParent( this ); //define the state machine's states igstkAddStateMacro( Idle ); igstkAddStateMacro( AttemptingToInitialize ); igstkAddStateMacro( AttemptingToInitializePolarisVicra ); igstkAddStateMacro( AttemptingToInitializePolarisHybrid ); igstkAddStateMacro( AttemptingToInitializeAurora ); igstkAddStateMacro( AttemptingToInitializeMicron ); igstkAddStateMacro( AttemptingToInitializeAscension3DG ); igstkAddStateMacro( AttemptingToInitializeAscension ); igstkAddStateMacro( Initialized ); igstkAddStateMacro( AttemptingToStartTracking ); igstkAddStateMacro( Tracking ); igstkAddStateMacro( AttemptingToCloseCommunication ); igstkAddStateMacro( AttemptingToStopTracking ); //define the state machine's inputs igstkAddInputMacro( TrackerInitialize ); igstkAddInputMacro( PolarisVicraInitialize ); igstkAddInputMacro( PolarisHybridInitialize ); igstkAddInputMacro( AuroraInitialize ); igstkAddInputMacro( AscensionInitialize ); igstkAddInputMacro( MicronInitialize ); igstkAddInputMacro( Ascension3DGInitialize ); igstkAddInputMacro( StartTracking ); igstkAddInputMacro( StopTracking ); igstkAddInputMacro( Failed ); igstkAddInputMacro( Succeeded ); igstkAddInputMacro( CloseCommunication ); igstkAddInputMacro( GetTools ); igstkAddInputMacro( GetTool ); igstkAddInputMacro( GetReferenceTool ); igstkAddInputMacro( SetParentSpatialObject ); igstkAddInputMacro( SetChildSpatialObject ); //define the state machine's transitions //transitions from Idle state igstkAddTransitionMacro( Idle, TrackerInitialize, AttemptingToInitialize, TrackerInitialize ); igstkAddTransitionMacro( Idle, PolarisVicraInitialize, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( Idle, PolarisHybridInitialize, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( Idle, AuroraInitialize, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( Idle, AscensionInitialize, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( Idle, MicronInitialize, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( Idle, Ascension3DGInitialize, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( Idle, StartTracking, Idle, ReportInvalidRequest); igstkAddTransitionMacro( Idle, StopTracking, Idle, ReportStopTrackingSuccess ); igstkAddTransitionMacro( Idle, Failed, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( Idle, Succeeded, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( Idle, CloseCommunication, Idle, ReportCloseCommunicationSuccess ); igstkAddTransitionMacro( Idle, GetTools, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( Idle, GetTool, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( Idle, GetReferenceTool, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( Idle, SetParentSpatialObject, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( Idle, SetChildSpatialObject, Idle, ReportInvalidRequest ); //transitions from AttemptingToInitialize state igstkAddTransitionMacro( AttemptingToInitialize, Failed, Idle, ReportInitializationFailure ); igstkAddTransitionMacro( AttemptingToInitialize, PolarisVicraInitialize, AttemptingToInitializePolarisVicra, PolarisVicraInitialize ); igstkAddTransitionMacro( AttemptingToInitialize, PolarisHybridInitialize, AttemptingToInitializePolarisHybrid, PolarisHybridInitialize ); igstkAddTransitionMacro( AttemptingToInitialize, AuroraInitialize, AttemptingToInitializeAurora, AuroraInitialize ); igstkAddTransitionMacro( AttemptingToInitialize, AscensionInitialize, AttemptingToInitializeAscension, AscensionInitialize ); igstkAddTransitionMacro( AttemptingToInitialize, MicronInitialize, AttemptingToInitializeMicron, MicronInitialize ); igstkAddTransitionMacro( AttemptingToInitialize, Ascension3DGInitialize, AttemptingToInitializeAscension3DG, Ascension3DGInitialize ); igstkAddTransitionMacro( AttemptingToInitialize, TrackerInitialize, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitialize, StartTracking, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitialize, StopTracking, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitialize, Succeeded, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitialize, CloseCommunication, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitialize, GetTools, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitialize, GetTool, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitialize, GetReferenceTool, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitialize, SetParentSpatialObject, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitialize, SetChildSpatialObject, Idle, ReportInvalidRequest ); //transitions from AttemptingToInitializePolarisVicra state igstkAddTransitionMacro( AttemptingToInitializePolarisVicra, Failed, Idle, ReportInitializationFailure ); igstkAddTransitionMacro( AttemptingToInitializePolarisVicra, Succeeded, Initialized, ReportInitializationSuccess ); igstkAddTransitionMacro( AttemptingToInitializePolarisVicra, TrackerInitialize, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializePolarisVicra, PolarisVicraInitialize, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializePolarisVicra, PolarisHybridInitialize, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializePolarisVicra, AuroraInitialize, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializePolarisVicra, AscensionInitialize, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializePolarisVicra, MicronInitialize, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializePolarisVicra, Ascension3DGInitialize, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializePolarisVicra, StartTracking, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializePolarisVicra, StopTracking, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializePolarisVicra, CloseCommunication, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializePolarisVicra, GetTools, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializePolarisVicra, GetTool, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializePolarisVicra, GetReferenceTool, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializePolarisVicra, SetParentSpatialObject, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializePolarisVicra, SetChildSpatialObject, Idle, ReportInvalidRequest ); //transitions from AttemptingToInitializePolarisHybrid state igstkAddTransitionMacro( AttemptingToInitializePolarisHybrid, Failed, Idle, ReportInitializationFailure ); igstkAddTransitionMacro( AttemptingToInitializePolarisHybrid, Succeeded, Initialized, ReportInitializationSuccess ); igstkAddTransitionMacro( AttemptingToInitializePolarisHybrid, TrackerInitialize, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializePolarisHybrid, PolarisVicraInitialize, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializePolarisHybrid, PolarisHybridInitialize, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializePolarisHybrid, AuroraInitialize, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializePolarisHybrid, AscensionInitialize, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializePolarisHybrid, MicronInitialize, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializePolarisHybrid, Ascension3DGInitialize, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializePolarisHybrid, StartTracking, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializePolarisHybrid, StopTracking, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializePolarisHybrid, CloseCommunication, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializePolarisHybrid, GetTools, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializePolarisHybrid, GetTool, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializePolarisHybrid, GetReferenceTool, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializePolarisHybrid, SetParentSpatialObject, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializePolarisHybrid, SetChildSpatialObject, Idle, ReportInvalidRequest ); //transitions from AttemptingToInitializeAurora state igstkAddTransitionMacro( AttemptingToInitializeAurora, Failed, Idle, ReportInitializationFailure ); igstkAddTransitionMacro( AttemptingToInitializeAurora, Succeeded, Initialized, ReportInitializationSuccess ); igstkAddTransitionMacro( AttemptingToInitializeAurora, TrackerInitialize, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializeAurora, PolarisVicraInitialize, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializeAurora, PolarisHybridInitialize, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializeAurora, AuroraInitialize, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializeAurora, AscensionInitialize, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializeAurora, MicronInitialize, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializeAurora, Ascension3DGInitialize, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializeAurora, StartTracking, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializeAurora, StopTracking, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializeAurora, CloseCommunication, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializeAurora, GetTools, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializeAurora, GetTool, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializeAurora, GetReferenceTool, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializeAurora, SetParentSpatialObject, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializeAurora, SetChildSpatialObject, Idle, ReportInvalidRequest ); //transitions from AttemptingToInitializeAscension state igstkAddTransitionMacro( AttemptingToInitializeAscension, Failed, Idle, ReportInitializationFailure ); igstkAddTransitionMacro( AttemptingToInitializeAscension, Succeeded, Initialized, ReportInitializationSuccess ); igstkAddTransitionMacro( AttemptingToInitializeAscension, TrackerInitialize, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializeAscension, PolarisVicraInitialize, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializeAscension, PolarisHybridInitialize, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializeAscension, AscensionInitialize, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializeAscension, AuroraInitialize, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializeAscension, MicronInitialize, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializeAscension, Ascension3DGInitialize, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializeAscension, StartTracking, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializeAscension, StopTracking, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializeAscension, CloseCommunication, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializeAscension, GetTools, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializeAscension, GetTool, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializeAscension, GetReferenceTool, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializeAscension, SetParentSpatialObject, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializeAscension, SetChildSpatialObject, Idle, ReportInvalidRequest ); //transitions from AttemptingToInitializeMicron state igstkAddTransitionMacro( AttemptingToInitializeMicron, Failed, Idle, ReportInitializationFailure ); igstkAddTransitionMacro( AttemptingToInitializeMicron, Succeeded, Initialized, ReportInitializationSuccess ); igstkAddTransitionMacro( AttemptingToInitializeMicron, TrackerInitialize, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializeMicron, PolarisVicraInitialize, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializeMicron, PolarisHybridInitialize, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializeMicron, AuroraInitialize, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializeMicron, AscensionInitialize, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializeMicron, MicronInitialize, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializeMicron, StartTracking, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializeMicron, StopTracking, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializeMicron, CloseCommunication, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializeMicron, GetTools, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializeMicron, GetTool, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializeMicron, GetReferenceTool, Idle, ReportInvalidRequest); igstkAddTransitionMacro( AttemptingToInitializeMicron, SetParentSpatialObject, Idle, ReportInvalidRequest); igstkAddTransitionMacro( AttemptingToInitializeMicron, SetChildSpatialObject, Idle, ReportInvalidRequest); //transitions from AttemptingToInitializeAscension3DG state igstkAddTransitionMacro( AttemptingToInitializeAscension3DG, Failed, Idle, ReportInitializationFailure ); igstkAddTransitionMacro( AttemptingToInitializeAscension3DG, Succeeded, Initialized, ReportInitializationSuccess ); igstkAddTransitionMacro( AttemptingToInitializeAscension3DG, TrackerInitialize, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializeAscension3DG, PolarisVicraInitialize, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializeAscension3DG, PolarisHybridInitialize, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializeAscension3DG, AuroraInitialize, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializeAscension3DG, AscensionInitialize, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializeAscension3DG, MicronInitialize, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializeAscension3DG, Ascension3DGInitialize, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializeAscension3DG, StartTracking, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializeAscension3DG, StopTracking, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializeAscension3DG, CloseCommunication, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializeAscension3DG, GetTools, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializeAscension3DG, GetTool, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToInitializeAscension3DG, GetReferenceTool, Idle, ReportInvalidRequest); igstkAddTransitionMacro( AttemptingToInitializeAscension3DG, SetParentSpatialObject, Idle, ReportInvalidRequest); igstkAddTransitionMacro( AttemptingToInitializeAscension3DG, SetChildSpatialObject, Idle, ReportInvalidRequest); //transitions from Initialized state igstkAddTransitionMacro( Initialized, GetTools, Initialized, GetTools ); igstkAddTransitionMacro( Initialized, GetTool, Initialized, GetTool ); igstkAddTransitionMacro( Initialized, GetReferenceTool, Initialized, GetReferenceTool ); igstkAddTransitionMacro( Initialized, SetParentSpatialObject, Initialized, SetParentSpatialObject ); igstkAddTransitionMacro( Initialized, SetChildSpatialObject, Initialized, SetChildSpatialObject ); igstkAddTransitionMacro( Initialized, StartTracking, AttemptingToStartTracking, StartTracking); igstkAddTransitionMacro( Initialized, StopTracking, Initialized, ReportStopTrackingSuccess); igstkAddTransitionMacro( Initialized, TrackerInitialize, AttemptingToInitialize, TrackerInitialize ); igstkAddTransitionMacro( Initialized, CloseCommunication, AttemptingToCloseCommunication, CloseCommunication ); igstkAddTransitionMacro( Initialized, PolarisVicraInitialize, Initialized, ReportInvalidRequest ); igstkAddTransitionMacro( Initialized, PolarisHybridInitialize, Initialized, ReportInvalidRequest ); igstkAddTransitionMacro( Initialized, AuroraInitialize, Initialized, ReportInvalidRequest ); igstkAddTransitionMacro( Initialized, AscensionInitialize, Initialized, ReportInvalidRequest ); igstkAddTransitionMacro( Initialized, MicronInitialize, Initialized, ReportInvalidRequest ); igstkAddTransitionMacro( Initialized, Ascension3DGInitialize, Initialized, ReportInvalidRequest ); igstkAddTransitionMacro( Initialized, Failed, Initialized, ReportInvalidRequest ); igstkAddTransitionMacro( Initialized, Succeeded, Initialized, ReportInvalidRequest ); //transitions from AttemptingToStartTracking state igstkAddTransitionMacro( AttemptingToStartTracking, Succeeded, Tracking, ReportStartTrackingSuccess ); igstkAddTransitionMacro( AttemptingToStartTracking, Failed, Initialized, ReportStartTrackingFailure ); igstkAddTransitionMacro( AttemptingToStartTracking, TrackerInitialize, AttemptingToStartTracking, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToStartTracking, PolarisVicraInitialize, AttemptingToStartTracking, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToStartTracking, PolarisHybridInitialize, AttemptingToStartTracking, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToStartTracking, AuroraInitialize, AttemptingToStartTracking, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToStartTracking, AscensionInitialize, AttemptingToStartTracking, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToStartTracking, MicronInitialize, AttemptingToStartTracking, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToStartTracking, Ascension3DGInitialize, AttemptingToStartTracking, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToStartTracking, StartTracking, AttemptingToStartTracking, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToStartTracking, StopTracking, AttemptingToStartTracking, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToStartTracking, CloseCommunication, AttemptingToStartTracking, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToStartTracking, GetTools, AttemptingToStartTracking, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToStartTracking, GetTool, AttemptingToStartTracking, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToStartTracking, GetReferenceTool, AttemptingToStartTracking, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToStartTracking, SetParentSpatialObject, AttemptingToStartTracking, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToStartTracking, SetChildSpatialObject, AttemptingToStartTracking, ReportInvalidRequest ); //transitions from Tracking state igstkAddTransitionMacro( Tracking, StopTracking, AttemptingToStopTracking, StopTracking ); igstkAddTransitionMacro( Tracking, TrackerInitialize, Tracking, ReportInvalidRequest ); igstkAddTransitionMacro( Tracking, PolarisVicraInitialize, Tracking, ReportInvalidRequest ); igstkAddTransitionMacro( Tracking, PolarisHybridInitialize, Tracking, ReportInvalidRequest ); igstkAddTransitionMacro( Tracking, AuroraInitialize, Tracking, ReportInvalidRequest ); igstkAddTransitionMacro( Tracking, AscensionInitialize, Tracking, ReportInvalidRequest ); igstkAddTransitionMacro( Tracking, MicronInitialize, Tracking, ReportInvalidRequest ); igstkAddTransitionMacro( Tracking, Ascension3DGInitialize, Tracking, ReportInvalidRequest ); igstkAddTransitionMacro( Tracking, StartTracking, Tracking, ReportInvalidRequest ); igstkAddTransitionMacro( Tracking, Failed, Tracking, ReportInvalidRequest ); igstkAddTransitionMacro( Tracking, Succeeded, Tracking, ReportInvalidRequest ); igstkAddTransitionMacro( Tracking, CloseCommunication, Tracking, ReportInvalidRequest ); igstkAddTransitionMacro( Tracking, GetTools, Tracking, ReportInvalidRequest ); igstkAddTransitionMacro( Tracking, GetTool, Tracking, ReportInvalidRequest ); igstkAddTransitionMacro( Tracking, GetReferenceTool, Tracking, ReportInvalidRequest ); igstkAddTransitionMacro( Tracking, SetParentSpatialObject, Tracking, SetParentSpatialObject ); igstkAddTransitionMacro( Tracking, SetChildSpatialObject, Tracking, SetChildSpatialObject ); //transitions from AttemtingtoStop state igstkAddTransitionMacro( AttemptingToStopTracking, Succeeded, Initialized, ReportStopTrackingSuccess ); igstkAddTransitionMacro( AttemptingToStopTracking, Failed, Tracking, ReportStopTrackingFailure ); igstkAddTransitionMacro( AttemptingToStopTracking, TrackerInitialize, AttemptingToStopTracking, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToStopTracking, PolarisVicraInitialize, AttemptingToStopTracking, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToStopTracking, PolarisHybridInitialize, AttemptingToStopTracking, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToStopTracking, AuroraInitialize, AttemptingToStopTracking, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToStopTracking, AscensionInitialize, AttemptingToStopTracking, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToStopTracking, MicronInitialize, AttemptingToStopTracking, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToStopTracking, Ascension3DGInitialize, AttemptingToStopTracking, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToStopTracking, StartTracking, AttemptingToStopTracking, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToStopTracking, StopTracking, AttemptingToStopTracking, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToStopTracking, CloseCommunication, AttemptingToStopTracking, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToStopTracking, GetTools, AttemptingToStopTracking, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToStopTracking, GetTool, AttemptingToStopTracking, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToStopTracking, GetReferenceTool, AttemptingToStopTracking, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToStopTracking, SetParentSpatialObject, AttemptingToStopTracking, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToStopTracking, SetChildSpatialObject, AttemptingToStopTracking, ReportInvalidRequest ); //transitions from AttemptingToCloseCommunication state igstkAddTransitionMacro( AttemptingToCloseCommunication, Succeeded, Idle, ReportCloseCommunicationSuccess ); igstkAddTransitionMacro( AttemptingToCloseCommunication, Failed, Initialized, ReportCloseCommunicationFailure ); igstkAddTransitionMacro( AttemptingToCloseCommunication, TrackerInitialize, AttemptingToCloseCommunication, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToCloseCommunication, PolarisVicraInitialize, AttemptingToCloseCommunication, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToCloseCommunication, PolarisHybridInitialize, AttemptingToCloseCommunication, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToCloseCommunication, AuroraInitialize, AttemptingToCloseCommunication, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToCloseCommunication, AscensionInitialize, AttemptingToCloseCommunication, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToCloseCommunication, MicronInitialize, AttemptingToCloseCommunication, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToCloseCommunication, Ascension3DGInitialize, AttemptingToCloseCommunication, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToCloseCommunication, StartTracking, AttemptingToCloseCommunication, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToCloseCommunication, StopTracking, AttemptingToCloseCommunication, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToCloseCommunication, CloseCommunication, AttemptingToCloseCommunication, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToCloseCommunication, GetTools, AttemptingToCloseCommunication, ReportInvalidRequest); igstkAddTransitionMacro( AttemptingToCloseCommunication, GetTool, AttemptingToCloseCommunication, ReportInvalidRequest); igstkAddTransitionMacro( AttemptingToCloseCommunication, GetReferenceTool, AttemptingToCloseCommunication, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToCloseCommunication, SetParentSpatialObject, AttemptingToCloseCommunication, ReportInvalidRequest ); igstkAddTransitionMacro( AttemptingToCloseCommunication, SetChildSpatialObject, AttemptingToCloseCommunication, ReportInvalidRequest ); //set the initial state of the state machine igstkSetInitialStateMacro( Idle ); // done setting the state machine, ready to run this->m_StateMachine.SetReadyToRun(); } TrackerController::~TrackerController() { } void TrackerController::RequestInitialize( const TrackerConfiguration *configuration) { igstkLogMacro( DEBUG, ""igstkTrackerController::RequestInitialize called...\\n"" ); this->m_TmpTrackerConfiguration = const_cast(configuration); igstkPushInputMacro( TrackerInitialize ); this->m_StateMachine.ProcessInputs(); } void TrackerController::RequestStartTracking( ) { igstkLogMacro( DEBUG, ""igstkTrackerController::RequestStartTracking called...\\n"" ); igstkPushInputMacro( StartTracking ); this->m_StateMachine.ProcessInputs(); } void TrackerController::RequestStopTracking() { igstkLogMacro( DEBUG, ""igstkTrackerController::RequestStopTracking called...\\n"" ); igstkPushInputMacro( StopTracking ); this->m_StateMachine.ProcessInputs(); } void TrackerController::RequestShutdown() { igstkLogMacro( DEBUG, ""igstkTrackerController::RequestShutdown called...\\n"" ); igstkPushInputMacro( StopTracking ); igstkPushInputMacro( CloseCommunication ); this->m_StateMachine.ProcessInputs(); } void TrackerController::RequestGetNonReferenceToolList() { igstkLogMacro( DEBUG, ""igstkTrackerController::RequestGetNonReferenceToolList called...\\n"" ); igstkPushInputMacro( GetTools ); this->m_StateMachine.ProcessInputs(); } void TrackerController::RequestGetTool( const std::string &toolName ) { igstkLogMacro( DEBUG, ""igstkTrackerController::RequestGetTool called...\\n"" ); this->m_RequestedToolName = toolName; igstkPushInputMacro( GetTool ); this->m_StateMachine.ProcessInputs(); } void TrackerController::RequestGetReferenceTool() { igstkLogMacro( DEBUG, ""igstkTrackerController::RequestGetReferenceTool called...\\n"" ); igstkPushInputMacro( GetReferenceTool ); this->m_StateMachine.ProcessInputs(); } void TrackerController::RequestSetParentSpatialObject( igstk::Transform transform, igstk::SpatialObject * spatialObject) { igstkLogMacro( DEBUG, ""igstkTrackerController::RequestSetParentSpatialObject called...\\n"" ); m_TmpTransform = transform; m_TmpSpatialObject = spatialObject; igstkPushInputMacro( SetParentSpatialObject ); this->m_StateMachine.ProcessInputs(); } void TrackerController::RequestAddChildSpatialObject( igstk::Transform transform, igstk::SpatialObject * spatialObject) { igstkLogMacro( DEBUG, ""igstkTrackerController::RequestAddChildSpatialObject called...\\n"" ); m_TmpTransform = transform; m_TmpSpatialObject = spatialObject; igstkPushInputMacro( SetChildSpatialObject ); this->m_StateMachine.ProcessInputs(); } void TrackerController::TrackerInitializeProcessing() { if( this->m_TmpTrackerConfiguration == NULL ) { this->m_ErrorMessage = ""Null tracker configuration received.""; igstkPushInputMacro( Failed ); } else { if( dynamic_cast ( this->m_TmpTrackerConfiguration ) ) { this->m_TrackerConfiguration = m_TmpTrackerConfiguration; igstkPushInputMacro( PolarisVicraInitialize ); } else if( dynamic_cast ( this->m_TmpTrackerConfiguration ) ) { this->m_TrackerConfiguration = m_TmpTrackerConfiguration; igstkPushInputMacro( PolarisHybridInitialize ); } else if( dynamic_cast ( this->m_TmpTrackerConfiguration ) ) { this->m_TrackerConfiguration = m_TmpTrackerConfiguration; igstkPushInputMacro( AuroraInitialize ); } else if( dynamic_cast ( this->m_TmpTrackerConfiguration ) ) { this->m_TrackerConfiguration = m_TmpTrackerConfiguration; igstkPushInputMacro( AscensionInitialize ); } #ifdef IGSTK_USE_MicronTracker else if( dynamic_cast ( this->m_TmpTrackerConfiguration ) ) { this->m_TrackerConfiguration = m_TmpTrackerConfiguration; igstkPushInputMacro( MicronInitialize ); } #endif #ifdef IGSTK_USE_Ascension3DGTracker else if( dynamic_cast ( this->m_TmpTrackerConfiguration ) ) { this->m_TrackerConfiguration = m_TmpTrackerConfiguration; igstkPushInputMacro( Ascension3DGInitialize ); } #endif else { this->m_ErrorMessage = ""Unrecognized tracker type (Possibly IGSTK_USE_MicronTracker flag is off).""; igstkPushInputMacro( Failed ); } } this->m_StateMachine.ProcessInputs(); } void TrackerController::StartTrackingProcessing() { unsigned long observerID; observerID = this->m_Tracker->AddObserver( IGSTKErrorEvent(), this->m_ErrorObserver ); m_Tracker->RequestStartTracking(); this->m_Tracker->RemoveObserver(observerID); if( this->m_ErrorObserver->ErrorOccured() ) { this->m_ErrorObserver->GetErrorMessage( this->m_ErrorMessage ); this->m_ErrorObserver->ClearError(); igstkPushInputMacro( Failed ); } else { igstkPushInputMacro( Succeeded ); } this->m_StateMachine.ProcessInputs(); } void TrackerController::StopTrackingProcessing() { unsigned long observerID; observerID = this->m_Tracker->AddObserver( IGSTKErrorEvent(), this->m_ErrorObserver ); this->m_Tracker->RequestStopTracking(); this->m_Tracker->RemoveObserver(observerID); if( this->m_ErrorObserver->ErrorOccured() ) { this->m_ErrorObserver->GetErrorMessage( this->m_ErrorMessage ); this->m_ErrorObserver->ClearError(); igstkPushInputMacro( Failed ); } else { igstkPushInputMacro( Succeeded ); } this->m_StateMachine.ProcessInputs(); } void TrackerController::CloseCommunicationProcessing() { CloseCommunicationErrorEvent evt; unsigned long observerID; observerID = this->m_Tracker->AddObserver( IGSTKErrorEvent(), this->m_ErrorObserver ); //close communication with tracker this->m_Tracker->RequestClose(); this->m_Tracker->RemoveObserver( observerID ); if( this->m_ErrorObserver->ErrorOccured() ) { this->m_ErrorObserver->GetErrorMessage( this->m_ErrorMessage ); this->m_ErrorObserver->ClearError(); igstkPushInputMacro( Failed ); } else { //if serial communication, close COM port if( this->m_SerialCommunication.IsNotNull() ) { observerID = this->m_SerialCommunication->AddObserver( ClosePortErrorEvent(), this->m_ErrorObserver ); this->m_SerialCommunication->CloseCommunication(); this->m_SerialCommunication->RemoveObserver(observerID); if( this->m_ErrorObserver->ErrorOccured() ) { this->m_ErrorObserver->GetErrorMessage( this->m_ErrorMessage ); this->m_ErrorObserver->ClearError(); igstkPushInputMacro( Failed ); } else { igstkPushInputMacro( Succeeded ); } } else //not serial communication { igstkPushInputMacro( Succeeded ); } } this->m_StateMachine.ProcessInputs(); } bool TrackerController::InitializeSerialCommunication() { SerialCommunicatingTrackerConfiguration *serialTrackerConfiguration = dynamic_cast ( this->m_TrackerConfiguration ); //create serial communication this->m_SerialCommunication = igstk::SerialCommunication::New(); //observe errors generated by the serial communication unsigned long observerID = this->m_SerialCommunication->AddObserver( OpenPortErrorEvent(), this->m_ErrorObserver ); this->m_SerialCommunication->SetPortNumber (serialTrackerConfiguration->GetCOMPort() ); this->m_SerialCommunication->SetParity ( serialTrackerConfiguration->GetParity() ); this->m_SerialCommunication->SetBaudRate ( serialTrackerConfiguration->GetBaudRate() ); this->m_SerialCommunication->SetDataBits ( serialTrackerConfiguration->GetDataBits() ); this->m_SerialCommunication->SetStopBits ( serialTrackerConfiguration->GetStopBits() ); this->m_SerialCommunication->SetHardwareHandshake ( serialTrackerConfiguration->GetHandshake() ); this->m_SerialCommunication->OpenCommunication(); //remove the observer, if an error occured we have already //been notified this->m_SerialCommunication->RemoveObserver(observerID); if( this->m_ErrorObserver->ErrorOccured() ) { this->m_ErrorObserver->GetErrorMessage( this->m_ErrorMessage ); this->m_ErrorObserver->ClearError(); return false; } return true; } PolarisTrackerTool::Pointer TrackerController::InitializePolarisWirelessTool( const PolarisWirelessToolConfiguration *toolConfiguration ) { PolarisTrackerTool::Pointer trackerTool = PolarisTrackerTool::New(); trackerTool->RequestSelectWirelessTrackerTool(); trackerTool->RequestSetSROMFileName( toolConfiguration->GetSROMFile() ); trackerTool->SetCalibrationTransform( toolConfiguration->GetCalibrationTransform() ); trackerTool->RequestConfigure(); return trackerTool; } PolarisTrackerTool::Pointer TrackerController::InitializePolarisWiredTool( const PolarisWiredToolConfiguration *toolConfiguration ) { PolarisTrackerTool::Pointer trackerTool = PolarisTrackerTool::New(); trackerTool->RequestSelectWiredTrackerTool(); trackerTool->RequestSetPortNumber( toolConfiguration->GetPortNumber() ); std::string sromFileName = toolConfiguration->GetSROMFile(); if( !sromFileName.empty() ) { trackerTool->RequestSetSROMFileName( sromFileName ); } trackerTool->SetCalibrationTransform( toolConfiguration->GetCalibrationTransform() ); trackerTool->RequestConfigure(); return trackerTool; } void TrackerController::PolarisVicraInitializeProcessing() { if( !InitializeSerialCommunication() ) { igstkPushInputMacro( Failed ); } else { //create tracker igstk::PolarisTracker::Pointer tracker = igstk::PolarisTracker::New(); this->m_Tracker = tracker; //don't need to observe this for errors because the //configuration class ensures that the frequency is valid tracker->RequestSetFrequency( this->m_TrackerConfiguration->GetFrequency() ); //observe all possible errors generated by the tracker //(TrackerOpenErrorEvent, TrackerInitializeErrorEvent) unsigned long observerID = tracker->AddObserver( IGSTKErrorEvent(), this->m_ErrorObserver ); tracker->SetCommunication( this->m_SerialCommunication ); tracker->RequestOpen(); tracker->RemoveObserver(observerID); if( this->m_ErrorObserver->ErrorOccured() ) { this->m_ErrorObserver->GetErrorMessage( this->m_ErrorMessage ); this->m_ErrorObserver->ClearError(); this->m_SerialCommunication->CloseCommunication(); igstkPushInputMacro( Failed ); } else //attach the tools { ToolAttachErrorObserver::Pointer attachErrorObserver = ToolAttachErrorObserver::New(); std::map toolConfigurations = this->m_TrackerConfiguration->m_TrackerToolList; //attach tools std::map::const_iterator it; std::map::const_iterator toolConfigEnd = toolConfigurations.end(); TrackerTool::Pointer currentTool; PolarisWirelessToolConfiguration * currentToolConfig; for( it = toolConfigurations.begin(); it != toolConfigEnd; it++ ) { currentToolConfig = static_cast( it->second ); currentTool = InitializePolarisWirelessTool( currentToolConfig ); this->m_Tools.insert( std::pair( it->first, currentTool ) ); unsigned long observerID = currentTool->AddObserver( TrackerToolAttachmentToTrackerErrorEvent(), attachErrorObserver ); currentTool->RequestAttachToTracker( tracker ); currentTool->RemoveObserver( observerID ); if( attachErrorObserver->GotToolAttachError() ) { igstkPushInputMacro( Failed ); this->m_StateMachine.ProcessInputs(); return; } } //add the reference if we have one TrackerToolConfiguration* referenceToolConfiguration = this->m_TrackerConfiguration->m_ReferenceTool; if( referenceToolConfiguration ) { currentToolConfig = static_cast ( referenceToolConfiguration ); currentTool = InitializePolarisWirelessTool( currentToolConfig ); this->m_ReferenceTool = currentTool; unsigned long observerID = currentTool->AddObserver( TrackerToolAttachmentToTrackerErrorEvent(), attachErrorObserver ); currentTool->RequestAttachToTracker( tracker ); currentTool->RemoveObserver( observerID ); if( attachErrorObserver->GotToolAttachError() ) { igstkPushInputMacro( Failed ); this->m_StateMachine.ProcessInputs(); return; } tracker->RequestSetReferenceTool( currentTool ); } igstkPushInputMacro( Succeeded ); } } this->m_StateMachine.ProcessInputs(); } void TrackerController::PolarisHybridInitializeProcessing() { if( !InitializeSerialCommunication() ) { igstkPushInputMacro( Failed ); } else { //create tracker igstk::PolarisTracker::Pointer tracker = igstk::PolarisTracker::New(); this->m_Tracker = tracker; //don't need to observe this for errors because the //configuration class ensures that the frequency is valid tracker->RequestSetFrequency( this->m_TrackerConfiguration->GetFrequency() ); //observe all possible errors generated by the tracker //(TrackerOpenErrorEvent, TrackerInitializeErrorEvent) unsigned long observerID = tracker->AddObserver( IGSTKErrorEvent(), this->m_ErrorObserver ); tracker->SetCommunication( this->m_SerialCommunication ); tracker->RequestOpen(); tracker->RemoveObserver(observerID); if( this->m_ErrorObserver->ErrorOccured() ) { this->m_ErrorObserver->GetErrorMessage( this->m_ErrorMessage ); this->m_ErrorObserver->ClearError(); this->m_SerialCommunication->CloseCommunication(); igstkPushInputMacro( Failed ); } else //attach the tools { ToolAttachErrorObserver::Pointer attachErrorObserver = ToolAttachErrorObserver::New(); std::map toolConfigurations = this->m_TrackerConfiguration->m_TrackerToolList; //attach tools std::map::const_iterator it; std::map::const_iterator toolConfigEnd = toolConfigurations.end(); TrackerTool::Pointer trackerTool; PolarisWirelessToolConfiguration * wirelessToolConfig; PolarisWiredToolConfiguration * wiredToolConfig; for( it = toolConfigurations.begin(); it != toolConfigEnd; it++ ) { if( ( wirelessToolConfig = dynamic_cast( it->second ) ) ) { trackerTool = InitializePolarisWirelessTool( wirelessToolConfig ); } else { wiredToolConfig = dynamic_cast( it->second ); trackerTool = InitializePolarisWiredTool( wiredToolConfig ); } this->m_Tools.insert( std::pair( it->first, trackerTool ) ); unsigned long observerID = trackerTool->AddObserver( TrackerToolAttachmentToTrackerErrorEvent(), attachErrorObserver ); trackerTool->RequestAttachToTracker( tracker ); trackerTool->RemoveObserver( observerID ); if( attachErrorObserver->GotToolAttachError() ) { igstkPushInputMacro( Failed ); this->m_StateMachine.ProcessInputs(); return; } } //add the reference if we have one TrackerToolConfiguration* referenceToolConfiguration = this->m_TrackerConfiguration->m_ReferenceTool; if( referenceToolConfiguration ) { if ( ( wirelessToolConfig = dynamic_cast( referenceToolConfiguration ) ) ) { trackerTool = InitializePolarisWirelessTool( wirelessToolConfig ); } else { wiredToolConfig = dynamic_cast( referenceToolConfiguration ); trackerTool = InitializePolarisWiredTool( wiredToolConfig ); } this->m_ReferenceTool = trackerTool; unsigned long observerID = trackerTool->AddObserver( TrackerToolAttachmentToTrackerErrorEvent(), attachErrorObserver ); trackerTool->RequestAttachToTracker( tracker ); trackerTool->RemoveObserver( observerID ); if( attachErrorObserver->GotToolAttachError() ) { igstkPushInputMacro( Failed ); this->m_StateMachine.ProcessInputs(); return; } tracker->RequestSetReferenceTool( trackerTool ); } igstkPushInputMacro( Succeeded ); } } this->m_StateMachine.ProcessInputs(); } AuroraTrackerTool::Pointer TrackerController::InitializeAuroraTool( const AuroraToolConfiguration *toolConfiguration ) { AuroraTrackerTool::Pointer trackerTool = AuroraTrackerTool::New(); bool is5DOF = toolConfiguration->GetIs5DOF(); if( is5DOF ) { trackerTool->RequestSelect5DOFTrackerTool(); } else { trackerTool->RequestSelect6DOFTrackerTool(); } // aurora internally handles [0-3] , so here we substract trackerTool->RequestSetPortNumber( toolConfiguration->GetPortNumber() - 1 ); if( is5DOF ) { trackerTool->RequestSetChannelNumber( toolConfiguration->GetChannelNumber() ); } std::string sromFileName = toolConfiguration->GetSROMFile(); if( !sromFileName.empty() ) { trackerTool->RequestSetSROMFileName( sromFileName ); } trackerTool->SetCalibrationTransform( toolConfiguration->GetCalibrationTransform() ); trackerTool->RequestConfigure(); return trackerTool; } AscensionTrackerTool::Pointer TrackerController::InitializeAscensionTool( const AscensionToolConfiguration *toolConfiguration ) { AscensionTrackerTool::Pointer trackerTool = AscensionTrackerTool::New(); trackerTool->RequestSetPortNumber( toolConfiguration->GetPortNumber() ); trackerTool->SetCalibrationTransform( toolConfiguration->GetCalibrationTransform() ); trackerTool->RequestConfigure(); return trackerTool; } void TrackerController::AscensionInitializeProcessing() { if( !InitializeSerialCommunication() ) { igstkPushInputMacro( Failed ); } else { //create tracker igstk::AscensionTracker::Pointer tracker = igstk::AscensionTracker::New(); this->m_Tracker = tracker; //don't need to observe this for errors because the //configuration class ensures that the frequency is valid tracker->RequestSetFrequency( this->m_TrackerConfiguration->GetFrequency() ); //observe all possible errors generated by the tracker unsigned long observerID = tracker->AddObserver( IGSTKErrorEvent(), this->m_ErrorObserver ); tracker->SetCommunication( this->m_SerialCommunication ); tracker->RequestOpen(); tracker->RemoveObserver(observerID); if( this->m_ErrorObserver->ErrorOccured() ) { this->m_ErrorObserver->GetErrorMessage( this->m_ErrorMessage ); this->m_ErrorObserver->ClearError(); this->m_SerialCommunication->CloseCommunication(); igstkPushInputMacro( Failed ); } else //attach the tools { ToolAttachErrorObserver::Pointer attachErrorObserver = ToolAttachErrorObserver::New(); std::map toolConfigurations = this->m_TrackerConfiguration->m_TrackerToolList; //attach tools std::map::const_iterator it; std::map::const_iterator toolConfigEnd = toolConfigurations.end(); TrackerTool::Pointer currentTool; AscensionToolConfiguration * currentToolConfig; for( it = toolConfigurations.begin(); it != toolConfigEnd; it++ ) { currentToolConfig = static_cast( it->second ); currentTool = InitializeAscensionTool( currentToolConfig ); this->m_Tools.insert( std::pair( it->first, currentTool ) ); unsigned long observerID = currentTool->AddObserver( TrackerToolAttachmentToTrackerErrorEvent(), attachErrorObserver ); currentTool->RequestAttachToTracker( tracker ); currentTool->RemoveObserver( observerID ); if( attachErrorObserver->GotToolAttachError() ) { igstkPushInputMacro( Failed ); this->m_StateMachine.ProcessInputs(); return; } } //add the reference if we have one TrackerToolConfiguration* referenceToolConfiguration = this->m_TrackerConfiguration->m_ReferenceTool; if( referenceToolConfiguration ) { currentToolConfig = static_cast( referenceToolConfiguration ); currentTool = InitializeAscensionTool( currentToolConfig ); this->m_ReferenceTool = currentTool; unsigned long observerID = currentTool->AddObserver( TrackerToolAttachmentToTrackerErrorEvent(), attachErrorObserver ); currentTool->RequestAttachToTracker( tracker ); currentTool->RemoveObserver( observerID ); if( attachErrorObserver->GotToolAttachError() ) { igstkPushInputMacro( Failed ); this->m_StateMachine.ProcessInputs(); return; } tracker->RequestSetReferenceTool( currentTool ); } igstkPushInputMacro( Succeeded ); } } this->m_StateMachine.ProcessInputs(); } void TrackerController::AuroraInitializeProcessing() { if( !InitializeSerialCommunication() ) { igstkPushInputMacro( Failed ); } else { //create tracker igstk::AuroraTracker::Pointer tracker = igstk::AuroraTracker::New(); this->m_Tracker = tracker; //don't need to observe this for errors because the //configuration class ensures that the frequency is valid tracker->RequestSetFrequency( this->m_TrackerConfiguration->GetFrequency() ); //observe all possible errors generated by the tracker //(TrackerOpenErrorEvent, TrackerInitializeErrorEvent) unsigned long observerID = tracker->AddObserver( IGSTKErrorEvent(), this->m_ErrorObserver ); tracker->SetCommunication( this->m_SerialCommunication ); tracker->RequestOpen(); tracker->RemoveObserver( observerID ); if( this->m_ErrorObserver->ErrorOccured() ) { this->m_ErrorObserver->GetErrorMessage( this->m_ErrorMessage ); this->m_ErrorObserver->ClearError(); this->m_SerialCommunication->CloseCommunication(); igstkPushInputMacro( Failed ); } else //attach the tools { ToolAttachErrorObserver::Pointer attachErrorObserver = ToolAttachErrorObserver::New(); std::map toolConfigurations = this->m_TrackerConfiguration->m_TrackerToolList; //attach tools std::map::const_iterator it; std::map::const_iterator toolConfigEnd = toolConfigurations.end(); TrackerTool::Pointer currentTool; AuroraToolConfiguration * currentToolConfig; for( it = toolConfigurations.begin(); it != toolConfigEnd; it++ ) { currentToolConfig = static_cast( it->second ); currentTool = InitializeAuroraTool( currentToolConfig ); this->m_Tools.insert( std::pair( it->first, currentTool ) ); unsigned long observerID = currentTool->AddObserver( TrackerToolAttachmentToTrackerErrorEvent(), attachErrorObserver ); currentTool->RequestAttachToTracker( tracker ); currentTool->RemoveObserver( observerID ); if( attachErrorObserver->GotToolAttachError() ) { igstkPushInputMacro( Failed ); this->m_StateMachine.ProcessInputs(); return; } } //add the reference if we have one TrackerToolConfiguration* referenceToolConfiguration = this->m_TrackerConfiguration->m_ReferenceTool; if( referenceToolConfiguration ) { currentToolConfig = static_cast( referenceToolConfiguration ); currentTool = InitializeAuroraTool( currentToolConfig ); this->m_ReferenceTool = currentTool; currentTool->AddObserver( TrackerToolAttachmentToTrackerErrorEvent(), attachErrorObserver ); currentTool->RequestAttachToTracker( tracker ); if( attachErrorObserver->GotToolAttachError() ) { igstkPushInputMacro( Failed ); this->m_StateMachine.ProcessInputs(); return; } tracker->RequestSetReferenceTool( currentTool ); } igstkPushInputMacro( Succeeded ); } } this->m_StateMachine.ProcessInputs(); } #ifdef IGSTK_USE_MicronTracker MicronTrackerTool::Pointer TrackerController::InitializeMicronTool( const MicronToolConfiguration *toolConfiguration ) { MicronTrackerTool::Pointer trackerTool = MicronTrackerTool::New(); trackerTool->RequestSetMarkerName( toolConfiguration->GetMarkerName() ); trackerTool->SetCalibrationTransform( toolConfiguration->GetCalibrationTransform() ); trackerTool->RequestConfigure(); return trackerTool; } #endif #ifdef IGSTK_USE_Ascension3DGTracker Ascension3DGTrackerTool::Pointer TrackerController::InitializeAscension3DGTool( const Ascension3DGToolConfiguration *toolConfiguration ) { Ascension3DGTrackerTool::Pointer trackerTool = Ascension3DGTrackerTool::New(); trackerTool->SetCalibrationTransform( toolConfiguration->GetCalibrationTransform() ); trackerTool->RequestSetPortNumber(toolConfiguration->GetPortNumber()); trackerTool->RequestConfigure(); return trackerTool; } #endif void TrackerController::MicronInitializeProcessing() { #ifdef IGSTK_USE_MicronTracker //create tracker igstk::MicronTracker::Pointer tracker = igstk::MicronTracker::New(); this->m_Tracker = tracker; //don't need to observe this for errors because the //configuration class ensures that the frequency is valid tracker->RequestSetFrequency( this->m_TrackerConfiguration->GetFrequency() ); MicronTrackerConfiguration *trackerConfiguration = dynamic_cast( this->m_TrackerConfiguration ); tracker->SetCameraCalibrationFilesDirectory( trackerConfiguration->GetCameraCalibrationFileDirectory() ); tracker->SetInitializationFile( trackerConfiguration->GetInitializationFile() ); tracker->SetMarkerTemplatesDirectory( trackerConfiguration->GetTemplatesDirectory() ); unsigned long observerID = tracker->AddObserver( IGSTKErrorEvent(), this->m_ErrorObserver ); tracker->RequestOpen(); tracker->RemoveObserver(observerID); if( this->m_ErrorObserver->ErrorOccured() ) { this->m_ErrorObserver->GetErrorMessage( this->m_ErrorMessage ); this->m_ErrorObserver->ClearError(); igstkPushInputMacro( Failed ); } else //attach the tools and start communication { ToolAttachErrorObserver::Pointer attachErrorObserver = ToolAttachErrorObserver::New(); std::map toolConfigurations = this->m_TrackerConfiguration->m_TrackerToolList; //attach tools std::map::const_iterator it; std::map::const_iterator toolConfigEnd = toolConfigurations.end(); TrackerTool::Pointer trackerTool; MicronToolConfiguration * currentToolConfig; for(it = toolConfigurations.begin(); it != toolConfigEnd; it++) { currentToolConfig = static_cast(it->second); trackerTool = InitializeMicronTool( currentToolConfig ); this->m_Tools.insert( std::pair( it->first, trackerTool ) ); unsigned long observerID = trackerTool->AddObserver( TrackerToolAttachmentToTrackerErrorEvent(), attachErrorObserver ); trackerTool->RequestAttachToTracker( tracker ); trackerTool->RemoveObserver( observerID ); if( attachErrorObserver->GotToolAttachError() ) { igstkPushInputMacro( Failed ); this->m_StateMachine.ProcessInputs(); return; } } //add the reference if we have one TrackerToolConfiguration* referenceToolConfiguration = this->m_TrackerConfiguration->m_ReferenceTool; if( referenceToolConfiguration ) { currentToolConfig = static_cast( referenceToolConfiguration ); trackerTool = InitializeMicronTool( currentToolConfig ); this->m_ReferenceTool = trackerTool; trackerTool->AddObserver( TrackerToolAttachmentToTrackerErrorEvent(), attachErrorObserver ); trackerTool->RequestAttachToTracker( tracker ); if( attachErrorObserver->GotToolAttachError() ) { igstkPushInputMacro( Failed ); this->m_StateMachine.ProcessInputs(); return; } tracker->RequestSetReferenceTool( trackerTool ); } igstkPushInputMacro( Succeeded ); } this->m_StateMachine.ProcessInputs(); #else igstkPushInputMacro( Failed ); this->m_StateMachine.ProcessInputs(); #endif } void TrackerController::Ascension3DGInitializeProcessing() { #ifdef IGSTK_USE_Ascension3DGTracker //create tracker igstk::Ascension3DGTracker::Pointer tracker = igstk::Ascension3DGTracker::New(); this->m_Tracker = tracker; //don't need to observe this for errors because the //configuration class ensures that the frequency is valid tracker->RequestSetFrequency( this->m_TrackerConfiguration->GetFrequency() ); Ascension3DGTrackerConfiguration *trackerConfiguration = dynamic_cast( this->m_TrackerConfiguration ); unsigned long observerID = tracker->AddObserver( IGSTKErrorEvent(), this->m_ErrorObserver ); tracker->RequestOpen(); tracker->RemoveObserver(observerID); if( this->m_ErrorObserver->ErrorOccured() ) { this->m_ErrorObserver->GetErrorMessage( this->m_ErrorMessage ); this->m_ErrorObserver->ClearError(); igstkPushInputMacro( Failed ); } else //attach the tools and start communication { ToolAttachErrorObserver::Pointer attachErrorObserver = ToolAttachErrorObserver::New(); std::map toolConfigurations = this->m_TrackerConfiguration->m_TrackerToolList; //attach tools std::map::const_iterator it; std::map::const_iterator toolConfigEnd = toolConfigurations.end(); TrackerTool::Pointer trackerTool; Ascension3DGToolConfiguration * currentToolConfig; for(it = toolConfigurations.begin(); it != toolConfigEnd; it++) { currentToolConfig = static_cast(it->second); trackerTool = InitializeAscension3DGTool( currentToolConfig ); this->m_Tools.insert( std::pair( it->first, trackerTool ) ); unsigned long observerID = trackerTool->AddObserver( TrackerToolAttachmentToTrackerErrorEvent(), attachErrorObserver ); trackerTool->RequestAttachToTracker( tracker ); trackerTool->RemoveObserver( observerID ); if( attachErrorObserver->GotToolAttachError() ) { igstkPushInputMacro( Failed ); this->m_StateMachine.ProcessInputs(); return; } } //add the reference if we have one TrackerToolConfiguration* referenceToolConfiguration = this->m_TrackerConfiguration->m_ReferenceTool; if( referenceToolConfiguration ) { currentToolConfig = static_cast( referenceToolConfiguration ); trackerTool = InitializeAscension3DGTool( currentToolConfig ); this->m_ReferenceTool = trackerTool; trackerTool->AddObserver( TrackerToolAttachmentToTrackerErrorEvent(), attachErrorObserver ); trackerTool->RequestAttachToTracker( tracker ); if( attachErrorObserver->GotToolAttachError() ) { igstkPushInputMacro( Failed ); this->m_StateMachine.ProcessInputs(); return; } tracker->RequestSetReferenceTool( trackerTool ); } igstkPushInputMacro( Succeeded ); } this->m_StateMachine.ProcessInputs(); #else igstkPushInputMacro( Failed ); this->m_StateMachine.ProcessInputs(); #endif } void TrackerController::GetToolsProcessing() { igstkLogMacro( DEBUG, ""igstk::TrackerController::"" ""GetToolsProcessing called...\\n""); RequestToolsEvent evt; evt.Set( this->m_Tools ); this->InvokeEvent( evt ); } void TrackerController::GetToolProcessing() { igstkLogMacro( DEBUG, ""igstk::TrackerController::"" ""GetToolProcessing called...\\n""); RequestToolEvent sevt; RequestToolErrorEvent fevt; std::map::iterator it = this->m_Tools.find( this->m_RequestedToolName ); this->m_RequestedToolName.clear(); if( it == this->m_Tools.end() ) { this->InvokeEvent( fevt ); } else { sevt.Set( *it ); this->InvokeEvent( sevt ); } } void TrackerController::GetReferenceToolProcessing() { igstkLogMacro( DEBUG, ""igstk::TrackerController::"" ""GetReferenceToolProcessing called...\\n""); RequestToolEvent evt; RequestToolErrorEvent fevt; //we don't have a reference if( this->m_ReferenceTool.IsNull() ) { this->InvokeEvent( fevt ); return; } evt.Set( std::pair( ""reference"", this->m_ReferenceTool ) ); this->InvokeEvent( evt ); } void TrackerController::SetParentSpatialObjectProcessing() { igstkLogMacro( DEBUG, ""igstk::TrackerController::"" ""SetParentSpatialObjectProcessing called...\\n""); this->m_Tracker->RequestDetachFromParent(); this->m_Tracker->RequestSetTransformAndParent(m_TmpTransform, m_TmpSpatialObject); } void TrackerController::SetChildSpatialObjectProcessing() { igstkLogMacro( DEBUG, ""igstk::TrackerController::"" ""SetParentSpatialObjectProcessing called...\\n""); m_TmpSpatialObject->RequestSetTransformAndParent(m_TmpTransform, this->m_Tracker); } void TrackerController::ReportInitializationSuccessProcessing() { igstkLogMacro( DEBUG, ""igstk::TrackerController::"" ""ReportInitializationSuccess called...\\n""); this->m_Tracker->AddObserver( igstk::TrackerUpdateStatusEvent(), this->m_TrackerUpdateStatusObserver ); this->m_Tracker->AddObserver( igstk::TrackerUpdateStatusErrorEvent(), this->m_TrackerUpdateStatusObserver ); this->InvokeEvent( InitializeEvent() ); } void TrackerController::ReportInitializationFailureProcessing() { igstkLogMacro( DEBUG, ""igstk::TrackerController::"" ""ReportInitializationFailureProcessing called...\\n""); InitializeErrorEvent evt; evt.Set( this->m_ErrorMessage ); this->InvokeEvent( evt ); } void TrackerController::ReportStartTrackingSuccessProcessing() { igstkLogMacro( DEBUG, ""igstk::TrackerController::"" ""ReportStartTrackingSuccessProcessing called...\\n""); this->InvokeEvent( TrackerStartTrackingEvent() ); } void TrackerController::ReportStartTrackingFailureProcessing() { igstkLogMacro( DEBUG, ""igstk::TrackerController::"" ""ReportStartTrackingFailureProcessing called...\\n""); TrackerStartTrackingErrorEvent evt; evt.Set( this->m_ErrorMessage ); this->InvokeEvent( evt ); } void TrackerController::ReportStopTrackingSuccessProcessing() { igstkLogMacro( DEBUG, ""igstk::TrackerController::"" ""ReportStopTrackingSuccessProcessing called...\\n""); this->InvokeEvent( TrackerStopTrackingEvent() ); } void TrackerController::ReportStopTrackingFailureProcessing() { igstkLogMacro( DEBUG, ""igstk::TrackerController::"" ""ReportStopTrackingFailureProcessing called...\\n""); TrackerStopTrackingErrorEvent evt; evt.Set( this->m_ErrorMessage ); this->InvokeEvent( evt ); } void TrackerController::ReportCloseCommunicationFailureProcessing() { igstkLogMacro( DEBUG, ""igstk::TrackerController::"" ""ReportCloseCommunicationFailureProcessing called...\\n""); CloseCommunicationErrorEvent evt; evt.Set( this->m_ErrorMessage ); this->InvokeEvent( evt ); } void TrackerController::ReportCloseCommunicationSuccessProcessing() { igstkLogMacro( DEBUG, ""igstk::TrackerController::"" ""ReportCloseCommunicationSuccessProcessing called...\\n""); this->InvokeEvent( CloseCommunicationEvent() ); } void TrackerController::ReportInvalidRequestProcessing() { igstkLogMacro( DEBUG, ""igstk::TrackerController::"" ""ReportInvalidRequestProcessing called...\\n""); this->InvokeEvent(InvalidRequestErrorEvent()); } TrackerController::ErrorObserver::ErrorObserver() : m_ErrorOccured( false ) { //serial communication errors this->m_ErrorEvent2ErrorMessage.insert( std::pair( OpenPortErrorEvent().GetEventName(), ""Error opening com port."" ) ); this->m_ErrorEvent2ErrorMessage.insert( std::pair( ClosePortErrorEvent().GetEventName(), ""Error closing com port."" ) ); //tracker errors this->m_ErrorEvent2ErrorMessage.insert( std::pair( TrackerOpenErrorEvent().GetEventName(), ""Error opening tracker communication."" ) ); this->m_ErrorEvent2ErrorMessage.insert( std::pair( TrackerInitializeErrorEvent().GetEventName(), ""Error initializing tracker."" ) ); this->m_ErrorEvent2ErrorMessage.insert( std::pair( TrackerStartTrackingErrorEvent().GetEventName(), ""Error starting tracking."" ) ); this->m_ErrorEvent2ErrorMessage.insert( std::pair( TrackerStopTrackingErrorEvent().GetEventName(), ""Error stopping tracking."" ) ); this->m_ErrorEvent2ErrorMessage.insert( std::pair( TrackerCloseErrorEvent().GetEventName(), ""Error closing tracker communication."" ) ); } void TrackerController::ErrorObserver::Execute( const itk::Object * itkNotUsed(caller), const itk::EventObject & event ) throw (std::exception) { std::map::iterator it; std::string className = event.GetEventName(); it = this->m_ErrorEvent2ErrorMessage.find(className); if( it != this->m_ErrorEvent2ErrorMessage.end() ) { this->m_ErrorOccured = true; this->m_ErrorMessage = (*it).second; } //if the event we got wasn't in the error events map then we //silently ignore it } void TrackerController::ErrorObserver::Execute( itk::Object *caller, const itk::EventObject & event ) throw (std::exception) { const itk::Object * constCaller = caller; this->Execute(constCaller, event); } void TrackerController::TrackerUpdateObserver::SetParent( TrackerController *parent ) { this->m_parent = parent; } void TrackerController::TrackerUpdateObserver::Execute( const itk::Object * itkNotUsed(caller), const itk::EventObject & event ) throw ( std::exception ) { if( igstk::TrackerUpdateStatusEvent().CheckEvent( &event ) || igstk::TrackerUpdateStatusErrorEvent().CheckEvent( &event ) ) { this->m_parent->InvokeEvent( event ); } } void TrackerController::TrackerUpdateObserver::Execute( itk::Object *caller, const itk::EventObject & event ) throw ( std::exception ) { const itk::Object * constCaller = caller; this->Execute(constCaller, event); } }//end namespace igstk ",16343,True,3002.8646925712083,median "// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XX XX XX Utils.cpp XX XX XX XX Has miscellaneous utility functions XX XX XX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX */ #include ""jitpch.h"" #ifdef _MSC_VER #pragma hdrstop #endif #include ""opcode.h"" /*****************************************************************************/ // Define the string platform name based on compilation #ifdefs. This is the // same code for all platforms, hence it is here instead of in the targetXXX.cpp // files. #ifdef _TARGET_UNIX_ // Should we distinguish Mac? Can we? // Should we distinguish flavors of Unix? Can we? const char* Target::g_tgtPlatformName = ""Unix""; #else // !_TARGET_UNIX_ const char* Target::g_tgtPlatformName = ""Windows""; #endif // !_TARGET_UNIX_ /*****************************************************************************/ #define DECLARE_DATA // clang-format off extern const signed char opcodeSizes[] = { #define InlineNone_size 0 #define ShortInlineVar_size 1 #define InlineVar_size 2 #define ShortInlineI_size 1 #define InlineI_size 4 #define InlineI8_size 8 #define ShortInlineR_size 4 #define InlineR_size 8 #define ShortInlineBrTarget_size 1 #define InlineBrTarget_size 4 #define InlineMethod_size 4 #define InlineField_size 4 #define InlineType_size 4 #define InlineString_size 4 #define InlineSig_size 4 #define InlineRVA_size 4 #define InlineTok_size 4 #define InlineSwitch_size 0 // for now #define InlinePhi_size 0 // for now #define InlineVarTok_size 0 // remove #define OPDEF(name,string,pop,push,oprType,opcType,l,s1,s2,ctrl) oprType ## _size , #include ""opcode.def"" #undef OPDEF #undef InlineNone_size #undef ShortInlineVar_size #undef InlineVar_size #undef ShortInlineI_size #undef InlineI_size #undef InlineI8_size #undef ShortInlineR_size #undef InlineR_size #undef ShortInlineBrTarget_size #undef InlineBrTarget_size #undef InlineMethod_size #undef InlineField_size #undef InlineType_size #undef InlineString_size #undef InlineSig_size #undef InlineRVA_size #undef InlineTok_size #undef InlineSwitch_size #undef InlinePhi_size }; // clang-format on const BYTE varTypeClassification[] = { #define DEF_TP(tn, nm, jitType, verType, sz, sze, asze, st, al, tf, howUsed) tf, #include ""typelist.h"" #undef DEF_TP }; /*****************************************************************************/ /*****************************************************************************/ #ifdef DEBUG extern const char* const opcodeNames[] = { #define OPDEF(name, string, pop, push, oprType, opcType, l, s1, s2, ctrl) string, #include ""opcode.def"" #undef OPDEF }; extern const BYTE opcodeArgKinds[] = { #define OPDEF(name, string, pop, push, oprType, opcType, l, s1, s2, ctrl) (BYTE) oprType, #include ""opcode.def"" #undef OPDEF }; #endif /*****************************************************************************/ const char* varTypeName(var_types vt) { static const char* const varTypeNames[] = { #define DEF_TP(tn, nm, jitType, verType, sz, sze, asze, st, al, tf, howUsed) nm, #include ""typelist.h"" #undef DEF_TP }; assert((unsigned)vt < sizeof(varTypeNames) / sizeof(varTypeNames[0])); return varTypeNames[vt]; } #if defined(DEBUG) || defined(LATE_DISASM) /***************************************************************************** * * Return the name of the given register. */ const char* getRegName(regNumber reg, bool isFloat) { // Special-case REG_NA; it's not in the regNames array, but we might want to print it. if (reg == REG_NA) { return ""NA""; } #if defined(_TARGET_X86_) && defined(LEGACY_BACKEND) static const char* const regNames[] = { #define REGDEF(name, rnum, mask, sname) sname, #include ""register.h"" }; static const char* const floatRegNames[] = { #define REGDEF(name, rnum, mask, sname) sname, #include ""registerxmm.h"" }; if (isFloat) { assert(reg < ArrLen(floatRegNames)); return floatRegNames[reg]; } else { assert(reg < ArrLen(regNames)); return regNames[reg]; } #elif defined(_TARGET_ARM64_) static const char* const regNames[] = { #define REGDEF(name, rnum, mask, xname, wname) xname, #include ""register.h"" }; assert(reg < ArrLen(regNames)); return regNames[reg]; #else static const char* const regNames[] = { #define REGDEF(name, rnum, mask, sname) sname, #include ""register.h"" }; assert(reg < ArrLen(regNames)); return regNames[reg]; #endif } const char* getRegName(unsigned reg, bool isFloat) // this is for gcencode.cpp and disasm.cpp that dont use the regNumber type { return getRegName((regNumber)reg, isFloat); } #endif // defined(DEBUG) || defined(LATE_DISASM) #if defined(DEBUG) const char* getRegNameFloat(regNumber reg, var_types type) { #ifdef _TARGET_ARM_ assert(genIsValidFloatReg(reg)); if (type == TYP_FLOAT) return getRegName(reg); else { const char* regName; switch (reg) { default: assert(!""Bad double register""); regName = ""d??""; break; case REG_F0: regName = ""d0""; break; case REG_F2: regName = ""d2""; break; case REG_F4: regName = ""d4""; break; case REG_F6: regName = ""d6""; break; case REG_F8: regName = ""d8""; break; case REG_F10: regName = ""d10""; break; case REG_F12: regName = ""d12""; break; case REG_F14: regName = ""d14""; break; case REG_F16: regName = ""d16""; break; case REG_F18: regName = ""d18""; break; case REG_F20: regName = ""d20""; break; case REG_F22: regName = ""d22""; break; case REG_F24: regName = ""d24""; break; case REG_F26: regName = ""d26""; break; case REG_F28: regName = ""d28""; break; case REG_F30: regName = ""d30""; break; } return regName; } #elif defined(_TARGET_X86_) && defined(LEGACY_BACKEND) static const char* regNamesFloat[] = { #define REGDEF(name, rnum, mask, sname) sname, #include ""registerxmm.h"" }; assert((unsigned)reg < ArrLen(regNamesFloat)); return regNamesFloat[reg]; #elif defined(_TARGET_ARM64_) static const char* regNamesFloat[] = { #define REGDEF(name, rnum, mask, xname, wname) xname, #include ""register.h"" }; assert((unsigned)reg < ArrLen(regNamesFloat)); return regNamesFloat[reg]; #else static const char* regNamesFloat[] = { #define REGDEF(name, rnum, mask, sname) ""x"" sname, #include ""register.h"" }; #ifdef FEATURE_AVX_SUPPORT static const char* regNamesYMM[] = { #define REGDEF(name, rnum, mask, sname) ""y"" sname, #include ""register.h"" }; #endif // FEATURE_AVX_SUPPORT assert((unsigned)reg < ArrLen(regNamesFloat)); #ifdef FEATURE_AVX_SUPPORT if (type == TYP_SIMD32) { return regNamesYMM[reg]; } #endif // FEATURE_AVX_SUPPORT return regNamesFloat[reg]; #endif } /***************************************************************************** * * Displays a register set. * TODO-ARM64-Cleanup: don't allow ip0, ip1 as part of a range. */ void dspRegMask(regMaskTP regMask, size_t minSiz) { const char* sep = """"; printf(""[""); bool inRegRange = false; regNumber regPrev = REG_NA; regNumber regHead = REG_NA; // When we start a range, remember the first register of the range, so we don't use // range notation if the range contains just a single register. for (regNumber regNum = REG_INT_FIRST; regNum <= REG_INT_LAST; regNum = REG_NEXT(regNum)) { regMaskTP regBit = genRegMask(regNum); if ((regMask & regBit) != 0) { // We have a register to display. It gets displayed now if: // 1. This is the first register to display of a new range of registers (possibly because // no register has ever been displayed). // 2. This is the last register of an acceptable range (either the last integer register, // or the last of a range that is displayed with range notation). if (!inRegRange) { // It's the first register of a potential range. const char* nam = getRegName(regNum); printf(""%s%s"", sep, nam); minSiz -= strlen(sep) + strlen(nam); // By default, we're not starting a potential register range. sep = "" ""; // What kind of separator should we use for this range (if it is indeed going to be a range)? CLANG_FORMAT_COMMENT_ANCHOR; #if defined(_TARGET_AMD64_) // For AMD64, create ranges for int registers R8 through R15, but not the ""old"" registers. if (regNum >= REG_R8) { regHead = regNum; inRegRange = true; sep = ""-""; } #elif defined(_TARGET_ARM64_) // R17 and R28 can't be the start of a range, since the range would include TEB or FP if ((regNum < REG_R17) || ((REG_R19 <= regNum) && (regNum < REG_R28))) { regHead = regNum; inRegRange = true; sep = ""-""; } #elif defined(_TARGET_ARM_) if (regNum < REG_R12) { regHead = regNum; inRegRange = true; sep = ""-""; } #elif defined(_TARGET_X86_) // No register ranges #else // _TARGET_* #error Unsupported or unset target architecture #endif // _TARGET_* } #if defined(_TARGET_ARM64_) // We've already printed a register. Is this the end of a range? else if ((regNum == REG_INT_LAST) || (regNum == REG_R17) // last register before TEB || (regNum == REG_R28)) // last register before FP #else // _TARGET_ARM64_ // We've already printed a register. Is this the end of a range? else if (regNum == REG_INT_LAST) #endif // _TARGET_ARM64_ { const char* nam = getRegName(regNum); printf(""%s%s"", sep, nam); minSiz -= strlen(sep) + strlen(nam); inRegRange = false; // No longer in the middle of a register range regHead = REG_NA; sep = "" ""; } } else // ((regMask & regBit) == 0) { if (inRegRange) { assert(regHead != REG_NA); if (regPrev != regHead) { // Close out the previous range, if it included more than one register. const char* nam = getRegName(regPrev); printf(""%s%s"", sep, nam); minSiz -= strlen(sep) + strlen(nam); } sep = "" ""; inRegRange = false; regHead = REG_NA; } } if (regBit > regMask) { break; } regPrev = regNum; } #if CPU_HAS_BYTE_REGS if (regMask & RBM_BYTE_REG_FLAG) { const char* nam = ""BYTE""; printf(""%s%s"", sep, nam); minSiz -= (strlen(sep) + strlen(nam)); } #endif #if !FEATURE_STACK_FP_X87 if (strlen(sep) > 0) { // We've already printed something. sep = "" ""; } inRegRange = false; regPrev = REG_NA; regHead = REG_NA; for (regNumber regNum = REG_FP_FIRST; regNum <= REG_FP_LAST; regNum = REG_NEXT(regNum)) { regMaskTP regBit = genRegMask(regNum); if (regMask & regBit) { if (!inRegRange || (regNum == REG_FP_LAST)) { const char* nam = getRegName(regNum); printf(""%s%s"", sep, nam); minSiz -= strlen(sep) + strlen(nam); sep = ""-""; regHead = regNum; } inRegRange = true; } else { if (inRegRange) { if (regPrev != regHead) { const char* nam = getRegName(regPrev); printf(""%s%s"", sep, nam); minSiz -= (strlen(sep) + strlen(nam)); } sep = "" ""; } inRegRange = false; } if (regBit > regMask) { break; } regPrev = regNum; } #endif printf(""]""); while ((int)minSiz > 0) { printf("" ""); minSiz--; } } //------------------------------------------------------------------------ // dumpILBytes: Helper for dumpSingleInstr() to dump hex bytes of an IL stream, // aligning up to a minimum alignment width. // // Arguments: // codeAddr - Pointer to IL byte stream to display. // codeSize - Number of bytes of IL byte stream to display. // alignSize - Pad out to this many characters, if fewer than this were written. // void dumpILBytes(const BYTE* const codeAddr, unsigned codeSize, unsigned alignSize) // number of characters to write, for alignment { for (IL_OFFSET offs = 0; offs < codeSize; ++offs) { printf("" %02x"", *(codeAddr + offs)); } unsigned charsWritten = 3 * codeSize; for (unsigned i = charsWritten; i < alignSize; i++) { printf("" ""); } } //------------------------------------------------------------------------ // dumpSingleInstr: Display a single IL instruction. // // Arguments: // codeAddr - Base pointer to a stream of IL instructions. // offs - Offset from codeAddr of the IL instruction to display. // prefix - Optional string to prefix the IL instruction with (if nullptr, no prefix is output). // // Return Value: // Size of the displayed IL instruction in the instruction stream, in bytes. (Add this to 'offs' to // get to the next instruction.) // unsigned dumpSingleInstr(const BYTE* const codeAddr, IL_OFFSET offs, const char* prefix) { const BYTE* opcodePtr = codeAddr + offs; const BYTE* startOpcodePtr = opcodePtr; const unsigned ALIGN_WIDTH = 3 * 6; // assume 3 characters * (1 byte opcode + 4 bytes data + 1 prefix byte) for // most things if (prefix != nullptr) { printf(""%s"", prefix); } OPCODE opcode = (OPCODE)getU1LittleEndian(opcodePtr); opcodePtr += sizeof(__int8); DECODE_OPCODE: if (opcode >= CEE_COUNT) { printf(""\\nIllegal opcode: %02X\\n"", (int)opcode); return (IL_OFFSET)(opcodePtr - startOpcodePtr); } /* Get the size of additional parameters */ size_t sz = opcodeSizes[opcode]; unsigned argKind = opcodeArgKinds[opcode]; /* See what kind of an opcode we have, then */ switch (opcode) { case CEE_PREFIX1: opcode = OPCODE(getU1LittleEndian(opcodePtr) + 256); opcodePtr += sizeof(__int8); goto DECODE_OPCODE; default: { __int64 iOp; double dOp; int jOp; DWORD jOp2; switch (argKind) { case InlineNone: dumpILBytes(startOpcodePtr, (unsigned)(opcodePtr - startOpcodePtr), ALIGN_WIDTH); printf("" %-12s"", opcodeNames[opcode]); break; case ShortInlineVar: iOp = getU1LittleEndian(opcodePtr); goto INT_OP; case ShortInlineI: iOp = getI1LittleEndian(opcodePtr); goto INT_OP; case InlineVar: iOp = getU2LittleEndian(opcodePtr); goto INT_OP; case InlineTok: case InlineMethod: case InlineField: case InlineType: case InlineString: case InlineSig: case InlineI: iOp = getI4LittleEndian(opcodePtr); goto INT_OP; case InlineI8: iOp = getU4LittleEndian(opcodePtr); iOp |= (__int64)getU4LittleEndian(opcodePtr + 4) << 32; goto INT_OP; INT_OP: dumpILBytes(startOpcodePtr, (unsigned)((opcodePtr - startOpcodePtr) + sz), ALIGN_WIDTH); printf("" %-12s 0x%X"", opcodeNames[opcode], iOp); break; case ShortInlineR: dOp = getR4LittleEndian(opcodePtr); goto FLT_OP; case InlineR: dOp = getR8LittleEndian(opcodePtr); goto FLT_OP; FLT_OP: dumpILBytes(startOpcodePtr, (unsigned)((opcodePtr - startOpcodePtr) + sz), ALIGN_WIDTH); printf("" %-12s %f"", opcodeNames[opcode], dOp); break; case ShortInlineBrTarget: jOp = getI1LittleEndian(opcodePtr); goto JMP_OP; case InlineBrTarget: jOp = getI4LittleEndian(opcodePtr); goto JMP_OP; JMP_OP: dumpILBytes(startOpcodePtr, (unsigned)((opcodePtr - startOpcodePtr) + sz), ALIGN_WIDTH); printf("" %-12s %d (IL_%04x)"", opcodeNames[opcode], jOp, (int)(opcodePtr + sz - codeAddr) + jOp); break; case InlineSwitch: jOp2 = getU4LittleEndian(opcodePtr); opcodePtr += 4; opcodePtr += jOp2 * 4; // Jump over the table dumpILBytes(startOpcodePtr, (unsigned)(opcodePtr - startOpcodePtr), ALIGN_WIDTH); printf("" %-12s"", opcodeNames[opcode]); break; case InlinePhi: jOp2 = getU1LittleEndian(opcodePtr); opcodePtr += 1; opcodePtr += jOp2 * 2; // Jump over the table dumpILBytes(startOpcodePtr, (unsigned)(opcodePtr - startOpcodePtr), ALIGN_WIDTH); printf("" %-12s"", opcodeNames[opcode]); break; default: assert(!""Bad argKind""); } opcodePtr += sz; break; } } printf(""\\n""); return (IL_OFFSET)(opcodePtr - startOpcodePtr); } //------------------------------------------------------------------------ // dumpILRange: Display a range of IL instructions from an IL instruction stream. // // Arguments: // codeAddr - Pointer to IL byte stream to display. // codeSize - Number of bytes of IL byte stream to display. // void dumpILRange(const BYTE* const codeAddr, unsigned codeSize) // in bytes { for (IL_OFFSET offs = 0; offs < codeSize;) { char prefix[100]; sprintf_s(prefix, _countof(prefix), ""IL_%04x "", offs); unsigned codeBytesDumped = dumpSingleInstr(codeAddr, offs, prefix); offs += codeBytesDumped; } } /***************************************************************************** * * Display a variable set. */ const char* genES2str(BitVecTraits* traits, EXPSET_TP set) { const int bufSize = 17; static char num1[bufSize]; static char num2[bufSize]; static char* nump = num1; char* temp = nump; nump = (nump == num1) ? num2 : num1; sprintf_s(temp, bufSize, ""%s"", BitVecOps::ToString(traits, set)); return temp; } const char* refCntWtd2str(unsigned refCntWtd) { const int bufSize = 17; static char num1[bufSize]; static char num2[bufSize]; static char* nump = num1; char* temp = nump; nump = (nump == num1) ? num2 : num1; if (refCntWtd == BB_MAX_WEIGHT) { sprintf_s(temp, bufSize, ""MAX ""); } else { unsigned valueInt = refCntWtd / BB_UNITY_WEIGHT; unsigned valueFrac = refCntWtd % BB_UNITY_WEIGHT; if (valueFrac == 0) { sprintf_s(temp, bufSize, ""%u "", valueInt); } else { sprintf_s(temp, bufSize, ""%u.%02u"", valueInt, (valueFrac * 100 / BB_UNITY_WEIGHT)); } } return temp; } #endif // DEBUG #if defined(DEBUG) || defined(INLINE_DATA) //------------------------------------------------------------------------ // Contains: check if the range includes a particular method // // Arguments: // info -- jit interface pointer // method -- method handle for the method of interest bool ConfigMethodRange::Contains(ICorJitInfo* info, CORINFO_METHOD_HANDLE method) { _ASSERT(m_inited == 1); // No ranges specified means all methods included. if (m_lastRange == 0) { return true; } // Check the hash. Note we can't use the cached hash here since // we may not be asking about the method currently being jitted. const unsigned hash = info->getMethodHash(method); for (unsigned i = 0; i < m_lastRange; i++) { if ((m_ranges[i].m_low <= hash) && (hash <= m_ranges[i].m_high)) { return true; } } return false; } //------------------------------------------------------------------------ // InitRanges: parse the range string and set up the range info // // Arguments: // rangeStr -- string to parse (may be nullptr) // capacity -- number ranges to allocate in the range array // // Notes: // Does some internal error checking; clients can use Error() // to determine if the range string couldn't be fully parsed // because of bad characters or too many entries, or had values // that were too large to represent. void ConfigMethodRange::InitRanges(const wchar_t* rangeStr, unsigned capacity) { // Make sure that the memory was zero initialized assert(m_inited == 0 || m_inited == 1); assert(m_entries == 0); assert(m_ranges == nullptr); assert(m_lastRange == 0); // Flag any crazy-looking requests assert(capacity < 100000); if (rangeStr == nullptr) { m_inited = 1; return; } // Allocate some persistent memory ICorJitHost* jitHost = g_jitHost; m_ranges = (Range*)jitHost->allocateMemory(capacity * sizeof(Range)); m_entries = capacity; const wchar_t* p = rangeStr; unsigned lastRange = 0; bool setHighPart = false; while ((*p != 0) && (lastRange < m_entries)) { while (*p == L' ') { p++; } int i = 0; while (L'0' <= *p && *p <= L'9') { int j = 10 * i + ((*p++) - L'0'); // Check for overflow if ((m_badChar != 0) && (j <= i)) { m_badChar = (p - rangeStr) + 1; } i = j; } // Was this the high part of a low-high pair? if (setHighPart) { // Yep, set it and move to the next range m_ranges[lastRange].m_high = i; // Sanity check that range is proper if ((m_badChar != 0) && (m_ranges[lastRange].m_high < m_ranges[lastRange].m_low)) { m_badChar = (p - rangeStr) + 1; } lastRange++; setHighPart = false; continue; } // Must have been looking for the low part of a range m_ranges[lastRange].m_low = i; while (*p == L' ') { p++; } // Was that the low part of a low-high pair? if (*p == L'-') { // Yep, skip the dash and set high part next time around. p++; setHighPart = true; continue; } // Else we have a point range, so set high = low m_ranges[lastRange].m_high = i; lastRange++; } // If we didn't parse the full range string, note index of the the // first bad char. if ((m_badChar != 0) && (*p != 0)) { m_badChar = (p - rangeStr) + 1; } // Finish off any remaining open range if (setHighPart) { m_ranges[lastRange].m_high = UINT_MAX; lastRange++; } assert(lastRange <= m_entries); m_lastRange = lastRange; m_inited = 1; } #endif // defined(DEBUG) || defined(INLINE_DATA) #if CALL_ARG_STATS || COUNT_BASIC_BLOCKS || COUNT_LOOPS || EMITTER_STATS || MEASURE_NODE_SIZE || MEASURE_MEM_ALLOC /***************************************************************************** * Histogram class. */ Histogram::Histogram(IAllocator* allocator, const unsigned* const sizeTable) : m_allocator(allocator), m_sizeTable(sizeTable), m_counts(nullptr) { unsigned sizeCount = 0; do { sizeCount++; } while ((sizeTable[sizeCount] != 0) && (sizeCount < 1000)); m_sizeCount = sizeCount; } Histogram::~Histogram() { if (m_counts != nullptr) { m_allocator->Free(m_counts); } } // We need to lazy allocate the histogram data so static `Histogram` variables don't try to // call the host memory allocator in the loader lock, which doesn't work. void Histogram::ensureAllocated() { if (m_counts == nullptr) { m_counts = new (m_allocator) unsigned[m_sizeCount + 1]; memset(m_counts, 0, (m_sizeCount + 1) * sizeof(*m_counts)); } } void Histogram::dump(FILE* output) { ensureAllocated(); unsigned t = 0; for (unsigned i = 0; i < m_sizeCount; i++) { t += m_counts[i]; } for (unsigned c = 0, i = 0; i <= m_sizeCount; i++) { if (i == m_sizeCount) { if (m_counts[i] == 0) { break; } fprintf(output, "" > %7u"", m_sizeTable[i - 1]); } else { if (i == 0) { fprintf(output, "" <= ""); } else { fprintf(output, ""%7u .. "", m_sizeTable[i - 1] + 1); } fprintf(output, ""%7u"", m_sizeTable[i]); } c += m_counts[i]; fprintf(output, "" ===> %7u count (%3u%% of total)\\n"", m_counts[i], (int)(100.0 * c / t)); } } void Histogram::record(unsigned size) { ensureAllocated(); unsigned i; for (i = 0; i < m_sizeCount; i++) { if (m_sizeTable[i] >= size) { break; } } m_counts[i]++; } #endif // CALL_ARG_STATS || COUNT_BASIC_BLOCKS || COUNT_LOOPS || EMITTER_STATS || MEASURE_NODE_SIZE /***************************************************************************** * Fixed bit vector class */ // bitChunkSize() - Returns number of bits in a bitVect chunk inline UINT FixedBitVect::bitChunkSize() { return sizeof(UINT) * 8; } // bitNumToBit() - Returns a bit mask of the given bit number inline UINT FixedBitVect::bitNumToBit(UINT bitNum) { assert(bitNum < bitChunkSize()); assert(bitChunkSize() <= sizeof(int) * 8); return 1 << bitNum; } // bitVectInit() - Initializes a bit vector of a given size FixedBitVect* FixedBitVect::bitVectInit(UINT size, Compiler* comp) { UINT bitVectMemSize, numberOfChunks; FixedBitVect* bv; assert(size != 0); numberOfChunks = (size - 1) / bitChunkSize() + 1; bitVectMemSize = numberOfChunks * (bitChunkSize() / 8); // size in bytes assert(bitVectMemSize * bitChunkSize() >= size); bv = (FixedBitVect*)comp->compGetMemA(sizeof(FixedBitVect) + bitVectMemSize, CMK_FixedBitVect); memset(bv->bitVect, 0, bitVectMemSize); bv->bitVectSize = size; return bv; } // bitVectSet() - Sets the given bit void FixedBitVect::bitVectSet(UINT bitNum) { UINT index; assert(bitNum <= bitVectSize); index = bitNum / bitChunkSize(); bitNum -= index * bitChunkSize(); bitVect[index] |= bitNumToBit(bitNum); } // bitVectTest() - Tests the given bit bool FixedBitVect::bitVectTest(UINT bitNum) { UINT index; assert(bitNum <= bitVectSize); index = bitNum / bitChunkSize(); bitNum -= index * bitChunkSize(); return (bitVect[index] & bitNumToBit(bitNum)) != 0; } // bitVectOr() - Or in the given bit vector void FixedBitVect::bitVectOr(FixedBitVect* bv) { UINT bitChunkCnt = (bitVectSize - 1) / bitChunkSize() + 1; assert(bitVectSize == bv->bitVectSize); // Or each chunks for (UINT i = 0; i < bitChunkCnt; i++) { bitVect[i] |= bv->bitVect[i]; } } // bitVectAnd() - And with passed in bit vector void FixedBitVect::bitVectAnd(FixedBitVect& bv) { UINT bitChunkCnt = (bitVectSize - 1) / bitChunkSize() + 1; assert(bitVectSize == bv.bitVectSize); // And each chunks for (UINT i = 0; i < bitChunkCnt; i++) { bitVect[i] &= bv.bitVect[i]; } } // bitVectGetFirst() - Find the first bit on and return bit num, // Return -1 if no bits found. UINT FixedBitVect::bitVectGetFirst() { return bitVectGetNext((UINT)-1); } // bitVectGetNext() - Find the next bit on given previous position and return bit num. // Return -1 if no bits found. UINT FixedBitVect::bitVectGetNext(UINT bitNumPrev) { UINT bitNum = (UINT)-1; UINT index; UINT bitMask; UINT bitChunkCnt = (bitVectSize - 1) / bitChunkSize() + 1; UINT i; if (bitNumPrev == (UINT)-1) { index = 0; bitMask = (UINT)-1; } else { UINT bit; index = bitNumPrev / bitChunkSize(); bitNumPrev -= index * bitChunkSize(); bit = bitNumToBit(bitNumPrev); bitMask = ~(bit | (bit - 1)); } // Find first bit for (i = index; i < bitChunkCnt; i++) { UINT bitChunk = bitVect[i] & bitMask; if (bitChunk != 0) { BitScanForward((ULONG*)&bitNum, bitChunk); break; } bitMask = 0xFFFFFFFF; } // Empty bit vector? if (bitNum == (UINT)-1) { return (UINT)-1; } bitNum += i * bitChunkSize(); assert(bitNum <= bitVectSize); return bitNum; } // bitVectGetNextAndClear() - Find the first bit on, clear it and return it. // Return -1 if no bits found. UINT FixedBitVect::bitVectGetNextAndClear() { UINT bitNum = (UINT)-1; UINT bitChunkCnt = (bitVectSize - 1) / bitChunkSize() + 1; UINT i; // Find first bit for (i = 0; i < bitChunkCnt; i++) { if (bitVect[i] != 0) { BitScanForward((ULONG*)&bitNum, bitVect[i]); break; } } // Empty bit vector? if (bitNum == (UINT)-1) { return (UINT)-1; } // Clear the bit in the right chunk bitVect[i] &= ~bitNumToBit(bitNum); bitNum += i * bitChunkSize(); assert(bitNum <= bitVectSize); return bitNum; } int SimpleSprintf_s(__in_ecount(cbBufSize - (pWriteStart - pBufStart)) char* pWriteStart, __in_ecount(cbBufSize) char* pBufStart, size_t cbBufSize, __in_z const char* fmt, ...) { assert(fmt); assert(pBufStart); assert(pWriteStart); assert((size_t)pBufStart <= (size_t)pWriteStart); int ret; // compute the space left in the buffer. if ((pBufStart + cbBufSize) < pWriteStart) { NO_WAY(""pWriteStart is past end of buffer""); } size_t cbSpaceLeft = (size_t)((pBufStart + cbBufSize) - pWriteStart); va_list args; va_start(args, fmt); ret = vsprintf_s(pWriteStart, cbSpaceLeft, const_cast(fmt), args); va_end(args); if (ret < 0) { NO_WAY(""vsprintf_s failed.""); } return ret; } #ifdef DEBUG void hexDump(FILE* dmpf, const char* name, BYTE* addr, size_t size) { if (!size) { return; } assert(addr); fprintf(dmpf, ""Hex dump of %s:\\n"", name); for (unsigned i = 0; i < size; i++) { if ((i % 16) == 0) { fprintf(dmpf, ""\\n %04X: "", i); } fprintf(dmpf, ""%02X "", *addr++); } fprintf(dmpf, ""\\n\\n""); } #endif // DEBUG void HelperCallProperties::init() { for (CorInfoHelpFunc helper = CORINFO_HELP_UNDEF; // initialize helper (helper < CORINFO_HELP_COUNT); // test helper for loop exit helper = CorInfoHelpFunc(int(helper) + 1)) // update helper to next { // Generally you want initialize these to their most typical/safest result // bool isPure = false; // true if the result only depends upon input args and not any global state bool noThrow = false; // true if the helper will never throw bool nonNullReturn = false; // true if the result will never be null or zero bool isAllocator = false; // true if the result is usually a newly created heap item, or may throw OutOfMemory bool mutatesHeap = false; // true if any previous heap objects [are|can be] modified bool mayRunCctor = false; // true if the helper call may cause a static constructor to be run. bool mayFinalize = false; // true if the helper call allocates an object that may need to run a finalizer switch (helper) { // Arithmetic helpers that cannot throw case CORINFO_HELP_LLSH: case CORINFO_HELP_LRSH: case CORINFO_HELP_LRSZ: case CORINFO_HELP_LMUL: case CORINFO_HELP_LNG2DBL: case CORINFO_HELP_ULNG2DBL: case CORINFO_HELP_DBL2INT: case CORINFO_HELP_DBL2LNG: case CORINFO_HELP_DBL2UINT: case CORINFO_HELP_DBL2ULNG: case CORINFO_HELP_FLTREM: case CORINFO_HELP_DBLREM: case CORINFO_HELP_FLTROUND: case CORINFO_HELP_DBLROUND: isPure = true; noThrow = true; break; // Arithmetic helpers that *can* throw. // This (or these) are not pure, in that they have ""VM side effects""...but they don't mutate the heap. case CORINFO_HELP_ENDCATCH: noThrow = true; break; // Arithmetic helpers that may throw case CORINFO_HELP_LMOD: // Mods throw div-by zero, and signed mods have problems with the smallest integer // mod -1, case CORINFO_HELP_MOD: // which is not representable as a positive integer. case CORINFO_HELP_UMOD: case CORINFO_HELP_ULMOD: case CORINFO_HELP_UDIV: // Divs throw divide-by-zero. case CORINFO_HELP_DIV: case CORINFO_HELP_LDIV: case CORINFO_HELP_ULDIV: case CORINFO_HELP_LMUL_OVF: case CORINFO_HELP_ULMUL_OVF: case CORINFO_HELP_DBL2INT_OVF: case CORINFO_HELP_DBL2LNG_OVF: case CORINFO_HELP_DBL2UINT_OVF: case CORINFO_HELP_DBL2ULNG_OVF: isPure = true; break; // Heap Allocation helpers, these all never return null case CORINFO_HELP_NEWSFAST: case CORINFO_HELP_NEWSFAST_ALIGN8: isAllocator = true; nonNullReturn = true; noThrow = true; // only can throw OutOfMemory break; case CORINFO_HELP_NEW_CROSSCONTEXT: case CORINFO_HELP_NEWFAST: case CORINFO_HELP_READYTORUN_NEW: mayFinalize = true; // These may run a finalizer isAllocator = true; nonNullReturn = true; noThrow = true; // only can throw OutOfMemory break; // These allocation helpers do some checks on the size (and lower bound) inputs, // and can throw exceptions other than OOM. case CORINFO_HELP_NEWARR_1_VC: case CORINFO_HELP_NEWARR_1_ALIGN8: isAllocator = true; nonNullReturn = true; break; // These allocation helpers do some checks on the size (and lower bound) inputs, // and can throw exceptions other than OOM. case CORINFO_HELP_NEW_MDARR: case CORINFO_HELP_NEWARR_1_DIRECT: case CORINFO_HELP_NEWARR_1_OBJ: case CORINFO_HELP_NEWARR_1_R2R_DIRECT: case CORINFO_HELP_READYTORUN_NEWARR_1: mayFinalize = true; // These may run a finalizer isAllocator = true; nonNullReturn = true; break; // Heap Allocation helpers that are also pure case CORINFO_HELP_STRCNS: isPure = true; isAllocator = true; nonNullReturn = true; noThrow = true; // only can throw OutOfMemory break; case CORINFO_HELP_BOX: nonNullReturn = true; isAllocator = true; noThrow = true; // only can throw OutOfMemory break; case CORINFO_HELP_BOX_NULLABLE: // Box Nullable is not a 'pure' function // It has a Byref argument that it reads the contents of. // // So two calls to Box Nullable that pass the same address (with the same Value Number) // will produce different results when the contents of the memory pointed to by the Byref changes // isAllocator = true; noThrow = true; // only can throw OutOfMemory break; case CORINFO_HELP_RUNTIMEHANDLE_METHOD: case CORINFO_HELP_RUNTIMEHANDLE_CLASS: case CORINFO_HELP_RUNTIMEHANDLE_METHOD_LOG: case CORINFO_HELP_RUNTIMEHANDLE_CLASS_LOG: // logging helpers are not technically pure but can be optimized away isPure = true; noThrow = true; nonNullReturn = true; break; // type casting helpers case CORINFO_HELP_ISINSTANCEOFINTERFACE: case CORINFO_HELP_ISINSTANCEOFARRAY: case CORINFO_HELP_ISINSTANCEOFCLASS: case CORINFO_HELP_ISINSTANCEOFANY: case CORINFO_HELP_READYTORUN_ISINSTANCEOF: case CORINFO_HELP_TYPEHANDLE_TO_RUNTIMETYPE: isPure = true; noThrow = true; // These return null for a failing cast break; // type casting helpers that throw case CORINFO_HELP_CHKCASTINTERFACE: case CORINFO_HELP_CHKCASTARRAY: case CORINFO_HELP_CHKCASTCLASS: case CORINFO_HELP_CHKCASTANY: case CORINFO_HELP_CHKCASTCLASS_SPECIAL: case CORINFO_HELP_READYTORUN_CHKCAST: // These throw for a failing cast // But if given a null input arg will return null isPure = true; break; // helpers returning addresses, these can also throw case CORINFO_HELP_UNBOX: case CORINFO_HELP_GETREFANY: case CORINFO_HELP_LDELEMA_REF: isPure = true; break; // helpers that return internal handle case CORINFO_HELP_GETCLASSFROMMETHODPARAM: case CORINFO_HELP_GETSYNCFROMCLASSHANDLE: isPure = true; noThrow = true; break; // Helpers that load the base address for static variables. // We divide these between those that may and may not invoke // static class constructors. case CORINFO_HELP_GETSHARED_GCSTATIC_BASE: case CORINFO_HELP_GETSHARED_NONGCSTATIC_BASE: case CORINFO_HELP_GETSHARED_GCSTATIC_BASE_DYNAMICCLASS: case CORINFO_HELP_GETSHARED_NONGCSTATIC_BASE_DYNAMICCLASS: case CORINFO_HELP_GETGENERICS_GCTHREADSTATIC_BASE: case CORINFO_HELP_GETGENERICS_NONGCTHREADSTATIC_BASE: case CORINFO_HELP_GETSHARED_GCTHREADSTATIC_BASE: case CORINFO_HELP_GETSHARED_NONGCTHREADSTATIC_BASE: case CORINFO_HELP_CLASSINIT_SHARED_DYNAMICCLASS: case CORINFO_HELP_GETSHARED_GCTHREADSTATIC_BASE_DYNAMICCLASS: case CORINFO_HELP_GETSHARED_NONGCTHREADSTATIC_BASE_DYNAMICCLASS: case CORINFO_HELP_GETSTATICFIELDADDR_CONTEXT: case CORINFO_HELP_GETSTATICFIELDADDR_TLS: case CORINFO_HELP_GETGENERICS_GCSTATIC_BASE: case CORINFO_HELP_GETGENERICS_NONGCSTATIC_BASE: case CORINFO_HELP_READYTORUN_STATIC_BASE: case CORINFO_HELP_READYTORUN_GENERIC_STATIC_BASE: // These may invoke static class constructors // These can throw InvalidProgram exception if the class can not be constructed // isPure = true; nonNullReturn = true; mayRunCctor = true; break; case CORINFO_HELP_GETSHARED_GCSTATIC_BASE_NOCTOR: case CORINFO_HELP_GETSHARED_NONGCSTATIC_BASE_NOCTOR: case CORINFO_HELP_GETSHARED_GCTHREADSTATIC_BASE_NOCTOR: case CORINFO_HELP_GETSHARED_NONGCTHREADSTATIC_BASE_NOCTOR: // These do not invoke static class constructors // isPure = true; noThrow = true; nonNullReturn = true; break; // GC Write barrier support // TODO-ARM64-Bug?: Can these throw or not? case CORINFO_HELP_ASSIGN_REF: case CORINFO_HELP_CHECKED_ASSIGN_REF: case CORINFO_HELP_ASSIGN_REF_ENSURE_NONHEAP: case CORINFO_HELP_ASSIGN_BYREF: case CORINFO_HELP_ASSIGN_STRUCT: mutatesHeap = true; break; // Accessing fields (write) case CORINFO_HELP_SETFIELD32: case CORINFO_HELP_SETFIELD64: case CORINFO_HELP_SETFIELDOBJ: case CORINFO_HELP_SETFIELDSTRUCT: case CORINFO_HELP_SETFIELDFLOAT: case CORINFO_HELP_SETFIELDDOUBLE: case CORINFO_HELP_ARRADDR_ST: mutatesHeap = true; break; // These helper calls always throw an exception case CORINFO_HELP_OVERFLOW: case CORINFO_HELP_VERIFICATION: case CORINFO_HELP_RNGCHKFAIL: case CORINFO_HELP_THROWDIVZERO: case CORINFO_HELP_THROWNULLREF: case CORINFO_HELP_THROW: case CORINFO_HELP_RETHROW: case CORINFO_HELP_THROW_ARGUMENTEXCEPTION: case CORINFO_HELP_THROW_ARGUMENTOUTOFRANGEEXCEPTION: break; // These helper calls may throw an exception case CORINFO_HELP_METHOD_ACCESS_CHECK: case CORINFO_HELP_FIELD_ACCESS_CHECK: case CORINFO_HELP_CLASS_ACCESS_CHECK: case CORINFO_HELP_DELEGATE_SECURITY_CHECK: case CORINFO_HELP_MON_EXIT_STATIC: break; // This is a debugging aid; it simply returns a constant address. case CORINFO_HELP_LOOP_CLONE_CHOICE_ADDR: isPure = true; noThrow = true; break; case CORINFO_HELP_DBG_IS_JUST_MY_CODE: case CORINFO_HELP_BBT_FCN_ENTER: case CORINFO_HELP_POLL_GC: case CORINFO_HELP_MON_ENTER: case CORINFO_HELP_MON_EXIT: case CORINFO_HELP_MON_ENTER_STATIC: case CORINFO_HELP_JIT_REVERSE_PINVOKE_ENTER: case CORINFO_HELP_JIT_REVERSE_PINVOKE_EXIT: case CORINFO_HELP_SECURITY_PROLOG: case CORINFO_HELP_SECURITY_PROLOG_FRAMED: case CORINFO_HELP_VERIFICATION_RUNTIME_CHECK: case CORINFO_HELP_GETFIELDADDR: case CORINFO_HELP_INIT_PINVOKE_FRAME: case CORINFO_HELP_JIT_PINVOKE_BEGIN: case CORINFO_HELP_JIT_PINVOKE_END: case CORINFO_HELP_GETCURRENTMANAGEDTHREADID: noThrow = true; break; // Not sure how to handle optimization involving the rest of these helpers default: // The most pessimistic results are returned for these helpers mutatesHeap = true; break; } m_isPure[helper] = isPure; m_noThrow[helper] = noThrow; m_nonNullReturn[helper] = nonNullReturn; m_isAllocator[helper] = isAllocator; m_mutatesHeap[helper] = mutatesHeap; m_mayRunCctor[helper] = mayRunCctor; m_mayFinalize[helper] = mayFinalize; } } //============================================================================= // AssemblyNamesList2 //============================================================================= // The string should be of the form // MyAssembly // MyAssembly;mscorlib;System // MyAssembly;mscorlib System AssemblyNamesList2::AssemblyNamesList2(const wchar_t* list, IAllocator* alloc) : m_alloc(alloc) { assert(m_alloc != nullptr); WCHAR prevChar = '?'; // dummy LPWSTR nameStart = nullptr; // start of the name currently being processed. nullptr if no current name AssemblyName** ppPrevLink = &m_pNames; for (LPWSTR listWalk = const_cast(list); prevChar != '\\0'; prevChar = *listWalk, listWalk++) { WCHAR curChar = *listWalk; if (iswspace(curChar) || curChar == W(';') || curChar == W('\\0')) { // // Found white-space // if (nameStart) { // Found the end of the current name; add a new assembly name to the list. AssemblyName* newName = new (m_alloc) AssemblyName(); // Null out the current character so we can do zero-terminated string work; we'll restore it later. *listWalk = W('\\0'); // How much space do we need? int convertedNameLenBytes = WszWideCharToMultiByte(CP_UTF8, 0, nameStart, -1, nullptr, 0, nullptr, nullptr); newName->m_assemblyName = new (m_alloc) char[convertedNameLenBytes]; // convertedNameLenBytes includes // the trailing null character if (WszWideCharToMultiByte(CP_UTF8, 0, nameStart, -1, newName->m_assemblyName, convertedNameLenBytes, nullptr, nullptr) != 0) { *ppPrevLink = newName; ppPrevLink = &newName->m_next; } else { // Failed to convert the string. Ignore this string (and leak the memory). } nameStart = nullptr; // Restore the current character. *listWalk = curChar; } } else if (!nameStart) { // // Found the start of a new name // nameStart = listWalk; } } assert(nameStart == nullptr); // cannot be in the middle of a name *ppPrevLink = nullptr; // Terminate the last element of the list. } AssemblyNamesList2::~AssemblyNamesList2() { for (AssemblyName* pName = m_pNames; pName != nullptr; /**/) { AssemblyName* cur = pName; pName = pName->m_next; m_alloc->Free(cur->m_assemblyName); m_alloc->Free(cur); } } bool AssemblyNamesList2::IsInList(const char* assemblyName) { for (AssemblyName* pName = m_pNames; pName != nullptr; pName = pName->m_next) { if (_stricmp(pName->m_assemblyName, assemblyName) == 0) { return true; } } return false; } #ifdef FEATURE_JIT_METHOD_PERF CycleCount::CycleCount() : cps(CycleTimer::CyclesPerSecond()) { } bool CycleCount::GetCycles(unsigned __int64* time) { return CycleTimer::GetThreadCyclesS(time); } bool CycleCount::Start() { return GetCycles(&beginCycles); } double CycleCount::ElapsedTime() { unsigned __int64 nowCycles; (void)GetCycles(&nowCycles); return ((double)(nowCycles - beginCycles) / cps) * 1000.0; } bool PerfCounter::Start() { bool result = QueryPerformanceFrequency(&beg) != 0; if (!result) { return result; } freq = (double)beg.QuadPart / 1000.0; (void)QueryPerformanceCounter(&beg); return result; } // Return elapsed time from Start() in millis. double PerfCounter::ElapsedTime() { LARGE_INTEGER li; (void)QueryPerformanceCounter(&li); return (double)(li.QuadPart - beg.QuadPart) / freq; } #endif #ifdef DEBUG /***************************************************************************** * Return the number of digits in a number of the given base (default base 10). * Used when outputting strings. */ unsigned CountDigits(unsigned num, unsigned base /* = 10 */) { assert(2 <= base && base <= 16); // sanity check unsigned count = 1; while (num >= base) { num /= base; ++count; } return count; } #endif // DEBUG double FloatingPointUtils::convertUInt64ToDouble(unsigned __int64 uIntVal) { __int64 s64 = uIntVal; double d; if (s64 < 0) { #if defined(_TARGET_XARCH_) // RyuJIT codegen and clang (or gcc) may produce different results for casting uint64 to // double, and the clang result is more accurate. For example, // 1) (double)0x84595161401484A0UL --> 43e08b2a2c280290 (RyuJIT codegen or VC++) // 2) (double)0x84595161401484A0UL --> 43e08b2a2c280291 (clang or gcc) // If the folding optimization below is implemented by simple casting of (double)uint64_val // and it is compiled by clang, casting result can be inconsistent, depending on whether // the folding optimization is triggered or the codegen generates instructions for casting. // // The current solution is to force the same math as the codegen does, so that casting // result is always consistent. // d = (double)(int64_t)uint64 + 0x1p64 uint64_t adjHex = 0x43F0000000000000UL; d = (double)s64 + *(double*)&adjHex; #else d = (double)uIntVal; #endif } else { d = (double)uIntVal; } return d; } float FloatingPointUtils::convertUInt64ToFloat(unsigned __int64 u64) { double d = convertUInt64ToDouble(u64); return (float)d; } unsigned __int64 FloatingPointUtils::convertDoubleToUInt64(double d) { unsigned __int64 u64; if (d >= 0.0) { // Work around a C++ issue where it doesn't properly convert large positive doubles const double two63 = 2147483648.0 * 4294967296.0; if (d < two63) { u64 = UINT64(d); } else { // subtract 0x8000000000000000, do the convert then add it back again u64 = INT64(d - two63) + I64(0x8000000000000000); } return u64; } #ifdef _TARGET_XARCH_ // While the Ecma spec does not specifically call this out, // the case of conversion from negative double to unsigned integer is // effectively an overflow and therefore the result is unspecified. // With MSVC for x86/x64, such a conversion results in the bit-equivalent // unsigned value of the conversion to integer. Other compilers convert // negative doubles to zero when the target is unsigned. // To make the behavior consistent across OS's on TARGET_XARCH, // this double cast is needed to conform MSVC behavior. u64 = UINT64(INT64(d)); #else u64 = UINT64(d); #endif // _TARGET_XARCH_ return u64; } // Rounds a double-precision floating-point value to the nearest integer, // and rounds midpoint values to the nearest even number. // Note this should align with classlib in floatdouble.cpp // Specializing for x86 using a x87 instruction is optional since // this outcome is identical across targets. double FloatingPointUtils::round(double x) { // If the number has no fractional part do nothing // This shortcut is necessary to workaround precision loss in borderline cases on some platforms if (x == (double)((INT64)x)) { return x; } // We had a number that was equally close to 2 integers. // We need to return the even one. double tempVal = (x + 0.5); double flrTempVal = floor(tempVal); if ((flrTempVal == tempVal) && (fmod(tempVal, 2.0) != 0)) { flrTempVal -= 1.0; } return _copysign(flrTempVal, x); } // Windows x86 and Windows ARM/ARM64 may not define _copysignf() but they do define _copysign(). // We will redirect the macro to this other functions if the macro is not defined for the platform. // This has the side effect of a possible implicit upcasting for arguments passed in and an explicit // downcasting for the _copysign() call. #if (defined(_TARGET_X86_) || defined(_TARGET_ARM_) || defined(_TARGET_ARM64_)) && !defined(FEATURE_PAL) #if !defined(_copysignf) #define _copysignf (float)_copysign #endif #endif // Rounds a single-precision floating-point value to the nearest integer, // and rounds midpoint values to the nearest even number. // Note this should align with classlib in floatsingle.cpp // Specializing for x86 using a x87 instruction is optional since // this outcome is identical across targets. float FloatingPointUtils::round(float x) { // If the number has no fractional part do nothing // This shortcut is necessary to workaround precision loss in borderline cases on some platforms if (x == (float)((INT32)x)) { return x; } // We had a number that was equally close to 2 integers. // We need to return the even one. float tempVal = (x + 0.5f); float flrTempVal = floorf(tempVal); if ((flrTempVal == tempVal) && (fmodf(tempVal, 2.0f) != 0)) { flrTempVal -= 1.0f; } return _copysignf(flrTempVal, x); } namespace MagicDivide { template static const Magic* TryGetMagic(const Magic (&table)[TableSize], typename Magic::DivisorType index) { if ((index < TableBase) || (TableBase + TableSize <= index)) { return nullptr; } const Magic* p = &table[index - TableBase]; if (p->magic == 0) { return nullptr; } return p; }; template struct UnsignedMagic { typedef T DivisorType; T magic; bool add; int shift; }; template const UnsignedMagic* TryGetUnsignedMagic(T divisor) { return nullptr; } template <> const UnsignedMagic* TryGetUnsignedMagic(uint32_t divisor) { static const UnsignedMagic table[]{ {0xaaaaaaab, false, 1}, // 3 {}, {0xcccccccd, false, 2}, // 5 {0xaaaaaaab, false, 2}, // 6 {0x24924925, true, 3}, // 7 {}, {0x38e38e39, false, 1}, // 9 {0xcccccccd, false, 3}, // 10 {0xba2e8ba3, false, 3}, // 11 {0xaaaaaaab, false, 3}, // 12 }; return TryGetMagic<3>(table, divisor); } template <> const UnsignedMagic* TryGetUnsignedMagic(uint64_t divisor) { static const UnsignedMagic table[]{ {0xaaaaaaaaaaaaaaab, false, 1}, // 3 {}, {0xcccccccccccccccd, false, 2}, // 5 {0xaaaaaaaaaaaaaaab, false, 2}, // 6 {0x2492492492492493, true, 3}, // 7 {}, {0xe38e38e38e38e38f, false, 3}, // 9 {0xcccccccccccccccd, false, 3}, // 10 {0x2e8ba2e8ba2e8ba3, false, 1}, // 11 {0xaaaaaaaaaaaaaaab, false, 3}, // 12 }; return TryGetMagic<3>(table, divisor); } //------------------------------------------------------------------------ // GetUnsignedMagic: Generates a magic number and shift amount for the magic // number unsigned division optimization. // // Arguments: // d - The divisor // add - Pointer to a flag indicating the kind of code to generate // shift - Pointer to the shift value to be returned // // Returns: // The magic number. // // Notes: // This code is adapted from _The_PowerPC_Compiler_Writer's_Guide_, pages 57-58. // The paper is based on ""Division by invariant integers using multiplication"" // by Torbjorn Granlund and Peter L. Montgomery in PLDI 94 template T GetUnsignedMagic(T d, bool* add /*out*/, int* shift /*out*/) { assert((d >= 3) && !isPow2(d)); const UnsignedMagic* magic = TryGetUnsignedMagic(d); if (magic != nullptr) { *shift = magic->shift; *add = magic->add; return magic->magic; } typedef typename jitstd::make_signed::type ST; const unsigned bits = sizeof(T) * 8; const unsigned bitsMinus1 = bits - 1; const T twoNMinus1 = T(1) << bitsMinus1; *add = false; const T nc = -ST(1) - -ST(d) % ST(d); unsigned p = bitsMinus1; T q1 = twoNMinus1 / nc; T r1 = twoNMinus1 - (q1 * nc); T q2 = (twoNMinus1 - 1) / d; T r2 = (twoNMinus1 - 1) - (q2 * d); T delta; do { p++; if (r1 >= (nc - r1)) { q1 = 2 * q1 + 1; r1 = 2 * r1 - nc; } else { q1 = 2 * q1; r1 = 2 * r1; } if ((r2 + 1) >= (d - r2)) { if (q2 >= (twoNMinus1 - 1)) { *add = true; } q2 = 2 * q2 + 1; r2 = 2 * r2 + 1 - d; } else { if (q2 >= twoNMinus1) { *add = true; } q2 = 2 * q2; r2 = 2 * r2 + 1; } delta = d - 1 - r2; } while ((p < (bits * 2)) && ((q1 < delta) || ((q1 == delta) && (r1 == 0)))); *shift = p - bits; // resulting shift return q2 + 1; // resulting magic number } uint32_t GetUnsigned32Magic(uint32_t d, bool* add /*out*/, int* shift /*out*/) { return GetUnsignedMagic(d, add, shift); } #ifdef _TARGET_64BIT_ uint64_t GetUnsigned64Magic(uint64_t d, bool* add /*out*/, int* shift /*out*/) { return GetUnsignedMagic(d, add, shift); } #endif template struct SignedMagic { typedef T DivisorType; T magic; int shift; }; template const SignedMagic* TryGetSignedMagic(T divisor) { return nullptr; } template <> const SignedMagic* TryGetSignedMagic(int32_t divisor) { static const SignedMagic table[]{ {0x55555556, 0}, // 3 {}, {0x66666667, 1}, // 5 {0x2aaaaaab, 0}, // 6 {0x92492493, 2}, // 7 {}, {0x38e38e39, 1}, // 9 {0x66666667, 2}, // 10 {0x2e8ba2e9, 1}, // 11 {0x2aaaaaab, 1}, // 12 }; return TryGetMagic<3>(table, divisor); } template <> const SignedMagic* TryGetSignedMagic(int64_t divisor) { static const SignedMagic table[]{ {0x5555555555555556, 0}, // 3 {}, {0x6666666666666667, 1}, // 5 {0x2aaaaaaaaaaaaaab, 0}, // 6 {0x4924924924924925, 1}, // 7 {}, {0x1c71c71c71c71c72, 0}, // 9 {0x6666666666666667, 2}, // 10 {0x2e8ba2e8ba2e8ba3, 1}, // 11 {0x2aaaaaaaaaaaaaab, 1}, // 12 }; return TryGetMagic<3>(table, divisor); } //------------------------------------------------------------------------ // GetSignedMagic: Generates a magic number and shift amount for // the magic number division optimization. // // Arguments: // denom - The denominator // shift - Pointer to the shift value to be returned // // Returns: // The magic number. // // Notes: // This code is previously from UTC where it notes it was taken from // _The_PowerPC_Compiler_Writer's_Guide_, pages 57-58. The paper is is based on // is ""Division by invariant integers using multiplication"" by Torbjorn Granlund // and Peter L. Montgomery in PLDI 94 template T GetSignedMagic(T denom, int* shift /*out*/) { const SignedMagic* magic = TryGetSignedMagic(denom); if (magic != nullptr) { *shift = magic->shift; return magic->magic; } const int bits = sizeof(T) * 8; const int bits_minus_1 = bits - 1; typedef typename jitstd::make_unsigned::type UT; const UT two_nminus1 = UT(1) << bits_minus_1; int p; UT absDenom; UT absNc; UT delta; UT q1; UT r1; UT r2; UT q2; UT t; T result_magic; int result_shift; int iters = 0; absDenom = abs(denom); t = two_nminus1 + ((unsigned int)denom >> 31); absNc = t - 1 - (t % absDenom); // absolute value of nc p = bits_minus_1; // initialize p q1 = two_nminus1 / absNc; // initialize q1 = 2^p / abs(nc) r1 = two_nminus1 - (q1 * absNc); // initialize r1 = rem(2^p, abs(nc)) q2 = two_nminus1 / absDenom; // initialize q1 = 2^p / abs(denom) r2 = two_nminus1 - (q2 * absDenom); // initialize r1 = rem(2^p, abs(denom)) do { iters++; p++; q1 *= 2; // update q1 = 2^p / abs(nc) r1 *= 2; // update r1 = rem(2^p / abs(nc)) if (r1 >= absNc) { // must be unsigned comparison q1++; r1 -= absNc; } q2 *= 2; // update q2 = 2^p / abs(denom) r2 *= 2; // update r2 = rem(2^p / abs(denom)) if (r2 >= absDenom) { // must be unsigned comparison q2++; r2 -= absDenom; } delta = absDenom - r2; } while (q1 < delta || (q1 == delta && r1 == 0)); result_magic = q2 + 1; // resulting magic number if (denom < 0) { result_magic = -result_magic; } *shift = p - bits; // resulting shift return result_magic; } int32_t GetSigned32Magic(int32_t d, int* shift /*out*/) { return GetSignedMagic(d, shift); } #ifdef _TARGET_64BIT_ int64_t GetSigned64Magic(int64_t d, int* shift /*out*/) { return GetSignedMagic(d, shift); } #endif } ",16155,False,2127.509176822791,median "open util/ordering [State] as ord pred test52 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State0->Chicken0 + State0->Grain0 + State1->Farmer0 + State1->Chicken0 + State1->Grain0 + State2->Chicken0 + State3->Farmer0 + State3->Chicken0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test52 for 4 expect 0 pred test51 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Farmer0 + State1->Fox0 + State1->Chicken0 + State1->Grain0 + State2->Fox0 + State2->Grain0 + State3->Farmer0 + State3->Fox0 + State3->Grain0 far = State2->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test51 for 4 expect 0 pred test28 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Chicken0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State1->Chicken0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Chicken0,Fox0 + Grain0,Chicken0] }}}}}} } run test28 for 4 expect 0 pred test35 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Chicken0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State1->Chicken0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Grain0,Fox0,none,Farmer0 + Grain0] }}}}}} } run test35 for 4 expect 1 pred test10 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Grain0,Fox0 + Grain0,none,Farmer0] }}}}}} } run test10 for 4 expect 1 pred test32 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Chicken0 + Grain0,Chicken0,none,Farmer0 + Grain0] }}}}}} } run test32 for 4 expect 1 pred test14 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Grain0,Fox0 + Grain0,Grain0,Fox0 + Chicken0] }}}}}} } run test14 for 4 expect 0 pred test46 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State1->Chicken0 + State2->Chicken0 + State3->Farmer0 + State3->Chicken0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 solvePuzzle[] }}}}}} } run test46 for 4 expect 0 pred test37 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Farmer0 + Fox0 + Grain0,Fox0,none,Farmer0 + Grain0] }}}}}} } run test37 for 4 expect 1 pred test25 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Chicken0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State1->Chicken0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Farmer0,Grain0,Fox0 + Chicken0] }}}}}} } run test25 for 4 expect 0 pred test56 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Chicken0 + State2->Farmer0 + State2->Chicken0 + State3->Chicken0 far = State1->Farmer0 + State1->Fox0 + State2->Fox0 + State3->Farmer0 + State3->Fox0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test56 for 4 expect 1 pred test12 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Farmer0,none,Farmer0] }}}}}} } run test12 for 4 expect 0 pred test15 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State1->Chicken0 + State2->Chicken0 + State3->Farmer0 + State3->Chicken0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Grain0,none,Farmer0] }}}}}} } run test15 for 4 expect 0 pred test45 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Chicken0,Fox0,Farmer0 + Fox0] }}}}}} } run test45 for 4 expect 1 pred test4 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Grain0: Grain {some disj Farmer0, Fox0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 no Chicken Grain = Grain0 Object = Farmer0 + Fox0 + Grain0 no eats State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State3->Fox0 far = State1->Farmer0 + State1->Grain0 + State2->Grain0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}} } run test4 for 4 expect 0 pred test1 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State1->Chicken0 + State2->Chicken0 + State3->Farmer0 + State3->Chicken0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test1 for 4 expect 1 pred test8 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Farmer0,Grain0,Fox0 + Chicken0] }}}}}} } run test8 for 4 expect 0 pred test23 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Chicken0,none,Farmer0 + Fox0] }}}}}} } run test23 for 4 expect 1 pred test48 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Chicken0 + State2->Farmer0 + State2->Fox0 + State2->Chicken0 + State2->Grain0 + State3->Fox0 + State3->Chicken0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test48 for 4 expect 0 pred test24 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Chicken0,none,none,Farmer0 + Grain0] }}}}}} } run test24 for 4 expect 0 pred test18 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Chicken0,Chicken0,none,Farmer0] }}}}}} } run test18 for 4 expect 1 pred test21 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Chicken0 + State2->Farmer0 + State2->Fox0 + State2->Chicken0 + State3->Fox0 far = State1->Farmer0 + State1->Fox0 + State3->Farmer0 + State3->Chicken0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Grain0,Fox0 + Grain0,none,Farmer0] }}}}}} } run test21 for 4 expect 1 pred test49 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test49 for 4 expect 1 pred test11 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Grain0,Fox0,none,Farmer0 + Grain0] }}}}}} } run test11 for 4 expect 1 pred test54 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Chicken0 + State2->Grain0 + State3->Fox0 + State3->Chicken0 far = State1->Farmer0 + State2->Fox0 + State2->Chicken0 + State2->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test54 for 4 expect 0 pred test38 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Grain0,Grain0,Fox0 + Grain0,Farmer0 + Fox0 + Grain0] }}}}}} } run test38 for 4 expect 1 pred test34 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Chicken0 + State2->Farmer0 + State2->Chicken0 far = State1->Farmer0 + State1->Fox0 + State2->Fox0 + State3->Farmer0 + State3->Fox0 + State3->Chicken0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Fox0 + Grain0,Fox0 + Grain0,Farmer0 + Fox0 + Chicken0 + Grain0] }}}}}} } run test34 for 4 expect 1 pred test19 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Farmer0 + Fox0 + Grain0,Fox0 + Grain0,none,Farmer0] }}}}}} } run test19 for 4 expect 1 ",8135,True,3075.8585407321334,median "// // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // ""License""); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // ""AS IS"" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // = NetBeans IDEでのエンタープライズ・アプリケーションのプロファイリング :jbake-type: tutorial :jbake-tags: tutorials :jbake-status: published :icons: font :syntax: true :source-highlighter: pygments :toc: left :toc-title: :description: NetBeans IDEでのエンタープライズ・アプリケーションのプロファイリング - Apache NetBeans :keywords: Apache NetBeans, Tutorials, NetBeans IDEでのエンタープライズ・アプリケーションのプロファイリング NetBeans IDEには、エンタープライズ・アプリケーションの実行時の動作に関する重要な情報を提供できる強力なプロファイリング・ツールが含まれています。プロファイリング・ツールを使用して、簡単にスレッドの状態をモニターしたり、アプリケーションのCPUパフォーマンスやメモリー使用状況に関するデータを取得したりできます。 このドキュメントでは、プロファイリング・ツールを使用して、アプリケーション・サーバーにWARとしてデプロイされている単純なエンタープライズ・アプリケーションに関するデータを取得します。このドキュメントでは、IDEを使用して次に関するプロファイリング結果を取得する方法を示します。 * アプリケーションの実行時動作 * アプリケーションのメソッドによって使用されたCPU時間 * オブジェクト作成 ローカルに登録されたTomcat、GlassFishサーバーまたはJBossインストールにアプリケーションをデプロイしている場合は、ほとんど構成せずに数回のマウス・クリックのみでアプリケーションをプロファイルできます。プロジェクトをプロファイリングするプロセスは、IDEで「実行」コマンドを使用する場合と非常に似ています。メイン・メニューから「プロファイリング」>「メイン・プロジェクトのプロファイル」を選択することで、エンタープライズ・アプリケーション・プロジェクトまたは個々のWebおよびEJBモジュールのプロファイリングを簡単に開始できます。 *このチュートリアルに従うには、次のソフトウェアとリソースが必要です。* |=== |ソフトウェアまたはリソース |必須バージョン |link:https://netbeans.org/downloads/index.html[+NetBeans IDE+] |7.3、7.4、8.0、Java EEバンドル版 |link:http://www.oracle.com/technetwork/java/javase/downloads/index.html[+Java Development Kit (JDK)+] |JDK 7または8 |GlassFishサーバー |3.1, 4.0 |=== [NOTE] ==== * プロファイラを初めて使用する場合は、タスクのモニタリングとプロファイリングの概要について説明しているlink:../java/profiler-intro.html[+NetBeans IDEでのJavaアプリケーションのプロファイリングの概要+]を読むことをお薦めします。 * NetBeans IDE 7.2またはそれ以前を使用している場合は、link:../../72/javaee/profiler-javaee.html[+NetBeans IDE 7.2でのエンタープライズ・アプリケーションのプロファイリング+]を参照してください。 * このドキュメントでは、GlassFishサーバーにデプロイされたエンタープライズ・アプリケーションをプロファイルします。開発中にエンタープライズ・アプリケーションまたはWebアプリケーションをプロファイリングする場合に推奨される最も単純な構成は、アプリケーションをローカルのTomcat、GlassFishまたはJBossサーバー上で実行しているときです。 ==== == IDEでのエンタープライズ・アプリケーションのプロファイリングについて エンタープライズ・アプリケーションをプロファイリングするときは、ほとんどの場合、アプリケーションのパフォーマンスを解析してプロジェクトのメソッドの実行時間を確認します。これにより、アプリケーションのトラブルシューティングを行い、パフォーマンスの向上を試みることができます。場合によっては、ガベージ・コレクションを最適化するためにメモリー使用状況に関するデータも入手します。 エンタープライズ・アプリケーション、EJBモジュールおよびWebアプリケーションをプロファイリングするためのプロセスは、基本的に「実行」コマンドを使用してプロジェクトを実行する場合と同じです。プロファイリング・タスクを選択し、プロファイリング・オプションを指定したら、「プロファイリング・タスクの選択」ダイアログ・ボックスで「実行」をクリックしてプロファイリング・セッションを開始します。プロファイリング・セッションを開始すると、IDEによって次が実行されます。 * アプリケーションをコンパイルする * ターゲット・サーバーをプロファイリング・モードで起動する * アプリケーションをデプロイする * アプリケーションにアタッチする * WebブラウザでWebページを開く(プロジェクト・プロパティで指定された場合) * 「プロファイリングのライブ結果」タブを開く プロファイリング・オプションによっては、IDEの「プロファイリングのライブ結果」タブにプロファイリング結果がただちに表示され始めます。プロファイリング用ルート・メソッドを指定したときなど、場合によっては、結果を表示する前にWebブラウザでいくつかのアクションを実行する必要がある場合があります。 === エンタープライズ・アプリケーション・プロジェクトのプロファイリング IDEで作成するエンタープライズ・アプリケーションは通常、Webアーカイブ(WAR)としてアプリケーション・サーバーにデプロイされるWebアプリケーション・プロジェクトか、またはWebアプリケーションと追加ライブラリを含み、エンタープライズ・アプリケーション・アーカイブ(EAR)としてデプロイされるエンタープライズ・アプリケーション・プロジェクトのどちらかです。 アプリケーションをEARアーカイブとしてデプロイする場合は、サブプロジェクトとライブラリを含むNetBeansエンタープライズ・アプリケーション・プロジェクトを作成できます。エンタープライズ・アプリケーション・プロジェクトには、ソース・ファイルは含まれず、アプリケーションのビルドとデプロイに関する情報とサーバー構成のメタデータのみが含まれます。エンタープライズ・アプリケーション・プロジェクトでは、一般にアプリケーションのビジネス・ロジックがEJBモジュールに含まれ、プレゼンテーション・レイヤーのソース・コードがWebモジュールに含まれます。 エンタープライズ・アプリケーション・プロジェクトのすべてのソースが存在する場合、アプリケーションをプロファイリングする最も適切で簡単な方法は、プロジェクトの1つのサブプロジェクトではなく、エンタープライズ・アプリケーション・プロジェクトをプロファイルすることです。これにより、必要なすべてのコードがコンパイルおよびデプロイされ、アプリケーションが正常に動作します。次のいずれかを実行することで、エンタープライズ・アプリケーション・プロジェクトをプロファイルできます。 * エンタープライズ・アプリケーション・プロジェクトがメイン・プロジェクトとして設定されている場合は、IDEツールバーから「メイン・プロジェクトのプロファイル」をクリックするか、メイン・メニューで「プロファイル」>「メイン・プロジェクトのプロファイル」を選択します。 * 「プロジェクト」ウィンドウでエンタープライズ・アプリケーション・プロジェクトのノードを右クリックし、ポップアップ・メニューから「プロファイル」を選択します。 エンタープライズ・アプリケーションをプロファイリングするときは、プロファイリング用ルート・メソッドを指定し、インストゥルメント・フィルタを使用してプロファイルされるクラスを制限することにより、プロファイリング結果の関連性を高めることができます。これは、プロファイリングのオーバーヘッドがアプリケーションのパフォーマンスに与える影響を最小限に抑え、プロファイリング結果の関連性を高めるのに役立ちます。 Webアプリケーションと異なり、エンタープライズ・アプリケーションを実行するときは、ブラウザが常に自動的に開くとはかぎりません。(これはプロジェクトの構成によって異なります。)これは、場合によってはWebアプリケーションのフロント・エンドを手動で起動してから、EJBモジュール内のビジネス・ロジックなどのコードをWebブラウザから呼び出す必要があることを意味します。 === EJBおよびWebモジュール・サブプロジェクトのプロファイリング 任意のEJBモジュールまたはWebモジュール・プロジェクトからプロファイリング・セッションを開始できます。この場合、次のいずれかの方法を試すことをお薦めします。 * *EJBモジュールのプロファイリング。*この方法を選択した場合、EJBモジュール・プロジェクトは一般にWebブラウザを開くように構成されていないため、通常はWebブラウザまたは別のクライアントからアプリケーション・コードを手動で呼び出す必要があります。EJBモジュールがサーバーにデプロイされたら、アプリケーション機能のデバッグや評価の場合と同じ方法で(通常はWebアプリケーションのフロント・エンドを起動してから、Webブラウザでアクションを実行することにより)、そのコードをコールするようにしてください。 * *Webモジュールのプロファイリング。*この方法を選択した場合は、Webモジュール・プロジェクトをプロファイリングする前に、EJBモジュールをコンパイルしてサーバーにデプロイする必要があります。通常、EJBのコードはブラウザ内でのなんらかのユーザー・アクションの結果として実行されます。このアクションがWebアプリケーション・コードによって実行または処理されると、EJBコードがそのコール・ツリーに表示されます。 == サンプル・プロジェクトの作成 このドキュメントでは、ServletStatelessサンプル・アプリケーションをプロファイルします。ServletStatelessアプリケーションは、IDEにサンプル・プロジェクトとして含まれている単純なエンタープライズWebアプリケーションです。 ServletStatelessアプリケーションを作成するには、次の手順を実行します。 1. メイン・メニューから「ファイル」>「新規プロジェクト」([Ctrl]-[Shift]-[N]、Macの場合は[⌘]-[Shift]-[N])を選択します。 2. 新規プロジェクト・ウィザードで、「サンプル」>「Java EE」カテゴリを選択します。 3. Servlet Statelessプロジェクトを選択します。「次」をクリックします。 4. プロジェクトの場所を指定します。「終了」をクリックします。 「終了」をクリックすると、IDEによってServletStatelessサンプル・プロジェクトが作成されます。「プロジェクト」ウィンドウにServletStatelessプロジェクトが表示されます。 [NOTE] ==== * デフォルトでは、IDEを使用してプロジェクトをプロファイルすると、複数のプロジェクトが開いている場合は、「プロジェクト」ウィンドウで選択したプロジェクトがプロファイルされます。メイン・メニューから「実行」>「メイン・プロジェクトとして設定」を選択し、プロジェクトをメイン・プロジェクトとして設定した場合は、メイン・プロジェクトがデフォルトでプロファイルされます。「プロジェクト」ウィンドウでプロジェクト・ノードを右クリックし、ポップアップ・メニューから「プロファイル」を選択できます。 * ``.jsp`` ページやサーブレットなどのファイルをプロファイルする場合は、そのファイルを右クリックして、ポップアップ・メニューから「ファイルをプロファイル」を選択します。動作は「(メイン)プロジェクトをプロファイル」とほぼ同じですが、プロファイリング・セッションを開始すると、プロジェクトのデフォルトのWebページではなく、選択されたWebページがブラウザで開きます。 ==== == アプリケーションのモニタリング アプリケーションをモニタリングすると、スレッドのアクティビティやメモリーの割当てなど、ターゲットJVMのプロパティに関する概要を取得できます。アプリケーションのモニタリングにかかるオーバーヘッドは非常に低いため、このモードではアプリケーションを長時間実行できます。「モニター」タスクを選択した場合、ターゲット・アプリケーションはインストゥルメントなしで起動されます。 ServletStatelessアプリケーションをモニターするには、次の手順を実行します。 1. 「実行」>「メイン・プロジェクトとして設定」>「ServletStateless」を選択し、プロジェクトをメイン・プロジェクトとして設定します。 プロジェクトをメイン・プロジェクトとして設定すると、「プロジェクト」ウィンドウでは、そのプロジェクト名が太字で表示されます。 . メイン・メニューから「プロファイル」>「メイン・プロジェクトのプロファイル」を選択します。 NOTE: プロファイリング用のJavaプラットフォームを選択するプロンプトが表示された場合は、JDK 1.7またはJDK 1.8を選択します。 . 「プロファイリング・タスクの選択」ダイアログ・ボックスで「モニター」を選択します。 . 「実行」をクリックします。 NOTE: プロファイラを以前に使用したことがない場合は、「実行」をクリックできるようになる前に、プロファイラを調整するためのプロンプトが表示される場合があります。プロファイラの調整の詳細は、link:../java/profiler-intro.html[+NetBeans IDEでのJavaアプリケーションのプロファイリングの概要+]のlink:../java/profiler-intro.html#calibrate[+初めてのプロファイラの使用+]の項を参照してください。 「実行」をクリックすると、IDEによってアプリケーションがビルドされ、プロファイル・モードでサーバーが起動され、サーバーにアプリケーションがデプロイされます。次に、IDEがアプリケーションにアタッチされ、データの取得が開始されます。 ターゲットJVM内のスレッド上のデータが「スレッド」タブに表示されます。「スレッド」タブには、すべてのスレッド、サーバー・スレッドおよびアプリケーション内のスレッド上のデータが表示されます。 「プロファイラ」ウィンドウの「遠隔測定の概要」ボタンをクリックして「VM遠隔測定の概要」ウィンドウを開くことにより、追加のモニタリング情報を表示できます。「VM遠隔測定の概要」ウィンドウでは、モニタリング・データの概要をリアル・タイムですばやく取得できます。「VM遠隔測定の概要」ウィンドウ内のいずれかのグラフをダブルクリックすると、そのグラフのより大きいバージョンを開くことができます。 エンタープライズ・アプリケーションをモニタリングするときは、メモリー(ヒープ)グラフとメモリー(GC)グラフを使用して、アプリケーションのメモリー使用状況をすばやく確認できます。グラフの上にカーソルを置くと、詳細情報を示すツールチップを開くことができます。ヒープ・サイズや生存中世代の数が徐々に増加している場合は、メモリー・リークを示している可能性があります。メモリー・リークが疑われる場合は、アプリケーションのメモリー使用状況をプロファイルすることをお薦めします。 image::images/monitor-memory-telemetry.png[title=""GCの情報を示すメモリー(GC)グラフ""] == アプリケーションのパフォーマンスの解析 「CPUパフォーマンスを解析」タスクを使用して、アプリケーションのメソッド・レベルのCPUパフォーマンス(実行時間)とメソッドが呼び出された回数に関するデータを確認できます。アプリケーション全体のパフォーマンスを解析するか、またはプロファイリング・ルートを選択してプロファイリングをアプリケーション・コードの一部に制限するかを選択できます。 image::images/sample-task.png[title=""「プロファイリング・タスクの選択」ダイアログ・ボックスの「CPU」ペインで選択された「サンプル・アプリケーション」モード""] 「プロファイリング・タスク」ウィンドウで「CPUパフォーマンスを解析」タスクを選択したときは、次のいずれかのオプションを選択することで、プロファイルするアプリケーションの部分を選択できます。 * *簡易(サンプリング)。*このモードでは、IDEはアプリケーションをサンプリングし、定期的にスタック・トレースを取得します。このオプションは、メソッドをインストゥルメントする方法と比較して正確性が低下しますが、オーバーヘッドは低くなります。このオプションは、インストゥルメントが必要になる可能性のあるメソッドを見つけるのに役立ちます。 * *詳細(インストゥルメント済)。*このモードでは、プロファイルされたアプリケーションのメソッドがインストゥルメントされます。IDEでは、スレッドがプロジェクトのメソッドに入った時刻と出た時刻が記録されるため、各メソッド内で費やされた時間の長さを確認できます。メソッドに入るときは、スレッドによって「メソッドに入る」イベントが生成されます。メソッドから出るときは、スレッドによって対応する「メソッドから出る」イベントが生成されます。この両方のイベントのタイムスタンプが記録されます。これらのデータはリアル・タイムで処理されます。 アプリケーション内のすべてのメソッドをインストゥルメントするか、または1つ以上の*ルート・メソッド*を指定することによってインストゥルメントをアプリケーションのコードのサブセットに制限するかを選択できます。ルート・メソッドを指定すると、プロファイリングのオーバーヘッドを大幅に削減できます。ルート・メソッドは、ユーザーがインストゥルメントのルートとして指定する、ソース・コード内のメソッド、クラス、またはパッケージです。プロファイリング・データは、アプリケーションのスレッドのいずれかがインストゥルメントのルートに入ったときと出たときに収集されます。アプリケーションのスレッドのいずれかがルート・メソッドに入るまで、プロファイリング・データは収集されません。ルート・メソッドは、ソース・コード内でポップアップ・メニューを使用するか、または「*カスタマイズ*」をクリックして「プロファイリング・ルートの編集」ダイアログ・ボックスを開くことによって指定できます。 *Webアプリケーションのプロファイリングに関するヒント* * エンタープライズ・アプリケーションは、通常、Javaコア・クラスに加えて、ターゲット・サーバーのクラスに含まれる多数のメソッドを呼び出します。このため、インストゥルメントされるソースを制限するためのフィルタを選択することが重要です。エンタープライズ・アプリケーションをプロファイリングするときは、「*プロジェクト・クラスだけをプロファイリング*」フィルタを使用することをお薦めします。 * プロファイリング結果は、プロファイリング・セッションが開始されるとすぐに収集されます。詳細方式の使用時にプロファイリング用ルート・メソッドが指定されていない場合は、サーバーの起動(特に、Webアプリケーションのリスナーおよびフィルタの初期化)の直後にいくつかの興味深いデータを取得できます。プロファイリング用ルート・メソッドを指定すると、選択したルート・メソッドによっては、このデータを取得できない可能性があります。 * 通常はリスナーやフィルタに関するデータは必要ないため、「収集結果をリセット」をクリックしてそのデータをクリアできます。Webブラウザでのアクションの結果としてなんらかのコード(通常はJavaBeans、カスタム・タグ、またはその両方を使用するJSPページの表示やサーブレットの ``doGet`` / ``doPost`` メソッドの処理)が呼び出されると、最初に使用可能なデータが収集されます。アプリケーションが初めて起動したときに収集されるデータは、多くの場合、Webアプリケーションの起動動作のみを表していることに注意してください。 * JSPページは、初めて表示されると、サーバーの内部でサーブレットにコンパイルされ、コール・ツリーやメソッドのタイミングに影響を与えます。また、サーブレットや他のアプリケーション・コードの動作は、最初の実行時とアプリケーションが継続的に実行される実際の本番環境とで少し異なる可能性があります。実際のアプリケーション・パフォーマンスをより的確に表すプロファイリング・データを取得するには、時間を測定する前に、プロファイルされるコードに対してある程度のワークロードをかけるようにしてください(コール・ツリーがこの影響を受けないようにしてください)。これは、負荷ジェネレータを使用して簡単に行うことができます。(詳細は、link:../java/profile-loadgenerator.html[+NetBeans IDEでの負荷ジェネレータの使用+]を参照してください。)様々なブラウザのキャッシュ機能も、パフォーマンスに影響を与える可能性があります。 NOTE: Windowsマシン上のGlassFishアプリケーション・サーバーでWebアプリケーションをプロファイリングする場合、スペースが使用されているパス(デフォルトの ``C:\\Program Files\\netbeans-7.4`` へのインストールなど)にNetBeans IDEがインストールされていると、プロファイリング用サーバーの起動が失敗することがあります。これを回避するには、NetBeans IDEのインストール・ディレクトリをパスにスペースが含まれない場所( ``C:\\netbeans-7.4`` など)にインストールまたはコピーします。 === アプリケーションのサンプリング アプリケーション全体の動作の概要が必要であり、メソッドをインストゥルメントしない場合は、簡易オプションを選択してください。簡易プロファイル・モードでは、IDEが定期的にスタック・トレースを取得します。簡易プロファイル・モードのオーバーヘッドは、詳細プロファイル・モードより少なくなります。 この課題では、簡易プロファイル・モードを選択して、アプリケーションのパフォーマンスを解析します。 1. 「プロファイラ」ウィンドウの「停止」ボタンをクリックして、モニタリング・セッションを停止します。 2. メイン・メニューから「プロファイル」>「メイン・プロジェクトのプロファイル」を選択します。 3. 「プロファイリング・タスクの選択」ダイアログ・ボックスで「CPU」を選択します。 4. *「簡易(サンプリング)」*モードを選択します。 5. 「フィルタ」ドロップダウン・リストから「*プロジェクト・クラスだけをプロファイル*」を選択します。「実行」をクリックします。 NOTE: このフィルタは、インストゥルメント対象クラスをエンタープライズ・アプリケーション・プロジェクト内のクラスに限定します。フィルタされたクラスの一覧を表示するには、「*フィルタ値を表示*」をクリックします。 image::images/sample-task.png[title=""「プロファイリング・タスクの選択」ダイアログ・ボックスの「CPU」ペインで選択された「サンプル・アプリケーション」モード""] ダイアログ内の目盛りを見ると、オーバーヘッドが比較的小さいことがわかります。 . 「プロファイラ」ウィンドウの「プロファイリングのライブ結果」ボタンをクリックして、「プロファイリングのライブ結果」タブを開きます。 image::images/sample-task-results.png[title=""「サンプル・アプリケーション」モードの結果""] 「プロファイリングのライブ結果」タブで、 ``Servlet2Stateless`` クラス内のサーブレットの ``service`` メソッドの実行時間と、このメソッドが1回呼び出されたことを確認できます。 === すべてのメソッドのインストゥルメント 「アプリケーションをプロファイル」モードでは、アプリケーションのメソッドがインストゥルメントされます。アプリケーションのパフォーマンスをより正確に測定できますが、プロファイリングのオーバーヘッドはサンプル・モードを選択した場合より大きくなります。プロファイリング用ルート・メソッドを指定すると、インストゥルメントされるメソッドが制限され、プロファイリングのオーバーヘッドを削減できます。一部のアプリケーションでは、アプリケーション全体をプロファイリングすると、大量のプロファイリング・データが生成されてアプリケーションが使用できなくなるか、またはアプリケーションがクラッシュする原因になる可能性があるため、ルート・メソッドを指定することが、詳細な、または現実的なパフォーマンス・データを取得するための唯一の方法である場合があります。 この課題では、エンタープライズ・アプリケーション内のすべてのメソッドをインストゥルメントすることにより、アプリケーションのパフォーマンスを解析します。 1. 「プロファイラ」ウィンドウの「停止」ボタンをクリックして、モニタリング・セッションを停止します。 2. メイン・メニューから「プロファイル」>「メイン・プロジェクトのプロファイル」を選択します。 3. 「プロファイリング・タスクの選択」ダイアログ・ボックスで「CPU」を選択します。 4. *「詳細(インストゥルメント済)」*モードを選択します。 5. 「フィルタ」ドロップダウン・リストから「*プロジェクト・クラスだけをプロファイル*」を選択します。「実行」をクリックします。 image::images/advanced-cpu-task.png[title=""「プロファイリング・タスクの選択」ダイアログ・ボックスの「CPU」ペインで選択された「アプリケーションをプロファイル」モード""] ダイアログ内の目盛りを見ると、オーバーヘッドが「簡易(サンプリング)」プロファイル・モードより大きいことがわかります。 . 「プロファイラ」ウィンドウの「プロファイリングのライブ結果」ボタンをクリックして、「プロファイリングのライブ結果」タブを開きます。 「プロファイリングのライブ結果」タブに ``Servlet2Stateless`` クラス内のサーブレットの ``init`` および ``service`` メソッドの実行時間が表示され、各メソッドが1回ずつ呼び出されたことを確認できます。 ``StatelessSessionBean`` クラス内の ``init`` メソッドも呼び出されました。 image::images/cpu-pane1-results.png[title=""「アプリケーションをプロファイル」モードの結果""] NOTE: デフォルトでは、自動リフレッシュ・モードがアクティブになっているため、表示されるデータは数秒ごとに更新されます。自動リフレッシュ・モードは、ツールバーの「自動リフレッシュ」ボタンをクリックすることでアクティブ化および非アクティブ化できます。 収集されるデータの読みやすさを向上させるため、「プロファイリングのライブ結果」ウィンドウのホット・スポット・ビューで結果フィルタを使用して、表示される結果をフィルタできます。結果フィルタは、結果の表示をフィルタするのみであり、インストゥルメントされるクラスには影響しません。結果フィルタを使用すると、定義されたパターン「で始まる」、「を含む」または「で終わる」結果がフィルタされます。より複雑な正規表現をフィルタリングに使用することもできます。データは、最初の結果表の列に表示されたとおりのパッケージ/クラス/メソッド名に基づいてフィルタされます。複数のパターンをスペースまたはカンマとスペースで区切って指定できます。 . Webブラウザで、フィールドに自分の名前を入力して「問合せを送信」をクリックします。 image::images/cpu-pane1-results1.png[title=""「アプリケーションをプロファイル」モードの結果""] 「問合せを送信」をクリックすると、「プロファイリングのライブ結果」タブが更新され、Webブラウザでのアクションが反映されたことがわかります。ボタンのクリックにより、 ``StatelessSessionBean`` クラス内の ``sayHello`` メソッドが呼び出され、 ``init`` メソッドが再度呼び出されました。 ``Servlet2Stateless`` 内のサーブレットの ``service`` メソッドも再度呼び出されました。タブには、各メソッドに費やされた時間も表示されます。 「ドリルダウン」ボタンをクリックすると、サーブレットやリスナーなど、アプリケーションの様々な領域で費やされた相対的な時間のグラフィカル表現を表示できます。グラフィックをクリックして、表示されているプロファイリング結果にドリルダウンできます。 image::images/drill-down.png[title=""アプリケーション内のサーブレットで費やされた相対的な時間のドリルダウン・グラフ""] アプリケーションのインストゥルメントでは、アプリケーションをプロファイリングするときに常にある程度のオーバーヘッドが発生します。このような単純なアプリケーションではオーバーヘッドがあまり目立ちませんが、複雑なアプリケーションではオーバーヘッドがかなり大きくなる可能性があります。プロファイリング用ルート・メソッドを選択してプロファイルされるクラスを制限することで、オーバーヘッドを削減できます。 === プロファイリング用ルート・メソッドの使用 この課題では、アプリケーションの一部のみをプロファイルします。パフォーマンスのボトルネックがどこにあるかわかっていると思われる場合や、コードの特定の部分(たとえば、1つまたは少数のサーブレットのみ)をプロファイルする場合は、このプロファイリング方法を使用するようにしてください。この方法では通常、プロファイリングによって発生するオーバーヘッドが、すべてのアプリケーション・メソッドをインストゥルメントする場合に比べてかなり小さくなります。アプリケーションの一部のみをインストゥルメントすることで、本当に必要なデータのみが収集され、表示されます。 アプリケーションの一部をプロファイルするには、1つまたは複数のプロファイリング用ルート・メソッドを設定する必要があります。IDEは、プロファイリング用ルート・メソッドに入っているスレッドによってコールされたメソッドのみをインストゥルメントします。たとえば、 ``StatelessSessionBean`` クラスの ``sayHello`` メソッドをルート・メソッドとして設定し、「プロジェクト・クラスだけをプロファイル」フィルタを使用すると、このメソッドが呼び出され、アプリケーション・スレッドがこのメソッドに入ったときにIDEがメソッドのインストゥルメントを開始します。このアプリケーションでは、 ``init`` コンストラクタは ``sayHello`` の前に呼び出されるため、インストゥルメントされません。 image::images/profileroot-sayhello-project.png[title=""アプリケーション内のサーブレットで費やされた相対的な時間のドリルダウン・グラフ""] 「すべてのクラスをプロファイル」フィルタを選択すると、IDEは ``sayHello`` によってコールされたJavaコア・クラスを含むすべてのメソッドをインストゥルメントします。 image::images/profileroot-sayhello-all.png[title=""アプリケーション内のサーブレットで費やされた相対的な時間のドリルダウン・グラフ""] NOTE: より複雑なアプリケーションでは、複数のルート・メソッドを指定することもできます。個々のメソッド、クラス全体およびパッケージをプロファイリング・ルートとして選択できます。 プロファイリング・ルートを指定してアプリケーションのパフォーマンスを解析するには、次の手順を実行します。 1. 「プロファイラ」ウィンドウの「停止」ボタンをクリックして、以前のプロファイリング・セッションを停止します(まだ実行されている場合)。 2. メイン・メニューから「プロファイル」>「メイン・プロジェクトのプロファイル」を選択します。 3. 「プロファイリング・タスクの選択」ダイアログ・ボックスで「CPU」を選択します。 4. *「詳細(インストゥルメント済)」*モードを選択します。 5. 「*カスタマイズ*」をクリックして「プロファイリング・ルートの編集」ダイアログ・ボックスを開きます。 アプリケーションの一部をプロファイルするには、最初にルート・メソッドを指定する必要があります。プロファイリング・ルートを選択することで、プロファイリングをプロファイリング・ルートに入っているスレッドによってコールされたメソッドに制限します。 . 「プロファイリング・ルートの編集」ダイアログ・ボックスの「ビューを選択」ドロップダウン・リストで、「Webアプリケーション・ビュー」を選択します。 . ServletStatelessノードを展開して、「サーブレット」パッケージ内の ``service`` メソッドを選択します。「OK」をクリックします。 image::images/edit-profiling-roots.png[title=""「プロファイリング・ルートの編集」ダイアログの「Webアプリケーション・ビュー」""] または、「パッケージ表示」を選択してアプリケーション内のすべてのソース・パッケージを表示し、 ``servlet.stateless`` パッケージに含まれる ``Servlet2Stateless`` クラスの ``service`` メソッドを選択することもできます。 image::images/edit-profiling-roots-pkg.png[title=""「プロファイリング・ルートの編集」ダイアログの「パッケージ表示」""] NOTE: ``Servlet2Stateless`` コンストラクタが選択されていないことに注意してください。「プロファイリング・ルートの編集」ダイアログを使用して、インストゥルメントをクラス内の特定のメソッドに制限できます。インストゥルメントを特定のメソッドに制限しない場合は、「パッケージ表示」を使用してクラスまたはパッケージ全体を選択できます。たとえば、「プロファイリング・ルートの編集」ダイアログ・ボックスの「パッケージ表示」で ``Servlet2Stateless`` クラスを選択すると、IDEは ``init`` コンストラクタと ``service`` メソッドをインストゥルメントします。 「詳細」ボタンをクリックすると、「プロファイリング・ルートの編集(詳細)」ダイアログ・ボックスに ``service`` メソッドが唯一のルート・メソッドとして表示されることがわかります。「追加」をクリックし、メソッドの署名とクラスを入力することでメソッドを明示的に定義できます。 image::images/edit-profilingroots-pkg-adv.png[title=""「プロファイリング・ルートの編集(詳細)」ダイアログ""] . 「プロファイリング・ルートの編集」ダイアログ・ボックスで「OK」をクリックします。 「プロファイリング・タスクの選択」ダイアログ・ボックスで、詳細プロファイリング・モードがカスタム・プロファイリング・ルートを使用して実行されることを確認できます。「*編集*」をクリックすると、選択したルート・メソッドを表示および変更できます。これで、ルート・メソッドを指定しなかった場合に比べてプロファイリングのオーバーヘッドが小さくなりました。 . 「フィルタ」ドロップダウン・リストから「*プロジェクト・クラスだけをプロファイル*」を選択します。「実行」をクリックします。 image::images/advanced-cpu-task-custom.png[title=""カスタム・プロファイリング・ルート付きで選択された「アプリケーションをプロファイル」モード""] 「実行」をクリックすると、IDEによってアプリケーションがビルドおよびデプロイされ、Webブラウザが開いてサーブレットのページが表示されます。 IDEの「プロファイリングのライブ結果」タブにプロファイリング結果が表示されます。 image::images/cpu-pane2-results.png[title=""プロファイリング・ルートを使用してメソッドをインストゥルメントした結果""] プロファイリング・ルートとして指定したメソッドの結果のみがIDEに表示されることがわかります。アプリケーション・スレッドは、プロファイリング・ルートに入った後、アプリケーション内の他のメソッドに入っていません。 アプリケーションはプロファイリング・ルートに入った後で他のメソッドに入っていますが、インストゥルメント・フィルタによってインストゥルメントがプロジェクトの一部のクラスに制限されているため、これらの他のメソッドは表示されません。 . Webブラウザで、フィールドに自分の名前を入力して「問合せを送信」をクリックします。 image::images/cpu-pane2-results1.png[title=""sayHelloメソッドの呼出し後にプロファイリング・ルートを使用してメソッドをインストゥルメントした結果""] 「問合せを送信」をクリックすると、「プロファイリングのライブ結果」タブが更新され、Webブラウザでのアクションが反映されたことがわかります。ボタンのクリックにより、 ``StatelessSessionBean`` クラス内の ``sayHello`` メソッドが1回呼び出されました。 ``service`` メソッドも再度呼び出されました。 結果には、アプリケーションのパフォーマンスが表示されますが、長期間実行されているアプリケーションのパフォーマンスが正確に表されていない可能性があります。より現実的な条件下でWebアプリケーションのパフォーマンスをエミュレートする1つの方法は、負荷ジェネレータ・スクリプトを実行することです。 . ブラウザで前のステップを数回繰り返してから、「プロファイリングのライブ結果」タブの「結果のリセット」をクリックして結果をクリアします。 . プロファイリング結果がリセットされたら、もう一度自分の名前を入力して「問合せを送信」をクリックします。 image::images/cpu-pane2-results2.png[title=""sayHelloメソッドの呼出し後にプロファイリング・ルートを使用してメソッドをインストゥルメントした結果""] プロファイリング結果を見ると、ほとんどの場合、パフォーマンスが向上していることがわかります。 === インストゥルメント・フィルタの使用 CPUパフォーマンスを解析するときは、ドロップダウン・リストからインストゥルメント・フィルタを選択し、プロファイリングを必要なソース・コードに制限することで、プロファイリングのオーバーヘッドを削減できます。フィルタを使用して、インストゥルメントされるパッケージまたはクラスを指定できます。次のデフォルト・フィルタから選択するか、カスタム・フィルタを作成できます。 * *すべてのクラスをプロファイル。*Webアプリケーションまたはエンタープライズ・アプリケーションをプロファイリングするときにこのフィルタを選択すると、コアJavaクラスやサーバー・クラスを含むすべてのクラスがインストゥルメントされます。これほど多くのクラスをインストゥルメントすると、*非常に*大きなオーバーヘッドが発生する可能性があるため、このフィルタを選択する場合は注意が必要です。 * *プロジェクト・クラスだけをプロファイリング*。エンタープライズ・アプリケーションをプロファイリングする場合は、このフィルタを使用して、インストゥルメントされるコードをプロジェクト内のクラスに制限することをお薦めします。サーバー・クラスはインストゥルメントされません。 * *プロジェクトとサブプロジェクトのクラスをプロファイル。*Webアプリケーション、EJBモジュール、クラス・ライブラリなどのサブプロジェクトを含むエンタープライズ・アプリケーション・プロジェクトをプロファイリングする場合は、このフィルタを選択して、インストゥルメント対象コードをサブプロジェクト内のクラスに制限できます。 カスタム・フィルタを作成して、特定のプロジェクトや特定タイプのプロファイリングで使用できます。たとえば、Oracle WebLogic Server上のWebアプリケーションをプロファイリングするときに使用するインストゥルメント・フィルタが必要な場合は、「フィルタ・セットを編集」をクリックして、Javaコア・クラス、Oracle WebLogicクラスおよびNetBeansクラスを除外するフィルタ・セットを作成できます(HTTPモニターが有効になっている場合に便利です)。フィルタ・セットに「WebLogic Webapp Exclusive」などの名前を設定しておき、WebLogicサーバーにデプロイされたアプリケーションをプロファイリングするときに、「フィルタ」ドロップダウン・リストからそのフィルタを選択できます。 image::images/custom-filter.png[title=""プロジェクトを初めてプロファイリングする場合に表示されるダイアログ・ボックス""] 「フィルタ」ドロップダウン・リストから「簡易フィルタ」を選択し、「簡易フィルタの設定」ダイアログ・ボックスを開くことで、簡易なインストゥルメント・フィルタを定義できます。インストゥルメントされるパッケージまたはクラスの一覧をすばやく編集できます。これにより、「フィルタ」ドロップダウン・リストから選択できる簡易フィルタが作成されます。 image::images/set-quick-filter.png[title=""プロジェクトを初めてプロファイリングする場合に表示されるダイアログ・ボックス""] インストゥルメント・フィルタの定義と使用の詳細は、IDEのプロファイリングに関するドキュメントを参照してください。 == アプリケーションのメモリー使用状況の解析 IDEのプロファイリング・ツールを使用して、エンタープライズ・アプリケーションのメモリー使用状況を解析し、オブジェクト割当てやガベージ・コレクションに関する詳細なデータを取得できます。「メモリー使用状況を解析」タスクによって、ターゲット・アプリケーション内で割り当てられているオブジェクトに関するデータ(割り当てられたオブジェクトの数、型、場所など)が提供されます。 メモリー使用状況をプロファイリングするときは、プロファイリング用ルート・メソッドやインストゥルメント・フィルタを設定できないため、サーバーの実行中に作成されたすべてのオブジェクトがトラックされます。このため、複雑なアプリケーション・サーバーでは、プロファイリングのオーバーヘッドやメモリーの消費量が大きくなる可能性があります。したがって、このタイプのプロファイリングを実行する前に、マシンの潜在的な制限事項について知っておくようにしてください。プロファイリングのオーバーヘッドを軽減するため、10個に1個の割合でのみオブジェクトをプロファイルするように設定を変更できます。オブジェクト割当てのスタック・トレースの記録を無効化(制限)することもできます。 メモリー・リークを検出するためにエンタープライズ・アプリケーションをプロファイリングするときは、「生存中世代」のメトリックを使用すると非常に便利なことがあります。このツールは、ガベージ・コレクションのサイクルを経て生存する様々なオブジェクト世代の数をトラックすることにより、アプリケーションのメモリー使用量が著しく大きくなる前にメモリー・リークを検出できます。 メモリー・パフォーマンスを解析するには、次のオプションのいずれかを選択することによって、取得するデータの量を選択します。 * *簡易。*このオプションが選択されている場合、プロファイラはアプリケーションをサンプリングして、ライブ・オブジェクトに限定されたデータを提供します。ライブ・オブジェクトとは、ガベージ・コレクタによって回収されていないアクセス可能(およびアクセス不能)なすべてのオブジェクトです。このオプションは、ライブ・オブジェクトのみ追跡し、計測時に割当てを追跡しません。このオプションを選択した場合は、スタック・トレースを記録したり、プロファイリング・ポイントを使用したりすることはできません。このオプションを選択すると、「詳細」オプションよりもオーバーヘッドが大幅に削減されます。 * *詳細。*このオプションを選択すると、割り当てられたオブジェクトの数、タイプおよび場所に関する情報を取得できます。割り当てられたオブジェクトとは、アプリケーションを起動してから(またはプロファイラでの収集結果が最後にリセットされてから)これまでに作成されたオブジェクトです。ターゲットJVMによって現在ロードされているすべてのクラス(および新規にロードされる各クラス)が計測され、オブジェクト割当てに関する情報が生成されます。メモリ使用状況の分析時にプロファイリング・ポイントを使用する場合、またはコール・スタックを記録する場合は、このオプションを選択する必要があります。このオプションを選択すると、簡易オプションよりもプロファイリング・オーバーヘッドが増加します。 「詳細」オプションを選択した場合は、次のオプションも設定できます。 * *完全なオブジェクト・ライフスタイルを記録。*存続している世代数など、各オブジェクトのすべての情報を記録するには、このオプションを選択します。 * *割当てのスタック・トレースを記録。*完全なコール・スタックを記録するには、このオプションを選択します。このオプションでは、メモリー・スナップショットを表示する際にメソッド呼出しの逆呼出しツリーを表示できます。 * *定義済みプロファイリング・ポイントを使用。*プロファイリング・ポイントを有効にするには、このオプションを選択します。無効なプロファイリング・ポイントは無視されます。選択解除されている場合は、プロジェクト内のすべてのプロファイリング・ポイントが無視されます。 「プロファイリング・タスクの選択」ウィンドウの「オーバーヘッド」メーターは、ユーザーが選択したプロファイリング・オプションに応じて、プロファイリングのオーバーヘッドの大まかな増減を示します。 ここで、IDEを使用してエンタープライズ・アプリケーションのメモリー・パフォーマンスを解析します。存続している世代に関する情報を取得する場合は、*「詳細」*オプションを選択する必要があります。または、ライブ・オブジェクトに関するデータが必要な場合は、*簡易*オプションを選択できます。 1. 「プロファイラ」ウィンドウの「停止」ボタンをクリックして、以前のプロファイリング・セッションを停止します(まだ実行されている場合)。 「停止」をクリックすると、IDEがアプリケーションからデタッチされます。 . メイン・メニューから「プロファイル」>「メイン・プロジェクトのプロファイル」を選択します。 . 「プロファイリング・タスクの選択」ダイアログ・ボックスで「*メモリー*」を選択します。 . *「詳細」*を選択します。 . *「完全なオブジェクト・ライフサイクルを記録」*を選択して、存続している世代に関するデータを取得します。 NOTE: このオプションを選択すると、「オーバーヘッド」メーターが大幅に増加します。エンタープライズ・アプリケーションをプロファイリングするときは、収集されるデータ量のため、ほとんどの場合、IDE用のメモリーを増やす必要がありあります。 . 「*定義済みプロファイリング・ポイントを使用*」を選択解除します(選択されている場合)。「実行」をクリックします。 image::images/profile-memory-advanced.png[title=""「メモリー」タスクとオプションが表示された「プロファイリング・タスクの選択」ダイアログ""] 「実行」をクリックすると、IDEによってアプリケーションがコンパイルされ、プロファイル・モードでサーバーが起動され、サーバーにアプリケーションがデプロイされます。プロファイリング結果を表示するには、「プロファイラ」ウィンドウ内の「ライブ結果」をクリックして「ライブ結果」ウィンドウを開きます。「ライブ結果」ウィンドウに、ターゲットJVMに割り当てられたオブジェクトのサイズと数に関する情報が表示されます。結果には、エンタープライズ・アプリケーションによって割り当てられたオブジェクトに加えて、アプリケーション・サーバーによって割り当てられたオブジェクトもすべて含まれています。 image::images/profile-memory-results.png[title=""メモリー使用状況のプロファイリングの結果が表示された「プロファイリング結果」タブ""] デフォルトでは、結果は「ライブ・バイト数」の数でソートされて表示されますが、列ヘッダーをクリックすると結果の表示方法を変更できます。また、リストの下にあるフィルタ・ボックスにクラス名を入力して結果をフィルタすることもできます。 link:/about/contact_form.html?to=3&subject=Feedback:%20Profiling%20Enterprise%20Applications[+このチュートリアルに関するご意見をお寄せください+] == 関連項目 このドキュメントでは、GlassFishアプリケーション・サーバーにデプロイされたエンタープライズ・アプリケーションをプロファイリングするときにプロファイリング・データを取得する基本的な方法について説明しました。 このドキュメントで説明されていないプロファイリング設定および機能の詳細は、製品に含まれ、「ヘルプ」メニュー項目から使用できるドキュメントを参照してください。 関連ドキュメントについては、次のリソースを参照してください。 * link:http://wiki.netbeans.org/wiki/view/NetBeansUserFAQ#section-NetBeansUserFAQ-Profiler[+NetBeansプロファイラのFAQ+] NetBeans IDEでのアプリケーションのプロファイリングに関連した、よくある質問を含むドキュメント * link:http://wiki.netbeans.org/wiki/view/FaqProfilerProfileFreeForm[+FAQ: 自由形式プロジェクトのプロファイリング+] * link:../java/profiler-screencast.html[+スクリーンキャスト: プロファイリング・ポイント、ドリルダウン・グラフ、ヒープ・ウォーカ+] NetBeans IDEのいくつかのプロファイリング機能を示すデモ。 * link:../../../community/magazine/html/04/profiler.html[+詳細なプロファイリング: 実行理論+] * link:http://profiler.netbeans.org/index.html[+profiler.netbeans.org+] NetBeansプロファイラ・プロジェクトのサイト * link:http://blogs.oracle.com/nbprofiler/[+NetBeansプロファイラのブログ+] * link:http://profiler.netbeans.org/mailinglists.html[+NetBeansプロファイラのメーリング・リスト+] * link:http://profiler.netbeans.org/docs/help/5.5/index.html[+NetBeansプロファイラ5.5の使用+] <> ",12233,True,2638.460293675305,median "[[flowableApps]] == Flowable applications Flowable provides several ui web applications to demonstrate and leverage the functionality provided by the Flowable project: * Flowable IDM: an Identity Management application that provides single sign-on authentication functionality for all the Flowable UI applications, and, for users with the IDM administrative privilege, it also provides functionality to manage users, groups and privileges. * Flowable Modeler: an application that allows users with modeler privileges to model processes, forms, decision tables and application definitions. * Flowable Task: a runtime task application that provides functionality to start process instances, edit task forms, complete tasks and query on tasks and process instances. * Flowable Admin: an administrative application that allows users with admin privilege to query the BPMN, DMN, form and content engines and provides several options to change process instances, tasks, jobs and so on. The admin application connects to the engines through the REST API that is deployed together with the Flowable Task app and the Flowable REST app. The Flowable IDM is required for all other apps to enable authentication. The WAR files for each app can be deployed to the same servlet container (such as Apache Tomcat), but can also be deployed on different servlet containers. Because the same cookie is used for authentication with each app, the apps need to run on the same domain. Flowable also provides the `flowable-rest.war` which contains the Flowable REST API. More about this can be read in the <> chapter. The apps are Spring Boot 2.0 based, which means that that the WAR files are actually executable and can be run as a normal standalone applications. See https://docs.spring.io/spring-boot/docs/current/reference/html/build-tool-plugins-maven-plugin.html#build-tool-plugins-maven-packaging[The Executable Jar Format] in the Spring Boot reference documentation. [[uiAppInstallation]] === Flowable UI Applications installation As mentioned before, all four UI apps can be deployed together on the same Tomcat server, and to get started this is probably the easiest approach. You can choose to only install the Modeler app, for example, but make sure the Flowable IDM app is always running/deployed as well. For this installation guide we'll describe the installation of all four apps to a Tomcat server. 1. Download a recent stable version of link:$$http://tomcat.apache.org$$[Apache Tomcat]. 2. Download the latest stable link:$$http://www.flowable.org/downloads.html$$[Flowable 6 version]. 3. Copy the flowable-admin.war, flowable-idm.war, flowable-modeler.war and flowable-task.war files from the Flowable distribution __wars__ folder to the Tomcat webapps folder. 4. Startup the Tomcat server by running the bin/startup.sh (Mac OS and Linux) or bin/startup.bat (Windows) script. 5. Open a web browser and go to link:$$http://localhost:8080/flowable-modeler$$[http://localhost:8080/flowable-modeler]. All Flowable UI apps should now be running with an H2 in-memory database and the following login screen should be shown in your web browser: image::images/flowable_idm_login_screen.png[align=""center""] By default, the Flowable IDM application will create an admin user that has privileges to all the Flowable UI apps. You can login with admin/test and the browser should redirect to the Flowable Modeler application: image::images/flowable_modeler_startup_screen.png[align=""center""] Since the UI apps are Spring Boot executable apps it is possible to run them as standalone applications without the need of an application server. Starting single application looks like: ``` java -jar flowable-idm.war ``` Usually, you will want to change the default H2 in-memory database configuration to a MySQL or Postgres (or other persistent database) configuration. You can do this per app by changing the application.properties file in the _WEB-INF/classes/_ directory of each app. However, it is easier to use the Spring Boot https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html[Externalized Configuration]. An example configuration can be found on link:$$https://github.com/flowable/flowable-engine/blob/master/modules/flowable-ui-task/flowable-ui-task-app/src/main/resources/flowable-default.properties$$[Github] To change the default configuration to MySQL the following changes are needed to the properties file: [source,linenums] ---- spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://127.0.0.1:3306/flowable?characterEncoding=UTF-8 spring.datasource.username=flowable spring.datasource.password=flowable ---- This configuration will expect a flowable database to be present in the MySQL server and the UI apps will automatically generate the necessary database tables. For Postgres the following changes are necessary: [source,linenums] ---- spring.datasource.driver-class-name=org.postgresql.Driver spring.datasource.url=jdbc:postgresql://localhost:5432/flowable spring.datasource.username=flowable spring.datasource.password=flowable ---- In addition to changing the configuration, make sure the database driver is available on the classpath. Again, you could do this for every web application separately by adding the driver JAR file to the WEB-INF/lib folder, but you can also copy the JAR file once to the Tomcat lib folder. For MySQL and Postgres the database drivers can be downloaded from: * MySQL: link:$$https://dev.mysql.com/downloads/connector/j$$[https://dev.mysql.com/downloads/connector/j] * Postgres: link:$$https://jdbc.postgresql.org/$$[https://jdbc.postgresql.org/] When running the apps as standalone applications the database driver can be added by using the `loader.path` property. ``` java -Dloader.path=/location/to/your/driverfolder -jar flowable-idm.war ``` See the https://docs.spring.io/spring-boot/docs/current/reference/html/executable-jar.html#executable-jar-property-launcher-features[`PropertiesLauncher` Features] in the Spring Boot reference documentation for more information. === Flowable UI Applications Configurations As the Flowable UI apps are Spring Boot applications you can use all the properties Spring Boot provides. In order to provide custom configuration for the apps have a look at the https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html[Externalized Configuration] section of the Spring Boot documentation. [TIP] ----- You can also use YAML based properties. ----- .Common UI App Properties [cols=""4*"",options=""header""] |=============== |Property name |Old Property |Default value |Description |flowable.common.app.idm-url |idm.app.url |- |The URL to the IDM application, used for the user info and token info REST GET calls. It's also used as a fallback for the redirect url to the login page in the UI apps. |flowable.common.app.idm-redirect-url |idm.app.redirect.url |- |The redirect URL to the IDM application, used for the login redirect when the cookie isn't set or is invalid. |flowable.common.app.redirect-on-auth-success |app.redirect.url.on.authsuccess |- |The URL to which the redirect should occur after a successful authentication. |flowable.common.app.role-prefix |- |ROLE_ |The default role prefix that needs to be used by Spring Security. |flowable.common.app.tenant-id |- |- |The static tenant id used for the DefaultTenantProvider. The modeler app uses this to determine under which tenant id to store and publish models. When not provided, empty or only contains whitespace it defaults to the user's tenant id if available otherwise it uses no tenant id. |flowable.common.app.cache-login-tokens.max-age |cache.login-tokens.max.age |30 |The max age in seconds after which the entry should be invalidated. |flowable.common.app.cache-login-tokens.max-size |cache.login-tokens.max.size |2048 |The maximum number of entries that the cache should contain. |flowable.common.app.cache-login-users.max-age |cache.login-users.max.age |30 |The max age in seconds after which the entry should be invalidated. |flowable.common.app.cache-login-users.max-size |cache.login-users.max.size |2048 |The maximum number of entries that the cache should contain. |flowable.common.app.cache-users.max-age |cache.users.max.age |30 |The max age in seconds after which the entry should be invalidated. |flowable.common.app.cache-users.max-size |cache.users.max.size |2048 |The maximum number of entries that the cache should contain. |flowable.common.app.idm-admin.password |idm.admin.password |- |The password used for executing the REST calls (with basic auth) to the IDM REST services. Default is test. |flowable.common.app.idm-admin.user |idm.admin.user |admin |The username used for executing the REST calls (with basic auth) to the IDM REST services. Default is admin |flowable.rest.app.authentication-mode |rest.authentication.mode |verify-privilege |Configures the way user credentials are verified when doing a REST API call: 'any-user' : the user needs to exist and the password need to match. Any user is allowed to do the call (this is the pre 6.3.0 behavior) 'verify-privilege' : the user needs to exist, the password needs to match and the user needs to have the 'rest-api' privilege If nothing set, defaults to 'verify-privilege' |=============== Some of the old properties have been moved to be managed by the Flowable Spring Boot starter (or Spring Boot itself) .Old properties managed by the Flowable Spring Boot Starter [cols=""4*"",options=""header""] |=============== |Property name |Old Property |Default value |Description |flowable.async-executor-activate |engine.process.asyncexecutor.activate |true |Whether the async executor should be activated. |flowable.database-schema-update |engine.process.schema.update |true |The strategy that should be used for the database schema. |flowable.history-level |engine.process.history.level |- |The history level that needs to be used. |flowable.process.servlet.name |flowable.rest-api-servlet-name |Flowable BPMN Rest API |The name of the Process servlet. |flowable.process.servlet.path |flowable.rest-api-mapping |/process-api |The context path for the Process rest servlet. |flowable.content.storage.create-root |contentstorage.fs.create-root |true |If the root folder doesn't exist, should it be created? |flowable.content.storage.root-folder |contentstorage.fs.root-folder |- |Root folder location where content files will be stored, for example, task attachments or form file uploads. |flowable.idm.enabled |flowable.db-identity-used |true |Whether the idm engine needs to be started. |flowable.idm.password-encoder |security.passwordencoder |- |The type of the password encoder that needs to be used. |flowable.idm.ldap.base-dn |ldap.basedn |- |The base 'distinguished name' (DN) from which the searches for users and groups are started. Use 'user-base-dn' or 'group-base-dn' when needing to differentiate between user and group base DN. |flowable.idm.ldap.enabled |ldap.enabled |false |Whether to enable LDAP IDM Service. |flowable.idm.ldap.password |ldap.password |- |The password that is used to connect to the LDAP system. |flowable.idm.ldap.port |ldap.port |-1 |The port on which the LDAP system is running. |flowable.idm.ldap.server |ldap.server |- |The server host on which the LDAP system can be reached. For example 'ldap://localhost'. |flowable.idm.ldap.user |ldap.user |- |The user id that is used to connect to the LDAP system. |flowable.idm.ldap.attribute.email |ldap.attribute.email |- |Name of the attribute that matches the user email. This property is used when looking for an 'org.flowable.idm.api.User' object and the mapping between the LDAP object and the Flowable 'org.flowable.idm.api.User' object is done. |flowable.idm.ldap.attribute.first-name |ldap.attribute.firstname |- |Name of the attribute that matches the user first name. This property is used when looking for a 'org.flowable.idm.api.User' object and the mapping between the LDAP object and the Flowable 'org.flowable.idm.api.User' object is done. |flowable.idm.ldap.attribute.group-id |ldap.attribute.groupid |- |Name of the attribute that matches the group id. This property is used when looking for a 'org.flowable.idm.api.Group' object and the mapping between the LDAP object and the Flowable 'org.flowable.idm.api.Group' object is done. |flowable.idm.ldap.attribute.group-name |ldap.attribute.groupname |- |Name of the attribute that matches the group name. This property is used when looking for a 'org.flowable.idm.api.Group' object and the mapping between the LDAP object and the Flowable 'org.flowable.idm.api.Group' object is done. |flowable.idm.ldap.attribute.last-name |ldap.attribute.lastname |- |Name of the attribute that matches the user last name. This property is used when looking for a 'org.flowable.idm.api.User' object and the mapping between the LDAP object and the Flowable 'org.flowable.idm.api.User' object is done. |flowable.idm.ldap.attribute.user-id |ldap.attribute.userid |- |Name of the attribute that matches the user id. This property is used when looking for a 'org.flowable.idm.api.User' object and the mapping between the LDAP object and the Flowable 'org.flowable.idm.api.User' object is done. This property is optional and is only needed if searching for 'org.flowable.idm.api.User' objects using the Flowable API. |flowable.idm.ldap.cache.group-size |ldap.cache.groupsize |-1 |Allows to set the size of the 'org.flowable.ldap.LDAPGroupCache'. This is an LRU cache that caches groups for users and thus avoids hitting the LDAP system each time the groups of a user needs to be known. The cache will not be instantiated if the value is less then zero. By default set to -1, so no caching is done. Note that the group cache is instantiated on the 'org.flowable.ldap.LDAPIdentityServiceImpl'. As such, if you have a custom implementation of the 'org.flowable.ldap.LDAPIdentityServiceImpl', do not forget to add the group cache functionality. |flowable.idm.ldap.query.all-groups |ldap.query.groupall |- |The query that is executed when searching for all groups. |flowable.idm.ldap.query.all-users |ldap.query.userall |- |The query that is executed when searching for all users. |flowable.idm.ldap.query.groups-for-user |ldap.query.groupsforuser |- |The query that is executed when searching for the groups of a specific user. For example: `(&(objectClass=groupOfUniqueNames)(uniqueMember={0}))` Here, all the objects in LDAP with the class 'groupOfUniqueNames' and where the provided DN is a 'uniqueMember' are returned. As shown in the example, the user id is injected by the typical {@link java.text.MessageFormat}, ie by using _{0}_ If setting the query alone is insufficient for your specific LDAP setup, you can alternatively plug in a different `org.flowable.ldap.LDAPQueryBuilder`, which allows for more customization than only the query. |flowable.idm.ldap.query.user-by-full-name-like |ldap.query.userbyname |- |The query that is executed when searching for a user by full name. For example: `(&(objectClass=inetOrgPerson)(\\|({0}=**{1}**)({2}={3})))` Here, all the objects in LDAP with the class 'inetOrgPerson' and who have the matching first name or last name will be returned Several things will be injected in the expression: {0} : the first name attribute {1} : the search text {2} : the last name attribute {3} : the search text If setting the query alone is insufficient for your specific LDAP setup, you can alternatively plug in a different 'org.flowable.ldap.LDAPQueryBuilder', which allows for more customization than only the query. |flowable.idm.ldap.query.user-by-id |ldap.query.userbyid |- |The query that is executed when searching for a user by userId. For example: `(&(objectClass=inetOrgPerson)(uid={0}))` Here, all the objects in LDAP with the class 'inetOrgPerson' and who have the matching 'uid' attribute value will be returned. As shown in the example, the user id is injected by the typical {@link java.text.MessageFormat}, ie by using _{0}_ If setting the query alone is insufficient for your specific LDAP setup, you can alternatively plug in a different 'org.flowable.ldap.LDAPQueryBuilder', which allows for more customization than only the query. |flowable.mail.server.host |email.host |localhost |The host of the mail server. |flowable.mail.server.password |email.password |- |The password for the mail server authentication. |flowable.mail.server.port |email.port |1025 |The port of the mail server. |flowable.mail.server.use-ssl |email.use-ssl |false |Sets whether SSL/TLS encryption should be enabled for the SMTP transport upon connection (SMTPS/POPS). |flowable.mail.server.use-tls |email.use-tls |false |Set or disable the STARTTLS encryption. |flowable.mail.server.username |email.username |- |The username that needs to be used for the mail server authentication. If empty no authentication would be used. |flowable.process.definition-cache-limit |flowable.process-definitions.cache.max |-1 |The maximum amount of process definitions available in the process definition cache. Per default it is -1 (all process definitions). |=============== .Old properties managed by Spring Boot [cols=""4*"",options=""header""] |=============== |Property name |Old Property |Default value |Description |spring.datasource.driver-class-name |datasource.driver |- |Fully qualified name of the JDBC driver. Auto-detected based on the URL by default. |spring.datasource.jndi-name |datasource.jndi.name |- |JNDI location of the datasource. Class, url, username & password are ignored when set. |spring.datasource.password |datasource.password |- |Login password of the database. |spring.datasource.url |datasource.url |- |JDBC URL of the database. |spring.datasource.username |datasource.username |- |Login username of the database. |spring.datasource.hikari.connection-test-query |datasource.preferred-test-query |- |The SQL query to be executed to test the validity of connections. |spring.datasource.hikari.connection-timeout |datasource.connection.timeout |- |The maximum number of milliseconds that a client will wait for a connection from the pool. If this time is exceeded without a connection becoming available, a SQLException will be thrown when getting a connection. |spring.datasource.hikari.idle-timeout |datasource.connection.idletimeout |- |The maximum amount of time (in milliseconds) that a connection is allowed to sit idle in the pool. Whether a connection is retired as idle or not is subject to a maximum variation of +30 seconds, and average variation of +15 seconds. A connection will never be retired as idle before this timeout. A value of 0 means that idle connections are never removed from the pool. |spring.datasource.hikari.max-lifetime |datasource.connection.maxlifetime |- |This property controls the maximum lifetime of a connection in the pool. When a connection reaches this timeout, even if recently used, it will be retired from the pool. An in-use connection will never be retired, only when it is idle will it be removed. |spring.datasource.hikari.maximum-pool-size |datasource.connection.maxpoolsize |- |The property controls the maximum size that the pool is allowed to reach, including both idle and in-use connections. Basically this value will determine the maximum number of actual connections to the database backend. When the pool reaches this size, and no idle connections are available, calls to getConnection() will block for up to connectionTimeout milliseconds before timing out. |spring.datasource.hikari.minimum-idle |datasource.connection.minidle |- |The property controls the minimum number of idle connections that HikariCP tries to maintain in the pool, including both idle and in-use connections. If the idle connections dip below this value, HikariCP will make a best effort to restore them quickly and efficiently. |spring.servlet.multipart.max-file-size |file.upload.max.size |10MB |Max file size. Values can use the suffixes ""MB"" or ""KB"" to indicate megabytes or kilobytes, respectively. |=============== .Not used old properties [cols=""2*"",options=""header""] |=============== |Old property |Description |datasource.jndi.resource-ref |Spring Boot does not support configuring JNDI resourceRef. Use entire resource reference in the name. |email.use-credentials |In case you don't want to use credentials, set the password and user to empty. |=============== [[flowableIDMApp]] === Flowable IDM application The Flowable IDM application is used by all other three Flowable web applications for authentication and authorization and is therefore required to be available when you want to run the Modeler, Task or Admin application. The Flowable IDM application is a simple identity management application and is targeted at providing single sign-on capabilities to the Flowable web applications, including providing a central place to define users, groups and privileges. The IDM application boots the IDM engine at startup and will create the identity tables as defined in the IDM engine in the datasource defined in the properties configuration. When the Flowable IDM application is deployed and started, it will check if there's a user available in the ACT_ID_USER table, and if not it will use the `flowable.common.app.idm-admin.user` property to create a new default admin user in this table. It will also add all available privileges in the Flowable project to the newly created admin user: * access-idm: provides the privilege to manage users, groups and privileges * access-admin: allows the user to login to the Flowable Admin application, manage the Flowable engines and access the Actuator endpoints of all the applications * access-modeler: enables access to the Flowable Modeler application * access-task: provides the privilege to login to the Flowable Task application * access-rest-api: allows the user to do call the REST API. Otherwise a 403 (forbidden) http status will be returned. Note that _flowable.rest.app.authentication-mode_ nees to be set to _verify-privilege_, which is the default. When logging in to link:$$http://localhost:8080/flowable-idm$$[http://localhost:8080/flowable-idm] with admin/test for the first time the following user overview screen is shown: image::images/flowable_idm_startup_screen.png[align=""center""] In this screen users can be added, removed and updated. The groups section can be used to create, delete and update groups. In the group details view you can also add and remove users to and from the group. The privilege screen allows you to add and remove privileges from users and groups: image::images/flowable_idm_privilege_screen.png[align=""center""] There's no option to define new privileges yet, but you can add and remove users and groups for the existing four privileges. This are the IDM UI App specific properties. .IDM UI App Properties [cols=""4*"",options=""header""] |=============== |Property name |Old Property |Default value |Description |flowable.idm.app.bootstrap |idm.bootstrap.enabled |true |Whether the IDM App needs to be bootstrapped. |flowable.idm.app.rest-enabled |rest.idm-app.enabled |true |Enables the REST API (this is not the REST api used by the UI, but an api that's available over basic auth authentication). |flowable.idm.app.admin.email |admin.email |- |The email of the admin user. |flowable.idm.app.admin.first-name |admin.firstname |- |The first name of the admin user. |flowable.idm.app.admin.last-name |admin.lastname |- |The last name of the admin user. |flowable.idm.app.admin.password |admin.password |- |The password for the admin user. |flowable.idm.app.admin.user-id |admin.userid |- |The id of the admin user. |flowable.idm.app.security.remember-me-key |security.rememberme.key |testKey |The hash key that is used by Spring Security to hash the password values in the applications. Make sure that you change the value of this property. |flowable.idm.app.security.user-validity-period |cache.users.recheck.period |30000 |How long should a user be cached before invalidating it in the cache for the cacheable CustomUserDetailsService. |flowable.idm.app.security.cookie.domain |security.cookie.domain |- |The domain for the cookie. |flowable.idm.app.security.cookie.max-age |security.cookie.max-age |2678400 |The max age of the security cookie in seconds. Default is 31 days. |flowable.idm.app.security.cookie.refresh-age |security.cookie.refresh-age |86400 |The refresh age of the cookie in seconds. Default is 1 day. |=============== In addition to the default identity tables, the IDM application can also be configured to use an LDAP server. To connect to a LDAP server, additional properties in the application.properties file (or any other way of configuring the application) are needed: [source,linenums] ---- # # LDAP # flowable.idm.ldap.enabled=true flowable.idm.ldap.server=ldap://localhost flowable.idm.ldap.port=10389 flowable.idm.ldap.user=uid=admin, ou=system flowable.idm.ldap.password=secret flowable.idm.ldap.base-dn=o=flowable flowable.idm.ldap.query.user-by-id=(&(objectClass=inetOrgPerson)(uid={0})) flowable.idm.ldap.query.user-by-full-name-like=(&(objectClass=inetOrgPerson)(|({0}=*{1}*)({2}=*{3}*))) flowable.idm.ldap.query.all-users=(objectClass=inetOrgPerson) flowable.idm.ldap.query.groups-for-user=(&(objectClass=groupOfUniqueNames)(uniqueMember={0})) flowable.idm.ldap.query.all-groups=(objectClass=groupOfUniqueNames) flowable.idm.ldap.query.group-by-id=(&(objectClass=groupOfUniqueNames)(uniqueId={0})) flowable.idm.ldap.attribute.user-id=uid flowable.idm.ldap.attribute.first-name=cn flowable.idm.ldap.attribute.last-name=sn flowable.idm.ldap.attribute.group-id=cn flowable.idm.ldap.attribute.group-name=cn flowable.idm.ldap.cache.group-size=10000 flowable.idm.ldap.cache.group-expiration=180000 ---- When the `flowable.idm.ldap.enabled` property is set to true, the IDM app will expect the other LDAP properties to have been filled-in. In this example configuration the server configuration + LDAP queries for the Apache Directory Server are provided. For other LDAP servers, like Active Directory, other configuration values are needed. When LDAP is configured, authentication and group retrieval for a user will be done through the LDAP server. Only privileges will still be retrieved from the Flowable identity tables. So make sure each LDAP user has the correct privileges defined in the IDM application. If the IDM application is booted with LDAP configuration the bootstrap logic will check if there are already privileges present in the Flowable identity tables. If there are no privileges (only when booting the first time), the 4 default privileges will be created and the `flowable.idm.app.admin.user-id` property value (from application.properties or configured in the environment) will be used as the user id to get all 4 privileges. So make sure that the `flowable.idm.app.admin.user-id` property value is set to a valid LDAP user, otherwise nobody will be able to login to any of the Flowable UI apps. [[flowableModelerApp]] === Flowable Modeler application The Flowable Modeler application can be used to model BPMN processes, DMN decision table, Form definitions and create app definitions. The BPMN modeler uses the same Oryx and Angular foundation as in Flowable 5, but the functionality has now been moved into a separate Modeler application. When using the Flowable Modeler application, make sure the Flowable IDM application is deployed and running as well (for authentication and authorization purposes). When you login to the Modeler application (link:$$http://localhost:8080/flowable-modeler$$[http://localhost:8080/flowable-modeler]) with your user (or the default admin/test user), you will see the process overview screen. From here you can start creating new BPMN process models by clicking on the Create Process or Import Process button. image::images/flowable_modeler_createmodel_popup.png[align=""center"", width=""600""] When creating a process model (but also any other model), it's important to think carefully about the model key value. The model key is a unique identifier for the model across the full model repository. If you choose a model key that already exists in the model repository, an error message is shown and the model is not saved. After creating the model with the popup, the BPMN modeling canvas is shown. The BPMN editor is very similar to the Flowable 5 BPMN editor that was part of the Explorer application. All BPMN elements supported by the Flowable engine are available to be used in the design of a process model. image::images/flowable_modeler_design_screen.png[align=""center""] The BPMN editor is divided into 4 parts: * Palette: the palette of BPMN elements available to design a process model * Toolbar: actions to change the model canvas, such as zooming, layout and saving a model * Model canvas: the modeling canvas on which to drag and drop BPMN elements and design the process model * Properties panel: the properties for the main process model if no element is select and otherwise the properties of the selected BPMN element For a User task element there's a _Referenced form_ property in the properties panel. If you select this property, a popup is opened where you can select a form definition from the repository or create a new form. When creating a new form, a similar create dialog to the process model create dialog is presented. After filling in the name and form model key, the form editor is opened. image::images/flowable_modeler_formdesign_screen.png[align=""center""] Form fields can be dragged from the form palette on to the form canvas. In this example, a name textfield, two date fields and a remarks multiline textfield are added to the form canvas. When editing a form field, the label, id, required status and placeholder can be filled in. image::images/flowable_modeler_editfield_popup.png[align=""center"", width=""600""] The id field is an important value, because a process variable will be created with the form field value using the id property value. When filling in the label property, the id property is automatically filled. If needed, you can also provide the id property value yourself by checking the override id checkbox. After saving the form model and closing the form editor, you are automatically navigated back to the process model (when the form editor was opened via the BPMN editor). When selecting the User task element again and clicking on the _Referenced form_ property you will see that the newly created form definition is now attached to the User task. When clicking on the _Form_ tab in the header of the Modeler application, all form definitions available in the model repository are shown. image::images/flowable_modeler_formoverview_screen.png[align=""center""] You can preview every form definition by opening the details view of a form definition. In the details view, the form name, key and description can be edited and the history of form models is available. You can also duplicate the form definition to create a new form definition with the same form fields. Now let's open the vacation request process model in the BPMN editor again and add a Script task to the process model, that will calculate the number of days between the vacation start and end dates. Click on the _Script format_ property and fill in a value of _groovy_ to instruct the Flowable engine to use the Groovy scripting engine. Now click on the _Script_ property and fill in the script that calculates the number of days. image::images/flowable_modeler_script_popup.png[align=""center"", width=""600""] Now we have a _amountOfVacationDays_ process variable we can add a Decision task to the process model. A decision task can be used to execute a DMN decision table in the Flowable DMN engine. Through the _Decision table reference_ property, a new decision table model can be created and the DMN editor is opened. image::images/flowable_modeler_dmneditor_screen.png[align=""center""] The DMN editor provides a table editor with input columns, where input conditions can be defined with the process variables available in the process context, and output columns, where output variable values can be defined. In this very simple example there's one input column using the _amountOfVacationDays_ variable that checks if it's less than 10 or higher or equal to 10. When the amount of days is less than 10, an output variable _managerApprovalNeeded_ is returned with value false, and otherwise a value of true is returned. You can define multiple input columns and have multiple input conditions per rule. It's also possible to leave an input column empty, which means that it's evaluated to true for that part of the rule. You can define one or multiple output variables. Another important part of the DMN decision table definition is the hit policy. Currently, Flowable supports the First and Any hit policy. With the First hit policy, when the first rule is found that evaluates to true the DMN execution will stop and its output variables are returned. For the Any hit policy, all rules will be executed and the output variables for the last rule that evaluates to true are returned. When the DMN editor is saved and closed, the Modeler application navigates back to the BPMN editor and the newly created DMN decision table is now attached to the Decision task. The decision task will be generated in the BPMN XML like; [source,xml,linenums] ---- ---- With the _managerApprovalNeeded_ variable available in the process instance context, we can now create an exclusive gateway with a sequence flow condition that evaluates the calculated value of the DMN Engine. image::images/flowable_modeler_sequenceflowcondition_popup.png[align=""center"", width=""500""] The full BPMN process model now looks like this: image::images/flowable_modeler_vacationrequest_screen.png[align=""center""] With the process model completed, we can now create an app definition that combines one or more process models with all their associated models (for example, decision tables and form definitions) into a single artifact. An app definition can be exported as a BAR file (zip format) that can be deployed on the Flowable engine. When creating a vacation request app definition, the app editor will look something like the screen below. image::images/flowable_modeler_appeditor_screen.png[align=""center""] In the app editor, an icon and a theme color can be selected that will be used in the Flowable Task application to show the application in the dashboard. The important step is to add the vacation request process model, and by selecting the process model, automatically include any form definitions and DMN decision tables. image::images/flowable_modeler_modelselection_popup.png[align=""center""] A process model can be selected by clicking on the model thumbnail. When one or more models are selected, you can close the popup, save the app definition and close it. When navigating to the details view of the newly created vacation request app definition, the following details screen is shown: image::images/flowable_modeler_appdetails_screen.png[align=""center""] From this view, you can download the app definition in two different formats. The first download button (with the arrow pointing downwards) can be used to download the app definition with the JSON model files for each included model. This makes it easy to share app definitions between different Flowable Modeler applications. The second download button (with the arrow point to upper right) will provide a BAR file of the app definition models, which can be deployed on the Flowable engine. In the BAR file, only the deployable artifacts are included, such as the BPMN 2.0 XML file and the DMN XML file, and not the JSON model files. All files in a BAR file deployed on a Flowable engine are stored in the database, so therefore only the deployable files are included. From the app definition details view, you can also _Publish_ the app definition directly to the Flowable engine. The Flowable Modeler uses the URL defined in the application.properties file with the _flowable.modeler.app.deployment-api-url_ property key. By default, the deployment URL is configured so the app definition will be deployed on the Flowable Task application when it's running. However, this can be changed to use the Flowable REST application, for example. Make sure the Flowable Task application is running and click on the _Publish_ button. The app definition is now deployed as a BAR file to the Flowable Task application. This are the Modeler UI App specific properties. .Modeler UI App Properties [cols=""4*"",options=""header""] |=============== |Property name |Old Property |Default value |Description |flowable.modeler.app.data-source-prefix |datasource.prefix |- |The prefix for the database tables. |flowable.modeler.app.deployment-api-url |deployment.api.url |http://localhost:8080/flowable-task/app-api |The root URI to the REST services of the Flowable engine, used by the Flowable Modeler application to deploy the application definition BAR file to the engine. Default url for the Flowable Task application is http://localhost:8080/flowable-task/app-api |flowable.modeler.app.rest-enabled |rest.modeler-app.enabled |true |Enables the REST API (this is not the REST api used by the UI, but an api that's available over basic auth authentication). |=============== [[flowableTaskApp]] === Flowable Task application The Flowable Task application is the runtime application of the Flowable project and includes the Flowable BPMN, DMN, Form and Content engines by default. With the Flowable Task application, new process instances can be started, tasks can be completed, task forms can be rendered and so on. In the previous section, the vacation request app definition was deployed on the Flowable Task application REST API, and through that deployed on the Flowable engine. If you look in the Flowable database, you can see a new deployment entry has been added to the ACT_RE_DEPLOYMENT table for the BPMN Engine. Also, new entries haven been created in the ACT_DMN_DEPLOYMENT and ACT_FO_FORM_DEPLOYMENT tables for the DMN and Form engines. On the dashboard on link:$$http://localhost:8080/flowable-task$$[http://localhost:8080/flowable-task], you can see a vacation request app in addition to the default Task app, and any other apps that have been deployed to the Flowable engine already. image::images/flowable_task_dashboard_screen.png[align=""center""] When clicking on the vacation request app, the task list for the logged-in user is shown (which is probably empty for now). image::images/flowable_task_tasklist_screen.png[align=""center""] When clicking on the _Processes_ tab you can choose to start a new process instance by clicking on the _Start a process_ button. The list of available process definitions within the context of this app definition is now displayed. In the general Task app this works in a similar way, but in the Task app, all process definitions deployed on the Flowable engine are shown. After selecting the vacation request process definition, the _Start process_ button can be clicked to start a new vacation request process instance. The Flowable Task application automatically navigates to the process instance details view. You can see the _Provide vacation information_ task is active and, for example, comments can be added and the process instance state can be shown diagrammatically using the _Show diagram_ button. image::images/flowable_task_processdetails_screen.png[align=""center""] When navigating to the task list, you can also see the _Provide vacation information_ task listed there as well. The task details are shown in this view, with the vacation info form being rendered. You can also switch to the details view by clicking on the _Show details_ button. In the details view, comments can be added, users can involved in the task and attachments can be added to the task. You can also change the due date and the assignee of a task. image::images/flowable_task_taskdetails_screen.png[align=""center""] Let's fill in the form and complete the task. First, select a start date and end date that have more than 10 days in between, so we can validate that a _Manager approval_ task is being generated. After filling in the vacation info form and clicking the _Complete_ button, the Flowable task app navigates directly to the _Manager approval_ task view. When you also complete this task (without a task form), the process instance is completed. When navigating to the _Processes_ tab and clicking on the _Showing running processes_ section, you can select an option to show completed process instances. The list of completed process instances is now shown and when clicking on the just completed vacation request process you can see the two completed tasks. image::images/flowable_task_processhistory_screen.png[align=""center""] The completed form of each task is stored in the ACT_FO_FORM_INSTANCE table of the Flowable Form engine. So it's possible to look at the values of each completed form when you navigate to the completed task. image::images/flowable_task_completedform_screen.png[align=""center""] Make sure to switch back to showing running processes instead of the completed ones, otherwise you won't see newly started process instances. You can also filter tasks in the task list view. There are options to search on the name of a task, the task state, only tasks for a specific process definition and change the assignment filter. image::images/flowable_task_taskfilter_screen.png[align=""center"", width=""400""] By default, the assignment filter is set to _Tasks where I am involved_. This doesn't show the tasks where you are a candidate, such as tasks that are available to a specific candidate group before they are assigned to a specific person. To show candidate tasks you can select the _Tasks where I am one of the candidates_ assignment filter option. This are the Task UI App specific properties. .Task UI App Properties [cols=""4*"",options=""header""] |=============== |Property name |Old Property |Default value |Description |flowable.experimental.debugger.enabled |debugger.enabled |false |Whether the process debugger should be enabled. |flowable.task.app.rest-enabled |rest.task-app.enabled |true |Enables the REST API (this is not the REST api used by the UI, but an api that's available over basic auth authentication). |flowable.form-field-validation-enabled | |false |Enable form field validation after form submission on the engine side. |=============== [[flowableAdminApp]] === Flowable Admin application The fourth UI application the Flowable project provides is the Flowable Admin application. This application provides ways to, for example, query deployments in the BPMN, DMN and Form Engines, but also shows the active state of a process instance with its active tasks and process variables. It also provides actions to assign a task to a different assignee and to complete an active task. The Flowable Admin application uses the REST API to communicate with the Flowable engines. By default, it is configured to connect to the Flowable Task REST API, but you can easily change this to use the Flowable REST app REST API instead. When going to link:$$http://localhost:8080/flowable-admin$$[http://localhost:8080/flowable-admin], the configuration screen is shown (which is also available by clicking on the arrow at the top right near the Flowable logo). image:images/flowable_admin_configuration_screen.png[align=""center""] For each engine, the REST endpoint can be configured with the basic authentication values. The configuration is done per engine, because it's possible to, for example, deploy the DMN Engine on a separate server from the BPMN Engine. When the configuration is defined with the correct values, the _Process Engine_ can be selected to administer the Flowable BPMN engine. By default, the deployments of the Flowable BPMN engine are shown. image::images/flowable_admin_deployments_screen.png[align=""center""] You can filter the deployments based on name and tenant identifier. In this view, it's also possible to deploy a new BPMN XML file or BAR file to the Flowable engine. When clicking on one of the deployments, the deployment details view is shown. image::images/flowable_admin_deploymentdetails_screen.png[align=""center""] More details of a deployment are shown here and also the process definitions that are part of this deployment on which you click to get more details. It's also possible to delete a deployment here. When you want to delete a deployed app definition, this is also the way to delete the app definition from the Flowable Task app dashboard. When clicking on one of the process definitions, the process definition details view is shown. image::images/flowable_admin_processdefinitiondetails_screen.png[align=""center""] In the process definition details view, the first page of process instances is shown, together with optional decision table definitions and form definitions that are used in the process definition. For the vacation request process definition, there's one connected decision table and one connected form definition. Clicking on the decision table definition navigates the Flowable Admin application to the DMN engine. You can always navigate back to the Process engine by clicking on the _Parent Deployment ID_ link. In addition to the deployments and definitions, you can also query on process instances, tasks, jobs and event subscriptions in the Process engine. The views all work in a similar way to what's already been described. This are the Admin UI App specific properties .Admin UI App Properties [cols=""4*"",options=""header""] |=============== |Property name |Old Property |Default value |Description |flowable.admin.app.data-source-prefix |datasource.prefix | |The prefix for the database tables. |flowable.admin.app.security.encryption.credentials-i-v-spec |security.encryption.credentials-i-v-spec |- |The string that needs to be used to create an IvParameterSpec object using it's the bytes. |flowable.admin.app.security.encryption.credentials-secret-spec |security.encryption.credentials-secret-spec |- |The string that needs to be used to create a SecretKeySpec using it's bytes. |flowable.admin.app.security.preemptive-basic-authentication | |false |Perform a preemptive basic authentication when issuing requests to the flowable REST API. **NB:** This is an experimental property and might be removed without notice. |=============== In addition to these properties, the Flowable admin application has a few more properties. The full content of the properties file can be viewed on {sc-flowable-ui-admin}/flowable-ui-admin-app/src/main/resources/application.properties[Github]. The additional properties are mainly used for defining the initial values for the REST endpoints for the different engines. The Admin application uses the initial values to make a connection to the Flowable engines, but the values can be overridden in the Admin application configuration view and these values are stored in the __ACT\\_ADM\\_SERVER\\_CONFIG__ table. An example of the BPMN Engine REST properties is shown below: [source,linenums] ---- flowable.admin.app.server-config.process.name=Flowable Process app flowable.admin.app.server-config.process.description=Flowable Process REST config flowable.admin.app.server-config.process.server-address=http://localhost flowable.admin.app.server-config.process.port=8080 flowable.admin.app.server-config.process.context-root=flowable-task flowable.admin.app.server-config.process.rest-root=process-api flowable.admin.app.server-config.process.user-name=admin flowable.admin.app.server-config.process.password=test ---- These values can be used when the Flowable Task app (with all the Flowable engines included) is managed by the Flowable Admin application. .Admin UI App Properties managed by Spring Boot [cols=""2*"",options=""header""] |=============== |Old property |Description |message.reloading.enabled |Using Spring Boot MessageSourceAutoConfiguration. Set the duration with `spring.messages.cache-duration`. |=============== === Internationalization The Flowable UI apps support internationalization (i18n). The project maintains the English translations. It is however possible to provide your own translation files in order to support other languages. The link:$$https://github.com/angular-translate/angular-translate[Angular Translate] library tries to load a specific translation file based on the browser's locale located in the _i18n_ folder (present in each UI module). When a matching translation file cannot be loaded the framework will fallback to the English translation. Mapping multiple browser locale keys to specific translations additional configuration can be provided (located in the Angular app config); [source,linenums] ---- // Initialize angular-translate $translateProvider.useStaticFilesLoader({ prefix: './i18n/', suffix: '.json' }) /* This can be used to map multiple browser language keys to a angular translate language key. */ // .registerAvailableLanguageKeys(['en'], { // 'en-*': 'en' // }) .useCookieStorage() .useSanitizeValueStrategy('sanitizeParameters') .uniformLanguageTag('bcp47') .determinePreferredLanguage(); ---- For example; your browser is configured for English (United States) and provides the language key _en-US_. Without the mapping Angular Translate will try to fetch the corresponding translation file _en-US.json_. (If this is not available it will fallback to 'en' and load the _en.json_ translation file) By uncommenting the _.registerAvailableLanguageKeys_ block you can map _en-US_ (and all other _en_ language keys) to the _en.json_ language file. === Production ready endpoints The https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-endpoints.html[Production ready endpoints] from Spring Boot are present for all applications. To have an overview of all the available Endpoints have a look at the https://docs.spring.io/spring-boot/docs/current/actuator-api/html/[Actuator Web API Documentation]. This properties are set per default: [source,linenums] ----- # Expose all actuator endpoints to the web # They are exposed, but only authenticated users can see /info and /health abd users with access-admin can see the others management.endpoints.web.exposure.include=* # Full health details should only be displayed when a user is authorized management.endpoint.health.show-details=when_authorized # Only users with role access-admin can access full health details management.endpoint.health.roles=access-admin ----- The security is configured in such way that the `info` and `health` endpoint are exposed to all authenticated users. Full details of the `health` endpoint can only be seen by users with the privilege `access-admin`. In case you want to change that you need to configure `management.endpoint.health.show-details`. All the rest of the endpoints are accessing only to users with the `access-admin` privilege. [[custom-bean-deployment]] === Custom bean deployment There are multiple ways of providing custom beans to the Flowable applications. [[custom-bean-deployment-spring-boot-auto]] ==== Using Spring Boot auto configuration The Flowable applications are Spring Boot 2 applications. Which means that normal Spring Boot auto configuration can be used to make the beans to Flowable. This can be done in the following manner ``` package com.your.own.package.configuration; @Configuration @AutoConfigureOrder(Ordered.LOWEST_PRECEDENCE) // Makes sure that this configuration will be processed last by Spring Boot @ConditionalOnBean(type = ""org.flowable.engine.ProcessEngine"") // The configuration will only be used when the ProcessEngine bean is present public class YourOwnConfiguration { @Configuration @ComponentScan (""com.your.own.package.beans"") public static class ComponentScanConfiguration { // This class is needed in order to conditionally perform the component scan (i.e. when the ProcessEngine bean is present) // It is an optional class, in case you don't need component scanning then you don't need to do this } @Bean public CustomBean customBean() { // create your bean } @Bean public EngineConfigurationConfigurer customProcessEngineConfigurationConfigurer() { return engineConfiguration -> { // You can use this to add extra configuration to the process engine } } } ``` Note that when using Spring Boot the configuration class can be under your own package and not under some Flowable package. In order to make this class an auto configuration class a file named `spring.factories` should be created in the `META-INF` folder of your jar. In this file you should add ``` org.springframework.boot.autoconfigure.EnableAutoConfiguration=\\ com.your.own.package.configuration.YourOwnCustomConfiguration ``` In order to use this approach you would need to include your jar in the `WEB-INF/lib` folder of the exploded war. Placing this jar in the lib folder of the servlet container (e.g. Tomcat) is not going to work due to the way Spring proxies the `@Configuration` classes. [[custom-bean-deployment-component-scan]] ==== Component scan Another way to provide custom Spring beans to the Flowable engine is to put them under a certain package and have the Flowable application component scan that package. Based on the used application this package is different: * `org.flowable.rest.app` for the `flowable-rest.war` * `org.flowable.ui.task.application` for the `flowable-task.war` The custom beans can be located in a single JAR and this jar should be present on the classpath when the applications are starting up. Depending where there JAR is placed, the lib folder of the servlet container (e.g. Tomcat) or the `WEB-INF/lib` folder of the exploded war, there are different possibilities. When using the lib folder of the servlet container then the created classes should be self contained, i.e. they should only use classes from within the jar. You can use any of the Spring `@Component` annotations (with the exception of `@Configuration`). The reason for not being able to use `@Configuration` classes is the fact that each configuration class is proxied by Spring with the help of the `ConfigurationClassPostProcessor`. However, the classloader loading the `@Configuration` class does not have access to the needed classes by Spring. When including the jar in the `WEB-INF/lib` folder of the exploded war then `@Configuration` classes and dependencies to other jars is possible. [[custom-bean-deployment-own-spring-boot]] ==== Creating your own Spring Boot application This approach is the most flexible and most powerful approach of all. In order to follow this approach have a look at the <> section of this documentation.",12338,False,2111.0585363153964,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. lv_ref_cell_addr = lv_ref_formula+lv_offset1(lv_tlen). ""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. ev_resulting_formula = lv_cur_form. 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. ",14442,True,2627.381098633476,median "open util/ordering [State] as ord pred test47 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Chicken0 + State2->Farmer0 + State2->Fox0 + State2->Chicken0 + State2->Grain0 + State3->Fox0 + State3->Chicken0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test47 for 4 expect 0 pred test22 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State1->Chicken0 + State2->Chicken0 + State3->Farmer0 + State3->Chicken0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Grain0,Fox0 + Grain0,Fox0 + Chicken0 + Grain0,none] }}}}}} } run test22 for 4 expect 0 pred test30 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Chicken0,Fox0 + Chicken0 + Grain0,Farmer0 + Fox0 + Chicken0 + Grain0] }}}}}} } run test30 for 4 expect 1 pred test15 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State1->Chicken0 + State2->Chicken0 + State3->Farmer0 + State3->Chicken0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Grain0,none,Farmer0] }}}}}} } run test15 for 4 expect 0 pred test53 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State0->Fox0 + State1->Farmer0 + State1->Fox0 + State1->Chicken0 + State2->Chicken0 + State3->Farmer0 + State3->Chicken0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test53 for 4 expect 0 pred test49 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test49 for 4 expect 1 pred test14 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Grain0,Fox0 + Grain0,Grain0,Fox0 + Chicken0] }}}}}} } run test14 for 4 expect 0 pred test26 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Chicken0 + State2->Farmer0 + State2->Fox0 + State2->Chicken0 + State3->Fox0 far = State1->Farmer0 + State1->Fox0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Chicken0 + Grain0,Grain0,Fox0 + Chicken0 + Grain0,Farmer0 + Fox0 + Chicken0 + Grain0] }}}}}} } run test26 for 4 expect 1 pred test6 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Chicken0 + State2->Farmer0 + State2->Chicken0 far = State1->Farmer0 + State1->Fox0 + State2->Fox0 + State3->Farmer0 + State3->Fox0 + State3->Chicken0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test6 for 4 expect 1 pred test20 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Chicken0 + State2->Farmer0 + State2->Fox0 + State2->Chicken0 + State3->Chicken0 far = State1->Farmer0 + State1->Fox0 + State3->Farmer0 + State3->Fox0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0,Fox0,none,Farmer0] }}}}}} } run test20 for 4 expect 1 pred test12 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Farmer0,none,Farmer0] }}}}}} } run test12 for 4 expect 0 pred test42 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Fox0 + Grain0,Fox0 + Grain0,Farmer0 + Fox0] }}}}}} } run test42 for 4 expect 0 pred test23 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Chicken0,none,Farmer0 + Fox0] }}}}}} } run test23 for 4 expect 1 pred test16 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Chicken0 + Grain0,Chicken0,none,Farmer0] }}}}}} } run test16 for 4 expect 1 pred test21 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Chicken0 + State2->Farmer0 + State2->Fox0 + State2->Chicken0 + State3->Fox0 far = State1->Farmer0 + State1->Fox0 + State3->Farmer0 + State3->Chicken0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Grain0,Fox0 + Grain0,none,Farmer0] }}}}}} } run test21 for 4 expect 1 pred test55 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Farmer0 + State1->Grain0 + State2->Grain0 + State3->Fox0 + State3->Chicken0 far = State1->Fox0 + State1->Chicken0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Chicken0 + State2->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test55 for 4 expect 0 pred test37 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Farmer0 + Fox0 + Grain0,Fox0,none,Farmer0 + Grain0] }}}}}} } run test37 for 4 expect 1 pred test11 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Grain0,Fox0,none,Farmer0 + Grain0] }}}}}} } run test11 for 4 expect 1 pred test44 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Chicken0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Chicken0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Grain0,none,none,Farmer0 + Grain0] }}}}}} } run test44 for 4 expect 1 pred test38 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Grain0,Grain0,Fox0 + Grain0,Farmer0 + Fox0 + Grain0] }}}}}} } run test38 for 4 expect 1 pred test34 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Chicken0 + State2->Farmer0 + State2->Chicken0 far = State1->Farmer0 + State1->Fox0 + State2->Fox0 + State3->Farmer0 + State3->Fox0 + State3->Chicken0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Fox0 + Grain0,Fox0 + Grain0,Farmer0 + Fox0 + Chicken0 + Grain0] }}}}}} } run test34 for 4 expect 1 pred test43 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0,Fox0,none,Farmer0 + Chicken0] }}}}}} } run test43 for 4 expect 1 pred test31 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Chicken0 + Grain0,Chicken0,none,Farmer0 + Grain0] }}}}}} } run test31 for 4 expect 1 pred test32 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Chicken0 + Grain0,Chicken0,none,Farmer0 + Grain0] }}}}}} } run test32 for 4 expect 1 pred test28 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Chicken0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State1->Chicken0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Chicken0,Fox0 + Grain0,Chicken0] }}}}}} } run test28 for 4 expect 0 pred test56 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Chicken0 + State2->Farmer0 + State2->Chicken0 + State3->Chicken0 far = State1->Farmer0 + State1->Fox0 + State2->Fox0 + State3->Farmer0 + State3->Fox0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test56 for 4 expect 1 pred test40 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Chicken0,none,Farmer0 + Fox0] }}}}}} } run test40 for 4 expect 1 pred test8 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Farmer0,Grain0,Fox0 + Chicken0] }}}}}} } run test8 for 4 expect 0 ",8240,True,3334.169586683331,median "[[features.external-config]] == Externalized Configuration Spring Boot lets you externalize your configuration so that you can work with the same application code in different environments. You can use a variety of external configuration sources, include Java properties files, YAML files, environment variables, and command-line arguments. Property values can be injected directly into your beans by using the `@Value` annotation, accessed through Spring's `Environment` abstraction, or be <> through `@ConfigurationProperties`. Spring Boot uses a very particular `PropertySource` order that is designed to allow sensible overriding of values. Properties are considered in the following order (with values from lower items overriding earlier ones): . Default properties (specified by setting `SpringApplication.setDefaultProperties`). . {spring-framework-api}/context/annotation/PropertySource.html[`@PropertySource`] annotations on your `@Configuration` classes. Please note that such property sources are not added to the `Environment` until the application context is being refreshed. This is too late to configure certain properties such as `+logging.*+` and `+spring.main.*+` which are read before refresh begins. . Config data (such as `application.properties` files). . A `RandomValuePropertySource` that has properties only in `+random.*+`. . OS environment variables. . Java System properties (`System.getProperties()`). . JNDI attributes from `java:comp/env`. . `ServletContext` init parameters. . `ServletConfig` init parameters. . Properties from `SPRING_APPLICATION_JSON` (inline JSON embedded in an environment variable or system property). . Command line arguments. . `properties` attribute on your tests. Available on {spring-boot-test-module-api}/context/SpringBootTest.html[`@SpringBootTest`] and the <>. . {spring-framework-api}/test/context/TestPropertySource.html[`@TestPropertySource`] annotations on your tests. . <> in the `$HOME/.config/spring-boot` directory when devtools is active. Config data files are considered in the following order: . <> packaged inside your jar (`application.properties` and YAML variants). . <> packaged inside your jar (`application-\\{profile}.properties` and YAML variants). . <> outside of your packaged jar (`application.properties` and YAML variants). . <> outside of your packaged jar (`application-\\{profile}.properties` and YAML variants). NOTE: It is recommended to stick with one format for your entire application. If you have configuration files with both `.properties` and `.yml` format in the same location, `.properties` takes precedence. To provide a concrete example, suppose you develop a `@Component` that uses a `name` property, as shown in the following example: include::code:MyBean[] On your application classpath (for example, inside your jar) you can have an `application.properties` file that provides a sensible default property value for `name`. When running in a new environment, an `application.properties` file can be provided outside of your jar that overrides the `name`. For one-off testing, you can launch with a specific command line switch (for example, `java -jar app.jar --name=""Spring""`). TIP: The `env` and `configprops` endpoints can be useful in determining why a property has a particular value. You can use these two endpoints to diagnose unexpected property values. See the ""<>"" section for details. [[features.external-config.command-line-args]] === Accessing Command Line Properties By default, `SpringApplication` converts any command line option arguments (that is, arguments starting with `--`, such as `--server.port=9000`) to a `property` and adds them to the Spring `Environment`. As mentioned previously, command line properties always take precedence over file-based property sources. If you do not want command line properties to be added to the `Environment`, you can disable them by using `SpringApplication.setAddCommandLineProperties(false)`. [[features.external-config.application-json]] === JSON Application Properties Environment variables and system properties often have restrictions that mean some property names cannot be used. To help with this, Spring Boot allows you to encode a block of properties into a single JSON structure. When your application starts, any `spring.application.json` or `SPRING_APPLICATION_JSON` properties will be parsed and added to the `Environment`. For example, the `SPRING_APPLICATION_JSON` property can be supplied on the command line in a UN{asterisk}X shell as an environment variable: [source,shell,indent=0,subs=""verbatim""] ---- $ SPRING_APPLICATION_JSON='{""my"":{""name"":""test""}}' java -jar myapp.jar ---- In the preceding example, you end up with `my.name=test` in the Spring `Environment`. The same JSON can also be provided as a system property: [source,shell,indent=0,subs=""verbatim""] ---- $ java -Dspring.application.json='{""my"":{""name"":""test""}}' -jar myapp.jar ---- Or you could supply the JSON by using a command line argument: [source,shell,indent=0,subs=""verbatim""] ---- $ java -jar myapp.jar --spring.application.json='{""my"":{""name"":""test""}}' ---- If you are deploying to a classic Application Server, you could also use a JNDI variable named `java:comp/env/spring.application.json`. NOTE: Although `null` values from the JSON will be added to the resulting property source, the `PropertySourcesPropertyResolver` treats `null` properties as missing values. This means that the JSON cannot override properties from lower order property sources with a `null` value. [[features.external-config.files]] === External Application Properties [[features.external-config.files]] Spring Boot will automatically find and load `application.properties` and `application.yaml` files from the following locations when your application starts: . From the classpath .. The classpath root .. The classpath `/config` package . From the current directory .. The current directory .. The `/config` subdirectory in the current directory .. Immediate child directories of the `/config` subdirectory The list is ordered by precedence (with values from lower items overriding earlier ones). Documents from the loaded files are added as `PropertySources` to the Spring `Environment`. If you do not like `application` as the configuration file name, you can switch to another file name by specifying a configprop:spring.config.name[] environment property. For example, to look for `myproject.properties` and `myproject.yaml` files you can run your application as follows: [source,shell,indent=0,subs=""verbatim""] ---- $ java -jar myproject.jar --spring.config.name=myproject ---- You can also refer to an explicit location by using the configprop:spring.config.location[] environment property. This property accepts a comma-separated list of one or more locations to check. The following example shows how to specify two distinct files: [source,shell,indent=0,subs=""verbatim""] ---- $ java -jar myproject.jar --spring.config.location=\\ optional:classpath:/default.properties,\\ optional:classpath:/override.properties ---- TIP: Use the prefix `optional:` if the <> and you do not mind if they do not exist. WARNING: `spring.config.name`, `spring.config.location`, and `spring.config.additional-location` are used very early to determine which files have to be loaded. They must be defined as an environment property (typically an OS environment variable, a system property, or a command-line argument). If `spring.config.location` contains directories (as opposed to files), they should end in `/`. At runtime they will be appended with the names generated from `spring.config.name` before being loaded. Files specified in `spring.config.location` are imported directly. NOTE: Both directory and file location values are also expanded to check for <>. For example, if you have a `spring.config.location` of `classpath:myconfig.properties`, you will also find appropriate `classpath:myconfig-.properties` files are loaded. In most situations, each configprop:spring.config.location[] item you add will reference a single file or directory. Locations are processed in the order that they are defined and later ones can override the values of earlier ones. [[features.external-config.files.location-groups]] If you have a complex location setup, and you use profile-specific configuration files, you may need to provide further hints so that Spring Boot knows how they should be grouped. A location group is a collection of locations that are all considered at the same level. For example, you might want to group all classpath locations, then all external locations. Items within a location group should be separated with `;`. See the example in the ""`<>`"" section for more details. Locations configured by using `spring.config.location` replace the default locations. For example, if `spring.config.location` is configured with the value `optional:classpath:/custom-config/,optional:file:./custom-config/`, the complete set of locations considered is: . `optional:classpath:custom-config/` . `optional:file:./custom-config/` If you prefer to add additional locations, rather than replacing them, you can use `spring.config.additional-location`. Properties loaded from additional locations can override those in the default locations. For example, if `spring.config.additional-location` is configured with the value `optional:classpath:/custom-config/,optional:file:./custom-config/`, the complete set of locations considered is: . `optional:classpath:/;optional:classpath:/config/` . `optional:file:./;optional:file:./config/;optional:file:./config/*/` . `optional:classpath:custom-config/` . `optional:file:./custom-config/` This search ordering lets you specify default values in one configuration file and then selectively override those values in another. You can provide default values for your application in `application.properties` (or whatever other basename you choose with `spring.config.name`) in one of the default locations. These default values can then be overridden at runtime with a different file located in one of the custom locations. NOTE: If you use environment variables rather than system properties, most operating systems disallow period-separated key names, but you can use underscores instead (for example, configprop:spring.config.name[format=envvar] instead of configprop:spring.config.name[]). See <> for details. NOTE: If your application runs in a servlet container or application server, then JNDI properties (in `java:comp/env`) or servlet context initialization parameters can be used instead of, or as well as, environment variables or system properties. [[features.external-config.files.optional-prefix]] ==== Optional Locations By default, when a specified config data location does not exist, Spring Boot will throw a `ConfigDataLocationNotFoundException` and your application will not start. If you want to specify a location, but you do not mind if it does not always exist, you can use the `optional:` prefix. You can use this prefix with the `spring.config.location` and `spring.config.additional-location` properties, as well as with <> declarations. For example, a `spring.config.import` value of `optional:file:./myconfig.properties` allows your application to start, even if the `myconfig.properties` file is missing. If you want to ignore all `ConfigDataLocationNotFoundExceptions` and always continue to start your application, you can use the `spring.config.on-not-found` property. Set the value to `ignore` using `SpringApplication.setDefaultProperties(...)` or with a system/environment variable. [[features.external-config.files.wildcard-locations]] ==== Wildcard Locations If a config file location includes the `{asterisk}` character for the last path segment, it is considered a wildcard location. Wildcards are expanded when the config is loaded so that immediate subdirectories are also checked. Wildcard locations are particularly useful in an environment such as Kubernetes when there are multiple sources of config properties. For example, if you have some Redis configuration and some MySQL configuration, you might want to keep those two pieces of configuration separate, while requiring that both those are present in an `application.properties` file. This might result in two separate `application.properties` files mounted at different locations such as `/config/redis/application.properties` and `/config/mysql/application.properties`. In such a case, having a wildcard location of `config/*/`, will result in both files being processed. By default, Spring Boot includes `config/*/` in the default search locations. It means that all subdirectories of the `/config` directory outside of your jar will be searched. You can use wildcard locations yourself with the `spring.config.location` and `spring.config.additional-location` properties. NOTE: A wildcard location must contain only one `{asterisk}` and end with `{asterisk}/` for search locations that are directories or `*/` for search locations that are files. Locations with wildcards are sorted alphabetically based on the absolute path of the file names. TIP: Wildcard locations only work with external directories. You cannot use a wildcard in a `classpath:` location. [[features.external-config.files.profile-specific]] ==== Profile Specific Files As well as `application` property files, Spring Boot will also attempt to load profile-specific files using the naming convention `application-\\{profile}`. For example, if your application activates a profile named `prod` and uses YAML files, then both `application.yml` and `application-prod.yml` will be considered. Profile-specific properties are loaded from the same locations as standard `application.properties`, with profile-specific files always overriding the non-specific ones. If several profiles are specified, a last-wins strategy applies. For example, if profiles `prod,live` are specified by the configprop:spring.profiles.active[] property, values in `application-prod.properties` can be overridden by those in `application-live.properties`. [NOTE] ==== The last-wins strategy applies at the <> level. A configprop:spring.config.location[] of `classpath:/cfg/,classpath:/ext/` will not have the same override rules as `classpath:/cfg/;classpath:/ext/`. For example, continuing our `prod,live` example above, we might have the following files: ---- /cfg application-live.properties /ext application-live.properties application-prod.properties ---- When we have a configprop:spring.config.location[] of `classpath:/cfg/,classpath:/ext/` we process all `/cfg` files before all `/ext` files: . `/cfg/application-live.properties` . `/ext/application-prod.properties` . `/ext/application-live.properties` When we have `classpath:/cfg/;classpath:/ext/` instead (with a `;` delimiter) we process `/cfg` and `/ext` at the same level: . `/ext/application-prod.properties` . `/cfg/application-live.properties` . `/ext/application-live.properties` ==== The `Environment` has a set of default profiles (by default, `[default]`) that are used if no active profiles are set. In other words, if no profiles are explicitly activated, then properties from `application-default` are considered. NOTE: Properties files are only ever loaded once. If you have already directly <> a profile specific property files then it will not be imported a second time. [[features.external-config.files.importing]] ==== Importing Additional Data Application properties may import further config data from other locations using the `spring.config.import` property. Imports are processed as they are discovered, and are treated as additional documents inserted immediately below the one that declares the import. For example, you might have the following in your classpath `application.properties` file: [source,yaml,indent=0,subs=""verbatim"",configblocks] ---- spring: application: name: ""myapp"" config: import: ""optional:file:./dev.properties"" ---- This will trigger the import of a `dev.properties` file in current directory (if such a file exists). Values from the imported `dev.properties` will take precedence over the file that triggered the import. In the above example, the `dev.properties` could redefine `spring.application.name` to a different value. An import will only be imported once no matter how many times it is declared. The order an import is defined inside a single document within the properties/yaml file does not matter. For instance, the two examples below produce the same result: [source,yaml,indent=0,subs=""verbatim"",configblocks] ---- spring: config: import: ""my.properties"" my: property: ""value"" ---- [source,yaml,indent=0,subs=""verbatim"",configblocks] ---- my: property: ""value"" spring: config: import: ""my.properties"" ---- In both of the above examples, the values from the `my.properties` file will take precedence over the file that triggered its import. Several locations can be specified under a single `spring.config.import` key. Locations will be processed in the order that they are defined, with later imports taking precedence. NOTE: When appropriate, <> are also considered for import. The example above would import both `my.properties` as well as any `my-.properties` variants. [TIP] ==== Spring Boot includes pluggable API that allows various different location addresses to be supported. By default you can import Java Properties, YAML and ""`<>`"". Third-party jars can offer support for additional technologies (there is no requirement for files to be local). For example, you can imagine config data being from external stores such as Consul, Apache ZooKeeper or Netflix Archaius. If you want to support your own locations, see the `ConfigDataLocationResolver` and `ConfigDataLoader` classes in the `org.springframework.boot.context.config` package. ==== [[features.external-config.files.importing-extensionless]] ==== Importing Extensionless Files Some cloud platforms cannot add a file extension to volume mounted files. To import these extensionless files, you need to give Spring Boot a hint so that it knows how to load them. You can do this by putting an extension hint in square brackets. For example, suppose you have a `/etc/config/myconfig` file that you wish to import as yaml. You can import it from your `application.properties` using the following: [source,yaml,indent=0,subs=""verbatim"",configprops,configblocks] ---- spring: config: import: ""file:/etc/config/myconfig[.yaml]"" ---- [[features.external-config.files.configtree]] ==== Using Configuration Trees When running applications on a cloud platform (such as Kubernetes) you often need to read config values that the platform supplies. It is not uncommon to use environment variables for such purposes, but this can have drawbacks, especially if the value is supposed to be kept secret. As an alternative to environment variables, many cloud platforms now allow you to map configuration into mounted data volumes. For example, Kubernetes can volume mount both https://kubernetes.io/docs/tasks/configure-pod-container/configure-pod-configmap/#populate-a-volume-with-data-stored-in-a-configmap[`ConfigMaps`] and https://kubernetes.io/docs/concepts/configuration/secret/#using-secrets-as-files-from-a-pod[`Secrets`]. There are two common volume mount patterns that can be used: . A single file contains a complete set of properties (usually written as YAML). . Multiple files are written to a directory tree, with the filename becoming the '`key`' and the contents becoming the '`value`'. For the first case, you can import the YAML or Properties file directly using `spring.config.import` as described <>. For the second case, you need to use the `configtree:` prefix so that Spring Boot knows it needs to expose all the files as properties. As an example, let's imagine that Kubernetes has mounted the following volume: [indent=0] ---- etc/ config/ myapp/ username password ---- The contents of the `username` file would be a config value, and the contents of `password` would be a secret. To import these properties, you can add the following to your `application.properties` or `application.yaml` file: [source,yaml,indent=0,subs=""verbatim"",configprops,configblocks] ---- spring: config: import: ""optional:configtree:/etc/config/"" ---- You can then access or inject `myapp.username` and `myapp.password` properties from the `Environment` in the usual way. TIP: The folders under the config tree form the property name. In the above example, to access the properties as `username` and `password`, you can set `spring.config.import` to `optional:configtree:/etc/config/myapp`. NOTE: Filenames with dot notation are also correctly mapped. For example, in the above example, a file named `myapp.username` in `/etc/config` would result in a `myapp.username` property in the `Environment`. TIP: Configuration tree values can be bound to both string `String` and `byte[]` types depending on the contents expected. If you have multiple config trees to import from the same parent folder you can use a wildcard shortcut. Any `configtree:` location that ends with `/*/` will import all immediate children as config trees. For example, given the following volume: [indent=0] ---- etc/ config/ dbconfig/ db/ username password mqconfig/ mq/ username password ---- You can use `configtree:/etc/config/*/` as the import location: [source,yaml,indent=0,subs=""verbatim"",configprops,configblocks] ---- spring: config: import: ""optional:configtree:/etc/config/*/"" ---- This will add `db.username`, `db.password`, `mq.username` and `mq.password` properties. NOTE: Directories loaded using a wildcard are sorted alphabetically. If you need a different order, then you should list each location as a separate import Configuration trees can also be used for Docker secrets. When a Docker swarm service is granted access to a secret, the secret gets mounted into the container. For example, if a secret named `db.password` is mounted at location `/run/secrets/`, you can make `db.password` available to the Spring environment using the following: [source,yaml,indent=0,subs=""verbatim"",configprops,configblocks] ---- spring: config: import: ""optional:configtree:/run/secrets/"" ---- [[features.external-config.files.property-placeholders]] ==== Property Placeholders The values in `application.properties` and `application.yml` are filtered through the existing `Environment` when they are used, so you can refer back to previously defined values (for example, from System properties or environment variables). The standard `$\\{name}` property-placeholder syntax can be used anywhere within a value. Property placeholders can also specify a default value using a `:` to separate the default value from the property name, for example `${name:default}`. The use of placeholders with and without defaults is shown in the following example: [source,yaml,indent=0,subs=""verbatim"",configblocks] ---- app: name: ""MyApp"" description: ""${app.name} is a Spring Boot application written by ${username:Unknown}"" ---- Assuming that the `username` property has not be set elsewhere, `app.description` will have the value `MyApp is a Spring Boot application written by Unknown`. TIP: You can also use this technique to create ""`short`"" variants of existing Spring Boot properties. See the _<>_ how-to for details. [[features.external-config.files.multi-document]] ==== Working with Multi-Document Files Spring Boot allows you to split a single physical file into multiple logical documents which are each added independently. Documents are processed in order, from top to bottom. Later documents can override the properties defined in earlier ones. For `application.yml` files, the standard YAML multi-document syntax is used. Three consecutive hyphens represent the end of one document, and the start of the next. For example, the following file has two logical documents: [source,yaml,indent=0,subs=""verbatim""] ---- spring: application: name: ""MyApp"" --- spring: application: name: ""MyCloudApp"" config: activate: on-cloud-platform: ""kubernetes"" ---- For `application.properties` files a special `#---` comment is used to mark the document splits: [source,properties,indent=0,subs=""verbatim""] ---- spring.application.name=MyApp #--- spring.application.name=MyCloudApp spring.config.activate.on-cloud-platform=kubernetes ---- NOTE: Property file separators must not have any leading whitespace and must have exactly three hyphen characters. The lines immediately before and after the separator must not be comments. TIP: Multi-document property files are often used in conjunction with activation properties such as `spring.config.activate.on-profile`. See the <> for details. WARNING: Multi-document property files cannot be loaded by using the `@PropertySource` or `@TestPropertySource` annotations. [[features.external-config.files.activation-properties]] ==== Activation Properties It is sometimes useful to only activate a given set of properties when certain conditions are met. For example, you might have properties that are only relevant when a specific profile is active. You can conditionally activate a properties document using `spring.config.activate.*`. The following activation properties are available: .activation properties [cols=""1,4""] |=== | Property | Note | `on-profile` | A profile expression that must match for the document to be active. | `on-cloud-platform` | The `CloudPlatform` that must be detected for the document to be active. |=== For example, the following specifies that the second document is only active when running on Kubernetes, and only when either the ""`prod`"" or ""`staging`"" profiles are active: [source,yaml,indent=0,subs=""verbatim"",configblocks] ---- myprop: ""always-set"" --- spring: config: activate: on-cloud-platform: ""kubernetes"" on-profile: ""prod | staging"" myotherprop: ""sometimes-set"" ---- [[features.external-config.encrypting]] === Encrypting Properties Spring Boot does not provide any built in support for encrypting property values, however, it does provide the hook points necessary to modify values contained in the Spring `Environment`. The `EnvironmentPostProcessor` interface allows you to manipulate the `Environment` before the application starts. See <> for details. If you need a secure way to store credentials and passwords, the https://cloud.spring.io/spring-cloud-vault/[Spring Cloud Vault] project provides support for storing externalized configuration in https://www.vaultproject.io/[HashiCorp Vault]. [[features.external-config.yaml]] === Working with YAML https://yaml.org[YAML] is a superset of JSON and, as such, is a convenient format for specifying hierarchical configuration data. The `SpringApplication` class automatically supports YAML as an alternative to properties whenever you have the https://bitbucket.org/asomov/snakeyaml[SnakeYAML] library on your classpath. NOTE: If you use ""`Starters`"", SnakeYAML is automatically provided by `spring-boot-starter`. [[features.external-config.yaml.mapping-to-properties]] ==== Mapping YAML to Properties YAML documents need to be converted from their hierarchical format to a flat structure that can be used with the Spring `Environment`. For example, consider the following YAML document: [source,yaml,indent=0,subs=""verbatim""] ---- environments: dev: url: ""https://dev.example.com"" name: ""Developer Setup"" prod: url: ""https://another.example.com"" name: ""My Cool App"" ---- In order to access these properties from the `Environment`, they would be flattened as follows: [source,properties,indent=0,subs=""verbatim""] ---- environments.dev.url=https://dev.example.com environments.dev.name=Developer Setup environments.prod.url=https://another.example.com environments.prod.name=My Cool App ---- Likewise, YAML lists also need to be flattened. They are represented as property keys with `[index]` dereferencers. For example, consider the following YAML: [source,yaml,indent=0,subs=""verbatim""] ---- my: servers: - ""dev.example.com"" - ""another.example.com"" ---- The preceding example would be transformed into these properties: [source,properties,indent=0,subs=""verbatim""] ---- my.servers[0]=dev.example.com my.servers[1]=another.example.com ---- TIP: Properties that use the `[index]` notation can be bound to Java `List` or `Set` objects using Spring Boot's `Binder` class. For more details see the ""`<>`"" section below. WARNING: YAML files cannot be loaded by using the `@PropertySource` or `@TestPropertySource` annotations. So, in the case that you need to load values that way, you need to use a properties file. [[features.external-config.yaml.directly-loading]] [[features.external-config.yaml.directly-loading]] ==== Directly Loading YAML Spring Framework provides two convenient classes that can be used to load YAML documents. The `YamlPropertiesFactoryBean` loads YAML as `Properties` and the `YamlMapFactoryBean` loads YAML as a `Map`. You can also use the `YamlPropertySourceLoader` class if you want to load YAML as a Spring `PropertySource`. [[features.external-config.random-values]] === Configuring Random Values The `RandomValuePropertySource` is useful for injecting random values (for example, into secrets or test cases). It can produce integers, longs, uuids, or strings, as shown in the following example: [source,yaml,indent=0,subs=""verbatim"",configblocks] ---- my: secret: ""${random.value}"" number: ""${random.int}"" bignumber: ""${random.long}"" uuid: ""${random.uuid}"" number-less-than-ten: ""${random.int(10)}"" number-in-range: ""${random.int[1024,65536]}"" ---- The `+random.int*+` syntax is `OPEN value (,max) CLOSE` where the `OPEN,CLOSE` are any character and `value,max` are integers. If `max` is provided, then `value` is the minimum value and `max` is the maximum value (exclusive). [[features.external-config.system-environment]] === Configuring System Environment Properties Spring Boot supports setting a prefix for environment properties. This is useful if the system environment is shared by multiple Spring Boot applications with different configuration requirements. The prefix for system environment properties can be set directly on `SpringApplication`. For example, if you set the prefix to `input`, a property such as `remote.timeout` will also be resolved as `input.remote.timeout` in the system environment. [[features.external-config.typesafe-configuration-properties]] === Type-safe Configuration Properties Using the `@Value(""$\\{property}"")` annotation to inject configuration properties can sometimes be cumbersome, especially if you are working with multiple properties or your data is hierarchical in nature. Spring Boot provides an alternative method of working with properties that lets strongly typed beans govern and validate the configuration of your application. TIP: See also the <>. [[features.external-config.typesafe-configuration-properties.java-bean-binding]] ==== JavaBean properties binding It is possible to bind a bean declaring standard JavaBean properties as shown in the following example: include::code:MyProperties[] The preceding POJO defines the following properties: * `my.service.enabled`, with a value of `false` by default. * `my.service.remote-address`, with a type that can be coerced from `String`. * `my.service.security.username`, with a nested ""security"" object whose name is determined by the name of the property. In particular, the type is not used at all there and could have been `SecurityProperties`. * `my.service.security.password`. * `my.service.security.roles`, with a collection of `String` that defaults to `USER`. NOTE: The properties that map to `@ConfigurationProperties` classes available in Spring Boot, which are configured through properties files, YAML files, environment variables, and other mechanisms, are public API but the accessors (getters/setters) of the class itself are not meant to be used directly. [NOTE] ==== Such arrangement relies on a default empty constructor and getters and setters are usually mandatory, since binding is through standard Java Beans property descriptors, just like in Spring MVC. A setter may be omitted in the following cases: * Maps, as long as they are initialized, need a getter but not necessarily a setter, since they can be mutated by the binder. * Collections and arrays can be accessed either through an index (typically with YAML) or by using a single comma-separated value (properties). In the latter case, a setter is mandatory. We recommend to always add a setter for such types. If you initialize a collection, make sure it is not immutable (as in the preceding example). * If nested POJO properties are initialized (like the `Security` field in the preceding example), a setter is not required. If you want the binder to create the instance on the fly by using its default constructor, you need a setter. Some people use Project Lombok to add getters and setters automatically. Make sure that Lombok does not generate any particular constructor for such a type, as it is used automatically by the container to instantiate the object. Finally, only standard Java Bean properties are considered and binding on static properties is not supported. ==== [[features.external-config.typesafe-configuration-properties.constructor-binding]] ==== Constructor binding The example in the previous section can be rewritten in an immutable fashion as shown in the following example: include::code:MyProperties[] In this setup, the presence of a single parameterized constructor implies that constructor binding should be used. This means that the binder will find a constructor with the parameters that you wish to have bound. If your class has multiple constructors, the `@ConstructorBinding` annotation can be used to specify which constructor to use for constructor binding. To opt out of constructor binding for a class with a single parameterized constructor, the constructor must be annotated with `@Autowired`. If you are using Java 16 or later, constructor binding can be used with records. Unless your record has multiple constructors, there is no need to use `@ConstructorBinding`. Nested members of a constructor bound class (such as `Security` in the example above) will also be bound through their constructor. Default values can be specified using `@DefaultValue` on constructor parameters and record components. The conversion service will be applied to coerce the annotation's `String` value to the target type of a missing property. Referring to the previous example, if no properties are bound to `Security`, the `MyProperties` instance will contain a `null` value for `security`. If you wish you return a non-null instance of `Security` even when no properties are bound to it, you can use an empty `@DefaultValue` annotation to do so: include::code:nonnull/MyProperties[tag=*] NOTE: To use constructor binding the class must be enabled using `@EnableConfigurationProperties` or configuration property scanning. You cannot use constructor binding with beans that are created by the regular Spring mechanisms (for example `@Component` beans, beans created by using `@Bean` methods or beans loaded by using `@Import`) NOTE: The use of `java.util.Optional` with `@ConfigurationProperties` is not recommended as it is primarily intended for use as a return type. As such, it is not well-suited to configuration property injection. For consistency with properties of other types, if you do declare an `Optional` property and it has no value, `null` rather than an empty `Optional` will be bound. [[features.external-config.typesafe-configuration-properties.enabling-annotated-types]] ==== Enabling @ConfigurationProperties-annotated types Spring Boot provides infrastructure to bind `@ConfigurationProperties` types and register them as beans. You can either enable configuration properties on a class-by-class basis or enable configuration property scanning that works in a similar manner to component scanning. Sometimes, classes annotated with `@ConfigurationProperties` might not be suitable for scanning, for example, if you're developing your own auto-configuration or you want to enable them conditionally. In these cases, specify the list of types to process using the `@EnableConfigurationProperties` annotation. This can be done on any `@Configuration` class, as shown in the following example: include::code:MyConfiguration[] To use configuration property scanning, add the `@ConfigurationPropertiesScan` annotation to your application. Typically, it is added to the main application class that is annotated with `@SpringBootApplication` but it can be added to any `@Configuration` class. By default, scanning will occur from the package of the class that declares the annotation. If you want to define specific packages to scan, you can do so as shown in the following example: include::code:MyApplication[] [NOTE] ==== When the `@ConfigurationProperties` bean is registered using configuration property scanning or through `@EnableConfigurationProperties`, the bean has a conventional name: `-`, where `` is the environment key prefix specified in the `@ConfigurationProperties` annotation and `` is the fully qualified name of the bean. If the annotation does not provide any prefix, only the fully qualified name of the bean is used. The bean name in the example above is `com.example.app-com.example.app.SomeProperties`. ==== We recommend that `@ConfigurationProperties` only deal with the environment and, in particular, does not inject other beans from the context. For corner cases, setter injection can be used or any of the `*Aware` interfaces provided by the framework (such as `EnvironmentAware` if you need access to the `Environment`). If you still want to inject other beans using the constructor, the configuration properties bean must be annotated with `@Component` and use JavaBean-based property binding. [[features.external-config.typesafe-configuration-properties.using-annotated-types]] ==== Using @ConfigurationProperties-annotated types This style of configuration works particularly well with the `SpringApplication` external YAML configuration, as shown in the following example: [source,yaml,indent=0,subs=""verbatim""] ---- my: service: remote-address: 192.168.1.1 security: username: ""admin"" roles: - ""USER"" - ""ADMIN"" ---- To work with `@ConfigurationProperties` beans, you can inject them in the same way as any other bean, as shown in the following example: include::code:MyService[] TIP: Using `@ConfigurationProperties` also lets you generate metadata files that can be used by IDEs to offer auto-completion for your own keys. See the <> for details. [[features.external-config.typesafe-configuration-properties.third-party-configuration]] ==== Third-party Configuration As well as using `@ConfigurationProperties` to annotate a class, you can also use it on public `@Bean` methods. Doing so can be particularly useful when you want to bind properties to third-party components that are outside of your control. To configure a bean from the `Environment` properties, add `@ConfigurationProperties` to its bean registration, as shown in the following example: include::code:ThirdPartyConfiguration[] Any JavaBean property defined with the `another` prefix is mapped onto that `AnotherComponent` bean in manner similar to the preceding `SomeProperties` example. [[features.external-config.typesafe-configuration-properties.relaxed-binding]] ==== Relaxed Binding Spring Boot uses some relaxed rules for binding `Environment` properties to `@ConfigurationProperties` beans, so there does not need to be an exact match between the `Environment` property name and the bean property name. Common examples where this is useful include dash-separated environment properties (for example, `context-path` binds to `contextPath`), and capitalized environment properties (for example, `PORT` binds to `port`). As an example, consider the following `@ConfigurationProperties` class: include::code:MyPersonProperties[] With the preceding code, the following properties names can all be used: .relaxed binding [cols=""1,4""] |=== | Property | Note | `my.main-project.person.first-name` | Kebab case, which is recommended for use in `.properties` and `.yml` files. | `my.main-project.person.firstName` | Standard camel case syntax. | `my.main-project.person.first_name` | Underscore notation, which is an alternative format for use in `.properties` and `.yml` files. | `MY_MAINPROJECT_PERSON_FIRSTNAME` | Upper case format, which is recommended when using system environment variables. |=== NOTE: The `prefix` value for the annotation _must_ be in kebab case (lowercase and separated by `-`, such as `my.main-project.person`). .relaxed binding rules per property source [cols=""2,4,4""] |=== | Property Source | Simple | List | Properties Files | Camel case, kebab case, or underscore notation | Standard list syntax using `[ ]` or comma-separated values | YAML Files | Camel case, kebab case, or underscore notation | Standard YAML list syntax or comma-separated values | Environment Variables | Upper case format with underscore as the delimiter (see <>). | Numeric values surrounded by underscores (see <>) | System properties | Camel case, kebab case, or underscore notation | Standard list syntax using `[ ]` or comma-separated values |=== TIP: We recommend that, when possible, properties are stored in lower-case kebab format, such as `my.person.first-name=Rod`. [[features.external-config.typesafe-configuration-properties.relaxed-binding.maps]] ===== Binding Maps When binding to `Map` properties you may need to use a special bracket notation so that the original `key` value is preserved. If the key is not surrounded by `[]`, any characters that are not alpha-numeric, `-` or `.` are removed. For example, consider binding the following properties to a `Map`: [source,properties,indent=0,subs=""verbatim"",role=""primary""] .Properties ---- my.map.[/key1]=value1 my.map.[/key2]=value2 my.map./key3=value3 ---- [source,yaml,indent=0,subs=""verbatim"",role=""secondary""] .Yaml ---- my: map: ""[/key1]"": ""value1"" ""[/key2]"": ""value2"" ""/key3"": ""value3"" ---- NOTE: For YAML files, the brackets need to be surrounded by quotes for the keys to be parsed properly. The properties above will bind to a `Map` with `/key1`, `/key2` and `key3` as the keys in the map. The slash has been removed from `key3` because it was not surrounded by square brackets. When binding to scalar values, keys with `.` in them do not need to be surrounded by `[]`. Scalar values include enums and all types in the `java.lang` package except for `Object`. Binding `a.b=c` to `Map` will preserve the `.` in the key and return a Map with the entry `{""a.b""=""c""}`. For any other types you need to use the bracket notation if your `key` contains a `.`. For example, binding `a.b=c` to `Map` will return a Map with the entry `{""a""={""b""=""c""}}` whereas `[a.b]=c` will return a Map with the entry `{""a.b""=""c""}`. [[features.external-config.typesafe-configuration-properties.relaxed-binding.environment-variables]] ===== Binding from Environment Variables Most operating systems impose strict rules around the names that can be used for environment variables. For example, Linux shell variables can contain only letters (`a` to `z` or `A` to `Z`), numbers (`0` to `9`) or the underscore character (`_`). By convention, Unix shell variables will also have their names in UPPERCASE. Spring Boot's relaxed binding rules are, as much as possible, designed to be compatible with these naming restrictions. To convert a property name in the canonical-form to an environment variable name you can follow these rules: * Replace dots (`.`) with underscores (`_`). * Remove any dashes (`-`). * Convert to uppercase. For example, the configuration property `spring.main.log-startup-info` would be an environment variable named `SPRING_MAIN_LOGSTARTUPINFO`. Environment variables can also be used when binding to object lists. To bind to a `List`, the element number should be surrounded with underscores in the variable name. For example, the configuration property `my.service[0].other` would use an environment variable named `MY_SERVICE_0_OTHER`. [[features.external-config.typesafe-configuration-properties.merging-complex-types]] ==== Merging Complex Types When lists are configured in more than one place, overriding works by replacing the entire list. For example, assume a `MyPojo` object with `name` and `description` attributes that are `null` by default. The following example exposes a list of `MyPojo` objects from `MyProperties`: include::code:list/MyProperties[] Consider the following configuration: [source,yaml,indent=0,subs=""verbatim"",configblocks] ---- my: list: - name: ""my name"" description: ""my description"" --- spring: config: activate: on-profile: ""dev"" my: list: - name: ""my another name"" ---- If the `dev` profile is not active, `MyProperties.list` contains one `MyPojo` entry, as previously defined. If the `dev` profile is enabled, however, the `list` _still_ contains only one entry (with a name of `my another name` and a description of `null`). This configuration _does not_ add a second `MyPojo` instance to the list, and it does not merge the items. When a `List` is specified in multiple profiles, the one with the highest priority (and only that one) is used. Consider the following example: [source,yaml,indent=0,subs=""verbatim"",configblocks] ---- my: list: - name: ""my name"" description: ""my description"" - name: ""another name"" description: ""another description"" --- spring: config: activate: on-profile: ""dev"" my: list: - name: ""my another name"" ---- In the preceding example, if the `dev` profile is active, `MyProperties.list` contains _one_ `MyPojo` entry (with a name of `my another name` and a description of `null`). For YAML, both comma-separated lists and YAML lists can be used for completely overriding the contents of the list. For `Map` properties, you can bind with property values drawn from multiple sources. However, for the same property in multiple sources, the one with the highest priority is used. The following example exposes a `Map` from `MyProperties`: include::code:map/MyProperties[] Consider the following configuration: [source,yaml,indent=0,subs=""verbatim"",configblocks] ---- my: map: key1: name: ""my name 1"" description: ""my description 1"" --- spring: config: activate: on-profile: ""dev"" my: map: key1: name: ""dev name 1"" key2: name: ""dev name 2"" description: ""dev description 2"" ---- If the `dev` profile is not active, `MyProperties.map` contains one entry with key `key1` (with a name of `my name 1` and a description of `my description 1`). If the `dev` profile is enabled, however, `map` contains two entries with keys `key1` (with a name of `dev name 1` and a description of `my description 1`) and `key2` (with a name of `dev name 2` and a description of `dev description 2`). NOTE: The preceding merging rules apply to properties from all property sources, and not just files. [[features.external-config.typesafe-configuration-properties.conversion]] ==== Properties Conversion Spring Boot attempts to coerce the external application properties to the right type when it binds to the `@ConfigurationProperties` beans. If you need custom type conversion, you can provide a `ConversionService` bean (with a bean named `conversionService`) or custom property editors (through a `CustomEditorConfigurer` bean) or custom `Converters` (with bean definitions annotated as `@ConfigurationPropertiesBinding`). NOTE: As this bean is requested very early during the application lifecycle, make sure to limit the dependencies that your `ConversionService` is using. Typically, any dependency that you require may not be fully initialized at creation time. You may want to rename your custom `ConversionService` if it is not required for configuration keys coercion and only rely on custom converters qualified with `@ConfigurationPropertiesBinding`. [[features.external-config.typesafe-configuration-properties.conversion.durations]] ===== Converting Durations Spring Boot has dedicated support for expressing durations. If you expose a `java.time.Duration` property, the following formats in application properties are available: * A regular `long` representation (using milliseconds as the default unit unless a `@DurationUnit` has been specified) * The standard ISO-8601 format {java-api}/java/time/Duration.html#parse-java.lang.CharSequence-[used by `java.time.Duration`] * A more readable format where the value and the unit are coupled (`10s` means 10 seconds) Consider the following example: include::code:javabeanbinding/MyProperties[] To specify a session timeout of 30 seconds, `30`, `PT30S` and `30s` are all equivalent. A read timeout of 500ms can be specified in any of the following form: `500`, `PT0.5S` and `500ms`. You can also use any of the supported units. These are: * `ns` for nanoseconds * `us` for microseconds * `ms` for milliseconds * `s` for seconds * `m` for minutes * `h` for hours * `d` for days The default unit is milliseconds and can be overridden using `@DurationUnit` as illustrated in the sample above. If you prefer to use constructor binding, the same properties can be exposed, as shown in the following example: include::code:constructorbinding/MyProperties[] TIP: If you are upgrading a `Long` property, make sure to define the unit (using `@DurationUnit`) if it is not milliseconds. Doing so gives a transparent upgrade path while supporting a much richer format. [[features.external-config.typesafe-configuration-properties.conversion.periods]] ===== Converting periods In addition to durations, Spring Boot can also work with `java.time.Period` type. The following formats can be used in application properties: * An regular `int` representation (using days as the default unit unless a `@PeriodUnit` has been specified) * The standard ISO-8601 format {java-api}/java/time/Period.html#parse-java.lang.CharSequence-[used by `java.time.Period`] * A simpler format where the value and the unit pairs are coupled (`1y3d` means 1 year and 3 days) The following units are supported with the simple format: * `y` for years * `m` for months * `w` for weeks * `d` for days NOTE: The `java.time.Period` type never actually stores the number of weeks, it is a shortcut that means ""`7 days`"". [[features.external-config.typesafe-configuration-properties.conversion.data-sizes]] ===== Converting Data Sizes Spring Framework has a `DataSize` value type that expresses a size in bytes. If you expose a `DataSize` property, the following formats in application properties are available: * A regular `long` representation (using bytes as the default unit unless a `@DataSizeUnit` has been specified) * A more readable format where the value and the unit are coupled (`10MB` means 10 megabytes) Consider the following example: include::code:javabeanbinding/MyProperties[] To specify a buffer size of 10 megabytes, `10` and `10MB` are equivalent. A size threshold of 256 bytes can be specified as `256` or `256B`. You can also use any of the supported units. These are: * `B` for bytes * `KB` for kilobytes * `MB` for megabytes * `GB` for gigabytes * `TB` for terabytes The default unit is bytes and can be overridden using `@DataSizeUnit` as illustrated in the sample above. If you prefer to use constructor binding, the same properties can be exposed, as shown in the following example: include::code:constructorbinding/MyProperties[] TIP: If you are upgrading a `Long` property, make sure to define the unit (using `@DataSizeUnit`) if it is not bytes. Doing so gives a transparent upgrade path while supporting a much richer format. [[features.external-config.typesafe-configuration-properties.validation]] ==== @ConfigurationProperties Validation Spring Boot attempts to validate `@ConfigurationProperties` classes whenever they are annotated with Spring's `@Validated` annotation. You can use JSR-303 `javax.validation` constraint annotations directly on your configuration class. To do so, ensure that a compliant JSR-303 implementation is on your classpath and then add constraint annotations to your fields, as shown in the following example: include::code:MyProperties[] TIP: You can also trigger validation by annotating the `@Bean` method that creates the configuration properties with `@Validated`. To ensure that validation is always triggered for nested properties, even when no properties are found, the associated field must be annotated with `@Valid`. The following example builds on the preceding `MyProperties` example: include::code:nested/MyProperties[] You can also add a custom Spring `Validator` by creating a bean definition called `configurationPropertiesValidator`. The `@Bean` method should be declared `static`. The configuration properties validator is created very early in the application's lifecycle, and declaring the `@Bean` method as static lets the bean be created without having to instantiate the `@Configuration` class. Doing so avoids any problems that may be caused by early instantiation. TIP: The `spring-boot-actuator` module includes an endpoint that exposes all `@ConfigurationProperties` beans. Point your web browser to `/actuator/configprops` or use the equivalent JMX endpoint. See the ""<>"" section for details. [[features.external-config.typesafe-configuration-properties.vs-value-annotation]] ==== @ConfigurationProperties vs. @Value The `@Value` annotation is a core container feature, and it does not provide the same features as type-safe configuration properties. The following table summarizes the features that are supported by `@ConfigurationProperties` and `@Value`: [cols=""4,2,2""] |=== | Feature |`@ConfigurationProperties` |`@Value` | <> | Yes | Limited (see <>) | <> | Yes | No | `SpEL` evaluation | No | Yes |=== [[features.external-config.typesafe-configuration-properties.vs-value-annotation.note]] NOTE: If you do want to use `@Value`, we recommend that you refer to property names using their canonical form (kebab-case using only lowercase letters). This will allow Spring Boot to use the same logic as it does when relaxed binding `@ConfigurationProperties`. For example, `@Value(""{demo.item-price}"")` will pick up `demo.item-price` and `demo.itemPrice` forms from the `application.properties` file, as well as `DEMO_ITEMPRICE` from the system environment. If you used `@Value(""{demo.itemPrice}"")` instead, `demo.item-price` and `DEMO_ITEMPRICE` would not be considered. If you define a set of configuration keys for your own components, we recommend you group them in a POJO annotated with `@ConfigurationProperties`. Doing so will provide you with structured, type-safe object that you can inject into your own beans. `SpEL` expressions from <> are not processed at time of parsing these files and populating the environment. However, it is possible to write a `SpEL` expression in `@Value`. If the value of a property from an application property file is a `SpEL` expression, it will be evaluated when consumed through `@Value`. ",12429,False,2158.919351606891,median "== AMQP Component *Available as of Camel version 1.2* The *amqp:* component supports the http://www.amqp.org/[AMQP 1.0 protocol] using the JMS Client API of the http://qpid.apache.org/[Qpid] project. In case you want to use AMQP 0.9 (in particular RabbitMQ) you might also be interested in the link:rabbitmq.html[Camel RabbitMQ] component. Please keep in mind that prior to the Camel 2.17.0 AMQP component supported AMQP 0.9 and above, however since Camel 2.17.0 it supports only AMQP 1.0. Maven users will need to add the following dependency to their `pom.xml` for this component: [source,xml] ------------------------------------------------------------------------------------------------ org.apache.camel camel-amqp ${camel.version} ------------------------------------------------------------------------------------------------ ### URI format [source,java] --------------------------------------------- amqp:[queue:|topic:]destinationName[?options] --------------------------------------------- ### AMQP Options You can specify all of the various configuration options of the link:../../../../camel-jms/src/main/docs/readme.html[JMS] component after the destination name. // component options: START The AMQP component supports 78 options which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *configuration* (advanced) | To use a shared JMS configuration | | JmsConfiguration | *acceptMessagesWhile Stopping* (consumer) | Specifies whether the consumer accept messages while it is stopping. You may consider enabling this option if you start and stop JMS routes at runtime while there are still messages enqueued on the queue. If this option is false and you stop the JMS route then messages may be rejected and the JMS broker would have to attempt redeliveries which yet again may be rejected and eventually the message may be moved at a dead letter queue on the JMS broker. To avoid this its recommended to enable this option. | false | boolean | *allowReplyManagerQuick Stop* (consumer) | Whether the DefaultMessageListenerContainer used in the reply managers for request-reply messaging allow the DefaultMessageListenerContainer.runningAllowed flag to quick stop in case JmsConfigurationisAcceptMessagesWhileStopping is enabled and org.apache.camel.CamelContext is currently being stopped. This quick stop ability is enabled by default in the regular JMS consumers but to enable for reply managers you must enable this flag. | false | boolean | *acknowledgementMode* (consumer) | The JMS acknowledgement mode defined as an Integer. Allows you to set vendor-specific extensions to the acknowledgment mode.For the regular modes it is preferable to use the acknowledgementModeName instead. | | int | *eagerLoadingOf Properties* (consumer) | Enables eager loading of JMS properties as soon as a message is loaded which generally is inefficient as the JMS properties may not be required but sometimes can catch early any issues with the underlying JMS provider and the use of JMS properties | false | boolean | *acknowledgementModeName* (consumer) | The JMS acknowledgement name which is one of: SESSION_TRANSACTED CLIENT_ACKNOWLEDGE AUTO_ACKNOWLEDGE DUPS_OK_ACKNOWLEDGE | AUTO_ ACKNOWLEDGE | String | *autoStartup* (consumer) | Specifies whether the consumer container should auto-startup. | true | boolean | *cacheLevel* (consumer) | Sets the cache level by ID for the underlying JMS resources. See cacheLevelName option for more details. | | int | *cacheLevelName* (consumer) | Sets the cache level by name for the underlying JMS resources. Possible values are: CACHE_AUTO CACHE_CONNECTION CACHE_CONSUMER CACHE_NONE and CACHE_SESSION. The default setting is CACHE_AUTO. See the Spring documentation and Transactions Cache Levels for more information. | CACHE_AUTO | String | *replyToCacheLevelName* (producer) | Sets the cache level by name for the reply consumer when doing request/reply over JMS. This option only applies when using fixed reply queues (not temporary). Camel will by default use: CACHE_CONSUMER for exclusive or shared w/ replyToSelectorName. And CACHE_SESSION for shared without replyToSelectorName. Some JMS brokers such as IBM WebSphere may require to set the replyToCacheLevelName=CACHE_NONE to work. Note: If using temporary queues then CACHE_NONE is not allowed and you must use a higher value such as CACHE_CONSUMER or CACHE_SESSION. | | String | *clientId* (common) | Sets the JMS client ID to use. Note that this value if specified must be unique and can only be used by a single JMS connection instance. It is typically only required for durable topic subscriptions. If using Apache ActiveMQ you may prefer to use Virtual Topics instead. | | String | *concurrentConsumers* (consumer) | Specifies the default number of concurrent consumers when consuming from JMS (not for request/reply over JMS). See also the maxMessagesPerTask option to control dynamic scaling up/down of threads. When doing request/reply over JMS then the option replyToConcurrentConsumers is used to control number of concurrent consumers on the reply message listener. | 1 | int | *replyToConcurrent Consumers* (producer) | Specifies the default number of concurrent consumers when doing request/reply over JMS. See also the maxMessagesPerTask option to control dynamic scaling up/down of threads. | 1 | int | *connectionFactory* (common) | The connection factory to be use. A connection factory must be configured either on the component or endpoint. | | ConnectionFactory | *username* (security) | Username to use with the ConnectionFactory. You can also configure username/password directly on the ConnectionFactory. | | String | *password* (security) | Password to use with the ConnectionFactory. You can also configure username/password directly on the ConnectionFactory. | | String | *deliveryPersistent* (producer) | Specifies whether persistent delivery is used by default. | true | boolean | *deliveryMode* (producer) | Specifies the delivery mode to be used. Possibles values are those defined by javax.jms.DeliveryMode. NON_PERSISTENT = 1 and PERSISTENT = 2. | | Integer | *durableSubscriptionName* (common) | The durable subscriber name for specifying durable topic subscriptions. The clientId option must be configured as well. | | String | *exceptionListener* (advanced) | Specifies the JMS Exception Listener that is to be notified of any underlying JMS exceptions. | | ExceptionListener | *errorHandler* (advanced) | Specifies a org.springframework.util.ErrorHandler to be invoked in case of any uncaught exceptions thrown while processing a Message. By default these exceptions will be logged at the WARN level if no errorHandler has been configured. You can configure logging level and whether stack traces should be logged using errorHandlerLoggingLevel and errorHandlerLogStackTrace options. This makes it much easier to configure than having to code a custom errorHandler. | | ErrorHandler | *errorHandlerLogging Level* (logging) | Allows to configure the default errorHandler logging level for logging uncaught exceptions. | WARN | LoggingLevel | *errorHandlerLogStack Trace* (logging) | Allows to control whether stacktraces should be logged or not by the default errorHandler. | true | boolean | *explicitQosEnabled* (producer) | Set if the deliveryMode priority or timeToLive qualities of service should be used when sending messages. This option is based on Spring's JmsTemplate. The deliveryMode priority and timeToLive options are applied to the current endpoint. This contrasts with the preserveMessageQos option which operates at message granularity reading QoS properties exclusively from the Camel In message headers. | false | boolean | *exposeListenerSession* (consumer) | Specifies whether the listener session should be exposed when consuming messages. | false | boolean | *idleTaskExecutionLimit* (advanced) | Specifies the limit for idle executions of a receive task not having received any message within its execution. If this limit is reached the task will shut down and leave receiving to other executing tasks (in the case of dynamic scheduling; see the maxConcurrentConsumers setting). There is additional doc available from Spring. | 1 | int | *idleConsumerLimit* (advanced) | Specify the limit for the number of consumers that are allowed to be idle at any given time. | 1 | int | *maxConcurrentConsumers* (consumer) | Specifies the maximum number of concurrent consumers when consuming from JMS (not for request/reply over JMS). See also the maxMessagesPerTask option to control dynamic scaling up/down of threads. When doing request/reply over JMS then the option replyToMaxConcurrentConsumers is used to control number of concurrent consumers on the reply message listener. | | int | *replyToMaxConcurrent Consumers* (producer) | Specifies the maximum number of concurrent consumers when using request/reply over JMS. See also the maxMessagesPerTask option to control dynamic scaling up/down of threads. | | int | *replyOnTimeoutToMax ConcurrentConsumers* (producer) | Specifies the maximum number of concurrent consumers for continue routing when timeout occurred when using request/reply over JMS. | 1 | int | *maxMessagesPerTask* (advanced) | The number of messages per task. -1 is unlimited. If you use a range for concurrent consumers (eg min max) then this option can be used to set a value to eg 100 to control how fast the consumers will shrink when less work is required. | -1 | int | *messageConverter* (advanced) | To use a custom Spring org.springframework.jms.support.converter.MessageConverter so you can be in control how to map to/from a javax.jms.Message. | | MessageConverter | *mapJmsMessage* (advanced) | Specifies whether Camel should auto map the received JMS message to a suited payload type such as javax.jms.TextMessage to a String etc. | true | boolean | *messageIdEnabled* (advanced) | When sending specifies whether message IDs should be added. This is just an hint to the JMS broker.If the JMS provider accepts this hint these messages must have the message ID set to null; if the provider ignores the hint the message ID must be set to its normal unique value | true | boolean | *messageTimestampEnabled* (advanced) | Specifies whether timestamps should be enabled by default on sending messages. This is just an hint to the JMS broker.If the JMS provider accepts this hint these messages must have the timestamp set to zero; if the provider ignores the hint the timestamp must be set to its normal value | true | boolean | *alwaysCopyMessage* (producer) | If true Camel will always make a JMS message copy of the message when it is passed to the producer for sending. Copying the message is needed in some situations such as when a replyToDestinationSelectorName is set (incidentally Camel will set the alwaysCopyMessage option to true if a replyToDestinationSelectorName is set) | false | boolean | *useMessageIDAs CorrelationID* (advanced) | Specifies whether JMSMessageID should always be used as JMSCorrelationID for InOut messages. | false | boolean | *priority* (producer) | Values greater than 1 specify the message priority when sending (where 0 is the lowest priority and 9 is the highest). The explicitQosEnabled option must also be enabled in order for this option to have any effect. | 4 | int | *pubSubNoLocal* (advanced) | Specifies whether to inhibit the delivery of messages published by its own connection. | false | boolean | *receiveTimeout* (advanced) | The timeout for receiving messages (in milliseconds). | 1000 | long | *recoveryInterval* (advanced) | Specifies the interval between recovery attempts i.e. when a connection is being refreshed in milliseconds. The default is 5000 ms that is 5 seconds. | 5000 | long | *taskExecutor* (consumer) | Allows you to specify a custom task executor for consuming messages. | | TaskExecutor | *timeToLive* (producer) | When sending messages specifies the time-to-live of the message (in milliseconds). | -1 | long | *transacted* (transaction) | Specifies whether to use transacted mode | false | boolean | *lazyCreateTransaction Manager* (transaction) | If true Camel will create a JmsTransactionManager if there is no transactionManager injected when option transacted=true. | true | boolean | *transactionManager* (transaction) | The Spring transaction manager to use. | | PlatformTransaction Manager | *transactionName* (transaction) | The name of the transaction to use. | | String | *transactionTimeout* (transaction) | The timeout value of the transaction (in seconds) if using transacted mode. | -1 | int | *testConnectionOn Startup* (common) | Specifies whether to test the connection on startup. This ensures that when Camel starts that all the JMS consumers have a valid connection to the JMS broker. If a connection cannot be granted then Camel throws an exception on startup. This ensures that Camel is not started with failed connections. The JMS producers is tested as well. | false | boolean | *asyncStartListener* (advanced) | Whether to startup the JmsConsumer message listener asynchronously when starting a route. For example if a JmsConsumer cannot get a connection to a remote JMS broker then it may block while retrying and/or failover. This will cause Camel to block while starting routes. By setting this option to true you will let routes startup while the JmsConsumer connects to the JMS broker using a dedicated thread in asynchronous mode. If this option is used then beware that if the connection could not be established then an exception is logged at WARN level and the consumer will not be able to receive messages; You can then restart the route to retry. | false | boolean | *asyncStopListener* (advanced) | Whether to stop the JmsConsumer message listener asynchronously when stopping a route. | false | boolean | *forceSendOriginal Message* (producer) | When using mapJmsMessage=false Camel will create a new JMS message to send to a new JMS destination if you touch the headers (get or set) during the route. Set this option to true to force Camel to send the original JMS message that was received. | false | boolean | *requestTimeout* (producer) | The timeout for waiting for a reply when using the InOut Exchange Pattern (in milliseconds). The default is 20 seconds. You can include the header CamelJmsRequestTimeout to override this endpoint configured timeout value and thus have per message individual timeout values. See also the requestTimeoutCheckerInterval option. | 20000 | long | *requestTimeoutChecker Interval* (advanced) | Configures how often Camel should check for timed out Exchanges when doing request/reply over JMS. By default Camel checks once per second. But if you must react faster when a timeout occurs then you can lower this interval to check more frequently. The timeout is determined by the option requestTimeout. | 1000 | long | *transferExchange* (advanced) | You can transfer the exchange over the wire instead of just the body and headers. The following fields are transferred: In body Out body Fault body In headers Out headers Fault headers exchange properties exchange exception. This requires that the objects are serializable. Camel will exclude any non-serializable objects and log it at WARN level. You must enable this option on both the producer and consumer side so Camel knows the payloads is an Exchange and not a regular payload. | false | boolean | *transferException* (advanced) | If enabled and you are using Request Reply messaging (InOut) and an Exchange failed on the consumer side then the caused Exception will be send back in response as a javax.jms.ObjectMessage. If the client is Camel the returned Exception is rethrown. This allows you to use Camel JMS as a bridge in your routing - for example using persistent queues to enable robust routing. Notice that if you also have transferExchange enabled this option takes precedence. The caught exception is required to be serializable. The original Exception on the consumer side can be wrapped in an outer exception such as org.apache.camel.RuntimeCamelException when returned to the producer. | false | boolean | *transferFault* (advanced) | If enabled and you are using Request Reply messaging (InOut) and an Exchange failed with a SOAP fault (not exception) on the consumer side then the fault flag on MessageisFault() will be send back in the response as a JMS header with the key org.apache.camel.component.jms.JmsConstantsJMS_TRANSFER_FAULTJMS_TRANSFER_FAULT. If the client is Camel the returned fault flag will be set on the link org.apache.camel.MessagesetFault(boolean). You may want to enable this when using Camel components that support faults such as SOAP based such as cxf or spring-ws. | false | boolean | *jmsOperations* (advanced) | Allows you to use your own implementation of the org.springframework.jms.core.JmsOperations interface. Camel uses JmsTemplate as default. Can be used for testing purpose but not used much as stated in the spring API docs. | | JmsOperations | *destinationResolver* (advanced) | A pluggable org.springframework.jms.support.destination.DestinationResolver that allows you to use your own resolver (for example to lookup the real destination in a JNDI registry). | | DestinationResolver | *replyToType* (producer) | Allows for explicitly specifying which kind of strategy to use for replyTo queues when doing request/reply over JMS. Possible values are: Temporary Shared or Exclusive. By default Camel will use temporary queues. However if replyTo has been configured then Shared is used by default. This option allows you to use exclusive queues instead of shared ones. See Camel JMS documentation for more details and especially the notes about the implications if running in a clustered environment and the fact that Shared reply queues has lower performance than its alternatives Temporary and Exclusive. | | ReplyToType | *preserveMessageQos* (producer) | Set to true if you want to send message using the QoS settings specified on the message instead of the QoS settings on the JMS endpoint. The following three headers are considered JMSPriority JMSDeliveryMode and JMSExpiration. You can provide all or only some of them. If not provided Camel will fall back to use the values from the endpoint instead. So when using this option the headers override the values from the endpoint. The explicitQosEnabled option by contrast will only use options set on the endpoint and not values from the message header. | false | boolean | *asyncConsumer* (consumer) | Whether the JmsConsumer processes the Exchange asynchronously. If enabled then the JmsConsumer may pickup the next message from the JMS queue while the previous message is being processed asynchronously (by the Asynchronous Routing Engine). This means that messages may be processed not 100 strictly in order. If disabled (as default) then the Exchange is fully processed before the JmsConsumer will pickup the next message from the JMS queue. Note if transacted has been enabled then asyncConsumer=true does not run asynchronously as transaction must be executed synchronously (Camel 3.0 may support async transactions). | false | boolean | *allowNullBody* (producer) | Whether to allow sending messages with no body. If this option is false and the message body is null then an JMSException is thrown. | true | boolean | *includeSentJMS MessageID* (producer) | Only applicable when sending to JMS destination using InOnly (eg fire and forget). Enabling this option will enrich the Camel Exchange with the actual JMSMessageID that was used by the JMS client when the message was sent to the JMS destination. | false | boolean | *includeAllJMSX Properties* (advanced) | Whether to include all JMSXxxx properties when mapping from JMS to Camel Message. Setting this to true will include properties such as JMSXAppID and JMSXUserID etc. Note: If you are using a custom headerFilterStrategy then this option does not apply. | false | boolean | *defaultTaskExecutor Type* (consumer) | Specifies what default TaskExecutor type to use in the DefaultMessageListenerContainer for both consumer endpoints and the ReplyTo consumer of producer endpoints. Possible values: SimpleAsync (uses Spring's SimpleAsyncTaskExecutor) or ThreadPool (uses Spring's ThreadPoolTaskExecutor with optimal values - cached threadpool-like). If not set it defaults to the previous behaviour which uses a cached thread pool for consumer endpoints and SimpleAsync for reply consumers. The use of ThreadPool is recommended to reduce thread trash in elastic configurations with dynamically increasing and decreasing concurrent consumers. | | DefaultTaskExecutor Type | *jmsKeyFormatStrategy* (advanced) | Pluggable strategy for encoding and decoding JMS keys so they can be compliant with the JMS specification. Camel provides two implementations out of the box: default and passthrough. The default strategy will safely marshal dots and hyphens (. and -). The passthrough strategy leaves the key as is. Can be used for JMS brokers which do not care whether JMS header keys contain illegal characters. You can provide your own implementation of the org.apache.camel.component.jms.JmsKeyFormatStrategy and refer to it using the notation. | | JmsKeyFormatStrategy | *allowAdditionalHeaders* (producer) | This option is used to allow additional headers which may have values that are invalid according to JMS specification. For example some message systems such as WMQ do this with header names using prefix JMS_IBM_MQMD_ containing values with byte array or other invalid types. You can specify multiple header names separated by comma and use as suffix for wildcard matching. | | String | *queueBrowseStrategy* (advanced) | To use a custom QueueBrowseStrategy when browsing queues | | QueueBrowseStrategy | *messageCreatedStrategy* (advanced) | To use the given MessageCreatedStrategy which are invoked when Camel creates new instances of javax.jms.Message objects when Camel is sending a JMS message. | | MessageCreatedStrategy | *waitForProvision CorrelationToBeUpdated Counter* (advanced) | Number of times to wait for provisional correlation id to be updated to the actual correlation id when doing request/reply over JMS and when the option useMessageIDAsCorrelationID is enabled. | 50 | int | *waitForProvision CorrelationToBeUpdated ThreadSleepingTime* (advanced) | Interval in millis to sleep each time while waiting for provisional correlation id to be updated. | 100 | long | *correlationProperty* (producer) | Use this JMS property to correlate messages in InOut exchange pattern (request-reply) instead of JMSCorrelationID property. This allows you to exchange messages with systems that do not correlate messages using JMSCorrelationID JMS property. If used JMSCorrelationID will not be used or set by Camel. The value of here named property will be generated if not supplied in the header of the message under the same name. | | String | *subscriptionDurable* (consumer) | Set whether to make the subscription durable. The durable subscription name to be used can be specified through the subscriptionName property. Default is false. Set this to true to register a durable subscription typically in combination with a subscriptionName value (unless your message listener class name is good enough as subscription name). Only makes sense when listening to a topic (pub-sub domain) therefore this method switches the pubSubDomain flag as well. | false | boolean | *subscriptionShared* (consumer) | Set whether to make the subscription shared. The shared subscription name to be used can be specified through the subscriptionName property. Default is false. Set this to true to register a shared subscription typically in combination with a subscriptionName value (unless your message listener class name is good enough as subscription name). Note that shared subscriptions may also be durable so this flag can (and often will) be combined with subscriptionDurable as well. Only makes sense when listening to a topic (pub-sub domain) therefore this method switches the pubSubDomain flag as well. Requires a JMS 2.0 compatible message broker. | false | boolean | *subscriptionName* (consumer) | Set the name of a subscription to create. To be applied in case of a topic (pub-sub domain) with a shared or durable subscription. The subscription name needs to be unique within this client's JMS client id. Default is the class name of the specified message listener. Note: Only 1 concurrent consumer (which is the default of this message listener container) is allowed for each subscription except for a shared subscription (which requires JMS 2.0). | | String | *headerFilterStrategy* (filter) | To use a custom org.apache.camel.spi.HeaderFilterStrategy to filter header to and from Camel message. | | HeaderFilterStrategy | *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 AMQP endpoint is configured using URI syntax: ---- amqp:destinationType:destinationName ---- with the following path and query parameters: ==== Path Parameters (2 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *destinationType* | The kind of destination to use | queue | String | *destinationName* | *Required* Name of the queue or topic to use as destination | | String |=== ==== Query Parameters (89 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *clientId* (common) | Sets the JMS client ID to use. Note that this value if specified must be unique and can only be used by a single JMS connection instance. It is typically only required for durable topic subscriptions. If using Apache ActiveMQ you may prefer to use Virtual Topics instead. | | String | *connectionFactory* (common) | The connection factory to be use. A connection factory must be configured either on the component or endpoint. | | ConnectionFactory | *disableReplyTo* (common) | If true a producer will behave like a InOnly exchange with the exception that JMSReplyTo header is sent out and not be suppressed like in the case of InOnly. Like InOnly the producer will not wait for a reply. A consumer with this flag will behave like InOnly. This feature can be used to bridge InOut requests to another queue so that a route on the other queue will send its response directly back to the original JMSReplyTo. | false | boolean | *durableSubscriptionName* (common) | The durable subscriber name for specifying durable topic subscriptions. The clientId option must be configured as well. | | String | *jmsMessageType* (common) | Allows you to force the use of a specific javax.jms.Message implementation for sending JMS messages. Possible values are: Bytes Map Object Stream Text. By default Camel would determine which JMS message type to use from the In body type. This option allows you to specify it. | | JmsMessageType | *testConnectionOnStartup* (common) | Specifies whether to test the connection on startup. This ensures that when Camel starts that all the JMS consumers have a valid connection to the JMS broker. If a connection cannot be granted then Camel throws an exception on startup. This ensures that Camel is not started with failed connections. The JMS producers is tested as well. | false | boolean | *acknowledgementModeName* (consumer) | The JMS acknowledgement name which is one of: SESSION_TRANSACTED CLIENT_ACKNOWLEDGE AUTO_ACKNOWLEDGE DUPS_OK_ACKNOWLEDGE | AUTO_ ACKNOWLEDGE | String | *asyncConsumer* (consumer) | Whether the JmsConsumer processes the Exchange asynchronously. If enabled then the JmsConsumer may pickup the next message from the JMS queue while the previous message is being processed asynchronously (by the Asynchronous Routing Engine). This means that messages may be processed not 100 strictly in order. If disabled (as default) then the Exchange is fully processed before the JmsConsumer will pickup the next message from the JMS queue. Note if transacted has been enabled then asyncConsumer=true does not run asynchronously as transaction must be executed synchronously (Camel 3.0 may support async transactions). | false | boolean | *autoStartup* (consumer) | Specifies whether the consumer container should auto-startup. | true | boolean | *bridgeErrorHandler* (consumer) | Allows for bridging the consumer to the Camel routing Error Handler which mean any exceptions occurred while the consumer is trying to pickup incoming messages or the likes will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions that will be logged at WARN or ERROR level and ignored. | false | boolean | *cacheLevel* (consumer) | Sets the cache level by ID for the underlying JMS resources. See cacheLevelName option for more details. | | int | *cacheLevelName* (consumer) | Sets the cache level by name for the underlying JMS resources. Possible values are: CACHE_AUTO CACHE_CONNECTION CACHE_CONSUMER CACHE_NONE and CACHE_SESSION. The default setting is CACHE_AUTO. See the Spring documentation and Transactions Cache Levels for more information. | CACHE_AUTO | String | *concurrentConsumers* (consumer) | Specifies the default number of concurrent consumers when consuming from JMS (not for request/reply over JMS). See also the maxMessagesPerTask option to control dynamic scaling up/down of threads. When doing request/reply over JMS then the option replyToConcurrentConsumers is used to control number of concurrent consumers on the reply message listener. | 1 | int | *maxConcurrentConsumers* (consumer) | Specifies the maximum number of concurrent consumers when consuming from JMS (not for request/reply over JMS). See also the maxMessagesPerTask option to control dynamic scaling up/down of threads. When doing request/reply over JMS then the option replyToMaxConcurrentConsumers is used to control number of concurrent consumers on the reply message listener. | | int | *replyTo* (consumer) | Provides an explicit ReplyTo destination which overrides any incoming value of Message.getJMSReplyTo(). | | String | *replyToDeliveryPersistent* (consumer) | Specifies whether to use persistent delivery by default for replies. | true | boolean | *selector* (consumer) | Sets the JMS selector to use | | String | *subscriptionDurable* (consumer) | Set whether to make the subscription durable. The durable subscription name to be used can be specified through the subscriptionName property. Default is false. Set this to true to register a durable subscription typically in combination with a subscriptionName value (unless your message listener class name is good enough as subscription name). Only makes sense when listening to a topic (pub-sub domain) therefore this method switches the pubSubDomain flag as well. | false | boolean | *subscriptionName* (consumer) | Set the name of a subscription to create. To be applied in case of a topic (pub-sub domain) with a shared or durable subscription. The subscription name needs to be unique within this client's JMS client id. Default is the class name of the specified message listener. Note: Only 1 concurrent consumer (which is the default of this message listener container) is allowed for each subscription except for a shared subscription (which requires JMS 2.0). | | String | *subscriptionShared* (consumer) | Set whether to make the subscription shared. The shared subscription name to be used can be specified through the subscriptionName property. Default is false. Set this to true to register a shared subscription typically in combination with a subscriptionName value (unless your message listener class name is good enough as subscription name). Note that shared subscriptions may also be durable so this flag can (and often will) be combined with subscriptionDurable as well. Only makes sense when listening to a topic (pub-sub domain) therefore this method switches the pubSubDomain flag as well. Requires a JMS 2.0 compatible message broker. | false | boolean | *acceptMessagesWhileStopping* (consumer) | Specifies whether the consumer accept messages while it is stopping. You may consider enabling this option if you start and stop JMS routes at runtime while there are still messages enqueued on the queue. If this option is false and you stop the JMS route then messages may be rejected and the JMS broker would have to attempt redeliveries which yet again may be rejected and eventually the message may be moved at a dead letter queue on the JMS broker. To avoid this its recommended to enable this option. | false | boolean | *allowReplyManagerQuickStop* (consumer) | Whether the DefaultMessageListenerContainer used in the reply managers for request-reply messaging allow the DefaultMessageListenerContainer.runningAllowed flag to quick stop in case JmsConfigurationisAcceptMessagesWhileStopping is enabled and org.apache.camel.CamelContext is currently being stopped. This quick stop ability is enabled by default in the regular JMS consumers but to enable for reply managers you must enable this flag. | false | boolean | *consumerType* (consumer) | The consumer type to use which can be one of: Simple Default or Custom. The consumer type determines which Spring JMS listener to use. Default will use org.springframework.jms.listener.DefaultMessageListenerContainer Simple will use org.springframework.jms.listener.SimpleMessageListenerContainer. When Custom is specified the MessageListenerContainerFactory defined by the messageListenerContainerFactory option will determine what org.springframework.jms.listener.AbstractMessageListenerContainer to use. | Default | ConsumerType | *defaultTaskExecutorType* (consumer) | Specifies what default TaskExecutor type to use in the DefaultMessageListenerContainer for both consumer endpoints and the ReplyTo consumer of producer endpoints. Possible values: SimpleAsync (uses Spring's SimpleAsyncTaskExecutor) or ThreadPool (uses Spring's ThreadPoolTaskExecutor with optimal values - cached threadpool-like). If not set it defaults to the previous behaviour which uses a cached thread pool for consumer endpoints and SimpleAsync for reply consumers. The use of ThreadPool is recommended to reduce thread trash in elastic configurations with dynamically increasing and decreasing concurrent consumers. | | DefaultTaskExecutor Type | *eagerLoadingOfProperties* (consumer) | Enables eager loading of JMS properties as soon as a message is loaded which generally is inefficient as the JMS properties may not be required but sometimes can catch early any issues with the underlying JMS provider and the use of JMS properties | false | boolean | *exceptionHandler* (consumer) | To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this options 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 | *exposeListenerSession* (consumer) | Specifies whether the listener session should be exposed when consuming messages. | false | boolean | *replyToSameDestination Allowed* (consumer) | Whether a JMS consumer is allowed to send a reply message to the same destination that the consumer is using to consume from. This prevents an endless loop by consuming and sending back the same message to itself. | false | boolean | *taskExecutor* (consumer) | Allows you to specify a custom task executor for consuming messages. | | TaskExecutor | *deliveryMode* (producer) | Specifies the delivery mode to be used. Possibles values are those defined by javax.jms.DeliveryMode. NON_PERSISTENT = 1 and PERSISTENT = 2. | | Integer | *deliveryPersistent* (producer) | Specifies whether persistent delivery is used by default. | true | boolean | *explicitQosEnabled* (producer) | Set if the deliveryMode priority or timeToLive qualities of service should be used when sending messages. This option is based on Spring's JmsTemplate. The deliveryMode priority and timeToLive options are applied to the current endpoint. This contrasts with the preserveMessageQos option which operates at message granularity reading QoS properties exclusively from the Camel In message headers. | false | Boolean | *preserveMessageQos* (producer) | Set to true if you want to send message using the QoS settings specified on the message instead of the QoS settings on the JMS endpoint. The following three headers are considered JMSPriority JMSDeliveryMode and JMSExpiration. You can provide all or only some of them. If not provided Camel will fall back to use the values from the endpoint instead. So when using this option the headers override the values from the endpoint. The explicitQosEnabled option by contrast will only use options set on the endpoint and not values from the message header. | false | boolean | *priority* (producer) | Values greater than 1 specify the message priority when sending (where 0 is the lowest priority and 9 is the highest). The explicitQosEnabled option must also be enabled in order for this option to have any effect. | 4 | int | *replyToConcurrentConsumers* (producer) | Specifies the default number of concurrent consumers when doing request/reply over JMS. See also the maxMessagesPerTask option to control dynamic scaling up/down of threads. | 1 | int | *replyToMaxConcurrent Consumers* (producer) | Specifies the maximum number of concurrent consumers when using request/reply over JMS. See also the maxMessagesPerTask option to control dynamic scaling up/down of threads. | | int | *replyToOnTimeoutMax ConcurrentConsumers* (producer) | Specifies the maximum number of concurrent consumers for continue routing when timeout occurred when using request/reply over JMS. | 1 | int | *replyToOverride* (producer) | Provides an explicit ReplyTo destination in the JMS message which overrides the setting of replyTo. It is useful if you want to forward the message to a remote Queue and receive the reply message from the ReplyTo destination. | | String | *replyToType* (producer) | Allows for explicitly specifying which kind of strategy to use for replyTo queues when doing request/reply over JMS. Possible values are: Temporary Shared or Exclusive. By default Camel will use temporary queues. However if replyTo has been configured then Shared is used by default. This option allows you to use exclusive queues instead of shared ones. See Camel JMS documentation for more details and especially the notes about the implications if running in a clustered environment and the fact that Shared reply queues has lower performance than its alternatives Temporary and Exclusive. | | ReplyToType | *requestTimeout* (producer) | The timeout for waiting for a reply when using the InOut Exchange Pattern (in milliseconds). The default is 20 seconds. You can include the header CamelJmsRequestTimeout to override this endpoint configured timeout value and thus have per message individual timeout values. See also the requestTimeoutCheckerInterval option. | 20000 | long | *timeToLive* (producer) | When sending messages specifies the time-to-live of the message (in milliseconds). | -1 | long | *allowAdditionalHeaders* (producer) | This option is used to allow additional headers which may have values that are invalid according to JMS specification. For example some message systems such as WMQ do this with header names using prefix JMS_IBM_MQMD_ containing values with byte array or other invalid types. You can specify multiple header names separated by comma and use as suffix for wildcard matching. | | String | *allowNullBody* (producer) | Whether to allow sending messages with no body. If this option is false and the message body is null then an JMSException is thrown. | true | boolean | *alwaysCopyMessage* (producer) | If true Camel will always make a JMS message copy of the message when it is passed to the producer for sending. Copying the message is needed in some situations such as when a replyToDestinationSelectorName is set (incidentally Camel will set the alwaysCopyMessage option to true if a replyToDestinationSelectorName is set) | false | boolean | *correlationProperty* (producer) | When using InOut exchange pattern use this JMS property instead of JMSCorrelationID JMS property to correlate messages. If set messages will be correlated solely on the value of this property JMSCorrelationID property will be ignored and not set by Camel. | | String | *disableTimeToLive* (producer) | Use this option to force disabling time to live. For example when you do request/reply over JMS then Camel will by default use the requestTimeout value as time to live on the message being sent. The problem is that the sender and receiver systems have to have their clocks synchronized so they are in sync. This is not always so easy to archive. So you can use disableTimeToLive=true to not set a time to live value on the sent message. Then the message will not expire on the receiver system. See below in section About time to live for more details. | false | boolean | *forceSendOriginalMessage* (producer) | When using mapJmsMessage=false Camel will create a new JMS message to send to a new JMS destination if you touch the headers (get or set) during the route. Set this option to true to force Camel to send the original JMS message that was received. | false | boolean | *includeSentJMSMessageID* (producer) | Only applicable when sending to JMS destination using InOnly (eg fire and forget). Enabling this option will enrich the Camel Exchange with the actual JMSMessageID that was used by the JMS client when the message was sent to the JMS destination. | false | boolean | *replyToCacheLevelName* (producer) | Sets the cache level by name for the reply consumer when doing request/reply over JMS. This option only applies when using fixed reply queues (not temporary). Camel will by default use: CACHE_CONSUMER for exclusive or shared w/ replyToSelectorName. And CACHE_SESSION for shared without replyToSelectorName. Some JMS brokers such as IBM WebSphere may require to set the replyToCacheLevelName=CACHE_NONE to work. Note: If using temporary queues then CACHE_NONE is not allowed and you must use a higher value such as CACHE_CONSUMER or CACHE_SESSION. | | String | *replyToDestinationSelector Name* (producer) | Sets the JMS Selector using the fixed name to be used so you can filter out your own replies from the others when using a shared queue (that is if you are not using a temporary reply queue). | | String | *allowSerializedHeaders* (advanced) | Controls whether or not to include serialized headers. Applies only when transferExchange is true. This requires that the objects are serializable. Camel will exclude any non-serializable objects and log it at WARN level. | false | boolean | *asyncStartListener* (advanced) | Whether to startup the JmsConsumer message listener asynchronously when starting a route. For example if a JmsConsumer cannot get a connection to a remote JMS broker then it may block while retrying and/or failover. This will cause Camel to block while starting routes. By setting this option to true you will let routes startup while the JmsConsumer connects to the JMS broker using a dedicated thread in asynchronous mode. If this option is used then beware that if the connection could not be established then an exception is logged at WARN level and the consumer will not be able to receive messages; You can then restart the route to retry. | false | boolean | *asyncStopListener* (advanced) | Whether to stop the JmsConsumer message listener asynchronously when stopping a route. | false | boolean | *destinationResolver* (advanced) | A pluggable org.springframework.jms.support.destination.DestinationResolver that allows you to use your own resolver (for example to lookup the real destination in a JNDI registry). | | DestinationResolver | *errorHandler* (advanced) | Specifies a org.springframework.util.ErrorHandler to be invoked in case of any uncaught exceptions thrown while processing a Message. By default these exceptions will be logged at the WARN level if no errorHandler has been configured. You can configure logging level and whether stack traces should be logged using errorHandlerLoggingLevel and errorHandlerLogStackTrace options. This makes it much easier to configure than having to code a custom errorHandler. | | ErrorHandler | *exceptionListener* (advanced) | Specifies the JMS Exception Listener that is to be notified of any underlying JMS exceptions. | | ExceptionListener | *headerFilterStrategy* (advanced) | To use a custom HeaderFilterStrategy to filter header to and from Camel message. | | HeaderFilterStrategy | *idleConsumerLimit* (advanced) | Specify the limit for the number of consumers that are allowed to be idle at any given time. | 1 | int | *idleTaskExecutionLimit* (advanced) | Specifies the limit for idle executions of a receive task not having received any message within its execution. If this limit is reached the task will shut down and leave receiving to other executing tasks (in the case of dynamic scheduling; see the maxConcurrentConsumers setting). There is additional doc available from Spring. | 1 | int | *includeAllJMSXProperties* (advanced) | Whether to include all JMSXxxx properties when mapping from JMS to Camel Message. Setting this to true will include properties such as JMSXAppID and JMSXUserID etc. Note: If you are using a custom headerFilterStrategy then this option does not apply. | false | boolean | *jmsKeyFormatStrategy* (advanced) | Pluggable strategy for encoding and decoding JMS keys so they can be compliant with the JMS specification. Camel provides two implementations out of the box: default and passthrough. The default strategy will safely marshal dots and hyphens (. and -). The passthrough strategy leaves the key as is. Can be used for JMS brokers which do not care whether JMS header keys contain illegal characters. You can provide your own implementation of the org.apache.camel.component.jms.JmsKeyFormatStrategy and refer to it using the notation. | | String | *mapJmsMessage* (advanced) | Specifies whether Camel should auto map the received JMS message to a suited payload type such as javax.jms.TextMessage to a String etc. | true | boolean | *maxMessagesPerTask* (advanced) | The number of messages per task. -1 is unlimited. If you use a range for concurrent consumers (eg min max) then this option can be used to set a value to eg 100 to control how fast the consumers will shrink when less work is required. | -1 | int | *messageConverter* (advanced) | To use a custom Spring org.springframework.jms.support.converter.MessageConverter so you can be in control how to map to/from a javax.jms.Message. | | MessageConverter | *messageCreatedStrategy* (advanced) | To use the given MessageCreatedStrategy which are invoked when Camel creates new instances of javax.jms.Message objects when Camel is sending a JMS message. | | MessageCreatedStrategy | *messageIdEnabled* (advanced) | When sending specifies whether message IDs should be added. This is just an hint to the JMS broker.If the JMS provider accepts this hint these messages must have the message ID set to null; if the provider ignores the hint the message ID must be set to its normal unique value | true | boolean | *messageListenerContainer Factory* (advanced) | Registry ID of the MessageListenerContainerFactory used to determine what org.springframework.jms.listener.AbstractMessageListenerContainer to use to consume messages. Setting this will automatically set consumerType to Custom. | | MessageListener ContainerFactory | *messageTimestampEnabled* (advanced) | Specifies whether timestamps should be enabled by default on sending messages. This is just an hint to the JMS broker.If the JMS provider accepts this hint these messages must have the timestamp set to zero; if the provider ignores the hint the timestamp must be set to its normal value | true | boolean | *pubSubNoLocal* (advanced) | Specifies whether to inhibit the delivery of messages published by its own connection. | false | boolean | *receiveTimeout* (advanced) | The timeout for receiving messages (in milliseconds). | 1000 | long | *recoveryInterval* (advanced) | Specifies the interval between recovery attempts i.e. when a connection is being refreshed in milliseconds. The default is 5000 ms that is 5 seconds. | 5000 | long | *requestTimeoutChecker Interval* (advanced) | Configures how often Camel should check for timed out Exchanges when doing request/reply over JMS. By default Camel checks once per second. But if you must react faster when a timeout occurs then you can lower this interval to check more frequently. The timeout is determined by the option requestTimeout. | 1000 | long | *synchronous* (advanced) | Sets whether synchronous processing should be strictly used or Camel is allowed to use asynchronous processing (if supported). | false | boolean | *transferException* (advanced) | If enabled and you are using Request Reply messaging (InOut) and an Exchange failed on the consumer side then the caused Exception will be send back in response as a javax.jms.ObjectMessage. If the client is Camel the returned Exception is rethrown. This allows you to use Camel JMS as a bridge in your routing - for example using persistent queues to enable robust routing. Notice that if you also have transferExchange enabled this option takes precedence. The caught exception is required to be serializable. The original Exception on the consumer side can be wrapped in an outer exception such as org.apache.camel.RuntimeCamelException when returned to the producer. | false | boolean | *transferExchange* (advanced) | You can transfer the exchange over the wire instead of just the body and headers. The following fields are transferred: In body Out body Fault body In headers Out headers Fault headers exchange properties exchange exception. This requires that the objects are serializable. Camel will exclude any non-serializable objects and log it at WARN level. You must enable this option on both the producer and consumer side so Camel knows the payloads is an Exchange and not a regular payload. | false | boolean | *transferFault* (advanced) | If enabled and you are using Request Reply messaging (InOut) and an Exchange failed with a SOAP fault (not exception) on the consumer side then the fault flag on MessageisFault() will be send back in the response as a JMS header with the key org.apache.camel.component.jms.JmsConstantsJMS_TRANSFER_FAULTJMS_TRANSFER_FAULT. If the client is Camel the returned fault flag will be set on the link org.apache.camel.MessagesetFault(boolean). You may want to enable this when using Camel components that support faults such as SOAP based such as cxf or spring-ws. | false | boolean | *useMessageIDAsCorrelation ID* (advanced) | Specifies whether JMSMessageID should always be used as JMSCorrelationID for InOut messages. | false | boolean | *waitForProvisionCorrelation ToBeUpdatedCounter* (advanced) | Number of times to wait for provisional correlation id to be updated to the actual correlation id when doing request/reply over JMS and when the option useMessageIDAsCorrelationID is enabled. | 50 | int | *waitForProvisionCorrelation ToBeUpdatedThreadSleeping Time* (advanced) | Interval in millis to sleep each time while waiting for provisional correlation id to be updated. | 100 | long | *errorHandlerLoggingLevel* (logging) | Allows to configure the default errorHandler logging level for logging uncaught exceptions. | WARN | LoggingLevel | *errorHandlerLogStackTrace* (logging) | Allows to control whether stacktraces should be logged or not by the default errorHandler. | true | boolean | *password* (security) | Password to use with the ConnectionFactory. You can also configure username/password directly on the ConnectionFactory. | | String | *username* (security) | Username to use with the ConnectionFactory. You can also configure username/password directly on the ConnectionFactory. | | String | *transacted* (transaction) | Specifies whether to use transacted mode | false | boolean | *lazyCreateTransaction Manager* (transaction) | If true Camel will create a JmsTransactionManager if there is no transactionManager injected when option transacted=true. | true | boolean | *transactionManager* (transaction) | The Spring transaction manager to use. | | PlatformTransaction Manager | *transactionName* (transaction) | The name of the transaction to use. | | String | *transactionTimeout* (transaction) | The timeout value of the transaction (in seconds) if using transacted mode. | -1 | int |=== // endpoint options: END ### Usage As AMQP component is inherited from JMS component, the usage of the former is almost identical to the latter: *Using AMQP component* [source,java] ------------------------------------ // Consuming from AMQP queue from(""amqp:queue:incoming""). to(...);   // Sending message to the AMQP topic from(...). to(""amqp:topic:notify""); ------------------------------------ ### Configuring AMQP component Starting from the Camel 2.16.1 you can also use the `AMQPComponent#amqp10Component(String connectionURI)` factory method to return the AMQP 1.0 component with the pre-configured topic prefix:  *Creating AMQP 1.0 component* [source,java] ----------------------------------------------------------------------------------------- AMQPComponent amqp = AMQPComponent.amqp10Component(""amqp://guest:guest@localhost:5672""); ----------------------------------------------------------------------------------------- Keep in mind that starting from the Camel 2.17 the `AMQPComponent#amqp10Component(String connectionURI)` factory method has been deprecated on the behalf of the `AMQPComponent#amqpComponent(String connectionURI)`:  *Creating AMQP 1.0 component* [source,java] -------------------------------------------------------------------------------------------------------- AMQPComponent amqp = AMQPComponent.amqpComponent(""amqp://localhost:5672"");   AMQPComponent authorizedAmqp = AMQPComponent.amqpComponent(""amqp://localhost:5672"", ""user"", ""password""); -------------------------------------------------------------------------------------------------------- Starting from Camel 2.17, in order to automatically configure the AMQP component, you can also add an instance of `org.apache.camel.component.amqp.AMQPConnectionDetails` to the registry. For example for Spring Boot you just have to define bean: *AMQP connection details auto-configuration* [source,java] ------------------------------------------------------------------------------------- @Bean AMQPConnectionDetails amqpConnection() { return new AMQPConnectionDetails(""amqp://localhost:5672""); }   @Bean AMQPConnectionDetails securedAmqpConnection() { return new AMQPConnectionDetails(""amqp://lcoalhost:5672"", ""username"", ""password""); } ------------------------------------------------------------------------------------- Likewise, you can also use CDI producer methods when using Camel-CDI *AMQP connection details auto-configuration for CDI* [source,java] ------------------------------------------------------------------------------------- @Produces AMQPConnectionDetails amqpConnection() { return new AMQPConnectionDetails(""amqp://localhost:5672""); } -------------------------------------------------------------------------------------  You can also rely on the link:properties.html[Camel properties] to read the AMQP connection details. Factory method `AMQPConnectionDetails.discoverAMQP()` attempts to read Camel properties in a Kubernetes-like convention, just as demonstrated on the snippet below:   *AMQP connection details auto-configuration* [source,java] ----------------------------------------------- export AMQP_SERVICE_HOST = ""mybroker.com"" export AMQP_SERVICE_PORT = ""6666"" export AMQP_SERVICE_USERNAME = ""username"" export AMQP_SERVICE_PASSWORD = ""password""   ...   @Bean AMQPConnectionDetails amqpConnection() { return AMQPConnectionDetails.discoverAMQP(); } ----------------------------------------------- ### Using topics To have using topics working with `camel-amqp` you need to configure the component to use `topic://` as topic prefix, as shown below: [source,java] ------------------------------------------------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------------------------------------------------- Keep in mind that both  `AMQPComponent#amqpComponent()` methods and `AMQPConnectionDetails` pre-configure the component with the topic prefix, so you don't have to configure it explicitly. ### See Also * link:configuring-camel.html[Configuring Camel] * link:component.html[Component] * link:endpoint.html[Endpoint] * link:getting-started.html[Getting Started] ",12294,True,2935.137490644197,median "pred test37 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2, Node3: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node3 Node = Node0 + Node1 + Node2 + Node3 no left right = Node0->Node1 + Node2->Node0 + Node3->Node2 elem = Node0->6 + Node1->6 + Node2->4 + Node3->-4 Sorted[] }} } run test37 for 4 expect 0 pred test64 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2, Node3: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node3 Node = Node0 + Node1 + Node2 + Node3 left = Node2->Node1 + Node3->Node2 right = Node3->Node0 elem = Node0->7 + Node1->0 + Node2->-2 + Node3->-5 Balanced[] }} } run test64 for 4 expect 1 pred test80 { some disj BinaryTree0: BinaryTree {some disj Node0: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node0 Node = Node0 left = Node0->Node0 no right elem = Node0->1 }} } run test80 for 4 expect 0 pred test4 { some disj BinaryTree0: BinaryTree { BinaryTree = BinaryTree0 no root no Node no left no right no elem } } run test4 for 4 expect 1 pred test1 { no BinaryTree no root no Node no left no right no elem } run test1 for 4 expect 0 pred test14 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node0->Node1 right = Node2->Node0 elem = Node0->7 + Node1->0 + Node2->-5 Sorted[] }} } run test14 for 4 expect 1 pred test54 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 left = Node1->Node0 no right elem = Node0->-6 + Node1->-5 HasAtMostOneChild[Node1] }} } run test54 for 4 expect 1 pred test71 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 left = Node1->Node0 no right elem = Node0->7 + Node1->-4 RepOk[] }} } run test71 for 4 expect 0 pred test57 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node0->Node1 + Node2->Node0 no right elem = Node0->7 + Node1->1 + Node2->-6 Balanced[] }} } run test57 for 4 expect 0 pred test13 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 left = Node1->Node0 no right elem = Node0->3 + Node1->0 Sorted[] }} } run test13 for 4 expect 0 pred test27 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2, Node3: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node3 Node = Node0 + Node1 + Node2 + Node3 left = Node3->Node2 right = Node1->Node0 + Node2->Node1 elem = Node0->3 + Node1->-1 + Node2->-5 + Node3->2 Sorted[] }} } run test27 for 4 expect 0 pred test41 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node0->Node1 right = Node2->Node0 elem = Node0->-5 + Node1->-8 + Node2->-8 Sorted[] }} } run test41 for 4 expect 0 pred test82 { some disj BinaryTree0: BinaryTree {some disj Node0: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node0 Node = Node0 no left right = Node0->Node0 elem = Node0->-2 }} } run test82 for 4 expect 0 pred test102 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node1->Node0 + Node2->Node1 no right elem = Node0->5 + Node1->5 + Node2->-1 }} } run test102 for 4 expect 1 pred test18 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 left = Node1->Node0 no right elem = Node0->4 + Node1->0 Sorted[] }} } run test18 for 4 expect 0 pred test36 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 no left right = Node1->Node0 elem = Node0->0 + Node1->-4 Sorted[] }} } run test36 for 4 expect 1 pred test101 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 no left right = Node1->Node0 elem = Node0->7 + Node1->0 }} } run test101 for 4 expect 1 pred test60 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node1->Node0 right = Node2->Node1 elem = Node0->7 + Node1->2 + Node2->1 Balanced[] }} } run test60 for 4 expect 0 pred test99 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node2->Node0 right = Node1->Node0 + Node2->Node1 elem = Node0->7 + Node1->6 + Node2->6 }} } run test99 for 4 expect 0 pred test88 { some disj BinaryTree0: BinaryTree {some disj Node0: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node0 Node = Node0 no left no right elem = Node0->-1 }} } run test88 for 4 expect 1 pred test25 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node2->Node1 right = Node1->Node0 elem = Node0->-3 + Node1->-7 + Node2->-3 Sorted[] }} } run test25 for 4 expect 0 pred test2 { some disj BinaryTree0, BinaryTree1: BinaryTree {some disj Node0, Node1, Node2, Node3: Node { BinaryTree = BinaryTree0 + BinaryTree1 root = BinaryTree1->Node3 Node = Node0 + Node1 + Node2 + Node3 left = Node1->Node0 + Node3->Node1 right = Node3->Node2 elem = Node0->6 + Node1->5 + Node2->1 + Node3->-8 }} } run test2 for 4 expect 0 pred test72 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node2->Node1 right = Node2->Node0 elem = Node0->3 + Node1->3 + Node2->2 RepOk[] }} } run test72 for 4 expect 0 pred test44 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 no left right = Node1->Node0 elem = Node0->1 + Node1->1 Sorted[] }} } run test44 for 4 expect 0 pred test68 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2, Node3: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node3 Node = Node0 + Node1 + Node2 + Node3 left = Node2->Node1 + Node3->Node2 right = Node3->Node0 elem = Node0->6 + Node1->3 + Node2->-7 + Node3->-8 Balanced[] }} } run test68 for 4 expect 1 pred test69 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2, Node3: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node3 Node = Node0 + Node1 + Node2 + Node3 left = Node2->Node1 + Node3->Node2 right = Node3->Node0 elem = Node0->7 + Node1->7 + Node2->6 + Node3->-1 Balanced[] }} } run test69 for 4 expect 1 pred test22 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 left = Node1->Node0 no right elem = Node0->1 + Node1->4 Sorted[] }} } run test22 for 4 expect 1 pred test56 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node2->Node1 right = Node1->Node0 elem = Node0->7 + Node1->7 + Node2->6 HasAtMostOneChild[Node2] }} } run test56 for 4 expect 1 pred test6 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 no left right = Node2->Node0 + Node2->Node1 elem = Node0->7 + Node1->6 + Node2->-8 }} } run test6 for 4 expect 0 pred test70 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2, Node3: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node3 Node = Node0 + Node1 + Node2 + Node3 left = Node2->Node1 + Node3->Node2 right = Node3->Node0 elem = Node0->7 + Node1->7 + Node2->-5 + Node3->-8 Balanced[] }} } run test70 for 4 expect 1 pred test10 { some disj BinaryTree0: BinaryTree {some disj Node0: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node0 Node = Node0 no left no right elem = Node0->-8 + Node0->-7 + Node0->-6 + Node0->-5 + Node0->-4 + Node0->-3 + Node0->-2 + Node0->-1 + Node0->0 + Node0->1 + Node0->2 + Node0->3 + Node0->4 + Node0->5 + Node0->6 + Node0->7 }} } run test10 for 4 expect 0 pred test45 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 no left right = Node1->Node0 elem = Node0->5 + Node1->5 Sorted[] }} } run test45 for 4 expect 0 pred test24 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2, Node3: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node3 Node = Node0 + Node1 + Node2 + Node3 left = Node0->Node1 + Node3->Node2 right = Node2->Node0 elem = Node0->6 + Node1->-7 + Node2->-8 + Node3->4 Sorted[] }} } run test24 for 4 expect 0 pred test42 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 no left right = Node1->Node0 elem = Node0->7 + Node1->6 Sorted[] }} } run test42 for 4 expect 1 pred test84 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 left = Node1->Node1 right = Node1->Node0 elem = Node0->-4 + Node1->-5 }} } run test84 for 4 expect 0 pred test87 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node0->Node1 + Node2->Node2 right = Node2->Node0 elem = Node0->7 + Node1->6 + Node2->4 }} } run test87 for 4 expect 0 pred test15 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 no left right = Node0->Node1 + Node2->Node0 elem = Node0->4 + Node1->2 + Node2->1 Sorted[] }} } run test15 for 4 expect 0 pred test43 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2, Node3: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node3 Node = Node0 + Node1 + Node2 + Node3 no left right = Node1->Node2 + Node2->Node0 + Node3->Node1 elem = Node0->7 + Node1->3 + Node2->2 + Node3->-2 Sorted[] }} } run test43 for 4 expect 0 pred test23 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 left = Node1->Node0 no right elem = Node0->0 + Node1->-2 Sorted[] }} } run test23 for 4 expect 0 pred test3 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node0 + BinaryTree0->Node1 Node = Node0 + Node1 left = Node0->Node1 no right elem = Node0->7 + Node1->6 }} } run test3 for 4 expect 0 pred test86 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node2->Node0 right = Node0->Node1 + Node2->Node0 elem = Node0->-6 + Node1->-7 + Node2->-8 }} } run test86 for 4 expect 0 pred test94 { some disj BinaryTree0: BinaryTree {some disj Node0: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node0 Node = Node0 no left no right elem = Node0->-4 }} } run test94 for 4 expect 1 pred test77 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node0 Node = Node0 + Node1 no left right = Node0->Node1 elem = Node0->7 + Node1->6 Depth[Node1] = 2 }} } run test77 for 4 expect 1 pred test103 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 left = Node1->Node0 no right elem = Node0->7 + Node1->0 }} } run test103 for 4 expect 1 pred test12 { some disj BinaryTree0: BinaryTree {some disj Node0: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node0 Node = Node0 no left no right elem = Node0->-1 Sorted[] }} } run test12 for 4 expect 1 pred test21 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 left = Node1->Node0 no right elem = Node0->3 + Node1->2 Sorted[] }} } run test21 for 4 expect 0 pred test110 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node1->Node0 + Node2->Node1 right = Node2->Node1 elem = Node0->7 + Node1->7 + Node2->-2 }} } run test110 for 4 expect 0 pred test106 { some disj BinaryTree0: BinaryTree {some disj Node0: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node0 Node = Node0 no left no right elem = Node0->-5 }} } run test106 for 4 expect 1 pred test9 { some disj BinaryTree0: BinaryTree {some disj Node0: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node0 Node = Node0 no left no right no elem }} } run test9 for 4 expect 0 pred test5 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 no left right = Node1->Node0 elem = Node0->7 + Node1->6 }} } run test5 for 4 expect 1 pred test46 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node2->Node0 right = Node2->Node1 elem = Node0->1 + Node1->-2 + Node2->-1 HasAtMostOneChild[Node2] }} } run test46 for 4 expect 0 pred test63 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2, Node3: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node3 Node = Node0 + Node1 + Node2 + Node3 left = Node2->Node1 + Node3->Node2 right = Node3->Node0 elem = Node0->7 + Node1->7 + Node2->3 + Node3->-6 Balanced[] }} } run test63 for 4 expect 1 pred test40 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2, Node3: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node3 Node = Node0 + Node1 + Node2 + Node3 left = Node0->Node2 right = Node2->Node1 + Node3->Node0 elem = Node0->7 + Node1->4 + Node2->3 + Node3->5 Sorted[] }} } run test40 for 4 expect 0 pred test81 { some disj BinaryTree0: BinaryTree {some disj Node0: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node0 Node = Node0 no left right = Node0->Node0 elem = Node0->-1 }} } run test81 for 4 expect 0 pred test28 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node1->Node0 right = Node2->Node1 elem = Node0->7 + Node1->7 + Node2->-2 Sorted[] }} } run test28 for 4 expect 0 pred test55 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 + Node2 left = Node2->Node0 right = Node1->Node2 elem = Node0->2 + Node1->-8 + Node2->7 HasAtMostOneChild[Node2] }} } run test55 for 4 expect 1 pred test29 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2, Node3: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node3 Node = Node0 + Node1 + Node2 + Node3 left = Node0->Node2 + Node1->Node0 right = Node3->Node1 elem = Node0->7 + Node1->6 + Node2->4 + Node3->3 Sorted[] }} } run test29 for 4 expect 0 pred test75 { some disj BinaryTree0: BinaryTree {some disj Node0: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node0 Node = Node0 no left no right elem = Node0->7 Depth[Node0] = 1 }} } run test75 for 4 expect 1 pred test33 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 left = Node1->Node0 no right elem = Node0->5 + Node1->5 Sorted[] }} } run test33 for 4 expect 0 pred test107 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 left = Node1->Node0 no right elem = Node0->7 + Node1->1 }} } run test107 for 4 expect 1 pred test48 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 no left right = Node1->Node0 elem = Node0->-7 + Node1->-8 HasAtMostOneChild[Node1] }} } run test48 for 4 expect 1 pred test49 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 left = Node1->Node0 no right elem = Node0->-5 + Node1->-4 HasAtMostOneChild[Node1] }} } run test49 for 4 expect 1 pred test47 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 no left right = Node1->Node0 elem = Node0->-8 + Node1->5 HasAtMostOneChild[Node1] }} } run test47 for 4 expect 1 pred test39 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 no left right = Node1->Node0 elem = Node0->-3 + Node1->-2 Sorted[] }} } run test39 for 4 expect 0 pred test62 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2, Node3: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node3 Node = Node0 + Node1 + Node2 + Node3 left = Node2->Node1 + Node3->Node2 right = Node3->Node0 elem = Node0->4 + Node1->4 + Node2->4 + Node3->0 Balanced[] }} } run test62 for 4 expect 1 pred test78 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 left = Node1->Node0 no right elem = Node0->7 + Node1->6 Depth[Node1] = 1 }} } run test78 for 4 expect 1 pred test65 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2, Node3: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node3 Node = Node0 + Node1 + Node2 + Node3 left = Node2->Node1 + Node3->Node2 right = Node3->Node0 elem = Node0->7 + Node1->-6 + Node2->-7 + Node3->-8 Balanced[] }} } run test65 for 4 expect 1 pred test92 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node0->Node2 right = Node0->Node1 + Node2->Node0 elem = Node0->7 + Node1->4 + Node2->0 }} } run test92 for 4 expect 0 pred test59 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2, Node3: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node3 Node = Node0 + Node1 + Node2 + Node3 left = Node2->Node1 + Node3->Node2 right = Node3->Node0 elem = Node0->7 + Node1->3 + Node2->0 + Node3->-5 Balanced[] }} } run test59 for 4 expect 1 pred test11 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 left = Node1->Node0 no right elem = Node0->4 + Node1->4 Sorted[] }} } run test11 for 4 expect 0 pred test30 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 left = Node1->Node0 no right elem = Node0->2 + Node1->2 Sorted[] }} } run test30 for 4 expect 0 pred test74 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2, Node3: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node3 Node = Node0 + Node1 + Node2 + Node3 left = Node0->Node2 right = Node2->Node1 + Node3->Node0 elem = Node0->7 + Node1->5 + Node2->4 + Node3->2 RepOk[] }} } run test74 for 4 expect 0 pred test34 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 no left right = Node1->Node0 elem = Node0->-7 + Node1->-8 Sorted[] }} } run test34 for 4 expect 1 pred test7 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node0->Node1 + Node2->Node0 no right elem = Node0->7 + Node1->3 + Node2->2 }} } run test7 for 4 expect 1 pred test100 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node2->Node0 right = Node1->Node0 + Node2->Node1 elem = Node0->7 + Node1->6 + Node2->5 }} } run test100 for 4 expect 0 pred test91 { some disj BinaryTree0: BinaryTree {some disj Node0: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node0 Node = Node0 no left right = Node0->Node0 elem = Node0->-8 }} } run test91 for 4 expect 0 pred test19 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 left = Node1->Node0 no right elem = Node0->1 + Node1->-3 Sorted[] }} } run test19 for 4 expect 0 pred test109 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node0->Node1 right = Node0->Node1 + Node2->Node0 elem = Node0->7 + Node1->6 + Node2->3 }} } run test109 for 4 expect 0 pred test108 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 left = Node1->Node0 no right elem = Node0->7 + Node1->4 }} } run test108 for 4 expect 1 pred test85 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node0->Node1 + Node2->Node0 right = Node2->Node1 elem = Node0->7 + Node1->6 + Node2->5 }} } run test85 for 4 expect 0 pred test61 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2, Node3: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node3 Node = Node0 + Node1 + Node2 + Node3 left = Node2->Node1 + Node3->Node2 right = Node3->Node0 elem = Node0->7 + Node1->-2 + Node2->-4 + Node3->-5 Balanced[] }} } run test61 for 4 expect 1 pred test105 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node2->Node0 right = Node0->Node1 + Node2->Node0 elem = Node0->7 + Node1->6 + Node2->5 }} } run test105 for 4 expect 0 pred test73 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2, Node3: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node3 Node = Node0 + Node1 + Node2 + Node3 left = Node2->Node1 + Node3->Node2 right = Node3->Node0 elem = Node0->7 + Node1->5 + Node2->5 + Node3->4 RepOk[] }} } run test73 for 4 expect 0 pred test97 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node2->Node0 right = Node2->Node1 elem = Node0->7 + Node1->6 + Node2->2 }} } run test97 for 4 expect 1 pred test17 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 no left right = Node1->Node0 elem = Node0->-3 + Node1->-1 Sorted[] }} } run test17 for 4 expect 0 pred test93 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node0->Node2 right = Node0->Node1 + Node2->Node0 elem = Node0->7 + Node1->5 + Node2->5 }} } run test93 for 4 expect 0 pred test50 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node2->Node0 right = Node2->Node1 elem = Node0->1 + Node1->-7 + Node2->-6 HasAtMostOneChild[Node2] }} } run test50 for 4 expect 0 pred test104 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 no left right = Node1->Node0 + Node2->Node1 elem = Node0->5 + Node1->5 + Node2->-1 }} } run test104 for 4 expect 1 ",8443,True,3322.4344586661264,median "#include ""../../JCharArray.hpp"" #include ""../os/Parcel.hpp"" #include ""./KeyCharacterMap.hpp"" #include ""./KeyCharacterMap_KeyData.hpp"" #include ""./KeyEvent_DispatcherState.hpp"" #include ""../../JObject.hpp"" #include ""../../JString.hpp"" #include ""./KeyEvent.hpp"" namespace android::view { // Fields jint KeyEvent::ACTION_DOWN() { return getStaticField( ""android.view.KeyEvent"", ""ACTION_DOWN"" ); } jint KeyEvent::ACTION_MULTIPLE() { return getStaticField( ""android.view.KeyEvent"", ""ACTION_MULTIPLE"" ); } jint KeyEvent::ACTION_UP() { return getStaticField( ""android.view.KeyEvent"", ""ACTION_UP"" ); } JObject KeyEvent::CREATOR() { return getStaticObjectField( ""android.view.KeyEvent"", ""CREATOR"", ""Landroid/os/Parcelable$Creator;"" ); } jint KeyEvent::FLAG_CANCELED() { return getStaticField( ""android.view.KeyEvent"", ""FLAG_CANCELED"" ); } jint KeyEvent::FLAG_CANCELED_LONG_PRESS() { return getStaticField( ""android.view.KeyEvent"", ""FLAG_CANCELED_LONG_PRESS"" ); } jint KeyEvent::FLAG_EDITOR_ACTION() { return getStaticField( ""android.view.KeyEvent"", ""FLAG_EDITOR_ACTION"" ); } jint KeyEvent::FLAG_FALLBACK() { return getStaticField( ""android.view.KeyEvent"", ""FLAG_FALLBACK"" ); } jint KeyEvent::FLAG_FROM_SYSTEM() { return getStaticField( ""android.view.KeyEvent"", ""FLAG_FROM_SYSTEM"" ); } jint KeyEvent::FLAG_KEEP_TOUCH_MODE() { return getStaticField( ""android.view.KeyEvent"", ""FLAG_KEEP_TOUCH_MODE"" ); } jint KeyEvent::FLAG_LONG_PRESS() { return getStaticField( ""android.view.KeyEvent"", ""FLAG_LONG_PRESS"" ); } jint KeyEvent::FLAG_SOFT_KEYBOARD() { return getStaticField( ""android.view.KeyEvent"", ""FLAG_SOFT_KEYBOARD"" ); } jint KeyEvent::FLAG_TRACKING() { return getStaticField( ""android.view.KeyEvent"", ""FLAG_TRACKING"" ); } jint KeyEvent::FLAG_VIRTUAL_HARD_KEY() { return getStaticField( ""android.view.KeyEvent"", ""FLAG_VIRTUAL_HARD_KEY"" ); } jint KeyEvent::FLAG_WOKE_HERE() { return getStaticField( ""android.view.KeyEvent"", ""FLAG_WOKE_HERE"" ); } jint KeyEvent::KEYCODE_0() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_0"" ); } jint KeyEvent::KEYCODE_1() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_1"" ); } jint KeyEvent::KEYCODE_11() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_11"" ); } jint KeyEvent::KEYCODE_12() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_12"" ); } jint KeyEvent::KEYCODE_2() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_2"" ); } jint KeyEvent::KEYCODE_3() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_3"" ); } jint KeyEvent::KEYCODE_3D_MODE() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_3D_MODE"" ); } jint KeyEvent::KEYCODE_4() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_4"" ); } jint KeyEvent::KEYCODE_5() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_5"" ); } jint KeyEvent::KEYCODE_6() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_6"" ); } jint KeyEvent::KEYCODE_7() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_7"" ); } jint KeyEvent::KEYCODE_8() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_8"" ); } jint KeyEvent::KEYCODE_9() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_9"" ); } jint KeyEvent::KEYCODE_A() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_A"" ); } jint KeyEvent::KEYCODE_ALL_APPS() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_ALL_APPS"" ); } jint KeyEvent::KEYCODE_ALT_LEFT() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_ALT_LEFT"" ); } jint KeyEvent::KEYCODE_ALT_RIGHT() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_ALT_RIGHT"" ); } jint KeyEvent::KEYCODE_APOSTROPHE() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_APOSTROPHE"" ); } jint KeyEvent::KEYCODE_APP_SWITCH() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_APP_SWITCH"" ); } jint KeyEvent::KEYCODE_ASSIST() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_ASSIST"" ); } jint KeyEvent::KEYCODE_AT() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_AT"" ); } jint KeyEvent::KEYCODE_AVR_INPUT() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_AVR_INPUT"" ); } jint KeyEvent::KEYCODE_AVR_POWER() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_AVR_POWER"" ); } jint KeyEvent::KEYCODE_B() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_B"" ); } jint KeyEvent::KEYCODE_BACK() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_BACK"" ); } jint KeyEvent::KEYCODE_BACKSLASH() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_BACKSLASH"" ); } jint KeyEvent::KEYCODE_BOOKMARK() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_BOOKMARK"" ); } jint KeyEvent::KEYCODE_BREAK() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_BREAK"" ); } jint KeyEvent::KEYCODE_BRIGHTNESS_DOWN() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_BRIGHTNESS_DOWN"" ); } jint KeyEvent::KEYCODE_BRIGHTNESS_UP() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_BRIGHTNESS_UP"" ); } jint KeyEvent::KEYCODE_BUTTON_1() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_BUTTON_1"" ); } jint KeyEvent::KEYCODE_BUTTON_10() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_BUTTON_10"" ); } jint KeyEvent::KEYCODE_BUTTON_11() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_BUTTON_11"" ); } jint KeyEvent::KEYCODE_BUTTON_12() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_BUTTON_12"" ); } jint KeyEvent::KEYCODE_BUTTON_13() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_BUTTON_13"" ); } jint KeyEvent::KEYCODE_BUTTON_14() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_BUTTON_14"" ); } jint KeyEvent::KEYCODE_BUTTON_15() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_BUTTON_15"" ); } jint KeyEvent::KEYCODE_BUTTON_16() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_BUTTON_16"" ); } jint KeyEvent::KEYCODE_BUTTON_2() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_BUTTON_2"" ); } jint KeyEvent::KEYCODE_BUTTON_3() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_BUTTON_3"" ); } jint KeyEvent::KEYCODE_BUTTON_4() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_BUTTON_4"" ); } jint KeyEvent::KEYCODE_BUTTON_5() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_BUTTON_5"" ); } jint KeyEvent::KEYCODE_BUTTON_6() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_BUTTON_6"" ); } jint KeyEvent::KEYCODE_BUTTON_7() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_BUTTON_7"" ); } jint KeyEvent::KEYCODE_BUTTON_8() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_BUTTON_8"" ); } jint KeyEvent::KEYCODE_BUTTON_9() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_BUTTON_9"" ); } jint KeyEvent::KEYCODE_BUTTON_A() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_BUTTON_A"" ); } jint KeyEvent::KEYCODE_BUTTON_B() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_BUTTON_B"" ); } jint KeyEvent::KEYCODE_BUTTON_C() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_BUTTON_C"" ); } jint KeyEvent::KEYCODE_BUTTON_L1() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_BUTTON_L1"" ); } jint KeyEvent::KEYCODE_BUTTON_L2() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_BUTTON_L2"" ); } jint KeyEvent::KEYCODE_BUTTON_MODE() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_BUTTON_MODE"" ); } jint KeyEvent::KEYCODE_BUTTON_R1() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_BUTTON_R1"" ); } jint KeyEvent::KEYCODE_BUTTON_R2() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_BUTTON_R2"" ); } jint KeyEvent::KEYCODE_BUTTON_SELECT() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_BUTTON_SELECT"" ); } jint KeyEvent::KEYCODE_BUTTON_START() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_BUTTON_START"" ); } jint KeyEvent::KEYCODE_BUTTON_THUMBL() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_BUTTON_THUMBL"" ); } jint KeyEvent::KEYCODE_BUTTON_THUMBR() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_BUTTON_THUMBR"" ); } jint KeyEvent::KEYCODE_BUTTON_X() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_BUTTON_X"" ); } jint KeyEvent::KEYCODE_BUTTON_Y() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_BUTTON_Y"" ); } jint KeyEvent::KEYCODE_BUTTON_Z() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_BUTTON_Z"" ); } jint KeyEvent::KEYCODE_C() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_C"" ); } jint KeyEvent::KEYCODE_CALCULATOR() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_CALCULATOR"" ); } jint KeyEvent::KEYCODE_CALENDAR() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_CALENDAR"" ); } jint KeyEvent::KEYCODE_CALL() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_CALL"" ); } jint KeyEvent::KEYCODE_CAMERA() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_CAMERA"" ); } jint KeyEvent::KEYCODE_CAPS_LOCK() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_CAPS_LOCK"" ); } jint KeyEvent::KEYCODE_CAPTIONS() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_CAPTIONS"" ); } jint KeyEvent::KEYCODE_CHANNEL_DOWN() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_CHANNEL_DOWN"" ); } jint KeyEvent::KEYCODE_CHANNEL_UP() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_CHANNEL_UP"" ); } jint KeyEvent::KEYCODE_CLEAR() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_CLEAR"" ); } jint KeyEvent::KEYCODE_COMMA() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_COMMA"" ); } jint KeyEvent::KEYCODE_CONTACTS() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_CONTACTS"" ); } jint KeyEvent::KEYCODE_COPY() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_COPY"" ); } jint KeyEvent::KEYCODE_CTRL_LEFT() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_CTRL_LEFT"" ); } jint KeyEvent::KEYCODE_CTRL_RIGHT() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_CTRL_RIGHT"" ); } jint KeyEvent::KEYCODE_CUT() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_CUT"" ); } jint KeyEvent::KEYCODE_D() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_D"" ); } jint KeyEvent::KEYCODE_DEL() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_DEL"" ); } jint KeyEvent::KEYCODE_DPAD_CENTER() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_DPAD_CENTER"" ); } jint KeyEvent::KEYCODE_DPAD_DOWN() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_DPAD_DOWN"" ); } jint KeyEvent::KEYCODE_DPAD_DOWN_LEFT() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_DPAD_DOWN_LEFT"" ); } jint KeyEvent::KEYCODE_DPAD_DOWN_RIGHT() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_DPAD_DOWN_RIGHT"" ); } jint KeyEvent::KEYCODE_DPAD_LEFT() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_DPAD_LEFT"" ); } jint KeyEvent::KEYCODE_DPAD_RIGHT() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_DPAD_RIGHT"" ); } jint KeyEvent::KEYCODE_DPAD_UP() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_DPAD_UP"" ); } jint KeyEvent::KEYCODE_DPAD_UP_LEFT() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_DPAD_UP_LEFT"" ); } jint KeyEvent::KEYCODE_DPAD_UP_RIGHT() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_DPAD_UP_RIGHT"" ); } jint KeyEvent::KEYCODE_DVR() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_DVR"" ); } jint KeyEvent::KEYCODE_E() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_E"" ); } jint KeyEvent::KEYCODE_EISU() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_EISU"" ); } jint KeyEvent::KEYCODE_ENDCALL() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_ENDCALL"" ); } jint KeyEvent::KEYCODE_ENTER() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_ENTER"" ); } jint KeyEvent::KEYCODE_ENVELOPE() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_ENVELOPE"" ); } jint KeyEvent::KEYCODE_EQUALS() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_EQUALS"" ); } jint KeyEvent::KEYCODE_ESCAPE() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_ESCAPE"" ); } jint KeyEvent::KEYCODE_EXPLORER() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_EXPLORER"" ); } jint KeyEvent::KEYCODE_F() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_F"" ); } jint KeyEvent::KEYCODE_F1() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_F1"" ); } jint KeyEvent::KEYCODE_F10() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_F10"" ); } jint KeyEvent::KEYCODE_F11() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_F11"" ); } jint KeyEvent::KEYCODE_F12() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_F12"" ); } jint KeyEvent::KEYCODE_F2() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_F2"" ); } jint KeyEvent::KEYCODE_F3() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_F3"" ); } jint KeyEvent::KEYCODE_F4() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_F4"" ); } jint KeyEvent::KEYCODE_F5() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_F5"" ); } jint KeyEvent::KEYCODE_F6() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_F6"" ); } jint KeyEvent::KEYCODE_F7() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_F7"" ); } jint KeyEvent::KEYCODE_F8() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_F8"" ); } jint KeyEvent::KEYCODE_F9() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_F9"" ); } jint KeyEvent::KEYCODE_FOCUS() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_FOCUS"" ); } jint KeyEvent::KEYCODE_FORWARD() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_FORWARD"" ); } jint KeyEvent::KEYCODE_FORWARD_DEL() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_FORWARD_DEL"" ); } jint KeyEvent::KEYCODE_FUNCTION() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_FUNCTION"" ); } jint KeyEvent::KEYCODE_G() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_G"" ); } jint KeyEvent::KEYCODE_GRAVE() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_GRAVE"" ); } jint KeyEvent::KEYCODE_GUIDE() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_GUIDE"" ); } jint KeyEvent::KEYCODE_H() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_H"" ); } jint KeyEvent::KEYCODE_HEADSETHOOK() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_HEADSETHOOK"" ); } jint KeyEvent::KEYCODE_HELP() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_HELP"" ); } jint KeyEvent::KEYCODE_HENKAN() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_HENKAN"" ); } jint KeyEvent::KEYCODE_HOME() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_HOME"" ); } jint KeyEvent::KEYCODE_I() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_I"" ); } jint KeyEvent::KEYCODE_INFO() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_INFO"" ); } jint KeyEvent::KEYCODE_INSERT() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_INSERT"" ); } jint KeyEvent::KEYCODE_J() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_J"" ); } jint KeyEvent::KEYCODE_K() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_K"" ); } jint KeyEvent::KEYCODE_KANA() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_KANA"" ); } jint KeyEvent::KEYCODE_KATAKANA_HIRAGANA() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_KATAKANA_HIRAGANA"" ); } jint KeyEvent::KEYCODE_L() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_L"" ); } jint KeyEvent::KEYCODE_LANGUAGE_SWITCH() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_LANGUAGE_SWITCH"" ); } jint KeyEvent::KEYCODE_LAST_CHANNEL() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_LAST_CHANNEL"" ); } jint KeyEvent::KEYCODE_LEFT_BRACKET() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_LEFT_BRACKET"" ); } jint KeyEvent::KEYCODE_M() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_M"" ); } jint KeyEvent::KEYCODE_MANNER_MODE() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_MANNER_MODE"" ); } jint KeyEvent::KEYCODE_MEDIA_AUDIO_TRACK() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_MEDIA_AUDIO_TRACK"" ); } jint KeyEvent::KEYCODE_MEDIA_CLOSE() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_MEDIA_CLOSE"" ); } jint KeyEvent::KEYCODE_MEDIA_EJECT() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_MEDIA_EJECT"" ); } jint KeyEvent::KEYCODE_MEDIA_FAST_FORWARD() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_MEDIA_FAST_FORWARD"" ); } jint KeyEvent::KEYCODE_MEDIA_NEXT() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_MEDIA_NEXT"" ); } jint KeyEvent::KEYCODE_MEDIA_PAUSE() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_MEDIA_PAUSE"" ); } jint KeyEvent::KEYCODE_MEDIA_PLAY() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_MEDIA_PLAY"" ); } jint KeyEvent::KEYCODE_MEDIA_PLAY_PAUSE() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_MEDIA_PLAY_PAUSE"" ); } jint KeyEvent::KEYCODE_MEDIA_PREVIOUS() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_MEDIA_PREVIOUS"" ); } jint KeyEvent::KEYCODE_MEDIA_RECORD() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_MEDIA_RECORD"" ); } jint KeyEvent::KEYCODE_MEDIA_REWIND() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_MEDIA_REWIND"" ); } jint KeyEvent::KEYCODE_MEDIA_SKIP_BACKWARD() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_MEDIA_SKIP_BACKWARD"" ); } jint KeyEvent::KEYCODE_MEDIA_SKIP_FORWARD() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_MEDIA_SKIP_FORWARD"" ); } jint KeyEvent::KEYCODE_MEDIA_STEP_BACKWARD() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_MEDIA_STEP_BACKWARD"" ); } jint KeyEvent::KEYCODE_MEDIA_STEP_FORWARD() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_MEDIA_STEP_FORWARD"" ); } jint KeyEvent::KEYCODE_MEDIA_STOP() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_MEDIA_STOP"" ); } jint KeyEvent::KEYCODE_MEDIA_TOP_MENU() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_MEDIA_TOP_MENU"" ); } jint KeyEvent::KEYCODE_MENU() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_MENU"" ); } jint KeyEvent::KEYCODE_META_LEFT() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_META_LEFT"" ); } jint KeyEvent::KEYCODE_META_RIGHT() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_META_RIGHT"" ); } jint KeyEvent::KEYCODE_MINUS() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_MINUS"" ); } jint KeyEvent::KEYCODE_MOVE_END() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_MOVE_END"" ); } jint KeyEvent::KEYCODE_MOVE_HOME() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_MOVE_HOME"" ); } jint KeyEvent::KEYCODE_MUHENKAN() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_MUHENKAN"" ); } jint KeyEvent::KEYCODE_MUSIC() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_MUSIC"" ); } jint KeyEvent::KEYCODE_MUTE() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_MUTE"" ); } jint KeyEvent::KEYCODE_N() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_N"" ); } jint KeyEvent::KEYCODE_NAVIGATE_IN() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_NAVIGATE_IN"" ); } jint KeyEvent::KEYCODE_NAVIGATE_NEXT() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_NAVIGATE_NEXT"" ); } jint KeyEvent::KEYCODE_NAVIGATE_OUT() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_NAVIGATE_OUT"" ); } jint KeyEvent::KEYCODE_NAVIGATE_PREVIOUS() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_NAVIGATE_PREVIOUS"" ); } jint KeyEvent::KEYCODE_NOTIFICATION() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_NOTIFICATION"" ); } jint KeyEvent::KEYCODE_NUM() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_NUM"" ); } jint KeyEvent::KEYCODE_NUMPAD_0() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_NUMPAD_0"" ); } jint KeyEvent::KEYCODE_NUMPAD_1() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_NUMPAD_1"" ); } jint KeyEvent::KEYCODE_NUMPAD_2() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_NUMPAD_2"" ); } jint KeyEvent::KEYCODE_NUMPAD_3() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_NUMPAD_3"" ); } jint KeyEvent::KEYCODE_NUMPAD_4() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_NUMPAD_4"" ); } jint KeyEvent::KEYCODE_NUMPAD_5() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_NUMPAD_5"" ); } jint KeyEvent::KEYCODE_NUMPAD_6() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_NUMPAD_6"" ); } jint KeyEvent::KEYCODE_NUMPAD_7() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_NUMPAD_7"" ); } jint KeyEvent::KEYCODE_NUMPAD_8() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_NUMPAD_8"" ); } jint KeyEvent::KEYCODE_NUMPAD_9() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_NUMPAD_9"" ); } jint KeyEvent::KEYCODE_NUMPAD_ADD() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_NUMPAD_ADD"" ); } jint KeyEvent::KEYCODE_NUMPAD_COMMA() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_NUMPAD_COMMA"" ); } jint KeyEvent::KEYCODE_NUMPAD_DIVIDE() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_NUMPAD_DIVIDE"" ); } jint KeyEvent::KEYCODE_NUMPAD_DOT() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_NUMPAD_DOT"" ); } jint KeyEvent::KEYCODE_NUMPAD_ENTER() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_NUMPAD_ENTER"" ); } jint KeyEvent::KEYCODE_NUMPAD_EQUALS() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_NUMPAD_EQUALS"" ); } jint KeyEvent::KEYCODE_NUMPAD_LEFT_PAREN() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_NUMPAD_LEFT_PAREN"" ); } jint KeyEvent::KEYCODE_NUMPAD_MULTIPLY() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_NUMPAD_MULTIPLY"" ); } jint KeyEvent::KEYCODE_NUMPAD_RIGHT_PAREN() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_NUMPAD_RIGHT_PAREN"" ); } jint KeyEvent::KEYCODE_NUMPAD_SUBTRACT() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_NUMPAD_SUBTRACT"" ); } jint KeyEvent::KEYCODE_NUM_LOCK() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_NUM_LOCK"" ); } jint KeyEvent::KEYCODE_O() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_O"" ); } jint KeyEvent::KEYCODE_P() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_P"" ); } jint KeyEvent::KEYCODE_PAGE_DOWN() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_PAGE_DOWN"" ); } jint KeyEvent::KEYCODE_PAGE_UP() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_PAGE_UP"" ); } jint KeyEvent::KEYCODE_PAIRING() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_PAIRING"" ); } jint KeyEvent::KEYCODE_PASTE() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_PASTE"" ); } jint KeyEvent::KEYCODE_PERIOD() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_PERIOD"" ); } jint KeyEvent::KEYCODE_PICTSYMBOLS() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_PICTSYMBOLS"" ); } jint KeyEvent::KEYCODE_PLUS() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_PLUS"" ); } jint KeyEvent::KEYCODE_POUND() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_POUND"" ); } jint KeyEvent::KEYCODE_POWER() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_POWER"" ); } jint KeyEvent::KEYCODE_PROG_BLUE() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_PROG_BLUE"" ); } jint KeyEvent::KEYCODE_PROG_GREEN() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_PROG_GREEN"" ); } jint KeyEvent::KEYCODE_PROG_RED() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_PROG_RED"" ); } jint KeyEvent::KEYCODE_PROG_YELLOW() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_PROG_YELLOW"" ); } jint KeyEvent::KEYCODE_Q() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_Q"" ); } jint KeyEvent::KEYCODE_R() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_R"" ); } jint KeyEvent::KEYCODE_REFRESH() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_REFRESH"" ); } jint KeyEvent::KEYCODE_RIGHT_BRACKET() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_RIGHT_BRACKET"" ); } jint KeyEvent::KEYCODE_RO() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_RO"" ); } jint KeyEvent::KEYCODE_S() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_S"" ); } jint KeyEvent::KEYCODE_SCROLL_LOCK() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_SCROLL_LOCK"" ); } jint KeyEvent::KEYCODE_SEARCH() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_SEARCH"" ); } jint KeyEvent::KEYCODE_SEMICOLON() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_SEMICOLON"" ); } jint KeyEvent::KEYCODE_SETTINGS() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_SETTINGS"" ); } jint KeyEvent::KEYCODE_SHIFT_LEFT() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_SHIFT_LEFT"" ); } jint KeyEvent::KEYCODE_SHIFT_RIGHT() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_SHIFT_RIGHT"" ); } jint KeyEvent::KEYCODE_SLASH() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_SLASH"" ); } jint KeyEvent::KEYCODE_SLEEP() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_SLEEP"" ); } jint KeyEvent::KEYCODE_SOFT_LEFT() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_SOFT_LEFT"" ); } jint KeyEvent::KEYCODE_SOFT_RIGHT() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_SOFT_RIGHT"" ); } jint KeyEvent::KEYCODE_SOFT_SLEEP() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_SOFT_SLEEP"" ); } jint KeyEvent::KEYCODE_SPACE() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_SPACE"" ); } jint KeyEvent::KEYCODE_STAR() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_STAR"" ); } jint KeyEvent::KEYCODE_STB_INPUT() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_STB_INPUT"" ); } jint KeyEvent::KEYCODE_STB_POWER() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_STB_POWER"" ); } jint KeyEvent::KEYCODE_STEM_1() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_STEM_1"" ); } jint KeyEvent::KEYCODE_STEM_2() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_STEM_2"" ); } jint KeyEvent::KEYCODE_STEM_3() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_STEM_3"" ); } jint KeyEvent::KEYCODE_STEM_PRIMARY() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_STEM_PRIMARY"" ); } jint KeyEvent::KEYCODE_SWITCH_CHARSET() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_SWITCH_CHARSET"" ); } jint KeyEvent::KEYCODE_SYM() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_SYM"" ); } jint KeyEvent::KEYCODE_SYSRQ() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_SYSRQ"" ); } jint KeyEvent::KEYCODE_SYSTEM_NAVIGATION_DOWN() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_SYSTEM_NAVIGATION_DOWN"" ); } jint KeyEvent::KEYCODE_SYSTEM_NAVIGATION_LEFT() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_SYSTEM_NAVIGATION_LEFT"" ); } jint KeyEvent::KEYCODE_SYSTEM_NAVIGATION_RIGHT() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_SYSTEM_NAVIGATION_RIGHT"" ); } jint KeyEvent::KEYCODE_SYSTEM_NAVIGATION_UP() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_SYSTEM_NAVIGATION_UP"" ); } jint KeyEvent::KEYCODE_T() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_T"" ); } jint KeyEvent::KEYCODE_TAB() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_TAB"" ); } jint KeyEvent::KEYCODE_TV() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_TV"" ); } jint KeyEvent::KEYCODE_TV_ANTENNA_CABLE() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_TV_ANTENNA_CABLE"" ); } jint KeyEvent::KEYCODE_TV_AUDIO_DESCRIPTION() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_TV_AUDIO_DESCRIPTION"" ); } jint KeyEvent::KEYCODE_TV_AUDIO_DESCRIPTION_MIX_DOWN() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_TV_AUDIO_DESCRIPTION_MIX_DOWN"" ); } jint KeyEvent::KEYCODE_TV_AUDIO_DESCRIPTION_MIX_UP() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_TV_AUDIO_DESCRIPTION_MIX_UP"" ); } jint KeyEvent::KEYCODE_TV_CONTENTS_MENU() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_TV_CONTENTS_MENU"" ); } jint KeyEvent::KEYCODE_TV_DATA_SERVICE() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_TV_DATA_SERVICE"" ); } jint KeyEvent::KEYCODE_TV_INPUT() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_TV_INPUT"" ); } jint KeyEvent::KEYCODE_TV_INPUT_COMPONENT_1() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_TV_INPUT_COMPONENT_1"" ); } jint KeyEvent::KEYCODE_TV_INPUT_COMPONENT_2() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_TV_INPUT_COMPONENT_2"" ); } jint KeyEvent::KEYCODE_TV_INPUT_COMPOSITE_1() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_TV_INPUT_COMPOSITE_1"" ); } jint KeyEvent::KEYCODE_TV_INPUT_COMPOSITE_2() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_TV_INPUT_COMPOSITE_2"" ); } jint KeyEvent::KEYCODE_TV_INPUT_HDMI_1() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_TV_INPUT_HDMI_1"" ); } jint KeyEvent::KEYCODE_TV_INPUT_HDMI_2() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_TV_INPUT_HDMI_2"" ); } jint KeyEvent::KEYCODE_TV_INPUT_HDMI_3() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_TV_INPUT_HDMI_3"" ); } jint KeyEvent::KEYCODE_TV_INPUT_HDMI_4() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_TV_INPUT_HDMI_4"" ); } jint KeyEvent::KEYCODE_TV_INPUT_VGA_1() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_TV_INPUT_VGA_1"" ); } jint KeyEvent::KEYCODE_TV_MEDIA_CONTEXT_MENU() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_TV_MEDIA_CONTEXT_MENU"" ); } jint KeyEvent::KEYCODE_TV_NETWORK() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_TV_NETWORK"" ); } jint KeyEvent::KEYCODE_TV_NUMBER_ENTRY() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_TV_NUMBER_ENTRY"" ); } jint KeyEvent::KEYCODE_TV_POWER() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_TV_POWER"" ); } jint KeyEvent::KEYCODE_TV_RADIO_SERVICE() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_TV_RADIO_SERVICE"" ); } jint KeyEvent::KEYCODE_TV_SATELLITE() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_TV_SATELLITE"" ); } jint KeyEvent::KEYCODE_TV_SATELLITE_BS() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_TV_SATELLITE_BS"" ); } jint KeyEvent::KEYCODE_TV_SATELLITE_CS() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_TV_SATELLITE_CS"" ); } jint KeyEvent::KEYCODE_TV_SATELLITE_SERVICE() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_TV_SATELLITE_SERVICE"" ); } jint KeyEvent::KEYCODE_TV_TELETEXT() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_TV_TELETEXT"" ); } jint KeyEvent::KEYCODE_TV_TERRESTRIAL_ANALOG() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_TV_TERRESTRIAL_ANALOG"" ); } jint KeyEvent::KEYCODE_TV_TERRESTRIAL_DIGITAL() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_TV_TERRESTRIAL_DIGITAL"" ); } jint KeyEvent::KEYCODE_TV_TIMER_PROGRAMMING() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_TV_TIMER_PROGRAMMING"" ); } jint KeyEvent::KEYCODE_TV_ZOOM_MODE() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_TV_ZOOM_MODE"" ); } jint KeyEvent::KEYCODE_U() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_U"" ); } jint KeyEvent::KEYCODE_UNKNOWN() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_UNKNOWN"" ); } jint KeyEvent::KEYCODE_V() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_V"" ); } jint KeyEvent::KEYCODE_VOICE_ASSIST() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_VOICE_ASSIST"" ); } jint KeyEvent::KEYCODE_VOLUME_DOWN() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_VOLUME_DOWN"" ); } jint KeyEvent::KEYCODE_VOLUME_MUTE() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_VOLUME_MUTE"" ); } jint KeyEvent::KEYCODE_VOLUME_UP() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_VOLUME_UP"" ); } jint KeyEvent::KEYCODE_W() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_W"" ); } jint KeyEvent::KEYCODE_WAKEUP() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_WAKEUP"" ); } jint KeyEvent::KEYCODE_WINDOW() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_WINDOW"" ); } jint KeyEvent::KEYCODE_X() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_X"" ); } jint KeyEvent::KEYCODE_Y() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_Y"" ); } jint KeyEvent::KEYCODE_YEN() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_YEN"" ); } jint KeyEvent::KEYCODE_Z() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_Z"" ); } jint KeyEvent::KEYCODE_ZENKAKU_HANKAKU() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_ZENKAKU_HANKAKU"" ); } jint KeyEvent::KEYCODE_ZOOM_IN() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_ZOOM_IN"" ); } jint KeyEvent::KEYCODE_ZOOM_OUT() { return getStaticField( ""android.view.KeyEvent"", ""KEYCODE_ZOOM_OUT"" ); } jint KeyEvent::MAX_KEYCODE() { return getStaticField( ""android.view.KeyEvent"", ""MAX_KEYCODE"" ); } jint KeyEvent::META_ALT_LEFT_ON() { return getStaticField( ""android.view.KeyEvent"", ""META_ALT_LEFT_ON"" ); } jint KeyEvent::META_ALT_MASK() { return getStaticField( ""android.view.KeyEvent"", ""META_ALT_MASK"" ); } jint KeyEvent::META_ALT_ON() { return getStaticField( ""android.view.KeyEvent"", ""META_ALT_ON"" ); } jint KeyEvent::META_ALT_RIGHT_ON() { return getStaticField( ""android.view.KeyEvent"", ""META_ALT_RIGHT_ON"" ); } jint KeyEvent::META_CAPS_LOCK_ON() { return getStaticField( ""android.view.KeyEvent"", ""META_CAPS_LOCK_ON"" ); } jint KeyEvent::META_CTRL_LEFT_ON() { return getStaticField( ""android.view.KeyEvent"", ""META_CTRL_LEFT_ON"" ); } jint KeyEvent::META_CTRL_MASK() { return getStaticField( ""android.view.KeyEvent"", ""META_CTRL_MASK"" ); } jint KeyEvent::META_CTRL_ON() { return getStaticField( ""android.view.KeyEvent"", ""META_CTRL_ON"" ); } jint KeyEvent::META_CTRL_RIGHT_ON() { return getStaticField( ""android.view.KeyEvent"", ""META_CTRL_RIGHT_ON"" ); } jint KeyEvent::META_FUNCTION_ON() { return getStaticField( ""android.view.KeyEvent"", ""META_FUNCTION_ON"" ); } jint KeyEvent::META_META_LEFT_ON() { return getStaticField( ""android.view.KeyEvent"", ""META_META_LEFT_ON"" ); } jint KeyEvent::META_META_MASK() { return getStaticField( ""android.view.KeyEvent"", ""META_META_MASK"" ); } jint KeyEvent::META_META_ON() { return getStaticField( ""android.view.KeyEvent"", ""META_META_ON"" ); } jint KeyEvent::META_META_RIGHT_ON() { return getStaticField( ""android.view.KeyEvent"", ""META_META_RIGHT_ON"" ); } jint KeyEvent::META_NUM_LOCK_ON() { return getStaticField( ""android.view.KeyEvent"", ""META_NUM_LOCK_ON"" ); } jint KeyEvent::META_SCROLL_LOCK_ON() { return getStaticField( ""android.view.KeyEvent"", ""META_SCROLL_LOCK_ON"" ); } jint KeyEvent::META_SHIFT_LEFT_ON() { return getStaticField( ""android.view.KeyEvent"", ""META_SHIFT_LEFT_ON"" ); } jint KeyEvent::META_SHIFT_MASK() { return getStaticField( ""android.view.KeyEvent"", ""META_SHIFT_MASK"" ); } jint KeyEvent::META_SHIFT_ON() { return getStaticField( ""android.view.KeyEvent"", ""META_SHIFT_ON"" ); } jint KeyEvent::META_SHIFT_RIGHT_ON() { return getStaticField( ""android.view.KeyEvent"", ""META_SHIFT_RIGHT_ON"" ); } jint KeyEvent::META_SYM_ON() { return getStaticField( ""android.view.KeyEvent"", ""META_SYM_ON"" ); } // QJniObject forward KeyEvent::KeyEvent(QJniObject obj) : android::view::InputEvent(obj) {} // Constructors KeyEvent::KeyEvent(android::view::KeyEvent &arg0) : android::view::InputEvent( ""android.view.KeyEvent"", ""(Landroid/view/KeyEvent;)V"", arg0.object() ) {} KeyEvent::KeyEvent(jint arg0, jint arg1) : android::view::InputEvent( ""android.view.KeyEvent"", ""(II)V"", arg0, arg1 ) {} KeyEvent::KeyEvent(android::view::KeyEvent &arg0, jlong arg1, jint arg2) : android::view::InputEvent( ""android.view.KeyEvent"", ""(Landroid/view/KeyEvent;JI)V"", arg0.object(), arg1, arg2 ) {} KeyEvent::KeyEvent(jlong arg0, JString arg1, jint arg2, jint arg3) : android::view::InputEvent( ""android.view.KeyEvent"", ""(JLjava/lang/String;II)V"", arg0, arg1.object(), arg2, arg3 ) {} KeyEvent::KeyEvent(jlong arg0, jlong arg1, jint arg2, jint arg3, jint arg4) : android::view::InputEvent( ""android.view.KeyEvent"", ""(JJIII)V"", arg0, arg1, arg2, arg3, arg4 ) {} KeyEvent::KeyEvent(jlong arg0, jlong arg1, jint arg2, jint arg3, jint arg4, jint arg5) : android::view::InputEvent( ""android.view.KeyEvent"", ""(JJIIII)V"", arg0, arg1, arg2, arg3, arg4, arg5 ) {} KeyEvent::KeyEvent(jlong arg0, jlong arg1, jint arg2, jint arg3, jint arg4, jint arg5, jint arg6, jint arg7) : android::view::InputEvent( ""android.view.KeyEvent"", ""(JJIIIIII)V"", arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7 ) {} KeyEvent::KeyEvent(jlong arg0, jlong arg1, jint arg2, jint arg3, jint arg4, jint arg5, jint arg6, jint arg7, jint arg8) : android::view::InputEvent( ""android.view.KeyEvent"", ""(JJIIIIIII)V"", arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8 ) {} KeyEvent::KeyEvent(jlong arg0, jlong arg1, jint arg2, jint arg3, jint arg4, jint arg5, jint arg6, jint arg7, jint arg8, jint arg9) : android::view::InputEvent( ""android.view.KeyEvent"", ""(JJIIIIIIII)V"", arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9 ) {} // Methods android::view::KeyEvent KeyEvent::changeAction(android::view::KeyEvent arg0, jint arg1) { return callStaticObjectMethod( ""android.view.KeyEvent"", ""changeAction"", ""(Landroid/view/KeyEvent;I)Landroid/view/KeyEvent;"", arg0.object(), arg1 ); } android::view::KeyEvent KeyEvent::changeFlags(android::view::KeyEvent arg0, jint arg1) { return callStaticObjectMethod( ""android.view.KeyEvent"", ""changeFlags"", ""(Landroid/view/KeyEvent;I)Landroid/view/KeyEvent;"", arg0.object(), arg1 ); } android::view::KeyEvent KeyEvent::changeTimeRepeat(android::view::KeyEvent arg0, jlong arg1, jint arg2) { return callStaticObjectMethod( ""android.view.KeyEvent"", ""changeTimeRepeat"", ""(Landroid/view/KeyEvent;JI)Landroid/view/KeyEvent;"", arg0.object(), arg1, arg2 ); } android::view::KeyEvent KeyEvent::changeTimeRepeat(android::view::KeyEvent arg0, jlong arg1, jint arg2, jint arg3) { return callStaticObjectMethod( ""android.view.KeyEvent"", ""changeTimeRepeat"", ""(Landroid/view/KeyEvent;JII)Landroid/view/KeyEvent;"", arg0.object(), arg1, arg2, arg3 ); } jint KeyEvent::getDeadChar(jint arg0, jint arg1) { return callStaticMethod( ""android.view.KeyEvent"", ""getDeadChar"", ""(II)I"", arg0, arg1 ); } jint KeyEvent::getMaxKeyCode() { return callStaticMethod( ""android.view.KeyEvent"", ""getMaxKeyCode"", ""()I"" ); } jint KeyEvent::getModifierMetaStateMask() { return callStaticMethod( ""android.view.KeyEvent"", ""getModifierMetaStateMask"", ""()I"" ); } jboolean KeyEvent::isGamepadButton(jint arg0) { return callStaticMethod( ""android.view.KeyEvent"", ""isGamepadButton"", ""(I)Z"", arg0 ); } jboolean KeyEvent::isModifierKey(jint arg0) { return callStaticMethod( ""android.view.KeyEvent"", ""isModifierKey"", ""(I)Z"", arg0 ); } jint KeyEvent::keyCodeFromString(JString arg0) { return callStaticMethod( ""android.view.KeyEvent"", ""keyCodeFromString"", ""(Ljava/lang/String;)I"", arg0.object() ); } JString KeyEvent::keyCodeToString(jint arg0) { return callStaticObjectMethod( ""android.view.KeyEvent"", ""keyCodeToString"", ""(I)Ljava/lang/String;"", arg0 ); } jboolean KeyEvent::metaStateHasModifiers(jint arg0, jint arg1) { return callStaticMethod( ""android.view.KeyEvent"", ""metaStateHasModifiers"", ""(II)Z"", arg0, arg1 ); } jboolean KeyEvent::metaStateHasNoModifiers(jint arg0) { return callStaticMethod( ""android.view.KeyEvent"", ""metaStateHasNoModifiers"", ""(I)Z"", arg0 ); } jint KeyEvent::normalizeMetaState(jint arg0) { return callStaticMethod( ""android.view.KeyEvent"", ""normalizeMetaState"", ""(I)I"", arg0 ); } jboolean KeyEvent::dispatch(JObject arg0) const { return callMethod( ""dispatch"", ""(Landroid/view/KeyEvent$Callback;)Z"", arg0.object() ); } jboolean KeyEvent::dispatch(JObject arg0, android::view::KeyEvent_DispatcherState arg1, JObject arg2) const { return callMethod( ""dispatch"", ""(Landroid/view/KeyEvent$Callback;Landroid/view/KeyEvent$DispatcherState;Ljava/lang/Object;)Z"", arg0.object(), arg1.object(), arg2.object() ); } jint KeyEvent::getAction() const { return callMethod( ""getAction"", ""()I"" ); } JString KeyEvent::getCharacters() const { return callObjectMethod( ""getCharacters"", ""()Ljava/lang/String;"" ); } jint KeyEvent::getDeviceId() const { return callMethod( ""getDeviceId"", ""()I"" ); } jchar KeyEvent::getDisplayLabel() const { return callMethod( ""getDisplayLabel"", ""()C"" ); } jlong KeyEvent::getDownTime() const { return callMethod( ""getDownTime"", ""()J"" ); } jlong KeyEvent::getEventTime() const { return callMethod( ""getEventTime"", ""()J"" ); } jint KeyEvent::getFlags() const { return callMethod( ""getFlags"", ""()I"" ); } android::view::KeyCharacterMap KeyEvent::getKeyCharacterMap() const { return callObjectMethod( ""getKeyCharacterMap"", ""()Landroid/view/KeyCharacterMap;"" ); } jint KeyEvent::getKeyCode() const { return callMethod( ""getKeyCode"", ""()I"" ); } jboolean KeyEvent::getKeyData(android::view::KeyCharacterMap_KeyData arg0) const { return callMethod( ""getKeyData"", ""(Landroid/view/KeyCharacterMap$KeyData;)Z"", arg0.object() ); } jchar KeyEvent::getMatch(JCharArray arg0) const { return callMethod( ""getMatch"", ""([C)C"", arg0.object() ); } jchar KeyEvent::getMatch(JCharArray arg0, jint arg1) const { return callMethod( ""getMatch"", ""([CI)C"", arg0.object(), arg1 ); } jint KeyEvent::getMetaState() const { return callMethod( ""getMetaState"", ""()I"" ); } jint KeyEvent::getModifiers() const { return callMethod( ""getModifiers"", ""()I"" ); } jchar KeyEvent::getNumber() const { return callMethod( ""getNumber"", ""()C"" ); } jint KeyEvent::getRepeatCount() const { return callMethod( ""getRepeatCount"", ""()I"" ); } jint KeyEvent::getScanCode() const { return callMethod( ""getScanCode"", ""()I"" ); } jint KeyEvent::getSource() const { return callMethod( ""getSource"", ""()I"" ); } jint KeyEvent::getUnicodeChar() const { return callMethod( ""getUnicodeChar"", ""()I"" ); } jint KeyEvent::getUnicodeChar(jint arg0) const { return callMethod( ""getUnicodeChar"", ""(I)I"", arg0 ); } jboolean KeyEvent::hasModifiers(jint arg0) const { return callMethod( ""hasModifiers"", ""(I)Z"", arg0 ); } jboolean KeyEvent::hasNoModifiers() const { return callMethod( ""hasNoModifiers"", ""()Z"" ); } jboolean KeyEvent::isAltPressed() const { return callMethod( ""isAltPressed"", ""()Z"" ); } jboolean KeyEvent::isCanceled() const { return callMethod( ""isCanceled"", ""()Z"" ); } jboolean KeyEvent::isCapsLockOn() const { return callMethod( ""isCapsLockOn"", ""()Z"" ); } jboolean KeyEvent::isCtrlPressed() const { return callMethod( ""isCtrlPressed"", ""()Z"" ); } jboolean KeyEvent::isFunctionPressed() const { return callMethod( ""isFunctionPressed"", ""()Z"" ); } jboolean KeyEvent::isLongPress() const { return callMethod( ""isLongPress"", ""()Z"" ); } jboolean KeyEvent::isMetaPressed() const { return callMethod( ""isMetaPressed"", ""()Z"" ); } jboolean KeyEvent::isNumLockOn() const { return callMethod( ""isNumLockOn"", ""()Z"" ); } jboolean KeyEvent::isPrintingKey() const { return callMethod( ""isPrintingKey"", ""()Z"" ); } jboolean KeyEvent::isScrollLockOn() const { return callMethod( ""isScrollLockOn"", ""()Z"" ); } jboolean KeyEvent::isShiftPressed() const { return callMethod( ""isShiftPressed"", ""()Z"" ); } jboolean KeyEvent::isSymPressed() const { return callMethod( ""isSymPressed"", ""()Z"" ); } jboolean KeyEvent::isSystem() const { return callMethod( ""isSystem"", ""()Z"" ); } jboolean KeyEvent::isTracking() const { return callMethod( ""isTracking"", ""()Z"" ); } void KeyEvent::setSource(jint arg0) const { callMethod( ""setSource"", ""(I)V"", arg0 ); } void KeyEvent::startTracking() const { callMethod( ""startTracking"", ""()V"" ); } JString KeyEvent::toString() const { return callObjectMethod( ""toString"", ""()Ljava/lang/String;"" ); } void KeyEvent::writeToParcel(android::os::Parcel arg0, jint arg1) const { callMethod( ""writeToParcel"", ""(Landroid/os/Parcel;I)V"", arg0.object(), arg1 ); } } // namespace android::view ",16331,True,4510.247249678562,median "[[netty-component]] = Netty Component *Available as of Camel version 2.14* The Netty component in Camel is a socket communication component, based on the http://netty.io/[Netty] project version 4. + Netty is a NIO client server framework which enables quick and easy development of networkServerInitializerFactory applications such as protocol servers and clients. + Netty greatly simplifies and streamlines network programming such as TCP and UDP socket server. This camel component supports both producer and consumer endpoints. The Netty component has several options and allows fine-grained control of a number of TCP/UDP communication parameters (buffer sizes, keepAlives, tcpNoDelay, etc) and facilitates both In-Only and In-Out communication on a Camel route. Maven users will need to add the following dependency to their `pom.xml` for this component: [source,xml] ---- org.apache.camel camel-netty x.x.x ---- == URI format The URI scheme for a netty component is as follows [source,text] ---- netty:tcp://0.0.0.0:99999[?options] netty:udp://remotehost:99999/[?options] ---- This component supports producer and consumer endpoints for both TCP and UDP. You can append query options to the URI in the following format, `?option=value&option=value&...` == Options // component options: START The Netty component supports 6 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *maximumPoolSize* (advanced) | The thread pool size for the EventExecutorGroup if its in use. The default value is 16. | 16 | int | *configuration* (advanced) | To use the NettyConfiguration as configuration when creating endpoints. | | NettyConfiguration | *executorService* (advanced) | To use the given EventExecutorGroup. | | EventExecutorGroup | *useGlobalSslContext Parameters* (security) | Enable usage of global SSL context parameters. | false | boolean | *sslContextParameters* (security) | To configure security using SSLContextParameters | | SSLContextParameters | *basicPropertyBinding* (advanced) | Whether the component should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities | false | boolean |=== // component options: END // endpoint options: START The Netty endpoint is configured using URI syntax: ---- netty:protocol:host:port ---- with the following path and query parameters: === Path Parameters (3 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *protocol* | *Required* The protocol to use which can be tcp or udp. | | String | *host* | *Required* The hostname. For the consumer the hostname is localhost or 0.0.0.0. For the producer the hostname is the remote host to connect to | | String | *port* | *Required* The host port number | | int |=== === Query Parameters (71 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *disconnect* (common) | Whether or not to disconnect(close) from Netty Channel right after use. Can be used for both consumer and producer. | false | boolean | *keepAlive* (common) | Setting to ensure socket is not closed due to inactivity | true | boolean | *reuseAddress* (common) | Setting to facilitate socket multiplexing | true | boolean | *reuseChannel* (common) | This option allows producers and consumers (in client mode) to reuse the same Netty Channel for the lifecycle of processing the Exchange. This is useful if you need to call a server multiple times in a Camel route and want to use the same network connection. When using this, the channel is not returned to the connection pool until the Exchange is done; or disconnected if the disconnect option is set to true. The reused Channel is stored on the Exchange as an exchange property with the key NettyConstants#NETTY_CHANNEL which allows you to obtain the channel during routing and use it as well. | false | boolean | *sync* (common) | Setting to set endpoint as one-way or request-response | true | boolean | *tcpNoDelay* (common) | Setting to improve TCP protocol performance | true | boolean | *bridgeErrorHandler* (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | *broadcast* (consumer) | Setting to choose Multicast over UDP | false | boolean | *clientMode* (consumer) | If the clientMode is true, netty consumer will connect the address as a TCP client. | false | boolean | *reconnect* (consumer) | Used only in clientMode in consumer, the consumer will attempt to reconnect on disconnection if this is enabled | true | boolean | *reconnectInterval* (consumer) | Used if reconnect and clientMode is enabled. The interval in milli seconds to attempt reconnection | 10000 | int | *backlog* (consumer) | Allows to configure a backlog for netty consumer (server). Note the backlog is just a best effort depending on the OS. Setting this option to a value such as 200, 500 or 1000, tells the TCP stack how long the accept queue can be If this option is not configured, then the backlog depends on OS setting. | | int | *bossCount* (consumer) | When netty works on nio mode, it uses default bossCount parameter from Netty, which is 1. User can use this operation to override the default bossCount from Netty | 1 | int | *bossGroup* (consumer) | Set the BossGroup which could be used for handling the new connection of the server side across the NettyEndpoint | | EventLoopGroup | *disconnectOnNoReply* (consumer) | If sync is enabled then this option dictates NettyConsumer if it should disconnect where there is no reply to send back. | true | boolean | *exceptionHandler* (consumer) | To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored. | | ExceptionHandler | *exchangePattern* (consumer) | Sets the exchange pattern when the consumer creates an exchange. | | ExchangePattern | *nettyServerBootstrapFactory* (consumer) | To use a custom NettyServerBootstrapFactory | | NettyServerBootstrap Factory | *networkInterface* (consumer) | When using UDP then this option can be used to specify a network interface by its name, such as eth0 to join a multicast group. | | String | *noReplyLogLevel* (consumer) | If sync is enabled this option dictates NettyConsumer which logging level to use when logging a there is no reply to send back. | WARN | LoggingLevel | *serverClosedChannel ExceptionCaughtLogLevel* (consumer) | If the server (NettyConsumer) catches an java.nio.channels.ClosedChannelException then its logged using this logging level. This is used to avoid logging the closed channel exceptions, as clients can disconnect abruptly and then cause a flood of closed exceptions in the Netty server. | DEBUG | LoggingLevel | *serverExceptionCaughtLog Level* (consumer) | If the server (NettyConsumer) catches an exception then its logged using this logging level. | WARN | LoggingLevel | *serverInitializerFactory* (consumer) | To use a custom ServerInitializerFactory | | ServerInitializer Factory | *usingExecutorService* (consumer) | Whether to use ordered thread pool, to ensure events are processed orderly on the same channel. | true | boolean | *connectTimeout* (producer) | Time to wait for a socket connection to be available. Value is in milliseconds. | 10000 | int | *lazyStartProducer* (producer) | Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel's routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | *requestTimeout* (producer) | Allows to use a timeout for the Netty producer when calling a remote server. By default no timeout is in use. The value is in milli seconds, so eg 30000 is 30 seconds. The requestTimeout is using Netty's ReadTimeoutHandler to trigger the timeout. | | long | *clientInitializerFactory* (producer) | To use a custom ClientInitializerFactory | | ClientInitializer Factory | *correlationManager* (producer) | To use a custom correlation manager to manage how request and reply messages are mapped when using request/reply with the netty producer. This should only be used if you have a way to map requests together with replies such as if there is correlation ids in both the request and reply messages. This can be used if you want to multiplex concurrent messages on the same channel (aka connection) in netty. When doing this you must have a way to correlate the request and reply messages so you can store the right reply on the inflight Camel Exchange before its continued routed. We recommend extending the TimeoutCorrelationManagerSupport when you build custom correlation managers. This provides support for timeout and other complexities you otherwise would need to implement as well. See also the producerPoolEnabled option for more details. | | NettyCamelState CorrelationManager | *lazyChannelCreation* (producer) | Channels can be lazily created to avoid exceptions, if the remote server is not up and running when the Camel producer is started. | true | boolean | *producerPoolEnabled* (producer) | Whether producer pool is enabled or not. Important: If you turn this off then a single shared connection is used for the producer, also if you are doing request/reply. That means there is a potential issue with interleaved responses if replies comes back out-of-order. Therefore you need to have a correlation id in both the request and reply messages so you can properly correlate the replies to the Camel callback that is responsible for continue processing the message in Camel. To do this you need to implement NettyCamelStateCorrelationManager as correlation manager and configure it via the correlationManager option. See also the correlationManager option for more details. | true | boolean | *producerPoolMaxActive* (producer) | Sets the cap on the number of objects that can be allocated by the pool (checked out to clients, or idle awaiting checkout) at a given time. Use a negative value for no limit. | -1 | int | *producerPoolMaxIdle* (producer) | Sets the cap on the number of idle instances in the pool. | 100 | int | *producerPoolMinEvictable Idle* (producer) | Sets the minimum amount of time (value in millis) an object may sit idle in the pool before it is eligible for eviction by the idle object evictor. | 300000 | long | *producerPoolMinIdle* (producer) | Sets the minimum number of instances allowed in the producer pool before the evictor thread (if active) spawns new objects. | | int | *udpConnectionlessSending* (producer) | This option supports connection less udp sending which is a real fire and forget. A connected udp send receive the PortUnreachableException if no one is listen on the receiving port. | false | boolean | *useByteBuf* (producer) | If the useByteBuf is true, netty producer will turn the message body into ByteBuf before sending it out. | false | boolean | *allowSerializedHeaders* (advanced) | Only used for TCP when transferExchange is true. When set to true, serializable objects in headers and properties will be added to the exchange. Otherwise Camel will exclude any non-serializable objects and log it at WARN level. | false | boolean | *basicPropertyBinding* (advanced) | Whether the endpoint should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities | false | boolean | *channelGroup* (advanced) | To use a explicit ChannelGroup. | | ChannelGroup | *nativeTransport* (advanced) | Whether to use native transport instead of NIO. Native transport takes advantage of the host operating system and is only supported on some platforms. You need to add the netty JAR for the host operating system you are using. See more details at: \\http://netty.io/wiki/native-transports.html | false | boolean | *options* (advanced) | Allows to configure additional netty options using option. as prefix. For example option.child.keepAlive=false to set the netty option child.keepAlive=false. See the Netty documentation for possible options that can be used. | | Map | *receiveBufferSize* (advanced) | The TCP/UDP buffer sizes to be used during inbound communication. Size is bytes. | 65536 | int | *receiveBufferSizePredictor* (advanced) | Configures the buffer size predictor. See details at Jetty documentation and this mail thread. | | int | *sendBufferSize* (advanced) | The TCP/UDP buffer sizes to be used during outbound communication. Size is bytes. | 65536 | int | *synchronous* (advanced) | Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported). | false | boolean | *transferExchange* (advanced) | Only used for TCP. You can transfer the exchange over the wire instead of just the body. The following fields are transferred: In body, Out body, fault body, In headers, Out headers, fault headers, exchange properties, exchange exception. This requires that the objects are serializable. Camel will exclude any non-serializable objects and log it at WARN level. | false | boolean | *udpByteArrayCodec* (advanced) | For UDP only. If enabled the using byte array codec instead of Java serialization protocol. | false | boolean | *workerCount* (advanced) | When netty works on nio mode, it uses default workerCount parameter from Netty, which is cpu_core_threads x 2. User can use this operation to override the default workerCount from Netty. | | int | *workerGroup* (advanced) | To use a explicit EventLoopGroup as the boss thread pool. For example to share a thread pool with multiple consumers or producers. By default each consumer or producer has their own worker pool with 2 x cpu count core threads. | | EventLoopGroup | *allowDefaultCodec* (codec) | The netty component installs a default codec if both, encoder/decoder is null and textline is false. Setting allowDefaultCodec to false prevents the netty component from installing a default codec as the first element in the filter chain. | true | boolean | *autoAppendDelimiter* (codec) | Whether or not to auto append missing end delimiter when sending using the textline codec. | true | boolean | *decoderMaxLineLength* (codec) | The max line length to use for the textline codec. | 1024 | int | *decoders* (codec) | A list of decoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. | | List | *delimiter* (codec) | The delimiter to use for the textline codec. Possible values are LINE and NULL. | LINE | TextLineDelimiter | *encoders* (codec) | A list of encoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. | | List | *encoding* (codec) | The encoding (a charset name) to use for the textline codec. If not provided, Camel will use the JVM default Charset. | | String | *textline* (codec) | Only used for TCP. If no codec is specified, you can use this flag to indicate a text line based codec; if not specified or the value is false, then Object Serialization is assumed over TCP. | false | boolean | *enabledProtocols* (security) | Which protocols to enable when using SSL | TLSv1,TLSv1.1,TLSv1.2 | String | *keyStoreFile* (security) | Client side certificate keystore to be used for encryption | | File | *keyStoreFormat* (security) | Keystore format to be used for payload encryption. Defaults to JKS if not set | | String | *keyStoreResource* (security) | Client side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with classpath:, file:, or http: to load the resource from different systems. | | String | *needClientAuth* (security) | Configures whether the server needs client authentication when using SSL. | false | boolean | *passphrase* (security) | Password setting to use in order to encrypt/decrypt payloads sent using SSH | | String | *securityProvider* (security) | Security provider to be used for payload encryption. Defaults to SunX509 if not set. | | String | *ssl* (security) | Setting to specify whether SSL encryption is applied to this endpoint | false | boolean | *sslClientCertHeaders* (security) | When enabled and in SSL mode, then the Netty consumer will enrich the Camel Message with headers having information about the client certificate such as subject name, issuer name, serial number, and the valid date range. | false | boolean | *sslContextParameters* (security) | To configure security using SSLContextParameters | | SSLContextParameters | *sslHandler* (security) | Reference to a class that could be used to return an SSL Handler | | SslHandler | *trustStoreFile* (security) | Server side certificate keystore to be used for encryption | | File | *trustStoreResource* (security) | Server side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with classpath:, file:, or http: to load the resource from different systems. | | String |=== // endpoint options: END // spring-boot-auto-configure options: START == Spring Boot Auto-Configuration When using Spring Boot make sure to use the following Maven dependency to have support for auto configuration: [source,xml] ---- org.apache.camel camel-netty-starter x.x.x ---- The component supports 78 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *camel.component.netty.basic-property-binding* | Whether the component should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities | false | Boolean | *camel.component.netty.configuration.allow-default-codec* | The netty component installs a default codec if both, encoder/decoder is null and textline is false. Setting allowDefaultCodec to false prevents the netty component from installing a default codec as the first element in the filter chain. | true | Boolean | *camel.component.netty.configuration.allow-serialized-headers* | Only used for TCP when transferExchange is true. When set to true, serializable objects in headers and properties will be added to the exchange. Otherwise Camel will exclude any non-serializable objects and log it at WARN level. | false | Boolean | *camel.component.netty.configuration.auto-append-delimiter* | Whether or not to auto append missing end delimiter when sending using the textline codec. | true | Boolean | *camel.component.netty.configuration.backlog* | Allows to configure a backlog for netty consumer (server). Note the backlog is just a best effort depending on the OS. Setting this option to a value such as 200, 500 or 1000, tells the TCP stack how long the ""accept"" queue can be If this option is not configured, then the backlog depends on OS setting. | | Integer | *camel.component.netty.configuration.boss-count* | When netty works on nio mode, it uses default bossCount parameter from Netty, which is 1. User can use this operation to override the default bossCount from Netty | 1 | Integer | *camel.component.netty.configuration.boss-group* | Set the BossGroup which could be used for handling the new connection of the server side across the NettyEndpoint | | EventLoopGroup | *camel.component.netty.configuration.broadcast* | Setting to choose Multicast over UDP | false | Boolean | *camel.component.netty.configuration.channel-group* | To use a explicit ChannelGroup. | | ChannelGroup | *camel.component.netty.configuration.client-initializer-factory* | To use a custom ClientInitializerFactory | | ClientInitializer Factory | *camel.component.netty.configuration.client-mode* | If the clientMode is true, netty consumer will connect the address as a TCP client. | false | Boolean | *camel.component.netty.configuration.connect-timeout* | Time to wait for a socket connection to be available. Value is in milliseconds. | 10000 | Integer | *camel.component.netty.configuration.correlation-manager* | To use a custom correlation manager to manage how request and reply messages are mapped when using request/reply with the netty producer. This should only be used if you have a way to map requests together with replies such as if there is correlation ids in both the request and reply messages. This can be used if you want to multiplex concurrent messages on the same channel (aka connection) in netty. When doing this you must have a way to correlate the request and reply messages so you can store the right reply on the inflight Camel Exchange before its continued routed.

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

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

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

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

The reused {@link Channel} is stored on the {@link Exchange} as an exchange property with the key {@link NettyConstants#NETTY_CHANNEL} which allows you to obtain the channel during routing and use it as well. | false | Boolean | *camel.component.netty.configuration.security-provider* | Security provider to be used for payload encryption. Defaults to ""SunX509"" if not set. | | String | *camel.component.netty.configuration.send-buffer-size* | The TCP/UDP buffer sizes to be used during outbound communication. Size is bytes. | 65536 | Integer | *camel.component.netty.configuration.server-closed-channel-exception-caught-log-level* | If the server (NettyConsumer) catches an java.nio.channels.ClosedChannelException then its logged using this logging level. This is used to avoid logging the closed channel exceptions, as clients can disconnect abruptly and then cause a flood of closed exceptions in the Netty server. | | LoggingLevel | *camel.component.netty.configuration.server-exception-caught-log-level* | If the server (NettyConsumer) catches an exception then its logged using this logging level. | | LoggingLevel | *camel.component.netty.configuration.server-initializer-factory* | To use a custom ServerInitializerFactory | | ServerInitializer Factory | *camel.component.netty.configuration.ssl* | Setting to specify whether SSL encryption is applied to this endpoint | false | Boolean | *camel.component.netty.configuration.ssl-client-cert-headers* | When enabled and in SSL mode, then the Netty consumer will enrich the Camel Message with headers having information about the client certificate such as subject name, issuer name, serial number, and the valid date range. | false | Boolean | *camel.component.netty.configuration.ssl-context-parameters* | To configure security using SSLContextParameters | | SSLContextParameters | *camel.component.netty.configuration.ssl-handler* | Reference to a class that could be used to return an SSL Handler | | SslHandler | *camel.component.netty.configuration.sync* | Setting to set endpoint as one-way or request-response | true | Boolean | *camel.component.netty.configuration.tcp-no-delay* | Setting to improve TCP protocol performance | true | Boolean | *camel.component.netty.configuration.textline* | Only used for TCP. If no codec is specified, you can use this flag to indicate a text line based codec; if not specified or the value is false, then Object Serialization is assumed over TCP. | false | Boolean | *camel.component.netty.configuration.transfer-exchange* | Only used for TCP. You can transfer the exchange over the wire instead of just the body. The following fields are transferred: In body, Out body, fault body, In headers, Out headers, fault headers, exchange properties, exchange exception. This requires that the objects are serializable. Camel will exclude any non-serializable objects and log it at WARN level. | false | Boolean | *camel.component.netty.configuration.trust-store-resource* | Server side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with ""classpath:"", ""file:"", or ""http:"" to load the resource from different systems. | | String | *camel.component.netty.configuration.udp-byte-array-codec* | For UDP only. If enabled the using byte array codec instead of Java serialization protocol. | false | Boolean | *camel.component.netty.configuration.udp-connectionless-sending* | This option supports connection less udp sending which is a real fire and forget. A connected udp send receive the PortUnreachableException if no one is listen on the receiving port. | false | Boolean | *camel.component.netty.configuration.use-byte-buf* | If the useByteBuf is true, netty producer will turn the message body into {@link ByteBuf} before sending it out. | false | Boolean | *camel.component.netty.configuration.using-executor-service* | Whether to use ordered thread pool, to ensure events are processed orderly on the same channel. | true | Boolean | *camel.component.netty.configuration.worker-count* | When netty works on nio mode, it uses default workerCount parameter from Netty, which is cpu_core_threads x 2. User can use this operation to override the default workerCount from Netty. | | Integer | *camel.component.netty.configuration.worker-group* | To use a explicit EventLoopGroup as the boss thread pool. For example to share a thread pool with multiple consumers or producers. By default each consumer or producer has their own worker pool with 2 x cpu count core threads. | | EventLoopGroup | *camel.component.netty.enabled* | Whether to enable auto configuration of the netty component. This is enabled by default. | | Boolean | *camel.component.netty.executor-service* | To use the given EventExecutorGroup. The option is a io.netty.util.concurrent.EventExecutorGroup type. | | String | *camel.component.netty.maximum-pool-size* | The thread pool size for the EventExecutorGroup if its in use. The default value is 16. | 16 | Integer | *camel.component.netty.ssl-context-parameters* | To configure security using SSLContextParameters. The option is a org.apache.camel.support.jsse.SSLContextParameters type. | | String | *camel.component.netty.use-global-ssl-context-parameters* | Enable usage of global SSL context parameters. | false | Boolean | *camel.component.netty.configuration.client-pipeline-factory* | *Deprecated* | | ClientInitializer Factory | *camel.component.netty.configuration.key-store-file* | *Deprecated* Client side certificate keystore to be used for encryption | | File | *camel.component.netty.configuration.server-pipeline-factory* | *Deprecated* | | ServerInitializer Factory | *camel.component.netty.configuration.trust-store-file* | *Deprecated* Server side certificate keystore to be used for encryption | | File |=== // spring-boot-auto-configure options: END == Registry based Options Codec Handlers and SSL Keystores can be enlisted in the Registry, such as in the Spring XML file. The values that could be passed in, are the following: [width=""100%"",cols=""10%,90%"",options=""header"",] |=== |Name |Description |`passphrase` |password setting to use in order to encrypt/decrypt payloads sent using SSH |`keyStoreFormat` |keystore format to be used for payload encryption. Defaults to ""JKS"" if not set |`securityProvider` |Security provider to be used for payload encryption. Defaults to ""SunX509"" if not set. |`keyStoreFile` |*deprecated:* Client side certificate keystore to be used for encryption |`trustStoreFile` |*deprecated:* Server side certificate keystore to be used for encryption |`keyStoreResource` |Client side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with `""classpath:""`, `""file:""`, or `""http:""` to load the resource from different systems. |`trustStoreResource` |Server side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with `""classpath:""`, `""file:""`, or `""http:""` to load the resource from different systems. |`sslHandler` |Reference to a class that could be used to return an SSL Handler |`encoder` |A custom `ChannelHandler` class that can be used to perform special marshalling of outbound payloads. Must override io.netty.channel.ChannelInboundHandlerAdapter. |`encoders` |A list of encoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. |`decoder` |A custom `ChannelHandler` class that can be used to perform special marshalling of inbound payloads. Must override io.netty.channel.ChannelOutboundHandlerAdapter. |`decoders` |A list of decoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. |=== NOTE: Read below about using non shareable encoders/decoders. === Using non shareable encoders or decoders If your encoders or decoders are not shareable (e.g. they don't have the @Shareable class annotation), then your encoder/decoder must implement the `org.apache.camel.component.netty.ChannelHandlerFactory` interface, and return a new instance in the `newChannelHandler` method. This is to ensure the encoder/decoder can safely be used. If this is not the case, then the Netty component will log a WARN when an endpoint is created. The Netty component offers a `org.apache.camel.component.netty.ChannelHandlerFactories` factory class, that has a number of commonly used methods. == Sending Messages to/from a Netty endpoint === Netty Producer In Producer mode, the component provides the ability to send payloads to a socket endpoint using either TCP or UDP protocols (with optional SSL support). The producer mode supports both one-way and request-response based operations. === Netty Consumer In Consumer mode, the component provides the ability to: * listen on a specified socket using either TCP or UDP protocols (with optional SSL support), * receive requests on the socket using text/xml, binary and serialized object based payloads and * send them along on a route as message exchanges. The consumer mode supports both one-way and request-response based operations. == Examples === A UDP Netty endpoint using Request-Reply and serialized object payload [source,java] ---- RouteBuilder builder = new RouteBuilder() { public void configure() { from(""netty:udp://0.0.0.0:5155?sync=true"") .process(new Processor() { public void process(Exchange exchange) throws Exception { Poetry poetry = (Poetry) exchange.getIn().getBody(); poetry.setPoet(""Dr. Sarojini Naidu""); exchange.getOut().setBody(poetry); } } } }; ---- === A TCP based Netty consumer endpoint using One-way communication [source,java] ---- RouteBuilder builder = new RouteBuilder() { public void configure() { from(""netty:tcp://0.0.0.0:5150"") .to(""mock:result""); } }; ---- === An SSL/TCP based Netty consumer endpoint using Request-Reply communication [[Netty-UsingtheJSSEConfigurationUtility]] Using the JSSE Configuration Utility The Netty component supports SSL/TLS configuration through the xref:manual::camel-configuration-utilities.adoc[Camel JSSE Configuration Utility]. This utility greatly decreases the amount of component specific code you need to write and is configurable at the endpoint and component levels. The following examples demonstrate how to use the utility with the Netty component. [[Netty-Programmaticconfigurationofthecomponent]] Programmatic configuration of the component [source,java] ---- KeyStoreParameters ksp = new KeyStoreParameters(); ksp.setResource(""/users/home/server/keystore.jks""); ksp.setPassword(""keystorePassword""); KeyManagersParameters kmp = new KeyManagersParameters(); kmp.setKeyStore(ksp); kmp.setKeyPassword(""keyPassword""); SSLContextParameters scp = new SSLContextParameters(); scp.setKeyManagers(kmp); NettyComponent nettyComponent = getContext().getComponent(""netty"", NettyComponent.class); nettyComponent.setSslContextParameters(scp); ---- [[Netty-SpringDSLbasedconfigurationofendpoint]] Spring DSL based configuration of endpoint [source,xml] ---- ... ... ... ... ---- [[Netty-UsingBasicSSL/TLSconfigurationontheJettyComponent]] Using Basic SSL/TLS configuration on the Jetty Component [source,java] ---- Registry registry = context.getRegistry(); registry.bind(""password"", ""changeit""); registry.bind(""ksf"", new File(""src/test/resources/keystore.jks"")); registry.bind(""tsf"", new File(""src/test/resources/keystore.jks"")); context.addRoutes(new RouteBuilder() { public void configure() { String netty_ssl_endpoint = ""netty:tcp://0.0.0.0:5150?sync=true&ssl=true&passphrase=#password"" + ""&keyStoreFile=#ksf&trustStoreFile=#tsf""; String return_string = ""When You Go Home, Tell Them Of Us And Say,"" + ""For Your Tomorrow, We Gave Our Today.""; from(netty_ssl_endpoint) .process(new Processor() { public void process(Exchange exchange) throws Exception { exchange.getOut().setBody(return_string); } } } }); ---- [[Netty-GettingaccesstoSSLSessionandtheclientcertificate]] Getting access to SSLSession and the client certificate You can get access to the `javax.net.ssl.SSLSession` if you eg need to get details about the client certificate. When `ssl=true` then the xref:netty-component.adoc[Netty] component will store the `SSLSession` as a header on the Camel Message as shown below: [source,java] ---- SSLSession session = exchange.getIn().getHeader(NettyConstants.NETTY_SSL_SESSION, SSLSession.class); // get the first certificate which is client certificate javax.security.cert.X509Certificate cert = session.getPeerCertificateChain()[0]; Principal principal = cert.getSubjectDN(); ---- Remember to set `needClientAuth=true` to authenticate the client, otherwise `SSLSession` cannot access information about the client certificate, and you may get an exception `javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated`. You may also get this exception if the client certificate is expired or not valid etc. TIP: The option `sslClientCertHeaders` can be set to `true` which then enriches the Camel Message with headers having details about the client certificate. For example the subject name is readily available in the header `CamelNettySSLClientCertSubjectName`. === Using Multiple Codecs In certain cases it may be necessary to add chains of encoders and decoders to the netty pipeline. To add multpile codecs to a camel netty endpoint the 'encoders' and 'decoders' uri parameters should be used. Like the 'encoder' and 'decoder' parameters they are used to supply references (lists of ChannelUpstreamHandlers and ChannelDownstreamHandlers) that should be added to the pipeline. Note that if encoders is specified then the encoder param will be ignored, similarly for decoders and the decoder param. NOTE: Read further above about using non shareable encoders/decoders. The lists of codecs need to be added to the Camel's registry so they can be resolved when the endpoint is created. [source,java] ---- ChannelHandlerFactory lengthDecoder = ChannelHandlerFactories.newLengthFieldBasedFrameDecoder(1048576, 0, 4, 0, 4); StringDecoder stringDecoder = new StringDecoder(); registry.bind(""length-decoder"", lengthDecoder); registry.bind(""string-decoder"", stringDecoder); LengthFieldPrepender lengthEncoder = new LengthFieldPrepender(4); StringEncoder stringEncoder = new StringEncoder(); registry.bind(""length-encoder"", lengthEncoder); registry.bind(""string-encoder"", stringEncoder); List decoders = new ArrayList(); decoders.add(lengthDecoder); decoders.add(stringDecoder); List encoders = new ArrayList(); encoders.add(lengthEncoder); encoders.add(stringEncoder); registry.bind(""encoders"", encoders); registry.bind(""decoders"", decoders); ---- Spring's native collections support can be used to specify the codec lists in an application context [source,xml] ---- ---- The bean names can then be used in netty endpoint definitions either as a comma separated list or contained in a List e.g. [source,java] ---- from(""direct:multiple-codec"").to(""netty:tcp://0.0.0.0:{{port}}?encoders=#encoders&sync=false""); from(""netty:tcp://0.0.0.0:{{port}}?decoders=#length-decoder,#string-decoder&sync=false"").to(""mock:multiple-codec""); ---- or via XML. [source,xml] ---- ---- == Closing Channel When Complete When acting as a server you sometimes want to close the channel when, for example, a client conversion is finished. + You can do this by simply setting the endpoint option `disconnect=true`. However you can also instruct Camel on a per message basis as follows. + To instruct Camel to close the channel, you should add a header with the key `CamelNettyCloseChannelWhenComplete` set to a boolean `true` value. + For instance, the example below will close the channel after it has written the bye message back to the client: [source,java] ---- from(""netty:tcp://0.0.0.0:8080"").process(new Processor() { public void process(Exchange exchange) throws Exception { String body = exchange.getIn().getBody(String.class); exchange.getOut().setBody(""Bye "" + body); // some condition which determines if we should close if (close) { exchange.getOut().setHeader(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, true); } } }); ---- [[Netty-Addingcustomchannelpipelinefactoriestogaincompletecontroloveracreatedpipeline]] Adding custom channel pipeline factories to gain complete control over a created pipeline == Custom pipeline Custom channel pipelines provide complete control to the user over the handler/interceptor chain by inserting custom handler(s), encoder(s) & decoder(s) without having to specify them in the Netty Endpoint URL in a very simple way. In order to add a custom pipeline, a custom channel pipeline factory must be created and registered with the context via the context registry (Registry, or the camel-spring ApplicationContextRegistry etc). A custom pipeline factory must be constructed as follows * A Producer linked channel pipeline factory must extend the abstract class `ClientPipelineFactory`. * A Consumer linked channel pipeline factory must extend the abstract class `ServerInitializerFactory`. * The classes should override the initChannel() method in order to insert custom handler(s), encoder(s) and decoder(s). Not overriding the `initChannel()` method creates a pipeline with no handlers, encoders or decoders wired to the pipeline. The example below shows how ServerInitializerFactory factory may be created === Using custom pipeline factory [source,java] ---- public class SampleServerInitializerFactory extends ServerInitializerFactory { private int maxLineSize = 1024; protected void initChannel(Channel ch) throws Exception { ChannelPipeline channelPipeline = ch.pipeline(); channelPipeline.addLast(""encoder-SD"", new StringEncoder(CharsetUtil.UTF_8)); channelPipeline.addLast(""decoder-DELIM"", new DelimiterBasedFrameDecoder(maxLineSize, true, Delimiters.lineDelimiter())); channelPipeline.addLast(""decoder-SD"", new StringDecoder(CharsetUtil.UTF_8)); // here we add the default Camel ServerChannelHandler for the consumer, to allow Camel to route the message etc. channelPipeline.addLast(""handler"", new ServerChannelHandler(consumer)); } } ---- The custom channel pipeline factory can then be added to the registry and instantiated/utilized on a camel route in the following way [source,java] ---- Registry registry = camelContext.getRegistry(); ServerInitializerFactory factory = new TestServerInitializerFactory(); registry.bind(""spf"", factory); context.addRoutes(new RouteBuilder() { public void configure() { String netty_ssl_endpoint = ""netty:tcp://0.0.0.0:5150?serverInitializerFactory=#spf"" String return_string = ""When You Go Home, Tell Them Of Us And Say,"" + ""For Your Tomorrow, We Gave Our Today.""; from(netty_ssl_endpoint) .process(new Processor() { public void process(Exchange exchange) throws Exception { exchange.getOut().setBody(return_string); } } } }); ---- == Reusing Netty boss and worker thread pools Netty has two kind of thread pools: boss and worker. By default each Netty consumer and producer has their private thread pools. If you want to reuse these thread pools among multiple consumers or producers then the thread pools must be created and enlisted in the Registry. For example using Spring XML we can create a shared worker thread pool using the `NettyWorkerPoolBuilder` with 2 worker threads as shown below: [source,xml] ---- ---- TIP: For boss thread pool there is a `org.apache.camel.component.netty.NettyServerBossPoolBuilder` builder for Netty consumers, and a `org.apache.camel.component.netty.NettyClientBossPoolBuilder` for the Netty producers. Then in the Camel routes we can refer to this worker pools by configuring the `workerPool` option in the URI as shown below: [source,xml] ---- ... ---- And if we have another route we can refer to the shared worker pool: [source,xml] ---- ... ---- and so forth. == Multiplexing concurrent messages over a single connection with request/reply When using Netty for request/reply messaging via the netty producer then by default each message is sent via a non-shared connection (pooled). This ensures that replies are automatic being able to map to the correct request thread for further routing in Camel. In other words correlation between request/reply messages happens out-of-the-box because the replies comes back on the same connection that was used for sending the request; and this connection is not shared with others. When the response comes back, the connection is returned back to the connection pool, where it can be reused by others. However if you want to multiplex concurrent request/responses on a single shared connection, then you need to turn off the connection pooling by setting `producerPoolEnabled=false`. Now this means there is a potential issue with interleaved responses if replies comes back out-of-order. Therefore you need to have a correlation id in both the request and reply messages so you can properly correlate the replies to the Camel callback that is responsible for continue processing the message in Camel. To do this you need to implement `NettyCamelStateCorrelationManager` as correlation manager and configure it via the `correlationManager=#myManager` option. NOTE: We recommend extending the `TimeoutCorrelationManagerSupport` when you build custom correlation managers. This provides support for timeout and other complexities you otherwise would need to implement as well. You can find an example with the Apache Camel source code in the examples directory under the `camel-example-netty-custom-correlation` directory. ",12470,False,2302.956756929155,median "open util/ordering [State] as ord pred test30 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Chicken0,Fox0 + Chicken0 + Grain0,Farmer0 + Fox0 + Chicken0 + Grain0] }}}}}} } run test30 for 4 expect 1 pred test49 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test49 for 4 expect 1 pred test10 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Grain0,Fox0 + Grain0,none,Farmer0] }}}}}} } run test10 for 4 expect 1 pred test44 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Chicken0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Chicken0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Grain0,none,none,Farmer0 + Grain0] }}}}}} } run test44 for 4 expect 1 pred test3 { some disj Farmer0: Farmer {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 no Fox Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Chicken0 + Grain0 eats = Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Chicken0 + State0->Grain0 + State1->Grain0 + State2->Farmer0 + State2->Grain0 + State3->Grain0 far = State1->Farmer0 + State1->Chicken0 + State2->Chicken0 + State3->Farmer0 + State3->Chicken0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}} } run test3 for 4 expect 0 pred test29 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Grain0,Fox0,none,Farmer0 + Grain0] }}}}}} } run test29 for 4 expect 1 pred test20 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Chicken0 + State2->Farmer0 + State2->Fox0 + State2->Chicken0 + State3->Chicken0 far = State1->Farmer0 + State1->Fox0 + State3->Farmer0 + State3->Fox0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0,Fox0,none,Farmer0] }}}}}} } run test20 for 4 expect 1 pred test35 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Chicken0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State1->Chicken0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Grain0,Fox0,none,Farmer0 + Grain0] }}}}}} } run test35 for 4 expect 1 pred test36 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0,Fox0,Fox0,Farmer0 + Fox0 + Chicken0] }}}}}} } run test36 for 4 expect 1 pred test56 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Chicken0 + State2->Farmer0 + State2->Chicken0 + State3->Chicken0 far = State1->Farmer0 + State1->Fox0 + State2->Fox0 + State3->Farmer0 + State3->Fox0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test56 for 4 expect 1 pred test19 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Farmer0 + Fox0 + Grain0,Fox0 + Grain0,none,Farmer0] }}}}}} } run test19 for 4 expect 1 pred test55 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Farmer0 + State1->Grain0 + State2->Grain0 + State3->Fox0 + State3->Chicken0 far = State1->Fox0 + State1->Chicken0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Chicken0 + State2->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test55 for 4 expect 0 pred test32 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Chicken0 + Grain0,Chicken0,none,Farmer0 + Grain0] }}}}}} } run test32 for 4 expect 1 pred test53 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State0->Fox0 + State1->Farmer0 + State1->Fox0 + State1->Chicken0 + State2->Chicken0 + State3->Farmer0 + State3->Chicken0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test53 for 4 expect 0 pred test31 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Chicken0 + Grain0,Chicken0,none,Farmer0 + Grain0] }}}}}} } run test31 for 4 expect 1 pred test47 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Chicken0 + State2->Farmer0 + State2->Fox0 + State2->Chicken0 + State2->Grain0 + State3->Fox0 + State3->Chicken0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test47 for 4 expect 0 pred test42 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Fox0 + Grain0,Fox0 + Grain0,Farmer0 + Fox0] }}}}}} } run test42 for 4 expect 0 pred test33 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0,Chicken0,none,Farmer0 + Fox0] }}}}}} } run test33 for 4 expect 1 pred test39 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Chicken0 + State2->Farmer0 + State2->Chicken0 + State3->Chicken0 far = State1->Farmer0 + State1->Fox0 + State2->Fox0 + State3->Farmer0 + State3->Fox0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Fox0,Fox0 + Chicken0 + Grain0,Farmer0 + Fox0 + Chicken0 + Grain0] }}}}}} } run test39 for 4 expect 1 pred test51 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Farmer0 + State1->Fox0 + State1->Chicken0 + State1->Grain0 + State2->Fox0 + State2->Grain0 + State3->Farmer0 + State3->Fox0 + State3->Grain0 far = State2->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test51 for 4 expect 0 pred test7 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test7 for 4 expect 1 pred test16 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Chicken0 + Grain0,Chicken0,none,Farmer0] }}}}}} } run test16 for 4 expect 1 pred test41 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Fox0 + Grain0,none,Farmer0 + Chicken0] }}}}}} } run test41 for 4 expect 1 pred test2 { some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { no Farmer Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Chicken0 far = State1->Fox0 + State2->Fox0 + State2->Chicken0 + State3->Fox0 + State3->Chicken0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}} } run test2 for 4 expect 0 pred test23 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Chicken0,none,Farmer0 + Fox0] }}}}}} } run test23 for 4 expect 1 pred test43 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0,Fox0,none,Farmer0 + Chicken0] }}}}}} } run test43 for 4 expect 1 pred test52 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State0->Chicken0 + State0->Grain0 + State1->Farmer0 + State1->Chicken0 + State1->Grain0 + State2->Chicken0 + State3->Farmer0 + State3->Chicken0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test52 for 4 expect 0 pred test12 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Farmer0,none,Farmer0] }}}}}} } run test12 for 4 expect 0 ",8054,True,3183.688190683191,median "open util/ordering [State] as ord pred test15 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State1->Chicken0 + State2->Chicken0 + State3->Farmer0 + State3->Chicken0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Grain0,none,Farmer0] }}}}}} } run test15 for 4 expect 0 pred test35 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Chicken0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State1->Chicken0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Grain0,Fox0,none,Farmer0 + Grain0] }}}}}} } run test35 for 4 expect 1 pred test13 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State1->Chicken0 + State2->Chicken0 + State3->Farmer0 + State3->Chicken0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Farmer0,none,Farmer0] }}}}}} } run test13 for 4 expect 0 pred test30 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Chicken0,Fox0 + Chicken0 + Grain0,Farmer0 + Fox0 + Chicken0 + Grain0] }}}}}} } run test30 for 4 expect 1 pred test32 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Chicken0 + Grain0,Chicken0,none,Farmer0 + Grain0] }}}}}} } run test32 for 4 expect 1 pred test36 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0,Fox0,Fox0,Farmer0 + Fox0 + Chicken0] }}}}}} } run test36 for 4 expect 1 pred test54 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Chicken0 + State2->Grain0 + State3->Fox0 + State3->Chicken0 far = State1->Farmer0 + State2->Fox0 + State2->Chicken0 + State2->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test54 for 4 expect 0 pred test22 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State1->Chicken0 + State2->Chicken0 + State3->Farmer0 + State3->Chicken0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Grain0,Fox0 + Grain0,Fox0 + Chicken0 + Grain0,none] }}}}}} } run test22 for 4 expect 0 pred test33 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0,Chicken0,none,Farmer0 + Fox0] }}}}}} } run test33 for 4 expect 1 pred test29 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Grain0,Fox0,none,Farmer0 + Grain0] }}}}}} } run test29 for 4 expect 1 pred test17 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Chicken0,Chicken0,none,Farmer0] }}}}}} } run test17 for 4 expect 1 pred test12 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Farmer0,none,Farmer0] }}}}}} } run test12 for 4 expect 0 pred test50 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State1->Farmer0 + State3->Farmer0 + State3->Fox0 far = State0->Fox0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test50 for 4 expect 0 pred test4 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Grain0: Grain {some disj Farmer0, Fox0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 no Chicken Grain = Grain0 Object = Farmer0 + Fox0 + Grain0 no eats State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State3->Fox0 far = State1->Farmer0 + State1->Grain0 + State2->Grain0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}} } run test4 for 4 expect 0 pred test23 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Chicken0,none,Farmer0 + Fox0] }}}}}} } run test23 for 4 expect 1 pred test3 { some disj Farmer0: Farmer {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 no Fox Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Chicken0 + Grain0 eats = Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Chicken0 + State0->Grain0 + State1->Grain0 + State2->Farmer0 + State2->Grain0 + State3->Grain0 far = State1->Farmer0 + State1->Chicken0 + State2->Chicken0 + State3->Farmer0 + State3->Chicken0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}} } run test3 for 4 expect 0 pred test48 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Chicken0 + State2->Farmer0 + State2->Fox0 + State2->Chicken0 + State2->Grain0 + State3->Fox0 + State3->Chicken0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test48 for 4 expect 0 pred test49 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test49 for 4 expect 1 pred test27 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Chicken0 + Grain0,Grain0,Chicken0 + Grain0,Farmer0 + Chicken0 + Grain0] }}}}}} } run test27 for 4 expect 1 pred test7 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test7 for 4 expect 1 pred test5 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Farmer0, Fox0, Chicken0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 no Grain Object = Farmer0 + Fox0 + Chicken0 eats = Fox0->Chicken0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State3->Fox0 far = State1->Farmer0 + State1->Chicken0 + State2->Chicken0 + State3->Farmer0 + State3->Chicken0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}} } run test5 for 4 expect 0 pred test24 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Chicken0,none,none,Farmer0 + Grain0] }}}}}} } run test24 for 4 expect 0 pred test43 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0,Fox0,none,Farmer0 + Chicken0] }}}}}} } run test43 for 4 expect 1 pred test55 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Farmer0 + State1->Grain0 + State2->Grain0 + State3->Fox0 + State3->Chicken0 far = State1->Fox0 + State1->Chicken0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Chicken0 + State2->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test55 for 4 expect 0 pred test42 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Grain0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Fox0 + Chicken0 + Grain0,Fox0 + Grain0,Fox0 + Grain0,Farmer0 + Fox0] }}}}}} } run test42 for 4 expect 0 pred test46 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Grain0 + State3->Fox0 far = State1->Farmer0 + State1->Chicken0 + State2->Chicken0 + State3->Farmer0 + State3->Chicken0 + State3->Grain0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 solvePuzzle[] }}}}}} } run test46 for 4 expect 0 pred test44 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Fox0 + State1->Grain0 + State2->Farmer0 + State2->Fox0 + State2->Chicken0 + State2->Grain0 + State3->Fox0 + State3->Grain0 far = State1->Farmer0 + State1->Chicken0 + State3->Farmer0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 crossRiver[Grain0,none,none,Farmer0 + Grain0] }}}}}} } run test44 for 4 expect 1 pred test56 { some disj Farmer0: Farmer {some disj Fox0: Fox {some disj Chicken0: Chicken {some disj Grain0: Grain {some disj Farmer0, Fox0, Chicken0, Grain0: Object {some disj State0, State1, State2, State3: State { Farmer = Farmer0 Fox = Fox0 Chicken = Chicken0 Grain = Grain0 Object = Farmer0 + Fox0 + Chicken0 + Grain0 eats = Fox0->Chicken0 + Chicken0->Grain0 State = State0 + State1 + State2 + State3 near = State0->Farmer0 + State0->Fox0 + State0->Chicken0 + State0->Grain0 + State1->Chicken0 + State2->Farmer0 + State2->Chicken0 + State3->Chicken0 far = State1->Farmer0 + State1->Fox0 + State2->Fox0 + State3->Farmer0 + State3->Fox0 ord/first = State0 ord/next = State0->State1 + State1->State2 + State2->State3 }}}}}} } run test56 for 4 expect 1 ",8011,True,3012.1310913961665,median "[appendix] [[_bayeux]] == The Bayeux Protocol Specification 1.0 Alex Russell; Greg Wilkins; David Davis; Mark Nesbitt (C) 2007 The Dojo Foundation === Status of this Document This document specifies a protocol for the Internet community, and requests discussion and suggestions for improvement. This document is written in the style and spirit of an IETF RFC but is not yet an official IETF RFC. Distribution of this document is unlimited. === Abstract Bayeux is a protocol for transporting asynchronous messages (primarily over web protocols such as HTTP and WebSocket), with low latency between a web server and web clients. === Introduction ==== Purpose The primary purpose of Bayeux is to support responsive bidirectional interactions between web clients, for example using https://en.wikipedia.org/wiki/AJAX[AJAX], and the web server. Bayeux is a protocol for transporting asynchronous messages (primarily over HTTP), with low latency between a web server and a web client. The messages are routed via named _channels_ and can be delivered: * server to client * client to server * client to client (via the server) By default, _publish/subscribe_ routing semantics are applied to the channels. Delivery of asynchronous messages from the server to a web client is often described as _server push_. The combination of server push techniques with an AJAX web application has been called _Comet_. CometD is a project to provide multiple implementation of the Bayeux protocol in several programming languages. Bayeux seeks to reduce the complexity of developing Comet web applications by allowing implementers to more easily interoperate, to solve common message distribution and routing problems, and to provide mechanisms for incremental improvements and extensions. ==== Requirements The keywords ""MUST"", ""MUST NOT"", ""REQUIRED"", ""SHALL"", ""SHALL NOT"", ""SHOULD"",""SHOULD NOT"", ""RECOMMENDED"", ""MAY"", and ""OPTIONAL"" in this document are to be interpreted as described in RFC2119. An implementation is not compliant if it fails to satisfy one or more of the MUST or REQUIRED level requirements for the protocols it implements. An implementation that satisfies all the MUST or REQUIRED level and all the SHOULD level requirements for its protocols is said to be ""unconditionally compliant""; one that satisfies all the MUST level requirements but not all the SHOULD level requirements for its protocols is said to be ""conditionally compliant."" ==== Terminology This specification uses a number of terms to refer to the roles played by participants in, and objects of, Bayeux communication: client:: A program that initiates the communication. server:: An application program that accepts communications from clients. A web server accepts TCP/IP connections in order to service web requests (HTTP requests or WebSocket requests) by sending back web responses. A Bayeux server accepts and responds to the message exchanges initiated by a Bayeux client. request:: For the HTTP protocol, an HTTP request message as defined by section 5 of RFC 2616. response:: For the HTTP protocol, an HTTP response message as defined by section 6 of RFC 2616. message:: A message is a JSON encoded object exchanged between client and server for the purpose of implementing the Bayeux protocol as defined by xref:_bayeux_message_fields[the message fields section], xref:_bayeux_meta_message[the meta messages section], and xref:_bayeux_event_message[the event messages section]. event:: Application specific data that is sent over the Bayeux protocol. envelope:: The transport specific message format that wraps a standard Bayeux message. channel:: A named destination and/or source of events. Events are published to channels and subscribers to channels receive published events. connection:: A communication link that is established either permanently or transiently, for the purposes of messages exchange. A client is connected if a link is established with the server, over which asynchronous events can be received. JSON:: JavaScript Object Notation (JSON) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition -- December 1999. JSON is described at https://www.json.org/. [[_bayeux_operation]] === Overall Operation [[_bayeux_http_transport]] ==== HTTP Transport The HTTP protocol is a request/response protocol. A client sends a request to the server in the form of a request method, URI, and protocol version, followed by a MIME-like message containing request modifiers, client information, and optional body content over a connection with a server. The server responds with a status line, including the message's protocol version and a success or error code, followed by a MIME-like message containing server information, entity meta-information, and possible entity-body content. The server may not initiate a connection with a client nor send an unrequested response to the client, thus asynchronous events cannot be delivered from server to client unless a previously issued request exists. In order to allow two-way asynchronous communication, Bayeux supports the use of multiple HTTP connections between a client and server, so that previously issued requests are available to transport server to client messages. The recommendation of section 8.1.4 of RFC 2616 is that a single client SHOULD NOT maintain more than 2 connection with any server, thus the Bayeux protocol MUST NOT require any more than 2 HTTP requests to be simultaneously handled by a server in order to handle all application (Bayeux based or otherwise) requests from a client. ==== Non HTTP Transports While HTTP is the predominant transport protocol used on the internet, it is not intended that it will be the only transport for Bayeux. Other transports that support a request/response paradigm may be used (for example, WebSocket is not a request/response protocol, but supports a request/response paradigm). However, this document assumes HTTP for reasons of clarity. When non-HTTP connection-level transport mechanisms are employed, conforming Bayeux servers and clients MUST still conform to the semantics of the JSON encoded messages outlined in this document. Several of the ""transport types"" described in this document are distinguished primarily by how they wrap messages for delivery over HTTP and the sequence and content of the HTTP connections initiated by clients. While this may seem like a set of implementation concerns to observant readers, the difficulties of creating interoperable implementations without specifying these semantics fully is a primary motivation for the development of this specification. Were the deployed universe of servers and clients more flexible, it may not have been necessary to develop Bayeux. Regardless, care has been taken in the development of this specification to ensure that future clients and servers which implement differing connection-level strategies and encodings may still evolve and continue to be conforming Bayeux implementations so long as they implement the JSON-based public/subscribe semantics outlined herein. [NOTE] ==== The rest of this document speaks as though HTTP will be used for message transport. ==== ==== JavaScript Bayeux clients implemented in JavaScript that run within the security framework of a browser MUST adhere to the restrictions imposed by the browser, such as the https://en.wikipedia.org/wiki/Same_origin_policy[same origin policy] or the https://www.w3.org/TR/access-control/[CORS] specification, or the threading model. These restrictions are normally enforced by the browser itself, but nonetheless the client implementation must be aware of these restrictions and adhere to them. Bayeux clients implemented in JavaScript but not running within a browser MAY relax the restrictions imposed by browsers. ==== Client to Server event delivery A Bayeux event is sent from the client to the server via an HTTP request initiated by a client and transmitted to the origin server via a chain of zero or more intermediaries (proxy, gateway or tunnel): ---- BC ---------- U ---------- P ------------ O ---------- BS | --M0(E)--> | | | | | | ---HTTP request(M0(E))--> | | | | | | --M0(E)--> | | | | | <---M1---- | | | <---HTTP response(M1)---- | | | <---M1--- | | | | | | | | | ---- The figure above represents a Bayeux event E encapsulated in a Bayeux message M0 being sent from a Bayeux client BC to a Bayeux server BS via an HTTP request transmitted from a User Agent U to an Origin server O via a proxy P. The HTTP response contains another Bayeux message M1 that will at least contain the protocol response to M0, but may contain other Bayeux events initiated on the server or on other clients. ==== Server to Client event delivery A Bayeux event is sent from the server to the client via an HTTP response to an HTTP request sent in anticipation by a client and transmitted to an origin server via a chain of zero or more intermediaries (proxy, gateway or tunnel): ---- BC ---------- U ---------- P ------------ O ---------- BS | ---M0---> | | | | | | --- HTTP request(M0) ---> | | | | | | ----M0---> | ~ ~ ~ ~ ~ wait | | | | <--M1(E)-- | | | <--HTTP response(M1(E))-- | | | <--M1(E)-- | | | | ~ ~ ~ ~ ~ ---- The figure above represents a Bayeux message M0 being sent from a Bayeux client BC to a Bayeux server BS via an HTTP request transmitted from a User Agent U to an Origin server O via a proxy P. The message M0 is sent in anticipation of a Bayeux event to be delivered from server to client, and the Bayeux server waits for such an event before sending a response. A Bayeux event E is shown being delivered via Bayeux message M1 in the HTTP response. M1 may contain zero, one or more Bayeux events destined for the Bayeux client. The transport used to send events from the server to the client may terminate the HTTP response (which does not imply that the connection is closed) after delivery of M1 or use techniques to leave the HTTP response uncompleted and stream additional messages to the client. ==== Polling transports Polling transports will always terminate the HTTP response after sending all available Bayeux messages. ---- BC ---------- U ---------- P ------------ O ---------- BS | ---M0---> | | | | | | --- HTTP request(M0) ---> | | | | | | ----M0---> | ~ ~ ~ ~ ~ wait | | | | <--M1(E)-- | | | <--HTTP response(M1(E))-- | | | <--M1(E)-- | | | | | ---M2---> | | | | | | --- HTTP request(M2) ---> | | | | | | ----M2---> | ~ ~ ~ ~ ~ wait ---- On receipt of the HTTP response containing M1, the Bayeux client issues a new Bayeux message M2 either immediately or after an interval in anticipation of more events to be delivered from server to client. Bayeux implementations MUST support a specific style of polling transport called _long polling_ (see also xref:_bayeux_long_polling[the long polling transport section]). ==== Streaming transports Some Bayeux transports use the _streaming technique_ (also called the _forever response_) that allows multiple messages to be sent within the same HTTP response: ---- BC ---------- U ---------- P ------------ O ---------- BS | ---M0---> | | | | | | --- HTTP request(M0) ---> | | | | | | ----M0---> | ~ ~ ~ ~ ~ wait | | | | <--M1(E0)- | | | <--HTTP response(M1(E0))- | | | <--M1(E0)- | | | | ~ ~ ~ ~ ~ wait | | | | <--M1(E1)- | | | <----(M1(E1))------------ | | | <--M1(E1)- | | | | ~ ~ ~ ~ ~ wait ---- Streaming techniques avoid the latency and extra messaging of anticipatory requests, but are subject to the implementation of user agents and proxies as they require incomplete HTTP responses to be delivered to the Bayeux client. ==== Two connection operation In order to achieve bidirectional communication, a Bayeux client uses 2 HTTP connections (see also xref:_bayeux_http_transport[the http transport section]) to a Bayeux server so that both server to client and client to server messaging may occur asynchronously: ---- BC ---------- U ---------- P ------------ O ---------- BS | ---M0---> | | | | | | ------ req0(M0) --------> | | | | | | ----M0---> | ~ ~ ~ ~ ~ wait | --M1(E1)-> | | | | | | ----- req1(M1(E1))------> | | | | | | --M1(E1)-> | | | | | <---M2---- | | | <---- resp1(M2)---------- | | | <---M2--- | | | | ~ ~ ~ ~ ~ wait | | | | <-M3(E2)-- | | | <-----resp2(M3(E2))------ | | | <-M3(E2)-- | | | | | ---M4---> | | | | | | ------req3(M4)----------> | | | | | | ----M4---> | ~ ~ ~ ~ ~ wait ---- HTTP requests req0 and req1 are sent on different TCP/IP connections, so that the response to req1 may be sent before the response to req0. Implementations MUST control HTTP pipelining so that req1 does not get queued behind req0 and thus enforce an ordering of responses. ==== Connection Negotiation Bayeux connections are negotiated between client and server with handshake messages that allow the connection type, authentication and other parameters to be agreed upon between the client and the server. ---- BC ----------------------------------------- BS | ------------------ handshake request ---> | | <---- handshake response ---------------- | | -------------------- connect request ---> | ~ ~ wait | <------ connect response ---------------- | ---- Bayeux connection negotiation may be iterative and several handshake messages may be exchanged before a successful connection is obtained. Servers may also request Bayeux connection renegotiation by sending an unsuccessful connect response with advice to reconnect with a handshake message. ---- BC ----------------------------------------- BS | ------------------ handshake request ---> | | <-- unsuccessful handshake response ----- | | ------------------ handshake request ---> | | <-- successful handshake response ------- | | -------------------- connect request ---> | ~ ~ wait | <------ connect response ---------------- | | -------------------- connect request ---> | | <---- unsuccessful connect response ----- | | ------------------ handshake request ---> | | <-- successful handshake response ------- | | -------------------- connect request ---> | ~ ~ wait | <------ connect response ---------------- | ---- ==== Unconnected operation OPTIONALLY, messages can be sent without a prior handshake (see also xref:_bayeux_publish[the publish section]). ---- BC ----------------------------------------- BS | ------------------- message request ----> | | <---- message response ------------------ | ---- This pattern is often useful when implementing non-browser clients for Bayeux servers. These clients often simply wish to address messages to other clients which the Bayeux server may be servicing, but do not wish to listen for events themselves. Bayeux servers MAY support messages sent without a prior handshake, but in any case MUST respond to such messages (eventually with an error message). ==== Client State Table ---- -------------++------------+-------------+------------+------------ State/Event || handshake | Timeout | Successful | Disconnect || request | | connect | request || sent | | response | sent -------------++------------+-------------+----------- +------------ UNCONNECTED || CONNECTING | UNCONNECTED | | CONNECTING || | UNCONNECTED | CONNECTED | UNCONNECTED CONNECTED || | UNCONNECTED | | UNCONNECTED -------------++------------+-------------+------------+------------ ---- [[_bayeux_protocol_elements]] === Protocol Elements ==== Common Elements The characters used for Bayeux names and identifiers are defined by the BNF definitions: ---- alpha = lowalpha | upalpha lowalpha = ""a"" | ""b"" | ""c"" | ""d"" | ""e"" | ""f"" | ""g"" | ""h"" | ""i"" | ""j"" | ""k"" | ""l"" | ""m"" | ""n"" | ""o"" | ""p"" | ""q"" | ""r"" | ""s"" | ""t"" | ""u"" | ""v"" | ""w"" | ""x"" | ""y"" | ""z"" upalpha = ""A"" | ""B"" | ""C"" | ""D"" | ""E"" | ""F"" | ""G"" | ""H"" | ""I"" | ""J"" | ""K"" | ""L"" | ""M"" | ""N"" | ""O"" | ""P"" | ""Q"" | ""R"" | ""S"" | ""T"" | ""U"" | ""V"" | ""W"" | ""X"" | ""Y"" | ""Z"" digit = ""0"" | ""1"" | ""2"" | ""3"" | ""4"" | ""5"" | ""6"" | ""7"" | ""8"" | ""9"" alphanum = alpha | digit mark = ""-"" | ""_"" | ""!"" | ""~"" | ""("" | "")"" | ""$"" | ""@"" string = *( alphanum | mark | "" "" | ""/"" | ""*"" | ""."" ) token = ( alphanum | mark ) *( alphanum | mark ) integer = digit *( digit ) ---- ==== Channels Channels are identified by names that are styled as the absolute path component of a URI without parameters. This is the BNF definition for channel names: ---- channel_name = ""/"" channel_segments channel_segments = channel_segment *( ""/"" channel_segment ) channel_segment = token ---- The channel name consists of an initial `/` followed by an optional sequence of path segments separated by a single slash `/` character. Within a path segment, the character `/` is reserved. Channel names commencing with `/meta/` are reserved for the Bayeux protocol (see also xref:_bayeux_meta_channels[the meta channels section]). Channel names commencing with `/service/` have a special meaning for the Bayeux protocol (see also xref:_bayeux_service_channels[the service channels section]). Example non-meta channel names are: `/foo/bar`:: Regular channel name `/foo-bar/(foobar)`:: Channel name with dash and parenthesis ===== Channel Globbing A set of channels may be specified with a channel globbing pattern: ---- channel_pattern = *( ""/"" channel_segment ) ""/"" wild_card wild_card = ""*"" | ""**"" ---- The channel patterns support only trailing wildcards of either `+*+` to match a single segment or `+**+` to match multiple segments. Example channel patterns are: `+/foo/*+`:: Matches `/foo/bar` and `/foo/boo`. Does not match `/foo`, `/foobar` or `/foo/bar/boo`. `+/foo/**+`:: Matches `/foo/bar`, `/foo/boo` and `/foo/bar/boo`. Does not match `/foo`, `/foobar` or `/foobar/boo`. [[_bayeux_meta_channels]] ==== Meta Channels The channels commencing with the `/meta/` segment are the channels used by the Bayeux protocol itself. Local server-side Bayeux clients MAY, and remote Bayeux clients SHOULD NOT, subscribe (see also xref:_bayeux_meta_subscribe[the bayeux subscribe section]) to meta channels. Messages published to meta channels MUST NOT be distributed to remote clients by Bayeux servers. A server side handler of a meta channel MAY publish response messages that are delivered only to the client that sent the original request message. If a message published to a meta channel contains an id field, then any response messages delivered to the client MUST contain an id field with the same value. [[_bayeux_service_channels]] ==== Service Channels The channels commencing with the `/service/` channel segment are special channels designed to assist request/response style messaging. Messages published to service channels are not distributed to any remote Bayeux clients. Handlers of service channels MAY deliver response messages to the client that published the request message. Servers SHOULD NOT record any subscriptions they receive for service channels. If a message published to a service channel contains an id field, then any response messages SHOULD contain an id field with the same value, or a value derived from the request id. Request/response operations are described in detail in xref:_bayeux_service_channel_operation[the service channel operation section]. ==== Version A protocol version is an integer followed by an optional ""."" separated sequence of alphanumeric elements: ---- version = integer *( ""."" version_element ) version_element = alphanum *( alphanum | ""-"" | ""_"" ) ---- Versions are compared element by element, applying normal alphanumeric comparison to each element. ==== Client ID A client ID is a random, non predictable sequence of alphanumeric characters: ---- clientId = alphanum *( alphanum ) ---- Client IDs are generated by the server and SHOULD be created with a strong random algorithm that contains at least 128 truly random bits. Servers MUST ensure that client IDs are unique and SHOULD attempt to avoid reuse of client IDs. Client IDs are encoded for delivery as strings. See also xref:_bayeux_clientid[the `clientId` field section]. ==== Messages Bayeux messages are JSON encoded objects that contain an unordered sequence of name value pairs representing fields and values. Values may be a simple strings, numbers, boolean values, or complex JSON encoded objects or arrays. A Bayeux message MUST contain one and only one channel field which determines the type of the message and the allowable fields. All Bayeux messages SHOULD be encapsulated in a JSON encoded array so that multiple messages may be transported together. A Bayeux client or server MUST accept either array of messages and MAY accept a single message. The JSON encoded message or array of messages is itself often encapsulated in transport specific formatting and encodings. Below is an example Bayeux message in a JSON encoded array representing an event sent from a client to a server: [source,json] ---- [{ ""channel"": ""/some/channel"", ""clientId"": ""83js73jsh29sjd92"", ""data"": { ""myapp"": ""specific data"", ""value"": 100 } }] ---- [[_bayeux_message_fields]] === Common Message Field Definitions ==== `channel` The `channel` message field MUST be included in every Bayeux message to specify the source or destination of the message. In a request, the channel specifies the destination of the message, and in a response it specifies the source of the message. ==== `version` The `version` message field MUST be included in messages to/from the `/meta/handshake` channel to indicate the protocol version expected by the client/server. ==== `minimumVersion` The `minimumVersion` message field MAY be included in messages to/from the `/meta/handshake` channel to indicate the oldest protocol version that can be handled by the client/server. [[_bayeux_supported_connections]] ==== `supportedConnectionTypes` The `supportedConnectionTypes` field is included in messages to/from the `/meta/handshake` channel to allow clients and servers to reveal the transports that are supported. The value is an array of strings, with each string representing a transport name. Defined connection types include: `long-polling`:: This transport is defined in xref:_bayeux_long_polling[the long polling transport section]. `callback-polling`:: This transport is defined in xref:_bayeux_callback_polling[the callback polling transport section] `iframe`:: OPTIONAL transport using the document content of a hidden iframe element. `flash`:: OPTIONAL transport using the capabilities of a browser flash plugin. All server and client implementations MUST support the `long-polling` connection type and SHOULD support `callback-polling`. All other connection types are OPTIONAL. [[_bayeux_clientid]] ==== `clientId` The `clientId` message field uniquely identifies a client to the Bayeux server. The `clientId` message field MUST be included in every message sent to the server except for messages sent to the `/meta/handshake` channel and MAY be omitted in a publish message (see also xref:_bayeux_event_message[the event message section]). The `clientId` message field MAY be returned in message responses except for failed handshake requests and for publish message responses that were sent without `clientId`. However, care must be taken to not _leak_ the `clientId` to other clients when broadcasting messages, because that would allow any other client to impersonate the client whose `clientId` was leaked. [[_bayeux_advice]] ==== `advice` The `advice` message field provides a way for servers to inform clients of their preferred mode of client operation so that in conjunction with server-enforced limits, Bayeux implementations can prevent resource exhaustion and inelegant failure modes. Furthermore, the `advice` message field provides a way for clients to inform servers of their preferred mode of operation so that they can better inform client-side applications of state changes (for example, connection state changes) that are relevant for applications. The `advice` field is a JSON encoded object containing general and transport specific values that indicate modes of operation, timeouts and other potential transport specific parameters. Advice fields may occur either in the top level of an advice object or within a transport specific section of the advice object. Unless otherwise specified in xref:_bayeux_event_message[the event message section], and xref:_bayeux_transports[the transports section], any Bayeux response message may contain an advice field. Advice received always supersedes any previous received advice. An example advice field sent by the server is: [source,json] ---- { ""advice"": { ""reconnect"": ""retry"", ""timeout"": 30000, ""interval"": 1000, ""callback-polling"": { ""reconnect"": ""handshake"" } } } ---- An example advice field sent by the client is: [source,json] ---- { ""advice"": { ""timeout"": 0 } } ---- ===== `reconnect` advice field The `reconnect` advice field is a string that indicates how the client should act in the case of a failure to connect. Defined `reconnect` advice field values are: `retry`:: a client MAY attempt to reconnect with a `/meta/connect` message after the interval (as defined by `interval` advice field or client-default backoff), and with the same credentials. `handshake`:: the server has terminated any prior connection status, and the client MUST reconnect with a `/meta/handshake` message. A client MUST NOT automatically retry when a `reconnect: ""handshake""` advice has been received. `none`:: indicates a hard failure for the connect attempt. A client MUST respect reconnect advice `none` and MUST NOT automatically retry or handshake. Any client that does not implement all defined values of reconnect MUST NOT automatically retry or handshake. ===== `timeout` advice field An integer representing the period of time, in milliseconds, for the server to delay responses to the `/meta/connect` channel. This value is merely informative for clients. Bayeux servers SHOULD honor timeout advices sent by clients. ===== `interval` advice field An integer representing the minimum period of time, in milliseconds, for a client to delay subsequent requests to the `/meta/connect` channel. A negative period indicates that the message should not be retried. A client MUST implement interval support, but a client MAY exceed the interval provided by the server. A client SHOULD implement a backoff strategy to increase the interval if requests to the server fail without new advice being received from the server. [[_bayeux_multiple_clients_advice]] ===== `multiple-clients` advice field This is a boolean field, which when true indicates that the server has detected multiple Bayeux client instances running within the same web client. ===== `hosts` advice field This is an array of strings, which when present indicates a list of host names or IP addresses that MAY be used as alternate servers with which the client may connect. If a client receives advice to rehandshake and the current server is not included in a supplied hosts list, then the client SHOULD try the hosts in order until a successful connection is established. Advice received during handshakes with hosts in the list supersedes any previously received advice. ==== `connectionType` The `connectionType` message field specifies the type of transport the client requires for communication. The `connectionType` message field MUST be included in request messages to the `/meta/connect` channel. Connection types are listed in xref:_bayeux_supported_connections[the supported connections section]. [[_bayeux_id]] ==== `id` An `id` message field MAY be included in any Bayeux message with an alphanumeric value: ---- id = alphanum *( alphanum ) ---- Generation of IDs is implementation specific and may be provided by the application. Messages published to `+/meta/**+` and `+/service/**+` SHOULD have `id` fields that are unique within the connection. Messages sent in response to messages delivered to `+/meta/**+` channels MUST use the same message id as the request message. Messages sent in response to messages delivered to `+/service/**+` channels SHOULD use the same message id as the request message, or an id derived from the request message id. ==== `timestamp` The `timestamp` message field SHOULD be specified in the following ISO 8601 profile (all times SHOULD be sent in GMT time): ---- YYYY-MM-DDThh:mm:ss.ss ---- A timestamp message field is OPTIONAL in all Bayeux messages. ==== `data` The `data` message field is an arbitrary JSON encoded object that contains event information. The `data` message field MUST be included in publish messages, and a Bayeux server MUST include the `data` message field in an event delivery message. ==== `successful` The boolean `successful` message field is used to indicate success or failure and MUST be included in responses to the `/meta/handshake`, `/meta/connect`, `/meta/subscribe`, `/meta/unsubscribe`, `/meta/disconnect`, and publish channels. ==== `subscription` The `subscription` message field specifies the channels the client wishes to subscribe to or unsubscribe from. The `subscription` message field MUST be included in requests and responses to/from the `/meta/subscribe` or `/meta/unsubscribe` channels. ==== `error` The `error` message field is OPTIONAL in any Bayeux response. The `error` message field MAY indicate the type of error that occurred when a request returns with a false successful message. The error message field should be sent as a string in the following format: ---- error = error_code "":"" error_args "":"" error_message | error_code "":"" "":"" error_message error_code = digit digit digit error_args = string *( "","" string ) error_message = string ---- Example error strings are: ---- 401::No client ID 402:xj3sjdsjdsjad:Unknown Client ID 403:xj3sjdsjdsjad,/foo/bar:Subscription denied 404:/foo/bar:Unknown Channel ---- [[_bayeux_ext]] ==== `ext` An `ext` message field MAY be included in any Bayeux message. Its value SHOULD be a JSON encoded object with top level names distinguished by implementation names (for example ""com.acme.ext.auth""). The contents of `ext` message field may be arbitrary values that allow extensions to be negotiated and implemented between server and client implementations. ==== `connectionId` The `connectionId` message field was used during development of the Bayeux protocol and its use is now deprecated and SHOULD not be used. ==== `json-comment-filtered` The `json-comment-filtered` message field of the handshake message is deprecated and SHOULD not be used. [[_bayeux_meta_message]] === Meta Message Field Definitions [[_bayeux_meta_handshake]] ==== Handshake ===== Handshake Request A Bayeux client initiates a connection negotiation by sending a message to the `/meta/handshake` channel. In case of HTTP same domain connections, the handshake requests MUST be sent to the server using the `long-polling` transport, while for cross domain connections the handshake request MAY be sent with the `long-polling` transport and failing that with the `callback-polling` transport. A handshake request MUST contain the following message fields: `channel`:: The value MUST be `/meta/handshake`. `version`:: The version of the protocol supported by the client. `supportedConnectionTypes`:: An array of the connection types supported by the client for the purposes of the connection being negotiated (see also xref:_bayeux_supported_connections[the supported connections section]). This list MAY be a subset of the connection types actually supported if the client wishes to negotiate a specific connection type. A handshake request MAY contain the message fields: `minimumVersion`:: The minimum version of the protocol supported by the client `ext`:: The xref:_bayeux_ext[extension object] `id`:: The xref:_bayeux_id[message id] A client SHOULD NOT send any other message in the request with a handshake message. A server MUST ignore any other message sent in the same request as a handshake message. An example handshake request is: [source,json] ---- [{ ""channel"": ""/meta/handshake"", ""version"": ""1.0"", ""minimumVersion"": ""1.0beta"", ""supportedConnectionTypes"": [""long-polling"", ""callback-polling"", ""iframe""] }] ---- ===== Handshake Response A Bayeux server MUST respond to a handshake request with a handshake response message. How the handshake response is formatted depends on the transport that has been agreed between client and server. ===== Successful Handshake Response A successful handshake response MUST contain the message fields: `channel`:: The value MUST be `/meta/handshake` `version`:: The version of the protocol that was negotiated `supportedConnectionTypes`:: The connection types supported by the server for the purposes of the connection being negotiated. This list MAY be a subset of the connection types actually supported if the server wishes to negotiate a specific connection type. This list MUST contain at least one element in common with the `supportedConnectionType` provided in the handshake request. If there are no connectionTypes in common, the handshake response MUST be unsuccessful. `clientId`:: A newly generated unique ID string. `successful`:: The value `true` A successful handshake response MAY contain the message fields: `minimumVersion`:: The minimum version of the protocol supported by the server `advice`:: The xref:_bayeux_advice[advice object] `ext`:: The xref:_bayeux_ext[extension object] `id`:: The same value as request message id `authSuccessful`:: The value `true`; this field MAY be included to support prototype client implementations that required the `authSuccessful` field An example successful handshake response is: [source,json] ---- [{ ""channel"": ""/meta/handshake"", ""version"": ""1.0"", ""minimumVersion"": ""1.0beta"", ""supportedConnectionTypes"": [""long-polling"",""callback-polling""], ""clientId"": ""Un1q31d3nt1f13r"", ""successful"": true, ""authSuccessful"": true, ""advice"": { ""reconnect"": ""retry"" } }] ---- ===== Unsuccessful Handshake Response An unsuccessful handshake response MUST contain the message fields: `channel`:: The value MUST be `/meta/handshake` `successful`:: The value `false` `error`:: A string with the description of the reason for the failure An unsuccessful handshake response MAY contain the message fields: `supportedConnectionTypes`:: The connection types supported by the server for the purposes of the connection being negotiated. This list MAY be a subset of the connection types actually supported if the server wishes to negotiate a specific connection type. `advice`:: The xref:_bayeux_advice[advice object] `version`:: The version of the protocol that was negotiated `minimumVersion`:: The minimum version of the protocol supported by the server `ext`:: The xref:_bayeux_ext[extension object] `id`:: The same value as request message id An example unsuccessful handshake response is: [source,json] ---- [{ ""channel"": ""/meta/handshake"", ""version"": ""1.0"", ""minimumVersion"": ""1.0beta"", ""supportedConnectionTypes"": [""long-polling"",""callback-polling""], ""successful"": false, ""error"": ""Authentication failed"", ""advice"": { ""reconnect"": ""none"" } }] ---- For complex connection negotiations, multiple handshake messages may be exchanged between the Bayeux client and server. The handshake response will set the `successful` message field to false until the handshake process is complete. The `advice` and `ext` message fields may be used to communicate additional information needed to complete the handshake process. An unsuccessful handshake response with `reconnect` advice field of `handshake` is used to continue the connection negotiation. An unsuccessful handshake response with `reconnect` advice field of `none` is used to terminate connection negotiations. [[_bayeux_meta_connect]] ==== Connect ===== Connect Request After a Bayeux client has discovered the server's capabilities with a handshake exchange, a connection is established by sending a message to the `/meta/connect` channel. This message may be transported over any of the transports indicated as supported by the server in the handshake response. A connect request MUST contain the message fields: `channel`:: The value MUST be `/meta/connect` `clientId`:: The client ID returned in the handshake response `connectionType`:: The connection type used by the client for the purposes of this connection. A connect request MAY contain the message fields: `ext`:: The xref:_bayeux_ext[extension object] `id`:: The xref:_bayeux_id[message id] A client MAY send other messages in the same HTTP request with a connection message. An example connect request is: [source,json] ---- [{ ""channel"": ""/meta/connect"", ""clientId"": ""Un1q31d3nt1f13r"", ""connectionType"": ""long-polling"" }] ---- A transport MUST maintain one and only one outstanding connect message. When an HTTP response that contains a `/meta/connect` response terminates, the client MUST wait at least the `interval` specified in the last received `advice` before following the advice to reestablish the connection. ===== Connect Response A Bayeux server MUST respond to a connect request with a connect response message over the same transport used for the request. A Bayeux server MAY wait to respond until there are event messages available in the subscribed channels for the client that need to be delivered to the client. A connect response MUST contain the message fields: `channel`:: value MUST be `/meta/connect` `successful`:: boolean indicating the success or failure of the connection A connect response MAY contain the message fields: `error`:: A string with the description of the reason for the failure `advice`:: The xref:_bayeux_advice[advice object] `ext`:: The xref:_bayeux_ext[extension object] `clientId`:: The client ID returned in the handshake response `id`:: The same value as request message id An example connect response is: [source,json] ---- [{ ""channel"": ""/meta/connect"", ""successful"": true, ""error"": """", ""clientId"": ""Un1q31d3nt1f13r"", ""advice"": { ""reconnect"": ""retry"" } }] ---- The client MUST maintain only a single outstanding connect message. If the server does not have a current outstanding connect, and a connect is not received within a configured timeout, then the server SHOULD act as if a disconnect message has been received. [[_bayeux_meta_disconnect]] ==== Disconnect ===== Disconnect Request When a connected client wishes to cease operation it should send a request to the `/meta/disconnect` channel for the server to remove any client-related state. The server SHOULD release any waiting meta message handlers. Bayeux client applications SHOULD send a disconnect request when the user shuts down a browser window or leaves the current page. A Bayeux server SHOULD NOT rely solely on the client sending a disconnect message to remove client-related state information because a disconnect message might not be sent from the client, or the disconnect request might not reach the server. A disconnect request MUST contain the message fields: `channel`:: The value MUST be `/meta/disconnect` `clientId`:: The client ID returned in the handshake response A disconnect request MAY contain the message fields: `ext`:: The xref:_bayeux_ext[extension object] `id`:: The xref:_bayeux_id[message id] An example disconnect request is: [source,json] ---- [{ ""channel"": ""/meta/disconnect"", ""clientId"": ""Un1q31d3nt1f13r"" }] ---- ===== Disconnect Response A Bayeux server MUST respond to a disconnect request with a disconnect response. A disconnect response MUST contain the message fields: `channel`:: The value MUST be `/meta/disconnect` `successful`:: A boolean value indicated the success or failure of the disconnect request A disconnect response MAY contain the message fields: `clientId`:: The client ID returned in the handshake response `error`:: A string with the description of the reason for the failure `ext`:: The xref:_bayeux_ext[extension object] `id`:: The same value as request message id An example disconnect response is: [source,json] ---- [{ ""channel"": ""/meta/disconnect"", ""successful"": true }] ---- [[_bayeux_meta_subscribe]] ==== Subscribe ===== Subscribe Request A connected Bayeux client may send subscribe messages to register interest in a channel and to request that messages published to that channel are delivered to itself. A subscribe request MUST contain the message fields: `channel`:: The value MUST be `/meta/subscribe` `clientId`:: The client ID returned in the handshake response `subscription`:: A channel name, or a channel pattern, or an array of channel names and channel patterns. A subscribe request MAY contain the message fields: `ext`:: The xref:_bayeux_ext[extension object] `id`:: The xref:_bayeux_id[message id] An example subscribe request is: [source,json] ---- [{ ""channel"": ""/meta/subscribe"", ""clientId"": ""Un1q31d3nt1f13r"", ""subscription"": ""/foo/**"" }] ---- ===== Subscribe Response A Bayeux server MUST respond to a subscribe request with a subscribe response message. A Bayeux server MAY send event messages for the client in the same HTTP response as the subscribe response, including events for the channels just subscribed to. A subscribe response MUST contain the message fields: `channel`:: The value MUST be `/meta/subscribe` `successful`:: A boolean indicating the success or failure of the subscription operation `subscription`:: A channel name, or a channel pattern, or an array of channel names and channel patterns. A subscribe response MAY contain the message fields: `error`:: A string with the description of the reason for the failure `advice`:: The xref:_bayeux_advice[advice object] `ext`:: The xref:_bayeux_ext[extension object] `clientId`:: The client ID returned in the handshake response `id`:: The same value as request message id An example successful subscribe response is: [source,json] ---- [{ ""channel"": ""/meta/subscribe"", ""clientId"": ""Un1q31d3nt1f13r"", ""subscription"": ""/foo/**"", ""successful"": true, ""error"": """" }] ---- An example failed subscribe response is: [source,json] ---- [{ ""channel"": ""/meta/subscribe"", ""clientId"": ""Un1q31d3nt1f13r"", ""subscription"": ""/bar/baz"", ""successful"": false, ""error"": ""403:/bar/baz:Permission Denied"" }] ---- [[_bayeux_meta_unsubscribe]] ==== Unsubscribe ===== Unsubscribe Request A connected Bayeux client may send unsubscribe messages to cancel interest in a channel and to request that messages published to that channel are not delivered to itself. An unsubscribe request MUST contain the message fields: `channel`:: The value MUST be `/meta/unsubscribe` `clientId`:: The client ID returned in the handshake response `subscription`:: A channel name, or a channel pattern, or an array of channel names and channel patterns. An unsubscribe request MAY contain the message fields: `ext`:: The xref:_bayeux_ext[extension object] `id`:: The xref:_bayeux_id[message id] An example unsubscribe request is: [source,json] ---- [{ ""channel"": ""/meta/unsubscribe"", ""clientId"": ""Un1q31d3nt1f13r"", ""subscription"": ""/foo/**"" }] ---- ===== Unsubscribe Response A Bayeux server MUST respond to an unsubscribe request with an unsubscribe response message. A Bayeux server MAY send event messages for the client in the same HTTP response as the unsubscribe response, including events for the channels just unsubscribed to as long as the event was processed before the unsubscribe request. An unsubscribe response MUST contain the message fields: `channel`:: The value MUST be `/meta/unsubscribe` `successful`:: A boolean indicating the success or failure of the unsubscribe operation `subscription`:: A channel name, or a channel pattern, or an array of channel names and channel patterns. A unsubscribe response MAY contain the message fields: `error`:: A string with the description of the reason for the failure `advice`:: The xref:_bayeux_advice[advice object] `ext`:: The xref:_bayeux_ext[extension object] `clientId`:: The client ID returned in the handshake response `id`:: The same value as request message id An example unsubscribe response is: [source,json] ---- [{ ""channel"": ""/meta/unsubscribe"", ""clientId"": ""Un1q31d3nt1f13r"", ""subscription"": ""/foo/**"", ""successful"": true, ""error"": """" }] ---- [[_bayeux_event_message]] === Event Message Field Definitions Application events are published in event messages sent from a Bayeux client to a Bayeux server and are delivered in event messages sent from a Bayeux server to a Bayeux client. [[_bayeux_publish]] ==== Publish ===== Publish Request A Bayeux client can publish events on a channel by sending event messages. An event message MAY be sent in new HTTP request, or it MAY be sent in the same HTTP request as any message other than a handshake meta message. A publish message MAY be sent from an unconnected client (that has not performed handshaking and thus does not have a client ID). It is OPTIONAL for a server to accept unconnected publish requests, and they should apply server specific authentication and authorization before doing so. A publish event message MUST contain the message fields: `channel`:: The channel to which the message is published `data`:: The message data as an arbitrary JSON encoded object A publish event message MAY contain the message fields: `clientId`:: The client ID returned in the handshake response `id`:: A unique ID for the message generated by the client `ext`:: The xref:_bayeux_ext[extension object] An example event message is: [source,json] ---- [{ ""channel"": ""/some/channel"", ""clientId"": ""Un1q31d3nt1f13r"", ""data"": ""some application string or JSON encoded object"", ""id"": ""some unique message id"" }] ---- ===== Publish Response A Bayeux server MAY respond to a publish event message with a publish event acknowledgement. A publish event message response MUST contain the message fields: `channel`:: The channel to which the message was published `successful`:: A boolean indicating the success or failure of the publish operation A publish event response MAY contain the message fields: `id`:: The xref:_bayeux_id[message id] `error`:: A string with the description of the reason for the failure `ext`:: The xref:_bayeux_ext[extension object] An example event response message is: [source,json] ---- [{ ""channel"": ""/some/channel"", ""successful"": true, ""id"": ""some unique message id"" }] ---- ==== Delivery Event messages MUST be delivered to clients if the client is subscribed to the channel of the event message. Event messages MAY be sent to the client in the same HTTP response as any other message other than a `/meta/handshake` response. If a Bayeux server has multiple HTTP requests from the same client, the server SHOULD deliver all available messages in the HTTP response that will be sent immediately in preference to waking a waiting connect meta message request. Event message delivery MAY not be acknowledged by the client. A deliver event message MUST contain the message fields: `channel`:: The channel to which the message was published `data`:: The message as an arbitrary JSON encoded object A deliver event response MAY contain the message fields: `id`:: Unique message ID from the publisher `ext`:: The xref:_bayeux_ext[extension object] `advice`:: The xref:_bayeux_advice[advice object] An example event deliver message is: [source,json] ---- [{ ""channel"": ""/some/channel"", ""data"": ""some application string or JSON encoded object"", ""id"": ""some unique message id"" }] ---- [[_bayeux_transports]] === Transports [[_bayeux_long_polling]] ==== The `long-polling` Transport The ""long-polling"" transport is a polling transport that attempts to minimize both latency in server-client message delivery, and the processing/network resources required for the connection. In ""traditional"" polling, servers send and terminate responses to requests immediately, even when there are no events to deliver, and worst-case latency is the polling delay between each client request. Long-polling server implementations attempt to hold open each request until there are events to deliver; the goal is to always have a pending request available to use for delivering events as they occur, thereby minimizing the latency in message delivery. Increased server load and resource starvation are addressed by using the `reconnect` and `interval` advice fields to throttle clients, which in the worst-case degenerate to traditional polling behaviour. ===== The `long-polling` request messages Messages SHOULD be sent to the server as the body of an `application/json` HTTP POST request with UTF-8 encoding. Alternatively, messages MAY be sent to the server as the `message` parameter of an `application/x-www-form-urlencoded` encoded POST request. If sent as form encoded, the Bayeux messages are sent as the `message` parameter in one of the following forms as: * Single valued and contain a single Bayeux message * Single valued and contain an array of Bayeux message * Multi valued and contain a several individual Bayeux message * Multi valued and contain a several arrays of Bayeux message * Multi valued and contain a mix of individual Bayeux messages and arrays of Bayeux message ===== The `long-polling` response messages Messages SHOULD be sent to the client as non encapsulated body content of an HTTP POST response with content type `application/json` with UTF-8 encoding. A `long-polling` response message may contain an advice field containing transport-specific fields to indicate the mode of operation of the transport. For the `long-polling` transport, the advice field MAY contain the following fields: `timeout`:: the number of milliseconds the server will hold the long poll request `interval`:: the number of milliseconds the client SHOULD wait before issuing another long poll request [[_bayeux_callback_polling]] ==== The `callback-polling` Transport ===== The `callback-polling` request messages Messages SHOULD be sent to the server as the `message` parameter of an url-encoded HTTP GET request. ===== The `callback-polling` response messages Responses are sent wrapped in a JavaScript callback in order to facilitate delivery. As specified by the https://en.wikipedia.org/wiki/JSONP[JSONP] pseudo-protocol, the name of the callback to be triggered is passed to the server via the `jsonp` HTTP GET parameter. In the absence of such a parameter, the name of the callback defaults to `jsonpcallback`. The called function will be passed a JSON encoded array of Bayeux messages. A `callback-polling` response message may contain an advice field containing transport-specific fields to indicate the mode of operation of the transport. For the `callback-polling` transport, the advice field MAY contain the following fields: `timeout`:: the number of milliseconds the server will hold the long poll request `interval`:: the number of milliseconds the client SHOULD wait before issuing another long poll request [[_bayeux_security]] === Security ==== Authentication The Bayeux protocol may be used with: * No authentication * Container supplied authentication (e.g. BASIC authentication or cookie managed session based authentication) * Bayeux extension authentication that exchanges authentication credentials and tokens within Bayeux messages `ext` fields For Bayeux authentication, no algorithm is specified for generating or validating security credentials or token. This version of the protocol only defines that the `ext` field may be used to exchange authentication challenges, credentials, and tokens and that the `advice` field may be used to control multiple iterations of the exchange. The connection negotiation mechanism may be used to negotiate authentication or request re-authentication. ==== AJAX Hijacking The AJAX hijacking vulnerability is when an attacking website uses a script tag to execute JSON encoded content obtained from an AJAX server. The Bayeux protocol is not vulnerable to this style of attack when cookies are not used for authentication, and a valid client ID is needed before private client data is returned. The use of POST by some transports further protects against this style of attack. [[_bayeux_multiple_clients]] === Multiple clients operation Current HTTP client implementations are RECOMMENDED to allow only 2 connections between a client and a server. This presents a problem when multiple instances of the Bayeux client are operating in multiple tabs or windows of the same browser instance. The 2 connection limit can be consumed by outstanding connect meta messages from each tab or window and thus prevent other messages from being delivered in a timely fashion. ==== Server-side Multiple clients detection It is RECOMMENDED that Bayeux server implementations use the cookie ""BAYEUX_BROWSER""to identify an HTTP client and to thus detect multiple Bayeux clients running within the same HTTP client. Once detected, the server SHOULD not wait for messages in connect and SHOULD use the advice interval mechanism to establish traditional polling. ==== Client-side Multiple clients handling It is RECOMMENDED that Bayeux client implementations use client side persistence or cookies to detect multiple instances of Bayeux clients running within the same HTTP client. Once detected, the user MAY be offered the option to disconnect all but one of the clients. It MAY be possible for client implementations to use client side persistence to share a Bayeux client instance. [[_bayeux_service_channel_operation]] === Request / Response operation with service channels The publish/subscribe paradigm that is directly supported by the Bayeux protocol is difficult to use to efficiently implement the request/response paradigm between a client and a server. The `+/service/**+` channel space has been designated as a special channel space to allow efficient transport of application request and responses over Bayeux channels. Messages published to service channels are not distributed to other Bayeux clients, so these channels can be used for private requests between a Bayeux client and a Bayeux server. A trivial example would be an echo service, that sent any message received from a client back to that client unaltered. Bayeux clients would subscribe the `/service/echo` channel, but the Bayeux server would not need to record this subscription. When a client publishes a message to the `/service/echo` channel, it will be delivered only to server-side subscribers (in an implementation dependent fashion). The server side subscriber for the echo service would handle each message received by publishing a response directly to the client regardless of any subscription. As the client has subscribed to `/service/echo`, the response message will be routed correctly within the client to the appropriate subscription handler. ",12380,False,2186.4890643819353,median "= Spring for GraphQL Documentation Brian Clozel; Andreas Marek; Rossen Stoyanchev; Mark Paluch include::attributes.adoc[] [[overview]] == Overview Spring for GraphQL provides support for Spring applications built on https://www.graphql-java.com/[GraphQL Java]. It is a joint collaboration between both teams. Our shared philosophy is to be less opinionated and more focused on comprehensive and wide-ranging support. Spring for GraphQL is the successor of the https://github.com/graphql-java/graphql-java-spring[GraphQL Java Spring] project from the GraphQL Java team. It aims to be the foundation for all Spring, GraphQL applications. The project is in a milestone phase towards a 1.0 release, currently, and looking for feedback. Please, use our https://github.com/spring-projects/spring-graphql/issues[issue tracker] to report a problem, discuss a design issue, or request a feature. To get started, check the Spring GraphQL starter on https://start.spring.io and the <> sections. [[requirements]] == Requirements Spring for GraphQL requires the following as a baseline: * JDK8 * Spring Framework 5.3 * GraphQL Java 17 * Spring Data 2021.1.0 or later for QueryDSL or Query by Example [[web-transports]] == Web Transports Spring for GraphQL supports GraphQL requests over HTTP and over WebSocket. [[web-http]] === HTTP `GraphQlHttpHandler` handles GraphQL over HTTP requests and delegates to the <> chain for request execution. There are two variants, one for Spring MVC and one for Spring WebFlux. Both handle requests asynchronously and have equivalent functionality, but rely on blocking vs non-blocking I/O respectively for writing the HTTP response. Requests must use HTTP POST with GraphQL request details included as JSON in the request body, as defined in the proposed https://github.com/graphql/graphql-over-http/blob/main/spec/GraphQLOverHTTP.md[GraphQL over HTTP] specification. Once the JSON body has been successfully decoded, the HTTP response status is always 200 (OK), and any errors from GraphQL request execution appear in the ""errors"" section of the GraphQL response. `GraphQlHttpHandler` can be exposed as an HTTP endpoint by declaring a `RouterFunction` bean and using the `RouterFunctions` from Spring MVC or WebFlux to create the route. The Boot starter does this, see the {spring-boot-ref-docs}/web.html#web.graphql.web-endpoints[Web Endpoints] section for details, or check `GraphQlWebMvcAutoConfiguration` or `GraphQlWebFluxAutoConfiguration` it contains, for the actual config. The Spring for GraphQL repository contains a Spring MVC {github-main-branch}/samples/webmvc-http[HTTP sample] application. [[web-websocket]] === WebSocket `GraphQlWebSocketHandler` handles GraphQL over WebSocket requests based on the https://github.com/enisdenjo/graphql-ws/blob/master/PROTOCOL.md[protocol] defined in the https://github.com/enisdenjo/graphql-ws[graphql-ws] library. The main reason to use GraphQL over WebSocket is subscriptions which allow sending a stream of GraphQL responses, but it can also be used for regular queries with a single response. The handler delegates every request to the <> chain for further request execution. [TIP] .GraphQL Over WebSocket Protocols ==== There are two such protocols, one in the https://github.com/apollographql/subscriptions-transport-ws[subscriptions-transport-ws] library and another in the https://github.com/enisdenjo/graphql-ws[graphql-ws] library. The former is not active and succeeded by the latter. Read this https://the-guild.dev/blog/graphql-over-websockets[blog post] for the history. ==== There are two variants of `GraphQlWebSocketHandler`, one for Spring MVC and one for Spring WebFlux. Both handle requests asynchronously and have equivalent functionality. The WebFlux handler also uses non-blocking I/O and back pressure to stream messages, which works well since in GraphQL Java a subscription response is a Reactive Streams `Publisher`. The `graphql-ws` project lists a number of https://github.com/enisdenjo/graphql-ws#recipes[recipes] for client use. `GraphQlWebSocketHandler` can be exposed as a WebSocket endpoint by declaring a `SimpleUrlHandlerMapping` bean and using it to map the handler to a URL path. The Boot starter has options to enable this, see the {spring-boot-ref-docs}/web.html#web.graphql.web-endpoints[Web Endpoints] section for details, or check `GraphQlWebMvcAutoConfiguration` or `GraphQlWebFluxAutoConfiguration` it contains, for the actual config. The Spring for GraphQL repository contains a WebFlux {github-main-branch}/samples/webflux-websocket[WebSocket sample] application. [[web-interception]] === Web Interception <> and <> transport handlers delegate to a common Web interception chain for request execution. The chain consists of a sequence of `WebInterceptor` components, followed by a `GraphQlService` that invokes the GraphQL Java engine. `WebInterceptor` is as a common contract to use in both Spring MVC and WebFlux applications. Use it to intercept requests, inspect HTTP request headers, or to register a transformation of the `graphql.ExecutionInput`: [source,java,indent=0,subs=""verbatim,quotes""] ---- class MyInterceptor implements WebInterceptor { @Override public Mono intercept(WebInput webInput, WebInterceptorChain chain) { webInput.configureExecutionInput((executionInput, builder) -> { Map map = ... ; return builder.extensions(map).build(); }); return chain.next(webInput); } } ---- Use `WebInterceptor` also to intercept responses, add HTTP response headers, or transform the `graphql.ExecutionResult`: [source,java,indent=0,subs=""verbatim,quotes""] ---- class MyInterceptor implements WebInterceptor { @Override public Mono intercept(WebInput webInput, WebInterceptorChain chain) { return chain.next(webInput) .map(webOutput -> { Object data = webOutput.getData(); Object updatedData = ... ; return webOutput.transform(builder -> builder.data(updatedData)); }); } } ---- `WebGraphQlHandler` provides a builder to initialize the Web interception chain. After you build the chain, you can use the resulting `WebGraphQlHandler` to initialize the HTTP or WebSocket transport handlers. The Boot starter configures all this, see the {spring-boot-ref-docs}/web.html#web.graphql.web-endpoints[Web Endpoints] section for details, or check `GraphQlWebMvcAutoConfiguration` or `GraphQlWebFluxAutoConfiguration` it contains, for the actual config. [[execution]] == Request Execution `GraphQlService` is the main Spring abstraction to call GraphQL Java to execute requests. Underlying transports, such as the <>, delegate to `GraphQlService` to handle requests. The main implementation, `ExecutionGraphQlService`, is a thin facade around the invocation of `graphql.GraphQL`. It is configured with a `GraphQlSource` for access to the `graphql.GraphQL` instance. [[execution-graphqlsource]] === `GraphQLSource` `GraphQlSource` is a core Spring abstraction for access to the `graphql.GraphQL` instance to use for request execution. It provides a builder API to initialize GraphQL Java and build a `GraphQlSource`. The default `GraphQlSource` builder, accessible via `GraphQlSource.builder()`, enables support for <>, <>, and <>. The Spring Boot {spring-boot-ref-docs}/web.html#web.graphql[starter] initializes a `GraphQlSource` instance through the default `GraphQlSource.Builder` and also enables the following: - Load <> from a configurable location. - Expose {spring-boot-ref-docs}/application-properties.html#appendix.application-properties.web[properties] that apply to `GraphQlSource.Builder`. - Detect <> beans. - Detect https://www.graphql-java.com/documentation/instrumentation[Instrumentation] beans for {spring-boot-ref-docs}/actuator.html#actuator.metrics.supported.spring-graphql[GraphQL metrics]. - Detect `DataFetcherExceptionResolver` beans for <>. For further customizations, you can declare your own `GraphQlSourceBuilderCustomizer` beans; for example, for configuring your own `ExecutionIdProvider`: [source,java,indent=0,subs=""verbatim,quotes""] ---- @Configuration(proxyBeanMethods = false) class GraphQlConfig { @Bean public GraphQlSourceBuilderCustomizer sourceBuilderCustomizer() { return (builder) -> { builder.configureGraphQl(graphQlBuilder -> graphQlBuilder.executionIdProvider(new CustomExecutionIdProvider())); }; } } ---- [[execution-graphqlsource-schema-resources]] ==== Schema Resources `GraphQlSource.Builder` can be configured with one or more `Resource` instances to be parsed and merged together. That means schema files can be loaded from just about any location. By default, the Spring Boot starter {spring-boot-ref-docs}/web.html#web.graphql.schema[finds schema files] from a well-known classpath location, but you can change that to a location on the file system via `FileSystemResource`, to byte content via `ByteArrayResource`, or implement a custom `Resource` that loads schema files from a remote location or storage. [[execution-graphqlsource-schema-creation]] ==== Schema Creation By default, `GraphQlSource.Builder` uses the GraphQL Java `GraphQLSchemaGenerator` to create the `graphql.schema.GraphQLSchema`. This works for most applications, but if necessary, you can hook into the schema creation through the builder: [source,java,indent=0,subs=""verbatim,quotes""] ---- GraphQlSource.Builder builder = ... builder.schemaResources(..) .configureRuntimeWiring(..) .schemaFactory((typeDefinitionRegistry, runtimeWiring) -> { // create GraphQLSchema }) ---- The primary reason for this is to create the schema through a federation library. The <> explains how to configure that with Spring Boot. [[execution-graphqlsource-runtimewiring-configurer]] ==== `RuntimeWiringConfigurer` You can use `RuntimeWiringConfigurer` to register: - Custom scalar types. - Directives handling code. - `TypeResolver`, if you need to override the <> for a type. - `DataFetcher` for a field, although most applications will simply configure `AnnotatedControllerConfigurer`, which detects annotated, `DataFetcher` handler methods. The Spring Boot starter adds the `AnnotatedControllerConfigurer` by default. NOTE: Unlike web frameworks, GraphQL does not use Jackson annotations to drive JSON serialization/deserialization. Custom data types and their serialization https://www.graphql-java.com/documentation/scalars/[must be described as Scalars]. The Spring Boot starter detects beans of type `RuntimeWiringConfigurer` and registers them in the `GraphQlSource.Builder`. That means in most cases, you'll' have something like the following in your configuration: [source,java,indent=0,subs=""verbatim,quotes""] ---- @Configuration public class GraphQlConfig { @Bean public RuntimeWiringConfigurer runtimeWiringConfigurer(BookRepository repository) { GraphQLScalarType scalarType = ... ; SchemaDirectiveWiring directiveWiring = ... ; DataFetcher dataFetcher = QuerydslDataFetcher.builder(repository).single(); return wiringBuilder -> wiringBuilder .scalar(scalarType) .directiveWiring(directiveWiring) .type(""Query"", builder -> builder.dataFetcher(""book"", dataFetcher)); } } ---- If you need to add a `WiringFactory`, e.g. to make registrations that take into account schema definitions, implement the alternative `configure` method that accepts both the `RuntimeWiring.Builder` and an output `List`. This allows you to add any number of factories that are then invoked in sequence. [[execution-graphqlsource-default-type-resolver]] ==== Default `TypeResolver` `GraphQlSource.Builder` registers `ClassNameTypeResolver` as the default `TypeResolver` to use for GraphQL Interfaces and Unions that don't already have such a registration through a <>. The purpose of a `TypeResolver` in GraphQL Java is to determine the GraphQL Object type for values returned from the `DataFetcher` for a GraphQL Interface or Union field. `ClassNameTypeResolver` tries to match the simple class name of the value to a GraphQL Object Type and if it is not successful, it also navigates its super types including base classes and interfaces, looking for a match. `ClassNameTypeResolver` provides an option to configure a name extracting function along with `Class` to GraphQL Object type name mappings that should help to cover more corner cases: [source,java,indent=0,subs=""verbatim,quotes""] ---- GraphQlSource.Builder builder = ... ClassNameTypeResolver classNameTypeResolver = new ClassNameTypeResolver(); classNameTypeResolver.setClassNameExtractor((klass) -> { // Implement Custom ClassName Extractor here }); builder.defaultTypeResolver(classNameTypeResolver); ---- The <> explains how to configure that with Spring Boot. [[execution-graphqlsource-operation-caching]] ==== Operation Caching GraphQL Java must _parse_ and _validate_ an operation before executing it. This may impact performance significantly. To avoid the need to re-parse and validate, an application may configure a `PreparsedDocumentProvider` that caches and reuses Document instances. The {graphql-java-docs}/execution/#query-caching[GraphQL Java docs] provide more details on query caching through a `PreparsedDocumentProvider`. In Spring GraphQL you can register a `PreparsedDocumentProvider` through `GraphQlSource.Builder#configureGraphQl`: . [source,java,indent=0,subs=""verbatim,quotes""] ---- // Typically, accessed through Spring Boot's GraphQlSourceBuilderCustomizer GraphQlSource.Builder builder = ... // Create provider PreparsedDocumentProvider provider = ... builder.schemaResources(..) .configureRuntimeWiring(..) .configureGraphQl(graphQLBuilder -> graphQLBuilder.preparsedDocumentProvider(provider)) ---- The <> explains how to configure that with Spring Boot. [[execution-graphqlsource-directives]] ==== Directives The GraphQL language supports directives that ""describe alternate runtime execution and type validation behavior in a GraphQL document"". Directives are similar to annotations in Java but declared on types, fields, fragments and operations in a GraphQL document. GraphQL Java provides the `SchemaDirectiveWiring` contract to help applications detect and handle directives. For more details, see {graphql-java-docs}/sdl-directives/[Schema Directives] in the GraphQL Java documentation. In Spring GraphQL you can register a `SchemaDirectiveWiring` through a <>. The Spring Boot starter detects such beans, so you might have something like: [source,java,indent=0,subs=""verbatim,quotes""] ---- @Configuration public class GraphQlConfig { @Bean public RuntimeWiringConfigurer runtimeWiringConfigurer() { return builder -> builder.directiveWiring(new MySchemaDirectiveWiring()); } } ---- TIP: For an example of directives support check out the https://github.com/graphql-java/graphql-java-extended-validation[Extended Validation for Graphql Java] library. [[execution-reactive-datafetcher]] === Reactive `DataFetcher` The default `GraphQlSource` builder enables support for a `DataFetcher` to return `Mono` or `Flux` which adapts those to a `CompletableFuture` where `Flux` values are aggregated and turned into a List, unless the request is a GraphQL subscription request, in which case the return value remains a Reactive Streams `Publisher` for streaming GraphQL responses. A reactive `DataFetcher` can rely on access to Reactor context propagated from the transport layer, such as from a WebFlux request handling, see <>. [[execution-context]] === Context Propagation Spring for GraphQL provides support to transparently propagate context from the <>, through the GraphQL engine, and to `DataFetcher` and other components it invokes. This includes both `ThreadLocal` context from the Spring MVC request handling thread and Reactor `Context` from the WebFlux processing pipeline. [[execution-context-webmvc]] ==== WebMvc A `DataFetcher` and other components invoked by GraphQL Java may not always execute on the same thread as the Spring MVC handler, for example if an asynchronous <> or `DataFetcher` switches to a different thread. Spring for GraphQL supports propagating `ThreadLocal` values from the Servlet container thread to the thread a `DataFetcher` and other components invoked by the GraphQL engine execute on. To do this, an application needs to create a `ThreadLocalAccessor` to extract `ThreadLocal` values of interest: [source,java,indent=0,subs=""verbatim,quotes""] ---- public class RequestAttributesAccessor implements ThreadLocalAccessor { private static final String KEY = RequestAttributesAccessor.class.getName(); @Override public void extractValues(Map container) { container.put(KEY, RequestContextHolder.getRequestAttributes()); } @Override public void restoreValues(Map values) { if (values.containsKey(KEY)) { RequestContextHolder.setRequestAttributes((RequestAttributes) values.get(KEY)); } } @Override public void resetValues(Map values) { RequestContextHolder.resetRequestAttributes(); } } ---- A `ThreadLocalAccessor` can be registered in the <> builder. The Boot starter detects beans of this type and automatically registers them for Spring MVC application, see the {spring-boot-ref-docs}/web.html#web.graphql.web-endpoints[Web Endpoints] section. [[execution-context-webflux]] ==== WebFlux A <> can rely on access to Reactor context that originates from the WebFlux request handling chain. This includes Reactor context added by <> components. [[execution-exceptions]] === Exception Resolution GraphQL Java applications can register a `DataFetcherExceptionHandler` to decide how to represent exceptions from the data layer in the ""errors"" section of the GraphQL response. Spring for GraphQL has a built-in `DataFetcherExceptionHandler` that is configured for use by the <> builder. It enables applications to register one or more Spring `DataFetcherExceptionResolver` components that are invoked sequentially until one resolves the `Exception` to a list of `graphql.GraphQLError` objects. `DataFetcherExceptionResolver` is an asynchronous contract. For most implementations, it would be sufficient to extend `DataFetcherExceptionResolverAdapter` and override one of its `resolveToSingleError` or `resolveToMultipleErrors` methods that resolve exceptions synchronously. A `GraphQLError` can be assigned an `graphql.ErrorClassification`. Spring for GraphQL defines an `ErrorType` enum with common, error classification categories: - `BAD_REQUEST` - `UNAUTHORIZED` - `FORBIDDEN` - `NOT_FOUND` - `INTERNAL_ERROR` Applications can use this to classify errors. If an error remains unresolved, by default it is marked as `INTERNAL_ERROR`. [[execution-batching]] === Batch Loading Given a `Book` and its `Author`, we can create one `DataFetcher` for a book and another for its author. This allows selecting books with or without authors, but it means books and authors aren't loaded together, which is especially inefficient when querying multiple books as the author for each book is loaded individually. This is known as the N+1 select problem. [[execution-batching-dataloader]] ==== `DataLoader` GraphQL Java provides a `DataLoader` mechanism for batch loading of related entities. You can find the full details in the {graphql-java-docs}/batching/[GraphQL Java docs]. Below is a summary of how it works: 1. Register ``DataLoader``'s in the `DataLoaderRegistry` that can load entities, given unique keys. 2. ``DataFetcher``'s can access ``DataLoader``'s and use them to load entities by id. 3. A `DataLoader` defers loading by returning a future so it can be done in a batch. 4. ``DataLoader``'s maintain a per request cache of loaded entities that can further improve efficiency. [[execution-batching-batch-loader-registry]] ==== `BatchLoaderRegistry` The complete batching loading mechanism in GraphQL Java requires implementing one of several `BatchLoader` interface, then wrapping and registering those as ``DataLoader``s with a name in the `DataLoaderRegistry`. The API in Spring GraphQL is slightly different. For registration, there is only one, central `BatchLoaderRegistry` exposing factory methods and a builder to create and register any number of batch loading functions: [source,java,indent=0,subs=""verbatim,quotes""] ---- @Configuration public class MyConfig { public MyConfig(BatchLoaderRegistry registry) { registry.forTypePair(Long.class, Author.class).registerMappedBatchLoader((authorIds, env) -> { // return Mono }); // more registrations ... } } ---- The Spring Boot starter declares a `BatchLoaderRegistry` bean that you can inject into your configuration, as shown above, or into any component such as a controller in order register batch loading functions. In turn the `BatchLoaderRegistry` is injected into `ExecutionGraphQlService` where it ensures `DataLoader` registrations per request. By default, the `DataLoader` name is based on the class name of the target entity. This allows an `@SchemaMapping` method to declare a <> with a generic type, and without the need for specifying a name. The name, however, can be customized through the `BatchLoaderRegistry` builder, if necessary, along with other `DataLoader` options. For many cases, when loading related entities, you can use <> controller methods, which are a shortcut for and replace the need to use `BatchLoaderRegistry` and `DataLoader` directly. s `BatchLoaderRegistry` provides other important benefits too. It supports access to the same `GraphQLContext` from batch loading functions and from `@BatchMapping` methods, as well as ensures <> to them. This is why applications are expected to use it. It is possible to perform your own `DataLoader` registrations directly but such registrations would forgo the above benefits. [[execution-batching-testing]] ==== Testing Batch Loading Start by having `BatchLoaderRegistry` perform registrations on a `DataLoaderRegistry`: [source,java,indent=0,subs=""verbatim,quotes""] ---- BatchLoaderRegistry batchLoaderRegistry = new DefaultBatchLoaderRegistry(); // perform registrations... DataLoaderRegistry dataLoaderRegistry = DataLoaderRegistry.newRegistry().build(); batchLoaderRegistry.registerDataLoaders(dataLoaderRegistry, graphQLContext); ---- Now you can access and test individual ``DataLoader``'s as follows: [source,java,indent=0,subs=""verbatim,quotes""] ---- DataLoader loader = dataLoaderRegistry.getDataLoader(Book.class.getName()); loader.load(1L); loader.loadMany(Arrays.asList(2L, 3L)); List books = loader.dispatchAndJoin(); // actual loading assertThat(books).hasSize(3); assertThat(books.get(0).getName()).isEqualTo(""...""); // ... ---- [[data]] == Data Integration Spring for GraphQL lets you leverage existing Spring technology, following common programming models to expose underlying data sources through GraphQL. This section discusses an integration layer for Spring Data that provides an easy way to adapt a Querydsl or a Query by Example repository to a `DataFetcher`, including the option for automated detection and GraphQL Query registration for repositories marked with `@GraphQlRepository`. [[data-querydsl]] === Querydsl Spring for GraphQL supports use of http://www.querydsl.com/[Querydsl] to fetch data through the Spring Data https://docs.spring.io/spring-data/commons/docs/current/reference/html/#core.extensions[Querydsl extension]. Querydsl provides a flexible yet typesafe approach to express query predicates by generating a meta-model using annotation processors. For example, declare a repository as `QuerydslPredicateExecutor`: [source,java,indent=0,subs=""verbatim,quotes""] ---- public interface AccountRepository extends Repository, QuerydslPredicateExecutor { } ---- Then use it to create a `DataFetcher`: [source,java,indent=0,subs=""verbatim,quotes""] ---- // For single result queries DataFetcher dataFetcher = QuerydslDataFetcher.builder(repository).single(); // For multi-result queries DataFetcher> dataFetcher = QuerydslDataFetcher.builder(repository).many(); ---- You can now register the above `DataFetcher` through a <>. The `DataFetcher` builds a Querydsl `Predicate` from GraphQL request parameters, and uses it to fetch data. Spring Data supports `QuerydslPredicateExecutor` for JPA, MongoDB, and LDAP. If the repository is `ReactiveQuerydslPredicateExecutor`, the builder returns `DataFetcher>` or `DataFetcher>`. Spring Data supports this variant for MongoDB. [[data-querydsl-build]] ==== Build Setup To configure Querydsl in your build, follow the https://querydsl.com/static/querydsl/latest/reference/html/ch02.html[official reference documentation]: For example: [source,groovy,indent=0,subs=""verbatim,quotes,attributes"",role=""primary""] .Gradle ---- dependencies { //... annotationProcessor ""com.querydsl:querydsl-apt:$querydslVersion:jpa"", 'org.hibernate.javax.persistence:hibernate-jpa-2.1-api:1.0.2.Final', 'javax.annotation:javax.annotation-api:1.3.2' } compileJava { options.annotationProcessorPath = configurations.annotationProcessor } ---- [source,xml,indent=0,subs=""verbatim,quotes,attributes"",role=""secondary""] .Maven ---- com.querydsl querydsl-apt ${querydsl.version} jpa provided org.hibernate.javax.persistence hibernate-jpa-2.1-api 1.0.2.Final javax.annotation javax.annotation-api 1.3.2 com.mysema.maven apt-maven-plugin ${apt-maven-plugin.version} process target/generated-sources/java com.querydsl.apt.jpa.JPAAnnotationProcessor ---- The {github-main-branch}/samples/webmvc-http[webmvc-http] sample uses Querydsl for `artifactRepositories`. [[data-querydsl-customizations]] ==== Customizations `QuerydslDataFetcher` supports customizing how GraphQL arguments are bound onto properties to create a Querydsl `Predicate`. By default, arguments are bound as ""is equal to"" for each available property. To customize that, you can use `QuerydslDataFetcher` builder methods to provide a `QuerydslBinderCustomizer`. A repository may itself be an instance of `QuerydslBinderCustomizer`. This is auto-detected and transparently applied during <>. However, when manually building a `QuerydslDataFetcher` you will need to use builder methods to apply it. `QuerydslDataFetcher` supports interface and DTO projections to transform query results before returning these for further GraphQL processing. TIP: To learn what projections are, please refer to the https://docs.spring.io/spring-data/commons/docs/current/reference/html/#projections[Spring Data docs]. To understand how to use projections in GraphQL, please see <>. To use Spring Data projections with Querydsl repositories, create either a projection interface or a target DTO class and configure it through the `projectAs` method to obtain a `DataFetcher` producing the target type: [source,java,indent=0,subs=""verbatim,quotes""] ---- class Account { String name, identifier, description; Person owner; } interface AccountProjection { String getName(); String getIdentifier(); } // For single result queries DataFetcher dataFetcher = QuerydslDataFetcher.builder(repository).projectAs(AccountProjection.class).single(); // For multi-result queries DataFetcher> dataFetcher = QuerydslDataFetcher.builder(repository).projectAs(AccountProjection.class).many(); ---- [[data-querydsl-registration]] ==== Auto-Registration If a repository is annotated with `@GraphQlRepository`, it is automatically registered for queries that do not already have a registered `DataFetcher` and whose return type matches that of the repository domain type. This includes both single value and multi-value queries. By default, the name of the GraphQL type returned by the query must match the simple name of the repository domain type. If needed, you can use the `typeName` attribute of `@GraphQlRepository` to specify the target GraphQL type name. Auto-registration detects if a given repository implements `QuerydslBinderCustomizer` and transparently applies that through `QuerydslDataFetcher` builder methods. Auto-registration is performed through a built-in `RuntimeWiringConfigurer` that can be obtained from `QuerydslDataFetcher`. The {spring-boot-ref-docs}/web.html#web.graphql.data-query[Boot starter] automatically detects `@GraphQlRepository` beans and uses them to initialize the `RuntimeWiringConfigurer` with. Auto-registration does not support <>. If you need that, you'll need to use `QueryByExampleDataFetcher` to build and register the `DataFetcher` manually through a <>. [[data-querybyexample]] === Query by Example Spring Data supports the use of https://docs.spring.io/spring-data/commons/docs/current/reference/html/#query-by-example[Query by Example] to fetch data. Query by Example (QBE) is a simple querying technique that does not require you to write queries through store-specific query languages. Start by declaring a repository that is `QueryByExampleExecutor`: [source,java,indent=0,subs=""verbatim,quotes""] ---- public interface AccountRepository extends Repository, QueryByExampleExecutor { } ---- Use `QueryByExampleDataFetcher` to turn the repository into a `DataFecher`: [source,java,indent=0,subs=""verbatim,quotes""] ---- // For single result queries DataFetcher dataFetcher = QueryByExampleDataFetcher.builder(repository).single(); // For multi-result queries DataFetcher> dataFetcher = QueryByExampleDataFetcher.builder(repository).many(); ---- You can now register the above `DataFetcher` through a <>. The `DataFetcher` uses the GraphQL arguments map to create the domain type of the repository and use that as the example object to fetch data with. Spring Data supports `QueryByExampleDataFetcher` for JPA, MongoDB, Neo4j, and Redis. If the repository is `ReactiveQueryByExampleExecutor`, the builder returns `DataFetcher>` or `DataFetcher>`. Spring Data supports this variant for MongoDB, Neo4j, Redis, and R2dbc. [[data-querybyexample-build]] ==== Build Setup Query by Example is already included in the Spring Data modules for the data stores where it is supported, so no extra setup is required to enable it. [[data-querybyexample-customizations]] ==== Customizations `QueryByExampleDataFetcher` supports interface and DTO projections to transform query results before returning these for further GraphQL processing. TIP: To learn what projections are, please refer to the https://docs.spring.io/spring-data/commons/docs/current/reference/html/#projections[Spring Data documentation]. To understand the role of projections in GraphQL, please see <>. To use Spring Data projections with Query by Example repositories, create either a projection interface or a target DTO class and configure it through the `projectAs` method to obtain a `DataFetcher` producing the target type: [source,java,indent=0,subs=""verbatim,quotes""] ---- class Account { String name, identifier, description; Person owner; } interface AccountProjection { String getName(); String getIdentifier(); } // For single result queries DataFetcher dataFetcher = QueryByExampleDataFetcher.builder(repository).projectAs(AccountProjection.class).single(); // For multi-result queries DataFetcher> dataFetcher = QueryByExampleDataFetcher.builder(repository).projectAs(AccountProjection.class).many(); ---- [[data-querybyexample-registration]] ==== Auto-Registration If a repository is annotated with `@GraphQlRepository`, it is automatically registered for queries that do not already have a registered `DataFetcher` and whose return type matches that of the repository domain type. This includes both single value and multi-value queries. By default, the name of the GraphQL type returned by the query must match the simple name of the repository domain type. If needed, you can use the `typeName` attribute of `@GraphQlRepository` to specify the target GraphQL type name. Auto-registration is performed through a built-in `RuntimeWiringConfigurer` that can be obtained from `QueryByExampleDataFetcher`. The {spring-boot-ref-docs}/web.html#web.graphql.data-query[Boot starter] automatically detects `@GraphQlRepository` beans and uses them to initialize the `RuntimeWiringConfigurer` with. Auto-registration does not support <>. If you need that, you'll need to use `QueryByExampleDataFetcher` to build and register the `DataFetcher` manually through a <>. [[data-projections]] === Selection Set vs Projections A common question that arises is, how GraphQL selection sets compare to https://docs.spring.io/spring-data/commons/docs/current/reference/html/#projections[Spring Data projections] and what role does each play? The short answer is that Spring for GraphQL is not a data gateway that translates GraphQL queries directly into SQL or JSON queries. Instead, it lets you leverage existing Spring technology and does not assume a one for one mapping between the GraphQL schema and the underlying data model. That is why client-driven selection and server-side transformation of the data model can play complementary roles. To better understand, consider that Spring Data promotes domain-driven (DDD) design as the recommended approach to manage complexity in the data layer. In DDD, it is important to adhere to the constraints of an aggregate. By definition an aggregate is valid only if loaded in its entirety, since a partially loaded aggregate may impose limitations on aggregate functionality. In Spring Data you can choose whether you want your aggregate be exposed as is, or whether to apply transformations to the data model before returning it as a GraphQL result. Sometimes it's enough to do the former, and by default the <> and the <> integrations turn the GraphQL selection set into property path hints that the underlying Spring Data module uses to limit the selection. In other cases, it's useful to reduce or even transform the underlying data model in order to adapt to the GraphQL schema. Spring Data supports this through Interface and DTO Projections. Interface projections define a fixed set of properties to expose where properties may or may not be `null`, depending on the data store query result. There are two kinds of interface projections both of which determine what properties to load from the underlying data source: - https://docs.spring.io/spring-data/commons/docs/current/reference/html/#projections.interfaces.closed[Closed interface projections] are helpful if you cannot partially materialize the aggregate object, but you still want to expose a subset of properties. - https://docs.spring.io/spring-data/commons/docs/current/reference/html/#projections.interfaces.open[Open interface projections] leverage Spring's `@Value` annotation and {spring-framework-ref-docs}/core.html#expressions[SpEL] expressions to apply lightweight data transformations, such as concatenations, computations, or applying static functions to a property. DTO projections offer a higher level of customization as you can place transformation code either in the constructor or in getter methods. DTO projections materialize from a query where the individual properties are determined by the projection itself. DTO projections are commonly used with full-args constructors (e.g. Java records), and therefore they can only be constructed if all required fields (or columns) are part of the database query result. [[controllers]] == Annotated Controllers Spring for GraphQL provides an annotation-based programming model where `@Controller` components use annotations to declare handler methods with flexible method signatures to fetch the data for specific GraphQL fields. For example: [source,java,indent=0,subs=""verbatim,quotes""] ---- @Controller public class GreetingController { @QueryMapping // <1> public String hello() { // <2> return ""Hello, world!""; } } ---- <1> Bind this method to a query, i.e. a field under the Query type. <2> Determine the query from the method name if not declared on the annotation. Spring for GraphQL uses `RuntimeWiring.Builder` to register the above handler method as a `graphql.schema.DataFetcher` for the query named ""hello"". [[controllers-declaration]] === Declaration You can define `@Controller` beans as standard Spring bean definitions. The `@Controller` stereotype allows for auto-detection, aligned with Spring general support for detecting `@Controller` and `@Component` classes on the classpath and auto-registering bean definitions for them. It also acts as a stereotype for the annotated class, indicating its role as a data fetching component in a GraphQL application. `AnnotatedControllerConfigurer` detects `@Controller` beans and registers their annotated handler methods as ``DataFetcher``s via `RuntimeWiring.Builder`. It is an implementation of `RuntimeWiringConfigurer` which can be added to `GraphQlSource.Builder`. The Spring Boot starter automatically declares `AnnotatedControllerConfigurer` as a bean and adds all `RuntimeWiringConfigurer` beans to `GraphQlSource.Builder` and that enables support for annotated ``DataFetcher``s, see the {spring-boot-ref-docs}/web.html#web.graphql.runtimewiring[GraphQL RuntimeWiring] section in the Boot starter documentation. [[controllers-schema-mapping]] === `@SchemaMapping` The `@SchemaMapping` annotation maps a handler method to a field in the GraphQL schema and declares it to be the `DataFetcher` for that field. The annotation can specify the parent type name, and the field name: [source,java,indent=0,subs=""verbatim,quotes""] ---- @Controller public class BookController { @SchemaMapping(typeName=""Book"", field=""author"") public Author getAuthor(Book book) { // ... } } ---- The `@SchemaMapping` annotation can also leave out those attributes, in which case the field name defaults to the method name, while the type name defaults to the simple class name of the source/parent object injected into the method. For example, the below defaults to type ""Book"" and field ""author"": [source,java,indent=0,subs=""verbatim,quotes""] ---- @Controller public class BookController { @SchemaMapping public Author author(Book book) { // ... } } ---- The `@SchemaMapping` annotation can be declared at the class level to specify a default type name for all handler methods in the class. [source,java,indent=0,subs=""verbatim,quotes""] ---- @Controller @SchemaMapping(typeName=""Book"") public class BookController { // @SchemaMapping methods for fields of the ""Book"" type } ---- `@QueryMapping`, `@MutationMapping`, and `@SubscriptionMapping` are meta annotations that are themselves annotated with `@SchemaMapping` and have the typeName preset to `Query`, `Mutation`, or `Subscription` respectively. Effectively, these are shortcut annotations for fields under the Query, Mutation, and Subscription types respectively. For example: [source,java,indent=0,subs=""verbatim,quotes""] ---- @Controller public class BookController { @QueryMapping public Book bookById(@Argument Long id) { // ... } @MutationMapping public Book addBook(@Argument BookInput bookInput) { // ... } @SubscriptionMapping public Flux newPublications() { // ... } } ---- `@SchemaMapping` handler methods have flexible signatures and can choose from a range of method arguments and return values.. [[controllers-schema-mapping-signature]] ==== Method Signature Schema mapping handler methods can have any of the following method arguments: [cols=""1,2""] |=== | Method Argument | Description | `@Argument` | For access to a named field argument converted to a higher-level, typed Object. See <>. | `@Arguments` | For access to all field arguments converted to a higher-level, typed Object. See <>. | `@ProjectedPayload` Interface | For access to field arguments through a project interface. See <>. | Source | For access to the source (i.e. parent/container) instance of the field. See <>. | `DataLoader` | For access to a `DataLoader` in the `DataLoaderRegistry`. See <>. | `@ContextValue` | For access to a value from the localContext, if it is an instance of `GraphQLContext`, or from the `GraphQLContext` of `DataFetchingEnvironment`. | `GraphQLContext` | For access to the context from the `DataFetchingEnvironment`. | `java.security.Principal` | Obtained from the Spring Security context, if available. | `@AuthenticationPrincipal` | For access to `Authentication#getPrincipal()` from the Spring Security context. | `DataFetchingFieldSelectionSet` | For access to the selection set for the query through the `DataFetchingEnvironment`. | `Locale`, `Optional` | For access to the `Locale` from the `DataFetchingEnvironment`. | `DataFetchingEnvironment` | For direct access to the underlying `DataFetchingEnvironment`. |=== Schema mapping handler methods can return any value, including Reactor `Mono` and `Flux` as described in <>. [[controllers-schema-mapping-argument]] ==== `@Argument` In GraphQL Java, `DataFetchingEnvironment` provides access to a map of field-specific argument values. The values can be simple scalar values (e.g. String, Long), a `Map` of values for more complex input, or a `List` of values. Use the `@Argument` annotation to inject a named field argument into a handler method. The method parameter can be a higher-level, typed Object of any type. It is created and initialized from the named field argument value(s), either matching them to single data constructor parameters, or using the default constructor and then matching keys onto Object properties through a `org.springframework.validation.DataBinder`: [source,java,indent=0,subs=""verbatim,quotes""] ---- @Controller public class BookController { @QueryMapping public Book bookById(@Argument Long id) { // ... } @MutationMapping public Book addBook(@Argument BookInput bookInput) { // ... } } ---- By default, if the method parameter name is available (requires the `-parameters` compiler flag with Java 8+ or debugging info from the compiler), it is used to look up the argument. If needed, you can customize the name through the annotation, e.g. `@Argument(""bookInput"")`. TIP: The `@Argument` annotation does not have a ""required"" flag, nor the option to specify a default value. Both of these can be specified at the GraphQL schema level and are enforced by the GraphQL Engine. You can use `@Argument` on a `Map` argument, to obtain all argument values. The name attribute on `@Argument` must not be set. [[controllers-schema-mapping-arguments]] ==== `@Arguments` Use the `@Arguments` annotation, if you want to bind the full arguments map onto a single target Object, in contrast to `@Argument`, which binds a specific, named argument. For example, `@Argument BookInput bookInput` uses the value of the argument ""bookInput"" to initialize `BookInput`, while `@Arguments` uses the full arguments map and in that case, top-level arguments are bound to `BookInput` properties. [[controllers-schema-mapping-validation]] ==== `@Argument(s)` Validation If a {spring-framework-ref-docs}/core.html#validation-beanvalidation-overview[Bean Validation] `Validator` (or typically, a `LocalValidatorFactoryBean`) bean is present in the application context, the `AnnotatedControllerConfigurer` will auto-detect it and configure support for validation. Controller arguments annotated with `@Valid` and `@Validated` are then validated before method invocation. Bean Validation lets you declare constraints on types, as the following example shows: [source,java,indent=0,subs=""verbatim,quotes""] ---- public class BookInput { @NotNull private String title; @NotNull @Size(max=13) private String isbn; } ---- We can then mark our argument for validation with `@Valid`: [source,java,indent=0,subs=""verbatim,quotes""] ---- @Controller public class BookController { @MutationMapping public Book addBook(@Argument @Valid BookInput bookInput) { // ... } } ---- If an error occurs during validation, a `ConstraintViolationException` is thrown and can be later <>. [TIP] ==== Unlike Spring MVC, handler method signatures do not support the injection of `BindingResult` for reacting to validation errors: those are globally dealt with as exceptions. ==== [[controllers-schema-mapping-projectedpayload-argument]] ==== `@ProjectedPayload` Interface As an alternative to using complete Objects with <>, you can also use a projection interface to access GraphQL request arguments through a well-defined, minimal interface. Argument projections are provided by https://docs.spring.io/spring-data/commons/docs/current/reference/html/#projections.interfaces[Spring Data's Interface projections] when Spring Data is on the class path. To make use of this, create an interface annotated with `@ProjectedPayload` and declare it as a controller method parameter. If the parameter is annotated with `@Argument`, it applies to an individual argument within the `DataFetchingEnvironment.getArguments()` map. When declared without `@Argument`, the projection works on top-level arguments in the complete arguments map. For example: [source,java,indent=0,subs=""verbatim,quotes""] ---- @Controller public class BookController { @QueryMapping public Book bookById(BookIdProjection bookId) { // ... } @MutationMapping public Book addBook(@Argument BookInputProjection bookInput) { // ... } } @ProjectedPayload interface BookIdProjection { Long getId(); } @ProjectedPayload interface BookInputProjection { String getName(); @Value(""#{target.author + ' ' + target.name}"") String getAuthorAndName(); } ---- [[controllers-schema-mapping-source]] ==== Source In GraphQL Java, the `DataFetchingEnvironment` provides access to the source (i.e. parent/container) instance of the field. To access this, simply declare a method parameter of the expected target type. [source,java,indent=0,subs=""verbatim,quotes""] ---- @Controller public class BookController { @SchemaMapping public Author author(Book book) { // ... } } ---- The source method argument also helps to determine the type name for the mapping. If the simple name of the Java class matches the GraphQL type, then there is no need to explicitly specify the type name in the `@SchemaMapping` annotation. [TIP] ==== A <> handler method can batch load all authors for a query, given a list of source/parent books objects. ==== [[controllers-schema-mapping-data-loader]] ==== `DataLoader` When you register a batch loading function for an entity, as explained in <>, you can access the `DataLoader` for the entity by declaring a method argument of type `DataLoader` and use it to load the entity: [source,java,indent=0,subs=""verbatim,quotes""] ---- @Controller public class BookController { public BookController(BatchLoaderRegistry registry) { registry.forTypePair(Long.class, Author.class).registerMappedBatchLoader((authorIds, env) -> { // return Map }); } @SchemaMapping public CompletableFuture author(Book book, DataLoader loader) { return loader.load(book.getAuthorId()); } } ---- By default, `BatchLoaderRegistry` uses the full class name of the value type (e.g. the class name for `Author`) for the key of the registration, and therefore simply declaring the `DataLoader` method argument with generic types provides enough information to locate it in the `DataLoaderRegistry`. As a fallback, the `DataLoader` method argument resolver will also try the method argument name as the key but typically that should not be necessary. Note that for many cases with loading related entities, where the `@SchemaMapping` simply delegates to a `DataLoader`, you can reduce boilerplate by using a <> method as described in the next section. [[controllers-batch-mapping]] === `@BatchMapping` <> addresses the N+1 select problem through the use of an `org.dataloader.DataLoader` to defer the loading of individual entity instances, so they can be loaded together. For example: [source,java,indent=0,subs=""verbatim,quotes""] ---- @Controller public class BookController { public BookController(BatchLoaderRegistry registry) { registry.forTypePair(Long.class, Author.class).registerMappedBatchLoader((authorIds, env) -> { // return Map }); } @SchemaMapping public CompletableFuture author(Book book, DataLoader loader) { return loader.load(book.getAuthorId()); } } ---- For the straight-forward case of loading an associated entity, shown above, the `@SchemaMapping` method does nothing more than delegate to the `DataLoader`. This is boilerplate that can be avoided with a `@BatchMapping` method. For example: [source,java,indent=0,subs=""verbatim,quotes""] ---- @Controller public class BookController { @BatchMapping public Mono> author(List books) { // ... } } ---- The above becomes a batch loading function in the `BatchLoaderRegistry` where keys are `Book` instances and the loaded values their authors. In addition, a `DataFetcher` is also transparently bound to the `author` field of the type `Book`, which simply delegates to the `DataLoader` for authors, given its source/parent `Book` instance. [TIP] ==== To be used as a unique key, `Book` must implement `hashcode` and `equals`. ==== By default, the field name defaults to the method name, while the type name defaults to the simple class name of the input `List` element type. Both can be customized through annotation attributes. The type name can also be inherited from a class level `@SchemaMapping`. [[controllers-batch-mapping-signature]] ==== Method Signature Batch mapping methods support the following arguments: [cols=""1,2""] |=== | Method Argument | Description | `List` | The source/parent objects. | `java.security.Principal` | Obtained from Spring Security context, if available. | `@ContextValue` | For access to a value from the `GraphQLContext` of `BatchLoaderEnvironment`, which is the same context as the one from the `DataFetchingEnvironment`. | `GraphQLContext` | For access to the context from the `BatchLoaderEnvironment`, which is the same context as the one from the `DataFetchingEnvironment`. | `BatchLoaderEnvironment` | The environment that is available in GraphQL Java to a `org.dataloader.BatchLoaderWithContext`. |=== Batch mapping methods can return: [cols=""1,2""] |=== | Return Type | Description | `Mono>` | A map with parent objects as keys, and batch loaded objects as values. | `Flux` | A sequence of batch loaded objects that must be in the same order as the source/parent objects passed into the method. | `Map`, `List` | Imperative variants, e.g. without remote calls to make. |=== [[security]] == Security The path to a <> GraphQL endpoint can be secured with HTTP URL security to ensure that only authenticated users can access it. This does not, however, differentiate among different GraphQL requests on such a shared endpoint on a single URL. To apply more fine-grained security, add Spring Security annotations such as `@PreAuthorize` or `@Secured` to service methods involved in fetching specific parts of the GraphQL response. This should work due to <> that aims to make Security, and other context, available at the data fetching level. The Spring for GraphQL repository contains samples for {github-main-branch}/samples/webmvc-http-security[Spring MVC] and for {github-main-branch}/samples/webflux-security[WebFlux]. include::client.adoc[leveloffset=+1] include::testing.adoc[leveloffset=+1] [[samples]] == Samples This Spring for GraphQL repository contains {github-main-branch}/samples[sample applications] for various scenarios. You can run those by cloning this repository and running main application classes from your IDE or by typing the following on the command line: [source,bash,indent=0,subs=""verbatim,quotes""] ---- $ ./gradlew :samples:{sample-directory-name}:bootRun ---- ",12168,False,2008.51473929956,median "/*============================================================================== Copyright (c) Laboratory for Percutaneous Surgery (PerkLab) Queen's University, Kingston, ON, Canada. All Rights Reserved. See COPYRIGHT.txt or http://www.slicer.org/copyright/copyright.txt for details. 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. This file was originally developed by Adam Rankin and Csaba Pinter, PerkLab, Queen's University and was supported through the Applied Cancer Research Unit program of Cancer Care Ontario with funds provided by the Ontario Ministry of Health and Long-Term Care ==============================================================================*/ // Segmentations includes #include ""vtkMRMLSegmentationStorageNode.h"" #include ""vtkSegmentation.h"" #include ""vtkOrientedImageData.h"" #include ""vtkOrientedImageDataResample.h"" // MRML includes #include #include #include ""vtkMRMLSegmentationNode.h"" #include ""vtkMRMLSegmentationDisplayNode.h"" // VTK includes #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef SUPPORT_4D_SPATIAL_NRRD // ITK includes #include #include #include #include #include #include #endif // STL & C++ includes #include #include //---------------------------------------------------------------------------- static const std::string SERIALIZATION_SEPARATOR = ""|""; static const std::string KEY_SEGMENT_ID = ""ID""; static const std::string KEY_SEGMENT_NAME = ""Name""; static const std::string KEY_SEGMENT_COLOR = ""Color""; static const std::string KEY_SEGMENT_TAGS = ""Tags""; static const std::string KEY_SEGMENT_EXTENT = ""Extent""; static const std::string KEY_SEGMENT_LABEL_VALUE = ""LabelValue""; static const std::string KEY_SEGMENT_LAYER = ""Layer""; static const std::string KEY_SEGMENT_NAME_AUTO_GENERATED = ""NameAutoGenerated""; static const std::string KEY_SEGMENT_COLOR_AUTO_GENERATED = ""ColorAutoGenerated""; static const std::string KEY_SEGMENTATION_MASTER_REPRESENTATION = ""MasterRepresentation""; static const std::string KEY_SEGMENTATION_CONVERSION_PARAMETERS = ""ConversionParameters""; static const std::string KEY_SEGMENTATION_EXTENT = ""Extent""; // Deprecated, kept only for being able to read legacy files. static const std::string KEY_SEGMENTATION_REFERENCE_IMAGE_EXTENT_OFFSET = ""ReferenceImageExtentOffset""; static const std::string KEY_SEGMENTATION_CONTAINED_REPRESENTATION_NAMES = ""ContainedRepresentationNames""; static const int SINGLE_SEGMENT_INDEX = -1; // used as segment index when there is only a single segment //---------------------------------------------------------------------------- vtkMRMLNodeNewMacro(vtkMRMLSegmentationStorageNode); //---------------------------------------------------------------------------- vtkMRMLSegmentationStorageNode::vtkMRMLSegmentationStorageNode() = default; //---------------------------------------------------------------------------- vtkMRMLSegmentationStorageNode::~vtkMRMLSegmentationStorageNode() = default; //---------------------------------------------------------------------------- void vtkMRMLSegmentationStorageNode::PrintSelf(ostream& os, vtkIndent indent) { Superclass::PrintSelf(os,indent); vtkMRMLPrintBeginMacro(os, indent); vtkMRMLPrintBooleanMacro(CropToMinimumExtent); vtkMRMLPrintEndMacro(); } //---------------------------------------------------------------------------- void vtkMRMLSegmentationStorageNode::ReadXMLAttributes(const char** atts) { MRMLNodeModifyBlocker blocker(this); Superclass::ReadXMLAttributes(atts); vtkMRMLReadXMLBeginMacro(atts); vtkMRMLReadXMLBooleanMacro(CropToMinimumExtent, CropToMinimumExtent); vtkMRMLReadXMLEndMacro(); } //---------------------------------------------------------------------------- void vtkMRMLSegmentationStorageNode::WriteXML(ostream& of, int nIndent) { Superclass::WriteXML(of, nIndent); vtkMRMLWriteXMLBeginMacro(of); vtkMRMLWriteXMLBooleanMacro(CropToMinimumExtent, CropToMinimumExtent); vtkMRMLWriteXMLEndMacro(); } //---------------------------------------------------------------------------- // Copy the node's attributes to this object. // Does NOT copy: ID, FilePrefix, Name, StorageID void vtkMRMLSegmentationStorageNode::Copy(vtkMRMLNode *anode) { MRMLNodeModifyBlocker blocker(anode); Superclass::Copy(anode); vtkMRMLCopyBeginMacro(anode); vtkMRMLCopyBooleanMacro(CropToMinimumExtent); vtkMRMLCopyEndMacro(); } //---------------------------------------------------------------------------- void vtkMRMLSegmentationStorageNode::InitializeSupportedReadFileTypes() { this->SupportedReadFileTypes->InsertNextValue(""Segmentation (.seg.nrrd)""); this->SupportedReadFileTypes->InsertNextValue(""Segmentation (.seg.vtm)""); this->SupportedReadFileTypes->InsertNextValue(""Segmentation (.nrrd)""); this->SupportedReadFileTypes->InsertNextValue(""Segmentation (.vtm)""); this->SupportedReadFileTypes->InsertNextValue(""Segmentation (.nii.gz)""); this->SupportedReadFileTypes->InsertNextValue(""Segmentation (.hdr)""); this->SupportedReadFileTypes->InsertNextValue(""Segmentation (.nii)""); } //---------------------------------------------------------------------------- void vtkMRMLSegmentationStorageNode::InitializeSupportedWriteFileTypes() { Superclass::InitializeSupportedWriteFileTypes(); vtkMRMLSegmentationNode* segmentationNode = this->GetAssociatedDataNode(); bool masterIsImage = true; bool masterIsPolyData = true; if (segmentationNode) { // restrict write file types to those that are suitable for current master representation masterIsImage = segmentationNode->GetSegmentation()->IsMasterRepresentationImageData(); masterIsPolyData = segmentationNode->GetSegmentation()->IsMasterRepresentationPolyData(); if (!masterIsImage && !masterIsPolyData) { // if contains unknown representation then enable all formats masterIsImage = true; masterIsPolyData = true; } } if (masterIsImage) { this->SupportedWriteFileTypes->InsertNextValue(""Segmentation (.seg.nrrd)""); this->SupportedWriteFileTypes->InsertNextValue(""Segmentation (.nrrd)""); } if (masterIsPolyData) { this->SupportedWriteFileTypes->InsertNextValue(""Segmentation (.seg.vtm)""); this->SupportedWriteFileTypes->InsertNextValue(""Segmentation (.vtm)""); } } //---------------------------------------------------------------------------- vtkMRMLSegmentationNode* vtkMRMLSegmentationStorageNode::GetAssociatedDataNode() { if (!this->GetScene()) { return nullptr; } std::vector segmentationNodes; unsigned int numberOfNodes = this->GetScene()->GetNodesByClass(""vtkMRMLSegmentationNode"", segmentationNodes); for (unsigned int nodeIndex=0; nodeIndexGetStorageNodeID(); if (storageNodeID && !strcmp(storageNodeID, this->ID)) { return vtkMRMLSegmentationNode::SafeDownCast(node); } } } return nullptr; } //---------------------------------------------------------------------------- const char* vtkMRMLSegmentationStorageNode::GetDefaultWriteFileExtension() { vtkMRMLSegmentationNode* segmentationNode = this->GetAssociatedDataNode(); if (!segmentationNode) { return nullptr; } if (segmentationNode->GetSegmentation()->IsMasterRepresentationImageData()) { return ""seg.nrrd""; } else if (segmentationNode->GetSegmentation()->IsMasterRepresentationPolyData()) { return ""seg.vtm""; } // Master representation is not supported for writing to file return nullptr; } //---------------------------------------------------------------------------- void vtkMRMLSegmentationStorageNode::ResetSupportedWriteFileTypes() { this->InitializeSupportedWriteFileTypes(); } //---------------------------------------------------------------------------- bool vtkMRMLSegmentationStorageNode::CanReadInReferenceNode(vtkMRMLNode *refNode) { return refNode->IsA(""vtkMRMLSegmentationNode""); } //---------------------------------------------------------------------------- int vtkMRMLSegmentationStorageNode::ReadDataInternal(vtkMRMLNode *refNode) { vtkMRMLSegmentationNode* segmentationNode = vtkMRMLSegmentationNode::SafeDownCast(refNode); if (!segmentationNode) { vtkErrorMacro(""ReadDataInternal: Reference node is not a segmentation node""); return 0; } MRMLNodeModifyBlocker blocker(segmentationNode); std::string fullName = this->GetFullNameFromFileName(); if (fullName.empty()) { vtkErrorMacro(""ReadDataInternal: File name not specified""); return 0; } // Check that the file exists if (vtksys::SystemTools::FileExists(fullName.c_str()) == false) { vtkErrorMacro(""ReadDataInternal: segmentation file '"" << fullName.c_str() << ""' not found.""); return 0; } bool success = false; // Try to read as labelmap first then as poly data if (this->ReadBinaryLabelmapRepresentation(segmentationNode, fullName)) { success = true; } #ifdef SUPPORT_4D_SPATIAL_NRRD else if (this->ReadBinaryLabelmapRepresentation4DSpatial(segmentationNode, fullName)) { success = true; } #endif else if (this->ReadPolyDataRepresentation(segmentationNode, fullName)) { success = true; } // Create display node if segmentation there is none if (success && !segmentationNode->GetDisplayNode()) { segmentationNode->CreateDefaultDisplayNodes(); } if (!success) { // Failed to read vtkErrorMacro(""ReadDataInternal: File "" << fullName << "" could not be read neither as labelmap nor poly data""); return 0; } return 1; } #ifdef SUPPORT_4D_SPATIAL_NRRD //---------------------------------------------------------------------------- int vtkMRMLSegmentationStorageNode::ReadBinaryLabelmapRepresentation4DSpatial(vtkMRMLSegmentationNode* segmentationNode, std::string path) { if (!vtksys::SystemTools::FileExists(path.c_str())) { vtkErrorMacro(""ReadBinaryLabelmapRepresentation: Input file "" << path << "" does not exist!""); return 0; } // Set up output segmentation if (!segmentationNode || segmentationNode->GetSegmentation()->GetNumberOfSegments() > 0) { vtkErrorMacro(""ReadBinaryLabelmapRepresentation: Output segmentation must exist and must be empty!""); return 0; } vtkSegmentation* segmentation = segmentationNode->GetSegmentation(); // Read 4D NRRD image file typedef itk::ImageFileReader FileReaderType; FileReaderType::Pointer reader = FileReaderType::New(); reader->SetFileName(path); try { reader->Update(); } catch (itk::ImageFileReaderException &error) { // Do not report error as the file might contain poly data in which case ReadPolyDataRepresentation will read it alright vtkDebugMacro(""ReadBinaryLabelmapRepresentation: Failed to load file "" << path << "" as segmentation. Exception:\\n"" << error); return 0; } BinaryLabelmap4DImageType::Pointer allSegmentLabelmapsImage = reader->GetOutput(); // Read succeeded, set master representation segmentation->SetMasterRepresentationName(vtkSegmentationConverter::GetSegmentationBinaryLabelmapRepresentationName()); // Get metadata dictionary from image itk::MetaDataDictionary metadata = allSegmentLabelmapsImage->GetMetaDataDictionary(); // Read common geometry extent std::string commonExtent; itk::ExposeMetaData(metadata, GetSegmentationMetaDataKey(KEY_SEGMENTATION_EXTENT).c_str(), commonExtent); int commonGeometryExtent[6] = {0,-1,0,-1,0,-1}; GetImageExtentFromString(commonGeometryExtent, commonExtent); // Read conversion parameters std::string conversionParameters; itk::ExposeMetaData(metadata, GetSegmentationMetaDataKey(KEY_SEGMENTATION_CONVERSION_PARAMETERS).c_str(), conversionParameters); segmentation->DeserializeConversionParameters(conversionParameters); // Read contained representation names std::string containedRepresentationNames; itk::ExposeMetaData(metadata, GetSegmentationMetaDataKey(KEY_SEGMENTATION_CONTAINED_REPRESENTATION_NAMES).c_str(), containedRepresentationNames); // Get image properties BinaryLabelmap4DImageType::RegionType itkRegion = allSegmentLabelmapsImage->GetLargestPossibleRegion(); BinaryLabelmap4DImageType::PointType itkOrigin = allSegmentLabelmapsImage->GetOrigin(); BinaryLabelmap4DImageType::SpacingType itkSpacing = allSegmentLabelmapsImage->GetSpacing(); BinaryLabelmap4DImageType::DirectionType itkDirections = allSegmentLabelmapsImage->GetDirection(); // Make image properties accessible for VTK double origin[3] = {itkOrigin[0], itkOrigin[1], itkOrigin[2]}; double spacing[3] = {itkSpacing[0], itkSpacing[1], itkSpacing[2]}; double directions[3][3] = {{1.0,0.0,0.0},{0.0,1.0,0.0},{0.0,0.0,1.0}}; for (unsigned int col=0; col<3; col++) { for (unsigned int row=0; row<3; row++) { directions[row][col] = itkDirections[row][col]; } } // Read segment binary labelmaps for (unsigned int segmentIndex = itkRegion.GetIndex()[3]; segmentIndex < itkRegion.GetIndex()[3]+itkRegion.GetSize()[3]; ++segmentIndex) { // Create segment vtkSmartPointer currentSegment = vtkSmartPointer::New(); // Get metadata for current segment // ID std::string currentSegmentID; itk::ExposeMetaData( metadata, GetSegmentMetaDataKey(segmentIndex, KEY_SEGMENT_ID), currentSegmentID); // Name std::string currentSegmentName; itk::ExposeMetaData( metadata, GetSegmentMetaDataKey(segmentIndex, KEY_SEGMENT_NAME), currentSegmentName); currentSegment->SetName(currentSegmentName.c_str()); // Color std::string colorString; itk::ExposeMetaData( metadata, GetSegmentMetaDataKey(segmentIndex, KEY_SEGMENT_COLOR), colorString); if (colorString.empty()) { // Backwards compatibility itk::ExposeMetaData(metadata, GetSegmentMetaDataKey(segmentIndex, ""DefaultColor""), colorString); } double currentSegmentColor[3] = {0.0,0.0,0.0}; GetSegmentColorFromString(currentSegmentColor, colorString); // Extent std::string extentValue; itk::ExposeMetaData( metadata, GetSegmentMetaDataKey(segmentIndex, KEY_SEGMENT_EXTENT), extentValue); int currentSegmentExtent[6] = {0,-1,0,-1,0,-1}; GetImageExtentFromString(currentSegmentExtent, extentValue); // Tags std::string tagsValue; itk::ExposeMetaData( metadata, GetSegmentMetaDataKey(segmentIndex, KEY_SEGMENT_TAGS), tagsValue); SetSegmentTagsFromString(currentSegment, tagsValue); // NameAutoGenerated std::string currentSegmentNameAutoGenerated; itk::ExposeMetaData( metadata, GetSegmentMetaDataKey(segmentIndex, KEY_SEGMENT_NAME_AUTO_GENERATED), currentSegmentNameAutoGenerated); currentSegment->SetNameAutoGenerated(!currentSegmentNameAutoGenerated.compare(""1"")); // ColorAutoGenerated std::string currentSegmentColorAutoGenerated; itk::ExposeMetaData( metadata, GetSegmentMetaDataKey(segmentIndex, KEY_SEGMENT_COLOR_AUTO_GENERATED), currentSegmentColorAutoGenerated); currentSegment->SetColorAutoGenerated(!currentSegmentColorAutoGenerated.compare(""1"")); // Create binary labelmap volume vtkSmartPointer currentBinaryLabelmap = vtkSmartPointer::New(); currentBinaryLabelmap->SetOrigin(origin); currentBinaryLabelmap->SetSpacing(spacing); currentBinaryLabelmap->SetDirections(directions); currentBinaryLabelmap->SetExtent(currentSegmentExtent); currentBinaryLabelmap->AllocateScalars(VTK_UNSIGNED_CHAR, 1); unsigned char* labelmapPtr = (unsigned char*)currentBinaryLabelmap->GetScalarPointerForExtent(currentSegmentExtent); // Define ITK region for current segment BinaryLabelmap4DImageType::RegionType segmentRegion; BinaryLabelmap4DImageType::SizeType segmentRegionSize; BinaryLabelmap4DImageType::IndexType segmentRegionIndex; segmentRegionIndex[0] = segmentRegionIndex[1] = segmentRegionIndex[2] = 0; segmentRegionIndex[3] = segmentIndex; segmentRegionSize = itkRegion.GetSize(); segmentRegionSize[3] = 1; segmentRegion.SetIndex(segmentRegionIndex); segmentRegion.SetSize(segmentRegionSize); // Iterate through current segment's region and read voxel values into segment labelmap BinaryLabelmap4DIteratorType segmentLabelmapIterator(allSegmentLabelmapsImage, segmentRegion); for (segmentLabelmapIterator.GoToBegin(); !segmentLabelmapIterator.IsAtEnd(); ++segmentLabelmapIterator) { // Skip region outside extent of current segment (consider common extent boundaries) BinaryLabelmap4DImageType::IndexType segmentIndex = segmentLabelmapIterator.GetIndex(); if ( segmentIndex[0] + commonGeometryExtent[0] < currentSegmentExtent[0] || segmentIndex[0] + commonGeometryExtent[0] > currentSegmentExtent[1] || segmentIndex[1] + commonGeometryExtent[2] < currentSegmentExtent[2] || segmentIndex[1] + commonGeometryExtent[2] > currentSegmentExtent[3] || segmentIndex[2] + commonGeometryExtent[4] < currentSegmentExtent[4] || segmentIndex[2] + commonGeometryExtent[4] > currentSegmentExtent[5] ) { continue; } // Get voxel value unsigned char voxelValue = segmentLabelmapIterator.Get(); // Set voxel value in current segment labelmap (*labelmapPtr) = voxelValue; ++labelmapPtr; } // Set loaded binary labelmap to segment currentSegment->AddRepresentation(vtkSegmentationConverter::GetSegmentationBinaryLabelmapRepresentationName(), currentBinaryLabelmap); // Add segment to segmentation segmentation->AddSegment(currentSegment, currentSegmentID); } // Create contained representations now that all the data is loaded this->CreateRepresentationsBySerializedNames(segmentation, containedRepresentationNames); return 1; } #endif // SUPPORT_4D_SPATIAL_NRRD //---------------------------------------------------------------------------- int vtkMRMLSegmentationStorageNode::ReadBinaryLabelmapRepresentation(vtkMRMLSegmentationNode* segmentationNode, std::string path) { if (!vtksys::SystemTools::FileExists(path.c_str())) { vtkErrorMacro(""ReadBinaryLabelmapRepresentation: Input file "" << path << "" does not exist!""); return 0; } // Set up output segmentation if (!segmentationNode || segmentationNode->GetSegmentation()->GetNumberOfSegments() > 0) { vtkErrorMacro(""ReadBinaryLabelmapRepresentation: Output segmentation must exist and must be empty!""); return 0; } vtkSegmentation* segmentation = segmentationNode->GetSegmentation(); vtkSmartPointer imageData = nullptr; vtkNew archetypeImageReader; archetypeImageReader->SetSingleFile(1); archetypeImageReader->SetUseOrientationFromFile(1); archetypeImageReader->ResetFileNames(); archetypeImageReader->SetArchetype(path.c_str()); archetypeImageReader->SetOutputScalarTypeToNative(); archetypeImageReader->SetDesiredCoordinateOrientationToNative(); archetypeImageReader->SetUseNativeOriginOn(); int numberOfSegments = 0; std::map > segmentIndexInLayer; std::string containedRepresentationNames; vtkMatrix4x4* rasToFileIjk = nullptr; int imageExtentInFile[6] = { 0, -1, 0, -1, 0, -1 }; int commonGeometryExtent[6] = { 0, -1, 0, -1, 0, -1 }; int referenceImageExtentOffset[3] = { 0, 0, 0 }; if (archetypeImageReader->CanReadFile(path.c_str())) { // Read the volume archetypeImageReader->Update(); if (archetypeImageReader->GetErrorCode() != vtkErrorCode::NoError) { vtkErrorMacro(""ReadBinaryLabelmapRepresentation: Error reading image!""); return 0; } // Copy image data to sequence of volume nodes imageData = archetypeImageReader->GetOutput(); rasToFileIjk = archetypeImageReader->GetRasToIjkMatrix(); imageData->GetExtent(imageExtentInFile); imageData->GetExtent(commonGeometryExtent); // Get metadata dictionary from image itk::MetaDataDictionary dictionary = archetypeImageReader->GetMetaDataDictionary(); std::string segmentationExtentString; if (this->GetSegmentationMetaDataFromDicitionary(segmentationExtentString, dictionary, KEY_SEGMENTATION_EXTENT)) { // Legacy format. Return and read using ReadBinaryLabelmapRepresentation4DSpatial if availiable. return 0; } // Read common geometry std::string referenceImageExtentOffsetStr; if (this->GetSegmentationMetaDataFromDicitionary(referenceImageExtentOffsetStr, dictionary, KEY_SEGMENTATION_REFERENCE_IMAGE_EXTENT_OFFSET)) { // Common geometry extent is specified by an offset (extent[0], extent[2], extent[4]) and the size of the image // NRRD file cannot store start extent, so we store that in KEY_SEGMENTATION_REFERENCE_IMAGE_EXTENT_OFFSET and from imageExtentInFile we // only use the extent size. std::stringstream ssExtentValue(referenceImageExtentOffsetStr); ssExtentValue >> referenceImageExtentOffset[0] >> referenceImageExtentOffset[1] >> referenceImageExtentOffset[2]; commonGeometryExtent[0] = referenceImageExtentOffset[0]; commonGeometryExtent[1] = referenceImageExtentOffset[0] + imageExtentInFile[1] - imageExtentInFile[0]; commonGeometryExtent[2] = referenceImageExtentOffset[1]; commonGeometryExtent[3] = referenceImageExtentOffset[1] + imageExtentInFile[3] - imageExtentInFile[2]; commonGeometryExtent[4] = referenceImageExtentOffset[2]; commonGeometryExtent[5] = referenceImageExtentOffset[2] + imageExtentInFile[5] - imageExtentInFile[4]; } else { // KEY_SEGMENTATION_REFERENCE_IMAGE_EXTENT_OFFSET is not specified, // which means that this is probably a regular NRRD file that should be imported as a segmentation. // Use the image extent as common geometry extent. vtkInfoMacro(<< KEY_SEGMENTATION_REFERENCE_IMAGE_EXTENT_OFFSET << "" attribute was not found in NRRD segmentation file. Assume no offset.""); imageData->GetExtent(commonGeometryExtent); } // Read conversion parameters std::string conversionParameters; if (this->GetSegmentationMetaDataFromDicitionary(conversionParameters, dictionary, KEY_SEGMENTATION_CONVERSION_PARAMETERS)) { segmentation->DeserializeConversionParameters(conversionParameters); } // Read contained representation names this->GetSegmentationMetaDataFromDicitionary(containedRepresentationNames, dictionary, KEY_SEGMENTATION_CONTAINED_REPRESENTATION_NAMES); // Read contained segment layer numbers while (dictionary.HasKey(GetSegmentMetaDataKey(numberOfSegments, KEY_SEGMENT_ID))) { int segmentIndex = numberOfSegments; std::string layerValue; if (this->GetSegmentMetaDataFromDicitionary(layerValue, dictionary, segmentIndex, KEY_SEGMENT_LAYER)) { segmentIndexInLayer[vtkVariant(layerValue).ToInt()].push_back(segmentIndex); } else { segmentIndexInLayer[segmentIndex].push_back(segmentIndex); } ++numberOfSegments; } } else { vtkDebugMacro(""ReadBinaryLabelmapRepresentation: File is not using a supported format!""); return 0; } if (imageData == nullptr) { vtkErrorMacro(""vtkMRMLVolumeSequenceStorageNode::ReadDataInternal: invalid image data""); return 0; } int numberOfFrames = imageData->GetNumberOfScalarComponents(); // Read succeeded, set master representation segmentation->SetMasterRepresentationName(vtkSegmentationConverter::GetSegmentationBinaryLabelmapRepresentationName()); MRMLNodeModifyBlocker blocker(segmentationNode); // Compensate for the extent shift in the image origin. // We change the origin so that if a reader ignores private fields, such as // referenceImageExtentOffset, the image is placed correctly in physical coordinate system. vtkNew fileIjkToIjk; fileIjkToIjk->SetElement(0, 3, referenceImageExtentOffset[0]); fileIjkToIjk->SetElement(1, 3, referenceImageExtentOffset[1]); fileIjkToIjk->SetElement(2, 3, referenceImageExtentOffset[2]); vtkNew rasToIjk; vtkMatrix4x4::Multiply4x4(fileIjkToIjk.GetPointer(), rasToFileIjk, rasToIjk.GetPointer()); vtkNew imageToWorldMatrix; // = ijkToRas; vtkMatrix4x4::Invert(rasToIjk.GetPointer(), imageToWorldMatrix.GetPointer()); imageData->SetExtent(commonGeometryExtent); vtkNew extractComponents; extractComponents->SetInputData(imageData); vtkNew padder; padder->SetInputConnection(extractComponents->GetOutputPort()); // Get metadata for current segment itk::MetaDataDictionary dictionary = archetypeImageReader->GetMetaDataDictionary(); std::vector > segments(numberOfSegments); std::map > layerToImage; for (int frameIndex = 0; frameIndex < numberOfFrames; ++frameIndex) { // Create binary labelmap volume vtkSmartPointer currentBinaryLabelmap = nullptr; if (numberOfSegments == 0) { currentBinaryLabelmap = vtkSmartPointer::New(); extractComponents->SetComponents(frameIndex); padder->SetOutputWholeExtent(imageExtentInFile); padder->Update(); currentBinaryLabelmap->ShallowCopy(padder->GetOutput()); double scalarRange[2] = { 0 }; currentBinaryLabelmap->GetScalarRange(scalarRange); vtkIdType lowLabel = (vtkIdType)(floor(scalarRange[0])); vtkIdType highLabel = (vtkIdType)(ceil(scalarRange[1])); vtkSmartPointer imageAccumulate = vtkSmartPointer::New(); imageAccumulate->SetInputData(currentBinaryLabelmap); imageAccumulate->IgnoreZeroOn(); // Ignore background value imageAccumulate->SetComponentExtent(lowLabel, highLabel, 0, 0, 0, 0); imageAccumulate->SetComponentOrigin(0, 0, 0); imageAccumulate->SetComponentSpacing(1, 1, 1); imageAccumulate->Update(); std::vector labelValues; for (vtkIdType labelValue = lowLabel; labelValue <= highLabel; ++labelValue) { if (labelValue == 0) { continue; } double frequency = imageAccumulate->GetOutput()->GetPointData()->GetScalars()->GetTuple1(labelValue - lowLabel); if (frequency == 0.0) { continue; } vtkSmartPointer currentSegment = vtkSmartPointer::New(); currentSegment->SetLabelValue(labelValue); currentBinaryLabelmap->SetImageToWorldMatrix(imageToWorldMatrix.GetPointer()); currentSegment->AddRepresentation(vtkSegmentationConverter::GetBinaryLabelmapRepresentationName(), currentBinaryLabelmap); segments.push_back(currentSegment); } } else { for (int segmentIndex : segmentIndexInLayer[frameIndex]) { // Create segment vtkSmartPointer currentSegment = vtkSmartPointer::New(); std::string segmentColor; if (this->GetSegmentMetaDataFromDicitionary(segmentColor, dictionary, segmentIndex, KEY_SEGMENT_COLOR)) { double currentSegmentColor[3] = { 0.0, 0.0, 0.0 }; this->GetSegmentColorFromString(currentSegmentColor, segmentColor); currentSegment->SetColor(currentSegmentColor); } else if (this->GetSegmentMetaDataFromDicitionary(segmentColor, dictionary, segmentIndex, ""DefaultColor"")) { double defaultSegmentColor[3] = { 0.0, 0.0, 0.0 }; this->GetSegmentColorFromString(defaultSegmentColor, segmentColor); currentSegment->SetColor(defaultSegmentColor); } // Tags std::string segmentTags; if (this->GetSegmentMetaDataFromDicitionary(segmentTags, dictionary, segmentIndex, KEY_SEGMENT_TAGS)) { this->SetSegmentTagsFromString(currentSegment, segmentTags); } // NameAutoGenerated std::string nameAutoGenerated; if (this->GetSegmentMetaDataFromDicitionary(nameAutoGenerated, dictionary, segmentIndex, KEY_SEGMENT_NAME_AUTO_GENERATED)) { currentSegment->SetNameAutoGenerated(!strcmp(nameAutoGenerated.c_str(), ""1"")); } // ColorAutoGenerated std::string colorAutoGenerated; if (this->GetSegmentMetaDataFromDicitionary(colorAutoGenerated, dictionary, segmentIndex, KEY_SEGMENT_COLOR_AUTO_GENERATED)) { currentSegment->SetColorAutoGenerated(!strcmp(colorAutoGenerated.c_str(),""1"")); } // Label value std::string labelValue; if (this->GetSegmentMetaDataFromDicitionary(labelValue, dictionary, segmentIndex, KEY_SEGMENT_LABEL_VALUE)) { currentSegment->SetLabelValue(vtkVariant(labelValue).ToInt()); } if (currentBinaryLabelmap == nullptr) { currentBinaryLabelmap = vtkSmartPointer::New(); // Extent int currentSegmentExtent[6] = { 0, -1, 0, -1, 0, -1 }; std::string currentExtentString; if (this->GetSegmentMetaDataFromDicitionary(currentExtentString, dictionary, segmentIndex, KEY_SEGMENT_EXTENT)) { GetImageExtentFromString(currentSegmentExtent, currentExtentString); } else { vtkWarningMacro(""Segment extent is missing for segment "" << segmentIndex); for (int i = 0; i < 6; i++) { currentSegmentExtent[i] = imageExtentInFile[i]; } } for (int i = 0; i < 3; i++) { currentSegmentExtent[i * 2] += referenceImageExtentOffset[i]; currentSegmentExtent[i * 2 + 1] += referenceImageExtentOffset[i]; } // Copy with clipping to specified extent if (currentSegmentExtent[0] <= currentSegmentExtent[1] && currentSegmentExtent[2] <= currentSegmentExtent[3] && currentSegmentExtent[4] <= currentSegmentExtent[5]) { // non-empty segment extractComponents->SetComponents(frameIndex); padder->SetOutputWholeExtent(currentSegmentExtent); padder->Update(); currentBinaryLabelmap->DeepCopy(padder->GetOutput()); } else { // empty segment for (int i = 0; i < 3; ++i) { currentSegmentExtent[2 * i] = 0; currentSegmentExtent[2 * i + 1] = -1; } currentBinaryLabelmap->SetExtent(currentSegmentExtent); currentBinaryLabelmap->AllocateScalars(VTK_UNSIGNED_CHAR, 1); } currentBinaryLabelmap->SetImageToWorldMatrix(imageToWorldMatrix.GetPointer()); } // Set loaded binary labelmap to segment currentSegment->AddRepresentation(vtkSegmentationConverter::GetSegmentationBinaryLabelmapRepresentationName(), currentBinaryLabelmap); segments[segmentIndex] = currentSegment; } } } // Add the created segments to the segmentation for (int segmentIndex = 0; segmentIndex < static_cast(segments.size()); ++segmentIndex) { vtkSegment* currentSegment = segments[segmentIndex]; if (!currentSegment) { vtkErrorMacro(""Could not find segment"" << segmentIndex); continue; } std::string currentSegmentID; if (numberOfSegments != 0) { // ID if (!this->GetSegmentMetaDataFromDicitionary(currentSegmentID, dictionary, segmentIndex, KEY_SEGMENT_ID)) { // No segment ID is specified, which may mean that it is an empty segmentation. // We consider a segmentation empty if it has only one scalar component that is empty. if (numberOfFrames == 1) { extractComponents->SetComponents(segmentIndex); extractComponents->Update(); vtkImageData* labelmap = extractComponents->GetOutput(); double* scalarRange = labelmap->GetScalarRange(); if (scalarRange[0] >= scalarRange[1]) { // Segmentation contains a single blank segment without segment ID, // which means that it is an empty segmentation. // It may still contain valuable metadata, but we don't create any segments. break; } } currentSegmentID = segmentation->GenerateUniqueSegmentID(""Segment""); vtkWarningMacro(""Segment ID is missing for segment "" << segmentIndex << "" adding segment with ID: "" << currentSegmentID); } // Name std::string segmentName; if (this->GetSegmentMetaDataFromDicitionary(segmentName, dictionary, segmentIndex, KEY_SEGMENT_NAME)) { currentSegment->SetName(segmentName.c_str()); } else { vtkWarningMacro(""Segment name is missing for segment "" << segmentIndex); currentSegment->SetName(currentSegmentID.c_str()); } } else { std::stringstream segmentNameSS; segmentNameSS << ""Segment_"" << currentSegment->GetLabelValue(); currentSegmentID = segmentation->GenerateUniqueSegmentID(segmentNameSS.str()); currentSegment->SetName(currentSegmentID.c_str()); } segmentation->AddSegment(currentSegment, currentSegmentID); } // Create contained representations now that all the data is loaded this->CreateRepresentationsBySerializedNames(segmentation, containedRepresentationNames); return 1; } //---------------------------------------------------------------------------- int vtkMRMLSegmentationStorageNode::ReadPolyDataRepresentation(vtkMRMLSegmentationNode* segmentationNode, std::string path) { if (!vtksys::SystemTools::FileExists(path.c_str())) { vtkErrorMacro(""ReadPolyDataRepresentation: Input file "" << path << "" does not exist!""); return 0; } // Set up output segmentation if (!segmentationNode || segmentationNode->GetSegmentation()->GetNumberOfSegments() > 0) { vtkErrorMacro(""ReadPolyDataRepresentation: Output segmentation must exist and must be empty!""); return 0; } vtkSegmentation* segmentation = segmentationNode->GetSegmentation(); // Add all files to storage node (multiblock dataset writes segments to individual files in a separate folder) this->AddPolyDataFileNames(path, segmentation); // Read multiblock dataset from disk vtkSmartPointer reader = vtkSmartPointer::New(); reader->SetFileName(path.c_str()); reader->Update(); vtkMultiBlockDataSet* multiBlockDataset = vtkMultiBlockDataSet::SafeDownCast(reader->GetOutput()); if (!multiBlockDataset || multiBlockDataset->GetNumberOfBlocks()==0) { vtkErrorMacro(""ReadPolyDataRepresentation: Failed to read file "" << path); return 0; } MRMLNodeModifyBlocker blocker(segmentationNode); // Read segment poly datas std::string masterRepresentationName; std::string containedRepresentationNames; std::string conversionParameters; for (unsigned int blockIndex = 0; blockIndexGetNumberOfBlocks(); ++blockIndex) { // Get poly data representation vtkPolyData* currentPolyData = vtkPolyData::SafeDownCast(multiBlockDataset->GetBlock(blockIndex)); // Set master representation if it has not been set yet // (there is no global place to store it, but every segment field data contains a copy of it) if (masterRepresentationName.empty()) { vtkStringArray* masterRepresentationArray = vtkStringArray::SafeDownCast( currentPolyData->GetFieldData()->GetAbstractArray(GetSegmentationMetaDataKey(KEY_SEGMENTATION_MASTER_REPRESENTATION).c_str())); if (!masterRepresentationArray) { vtkErrorMacro(""ReadPolyDataRepresentation: Unable to find master representation for segmentation in file "" << path); return 0; } masterRepresentationName = masterRepresentationArray->GetValue(0); segmentation->SetMasterRepresentationName(masterRepresentationName.c_str()); } // Read conversion parameters (stored in each segment file, but need to set only once) if ( conversionParameters.empty() && currentPolyData->GetFieldData()->GetAbstractArray(GetSegmentationMetaDataKey(KEY_SEGMENTATION_CONVERSION_PARAMETERS).c_str()) ) { vtkStringArray* conversionParametersArray = vtkStringArray::SafeDownCast( currentPolyData->GetFieldData()->GetAbstractArray(GetSegmentationMetaDataKey(KEY_SEGMENTATION_CONVERSION_PARAMETERS).c_str()) ); conversionParameters = conversionParametersArray->GetValue(0); segmentation->DeserializeConversionParameters(conversionParameters); } // Read contained representation names if ( containedRepresentationNames.empty() && currentPolyData->GetFieldData()->GetAbstractArray(GetSegmentationMetaDataKey(KEY_SEGMENTATION_CONTAINED_REPRESENTATION_NAMES).c_str()) ) { containedRepresentationNames = vtkStringArray::SafeDownCast( currentPolyData->GetFieldData()->GetAbstractArray(GetSegmentationMetaDataKey(KEY_SEGMENTATION_CONTAINED_REPRESENTATION_NAMES).c_str()) )->GetValue(0); } // Create segment vtkSmartPointer currentSegment = vtkSmartPointer::New(); currentSegment->AddRepresentation(segmentation->GetMasterRepresentationName(), currentPolyData); // Set segment properties std::string currentSegmentID; vtkStringArray* idArray = vtkStringArray::SafeDownCast( currentPolyData->GetFieldData()->GetAbstractArray(GetSegmentMetaDataKey(SINGLE_SEGMENT_INDEX, KEY_SEGMENT_ID).c_str()) ); if (idArray && idArray->GetNumberOfValues()>0) { currentSegmentID = idArray->GetValue(0); } else { vtkWarningMacro(""ReadPolyDataRepresentation: Segment ID property not found when reading segment "" << blockIndex << "" from file "" << path); } std::string currentSegmentName; vtkStringArray* nameArray = vtkStringArray::SafeDownCast( currentPolyData->GetFieldData()->GetAbstractArray(GetSegmentMetaDataKey(SINGLE_SEGMENT_INDEX, KEY_SEGMENT_NAME).c_str()) ); if (nameArray && nameArray->GetNumberOfValues()>0) { currentSegmentName = nameArray->GetValue(0); } else { vtkWarningMacro(""ReadPolyDataRepresentation: Segment Name property not found when reading segment "" << blockIndex << "" from file "" << path); std::stringstream ssCurrentSegmentName; ssCurrentSegmentName << ""Segment "" << blockIndex; currentSegmentName = ssCurrentSegmentName.str(); } currentSegment->SetName(currentSegmentName.c_str()); double color[3]={1.0, 0.0, 0.0}; vtkDoubleArray* colorArray = vtkDoubleArray::SafeDownCast( currentPolyData->GetFieldData()->GetArray(GetSegmentMetaDataKey(SINGLE_SEGMENT_INDEX, KEY_SEGMENT_COLOR).c_str()) ); if (!colorArray || colorArray->GetNumberOfTuples() == 0) { // Backwards compatibility colorArray = vtkDoubleArray::SafeDownCast( currentPolyData->GetFieldData()->GetArray(GetSegmentMetaDataKey(SINGLE_SEGMENT_INDEX, ""DefaultColor"").c_str()) ); } if (colorArray && colorArray->GetNumberOfTuples() > 0 && colorArray->GetNumberOfComponents() == 3) { colorArray->GetTuple(0, color); } else { vtkWarningMacro(""ReadPolyDataRepresentation: Segment color property not found when reading segment "" << blockIndex << "" from file "" << path); } currentSegment->SetColor(color); // Tags vtkStringArray* tagsArray = vtkStringArray::SafeDownCast( currentPolyData->GetFieldData()->GetAbstractArray(GetSegmentMetaDataKey(SINGLE_SEGMENT_INDEX, KEY_SEGMENT_TAGS).c_str()) ); if (tagsArray) { std::string tags(tagsArray->GetValue(0).c_str()); std::string separatorCharacter(""|""); size_t separatorPosition = tags.find(separatorCharacter); while (separatorPosition != std::string::npos) { std::string mapPairStr = tags.substr(0, separatorPosition); size_t colonPosition = mapPairStr.find("":""); if (colonPosition == std::string::npos) { continue; } currentSegment->SetTag(mapPairStr.substr(0, colonPosition), mapPairStr.substr(colonPosition+1)); tags = tags.substr(separatorPosition+1); separatorPosition = tags.find(separatorCharacter); } } // NameAutoGenerated vtkStringArray* nameAutoGeneratedArray = vtkStringArray::SafeDownCast( currentPolyData->GetFieldData()->GetAbstractArray(GetSegmentMetaDataKey(SINGLE_SEGMENT_INDEX, KEY_SEGMENT_NAME_AUTO_GENERATED).c_str()) ); if (nameAutoGeneratedArray && nameAutoGeneratedArray->GetNumberOfValues()>0) { currentSegment->SetNameAutoGenerated(!nameAutoGeneratedArray->GetValue(0).compare(""1"")); } // ColorAutoGenerated vtkStringArray* colorAutoGeneratedArray = vtkStringArray::SafeDownCast( currentPolyData->GetFieldData()->GetAbstractArray(GetSegmentMetaDataKey(SINGLE_SEGMENT_INDEX, KEY_SEGMENT_COLOR_AUTO_GENERATED).c_str()) ); if (colorAutoGeneratedArray && colorAutoGeneratedArray->GetNumberOfValues()>0) { currentSegment->SetColorAutoGenerated(!colorAutoGeneratedArray->GetValue(0).compare(""1"")); } // Add segment to segmentation segmentation->AddSegment(currentSegment, currentSegmentID); } // Create contained representations now that all the data is loaded this->CreateRepresentationsBySerializedNames(segmentation, containedRepresentationNames); return 1; } //---------------------------------------------------------------------------- int vtkMRMLSegmentationStorageNode::WriteDataInternal(vtkMRMLNode *refNode) { std::string fullName = this->GetFullNameFromFileName(); if (fullName.empty()) { vtkErrorMacro(""vtkMRMLModelNode: File name not specified""); return 0; } vtkMRMLSegmentationNode *segmentationNode = vtkMRMLSegmentationNode::SafeDownCast(refNode); if (segmentationNode == nullptr) { vtkErrorMacro(""Segmentation node expected. Unable to write node to file.""); return 0; } if (segmentationNode->GetSegmentation() == nullptr) { vtkErrorMacro(""Segmentation node does not contain segmentation object. Unable to write node to file.""); return 0; } // Write only master representation if (segmentationNode->GetSegmentation()->IsMasterRepresentationImageData()) { return this->WriteBinaryLabelmapRepresentation(segmentationNode, fullName); } else if (segmentationNode->GetSegmentation()->IsMasterRepresentationPolyData()) { return this->WritePolyDataRepresentation(segmentationNode, fullName); } vtkErrorMacro(""Segmentation master representation "" << segmentationNode->GetSegmentation()->GetMasterRepresentationName() << "" cannot be written to file""); return 0; } //---------------------------------------------------------------------------- int vtkMRMLSegmentationStorageNode::WriteBinaryLabelmapRepresentation(vtkMRMLSegmentationNode* segmentationNode, std::string fullName) { if (!segmentationNode) { vtkErrorMacro(""WriteBinaryLabelmapRepresentation: Invalid segmentation to write to disk""); return 0; } vtkSegmentation* segmentation = segmentationNode->GetSegmentation(); segmentation->CollapseBinaryLabelmaps(false); // Get and check master representation if (!segmentationNode->GetSegmentation()->IsMasterRepresentationImageData()) { vtkErrorMacro(""WriteBinaryLabelmapRepresentation: Invalid master representation to write as image data""); return 0; } vtkIdType scalarType = VTK_UNSIGNED_CHAR; vtkIdType scalarSize = 0; std::vector< std::string > segmentIDs; segmentation->GetSegmentIDs(segmentIDs); for (std::vector< std::string >::const_iterator segmentIdIt = segmentIDs.begin(); segmentIdIt != segmentIDs.end(); ++segmentIdIt) { std::string currentSegmentID = *segmentIdIt; vtkSegment* currentSegment = segmentation->GetSegment(*segmentIdIt); vtkSmartPointer currentBinaryLabelmap = vtkOrientedImageData::SafeDownCast( currentSegment->GetRepresentation(segmentationNode->GetSegmentation()->GetMasterRepresentationName())); if (currentBinaryLabelmap->GetScalarSize() > scalarSize) { scalarSize = currentBinaryLabelmap->GetScalarSize(); scalarType = currentBinaryLabelmap->GetScalarType(); } } // Determine shared labelmap dimensions and properties vtkSmartPointer commonGeometryImage = vtkSmartPointer::New(); int commonGeometryExtent[6] = { 0, -1, 0, -1, 0, -1 }; if (segmentation->GetNumberOfSegments() > 0) { std::string commonGeometryString = segmentation->DetermineCommonLabelmapGeometry( this->CropToMinimumExtent ? vtkSegmentation::EXTENT_UNION_OF_EFFECTIVE_SEGMENTS : vtkSegmentation::EXTENT_REFERENCE_GEOMETRY); vtkSegmentationConverter::DeserializeImageGeometry(commonGeometryString, commonGeometryImage, true, scalarType, 1); commonGeometryImage->GetExtent(commonGeometryExtent); } if (commonGeometryExtent[0] > commonGeometryExtent[1] || commonGeometryExtent[2] > commonGeometryExtent[3] || commonGeometryExtent[4] > commonGeometryExtent[5]) { // common image is empty, which cannot be written to image file // change it to a 1x1x1 image instead commonGeometryExtent[0] = 0; commonGeometryExtent[1] = 0; commonGeometryExtent[2] = 0; commonGeometryExtent[3] = 0; commonGeometryExtent[4] = 0; commonGeometryExtent[5] = 0; commonGeometryImage->SetExtent(commonGeometryExtent); commonGeometryImage->AllocateScalars(scalarType, 1); } vtkOrientedImageDataResample::FillImage(commonGeometryImage, 0); vtkNew writer; writer->SetFileName(fullName.c_str()); writer->SetUseCompression(this->GetUseCompression()); writer->SetSpace(nrrdSpaceLeftPosteriorSuperior); writer->SetMeasurementFrameMatrix(nullptr); // Create metadata dictionary // Save extent start of common geometry image so that we can restore original extents when reading from file //writer->SetAttribute(GetSegmentationMetaDataKey(KEY_SEGMENTATION_EXTENT).c_str(), GetImageExtentAsString(commonGeometryImage)); int referenceImageExtentOffset[3] = { commonGeometryExtent[0], commonGeometryExtent[2], commonGeometryExtent[4] }; std::stringstream ssReferenceImageExtentOffset; ssReferenceImageExtentOffset << referenceImageExtentOffset[0] << "" "" << referenceImageExtentOffset[1] << "" "" << referenceImageExtentOffset[2]; writer->SetAttribute(GetSegmentationMetaDataKey(KEY_SEGMENTATION_REFERENCE_IMAGE_EXTENT_OFFSET).c_str(), ssReferenceImageExtentOffset.str()); vtkNew rasToIjk; commonGeometryImage->GetWorldToImageMatrix(rasToIjk.GetPointer()); // Compensate for the extent shift in the image origin: vtkNew ijkToFileIjk; ijkToFileIjk->SetElement(0, 3, -referenceImageExtentOffset[0]); ijkToFileIjk->SetElement(1, 3, -referenceImageExtentOffset[1]); ijkToFileIjk->SetElement(2, 3, -referenceImageExtentOffset[2]); vtkNew rasToFileIjk; vtkMatrix4x4::Multiply4x4(ijkToFileIjk.GetPointer(), rasToIjk.GetPointer(), rasToFileIjk.GetPointer()); vtkNew fileIjkToRas; vtkMatrix4x4::Invert(rasToFileIjk.GetPointer(), fileIjkToRas.GetPointer()); writer->SetIJKToRASMatrix(fileIjkToRas.GetPointer()); // Save master representation name writer->SetAttribute(GetSegmentationMetaDataKey(KEY_SEGMENTATION_MASTER_REPRESENTATION).c_str(), segmentationNode->GetSegmentation()->GetMasterRepresentationName()); // Save conversion parameters std::string conversionParameters = segmentation->SerializeAllConversionParameters(); writer->SetAttribute(GetSegmentationMetaDataKey(KEY_SEGMENTATION_CONVERSION_PARAMETERS).c_str(), conversionParameters); // Save created representation names so that they are re-created when loading std::string containedRepresentationNames = this->SerializeContainedRepresentationNames(segmentation); writer->SetAttribute(GetSegmentationMetaDataKey(KEY_SEGMENTATION_CONTAINED_REPRESENTATION_NAMES).c_str(), containedRepresentationNames); vtkNew appender; unsigned int layerIndex = 0; std::map labelmapLayers; // Dimensions of the output 4D NRRD file: (i, j, k, segment) unsigned int segmentIndex = 0; for (std::vector< std::string >::const_iterator segmentIdIt = segmentIDs.begin(); segmentIdIt != segmentIDs.end(); ++segmentIdIt, ++segmentIndex) { std::string currentSegmentID = *segmentIdIt; vtkSegment* currentSegment = segmentation->GetSegment(*segmentIdIt); // Get master representation from segment vtkSmartPointer currentBinaryLabelmap = vtkOrientedImageData::SafeDownCast( currentSegment->GetRepresentation(segmentationNode->GetSegmentation()->GetMasterRepresentationName())); if (!currentBinaryLabelmap) { vtkErrorMacro(""WriteBinaryLabelmapRepresentation: Failed to retrieve master representation from segment "" << currentSegmentID); continue; } int currentBinaryLabelmapExtent[6] = { 0, -1, 0, -1, 0, -1 }; currentBinaryLabelmap->GetExtent(currentBinaryLabelmapExtent); if (currentBinaryLabelmapExtent[0] <= currentBinaryLabelmapExtent[1] && currentBinaryLabelmapExtent[2] <= currentBinaryLabelmapExtent[3] && currentBinaryLabelmapExtent[4] <= currentBinaryLabelmapExtent[5]) { // There is a valid labelmap // Get transformed extents of the segment in the common labelmap geometry vtkNew currentBinaryLabelmapToCommonGeometryImageTransform; vtkOrientedImageDataResample::GetTransformBetweenOrientedImages(currentBinaryLabelmap, commonGeometryImage, currentBinaryLabelmapToCommonGeometryImageTransform.GetPointer()); int currentBinaryLabelmapExtentInCommonGeometryImageFrame[6] = { 0, -1, 0, -1, 0, -1 }; vtkOrientedImageDataResample::TransformExtent(currentBinaryLabelmapExtent, currentBinaryLabelmapToCommonGeometryImageTransform.GetPointer(), currentBinaryLabelmapExtentInCommonGeometryImageFrame); for (int i = 0; i < 3; i++) { currentBinaryLabelmapExtent[i * 2] = std::max(currentBinaryLabelmapExtentInCommonGeometryImageFrame[i * 2], commonGeometryExtent[i * 2]); currentBinaryLabelmapExtent[i * 2 + 1] = std::min(currentBinaryLabelmapExtentInCommonGeometryImageFrame[i * 2 + 1], commonGeometryExtent[i * 2 + 1]); } // TODO: maybe calculate effective extent to make sure the data is as compact as possible? (saving may be a good time to make segments more compact) // Pad/resample current binary labelmap representation to common geometry vtkSmartPointer resampledCurrentBinaryLabelmap = vtkSmartPointer::New(); bool success = vtkOrientedImageDataResample::ResampleOrientedImageToReferenceOrientedImage( currentBinaryLabelmap, commonGeometryImage, resampledCurrentBinaryLabelmap); if (!success) { vtkWarningMacro(""WriteBinaryLabelmapRepresentation: Segment "" << currentSegmentID << "" cannot be resampled to common geometry!""); continue; } // currentBinaryLabelmap smart pointer will keep the temporary labelmap valid until it is needed currentBinaryLabelmap = resampledCurrentBinaryLabelmap; if (currentBinaryLabelmap->GetScalarType() != scalarType) { vtkNew castFilter; castFilter->SetInputData(resampledCurrentBinaryLabelmap); castFilter->SetOutputScalarType(scalarType); castFilter->Update(); currentBinaryLabelmap->ShallowCopy(castFilter->GetOutput()); } } else { // empty segment, use the commonGeometryImage (filled with 0) currentBinaryLabelmap = commonGeometryImage; } // Set metadata for current segment writer->SetAttribute(GetSegmentMetaDataKey(segmentIndex, KEY_SEGMENT_ID).c_str(), currentSegmentID); writer->SetAttribute(GetSegmentMetaDataKey(segmentIndex, KEY_SEGMENT_NAME).c_str(), currentSegment->GetName()); writer->SetAttribute(GetSegmentMetaDataKey(segmentIndex, KEY_SEGMENT_COLOR).c_str(), GetSegmentColorAsString(segmentationNode, currentSegmentID)); writer->SetAttribute(GetSegmentMetaDataKey(segmentIndex, KEY_SEGMENT_NAME_AUTO_GENERATED).c_str(), (currentSegment->GetNameAutoGenerated() ? ""1"" : ""0"") ); writer->SetAttribute(GetSegmentMetaDataKey(segmentIndex, KEY_SEGMENT_COLOR_AUTO_GENERATED).c_str(), (currentSegment->GetColorAutoGenerated() ? ""1"" : ""0"") ); // Save the geometry relative to the current image (so that the extent in the file describe the extent of the segment in the // saved image buffer) for (int i = 0; i < 3; i++) { currentBinaryLabelmapExtent[i * 2] -= referenceImageExtentOffset[i]; currentBinaryLabelmapExtent[i * 2 + 1] -= referenceImageExtentOffset[i]; } writer->SetAttribute(GetSegmentMetaDataKey(segmentIndex, KEY_SEGMENT_EXTENT).c_str(), GetImageExtentAsString(currentBinaryLabelmapExtent)); writer->SetAttribute(GetSegmentMetaDataKey(segmentIndex, KEY_SEGMENT_TAGS).c_str(), GetSegmentTagsAsString(currentSegment)); std::stringstream labelValueSS; labelValueSS << currentSegment->GetLabelValue(); writer->SetAttribute(GetSegmentMetaDataKey(segmentIndex, KEY_SEGMENT_LABEL_VALUE).c_str(), labelValueSS.str()); vtkDataObject* originalRepresentation = currentSegment->GetRepresentation(segmentationNode->GetSegmentation()->GetMasterRepresentationName()); if (labelmapLayers.find(originalRepresentation) == labelmapLayers.end()) { labelmapLayers[originalRepresentation] = layerIndex; appender->AddInputData(currentBinaryLabelmap); ++layerIndex; } unsigned int layer = labelmapLayers[originalRepresentation]; std::stringstream layerIndexSS; layerIndexSS << layer; writer->SetAttribute(GetSegmentMetaDataKey(segmentIndex, KEY_SEGMENT_LAYER).c_str(), layerIndexSS.str()); } // For each segment if (segmentationNode->GetSegmentation()->GetNumberOfSegments() > 0) { appender->Update(); writer->SetInputConnection(appender->GetOutputPort()); writer->SetVectorAxisKind(nrrdKindList); } else { // If there are no segments, we still write the data so that we can store // various metadata fields. writer->SetInputData(commonGeometryImage); } writer->Write(); int writeFlag = 1; if (writer->GetWriteError()) { vtkErrorMacro(""ERROR writing NRRD file "" << (writer->GetFileName() == nullptr ? ""null"" : writer->GetFileName())); writeFlag = 0; } return writeFlag; } //---------------------------------------------------------------------------- int vtkMRMLSegmentationStorageNode::WritePolyDataRepresentation(vtkMRMLSegmentationNode* segmentationNode, std::string path) { if (!segmentationNode || segmentationNode->GetSegmentation()->GetNumberOfSegments() == 0) { vtkErrorMacro(""WritePolyDataRepresentation: Invalid segmentation to write to disk""); return 0; } vtkSegmentation* segmentation = segmentationNode->GetSegmentation(); // Get and check master representation if (!segmentationNode->GetSegmentation()->IsMasterRepresentationPolyData()) { vtkErrorMacro(""WritePolyDataRepresentation: Invalid master representation to write as poly data""); return 0; } // Initialize dataset to write vtkSmartPointer multiBlockDataset = vtkSmartPointer::New(); multiBlockDataset->SetNumberOfBlocks(segmentation->GetNumberOfSegments()); // Add segment polydata objects to dataset std::vector< std::string > segmentIDs; segmentation->GetSegmentIDs(segmentIDs); unsigned int segmentIndex = 0; for (std::vector< std::string >::const_iterator segmentIdIt = segmentIDs.begin(); segmentIdIt != segmentIDs.end(); ++segmentIdIt, ++segmentIndex) { std::string currentSegmentID = *segmentIdIt; vtkSegment* currentSegment = segmentation->GetSegment(*segmentIdIt); // Get master representation from segment vtkPolyData* currentPolyData = vtkPolyData::SafeDownCast(currentSegment->GetRepresentation( segmentationNode->GetSegmentation()->GetMasterRepresentationName())); if (!currentPolyData) { vtkErrorMacro(""WritePolyDataRepresentation: Failed to retrieve master representation from segment "" << currentSegmentID); continue; } // Make temporary duplicate of the poly data so that adding the metadata does not cause invalidating the other // representations (which is done when the master representation is modified) vtkSmartPointer currentPolyDataCopy = vtkSmartPointer::New(); currentPolyDataCopy->ShallowCopy(currentPolyData); // Set metadata for current segment // MasterRepresentation vtkSmartPointer masterRepresentationArray = vtkSmartPointer::New(); masterRepresentationArray->SetNumberOfValues(1); masterRepresentationArray->SetValue(0, segmentationNode->GetSegmentation()->GetMasterRepresentationName()); masterRepresentationArray->SetName(GetSegmentationMetaDataKey(KEY_SEGMENTATION_MASTER_REPRESENTATION).c_str()); currentPolyDataCopy->GetFieldData()->AddArray(masterRepresentationArray); // ID vtkSmartPointer idArray = vtkSmartPointer::New(); idArray->SetNumberOfValues(1); idArray->SetValue(0,currentSegmentID.c_str()); idArray->SetName(GetSegmentMetaDataKey(SINGLE_SEGMENT_INDEX, KEY_SEGMENT_ID).c_str()); currentPolyDataCopy->GetFieldData()->AddArray(idArray); // Name vtkSmartPointer nameArray = vtkSmartPointer::New(); nameArray->SetNumberOfValues(1); nameArray->SetValue(0,currentSegment->GetName()); nameArray->SetName(GetSegmentMetaDataKey(SINGLE_SEGMENT_INDEX, KEY_SEGMENT_NAME).c_str()); currentPolyDataCopy->GetFieldData()->AddArray(nameArray); // Color vtkSmartPointer colorArray = vtkSmartPointer::New(); colorArray->SetNumberOfComponents(3); colorArray->SetNumberOfTuples(1); colorArray->SetTuple(0, currentSegment->GetColor()); colorArray->SetName(GetSegmentMetaDataKey(SINGLE_SEGMENT_INDEX, KEY_SEGMENT_COLOR).c_str()); currentPolyDataCopy->GetFieldData()->AddArray(colorArray); // Tags std::map tags; currentSegment->GetTags(tags); std::stringstream ssTags; std::map::iterator tagIt; for (tagIt=tags.begin(); tagIt!=tags.end(); ++tagIt) { ssTags << tagIt->first << "":"" << tagIt->second << ""|""; } vtkSmartPointer tagsArray = vtkSmartPointer::New(); tagsArray->SetNumberOfValues(1); tagsArray->SetValue(0,ssTags.str().c_str()); tagsArray->SetName(GetSegmentMetaDataKey(SINGLE_SEGMENT_INDEX, KEY_SEGMENT_TAGS).c_str()); currentPolyDataCopy->GetFieldData()->AddArray(tagsArray); // NameAutoGenerated vtkSmartPointer nameAutoGeneratedArray = vtkSmartPointer::New(); nameAutoGeneratedArray->SetNumberOfValues(1); nameAutoGeneratedArray->SetValue(0, (currentSegment->GetNameAutoGenerated() ? ""1"" : ""0"") ); nameAutoGeneratedArray->SetName(GetSegmentMetaDataKey(SINGLE_SEGMENT_INDEX, KEY_SEGMENT_NAME_AUTO_GENERATED).c_str()); currentPolyDataCopy->GetFieldData()->AddArray(nameAutoGeneratedArray); // ColorAutoGenerated vtkSmartPointer colorAutoGeneratedArray = vtkSmartPointer::New(); colorAutoGeneratedArray->SetNumberOfValues(1); colorAutoGeneratedArray->SetValue(0, (currentSegment->GetColorAutoGenerated() ? ""1"" : ""0"") ); colorAutoGeneratedArray->SetName(GetSegmentMetaDataKey(SINGLE_SEGMENT_INDEX, KEY_SEGMENT_COLOR_AUTO_GENERATED).c_str()); currentPolyDataCopy->GetFieldData()->AddArray(colorAutoGeneratedArray); // Save conversion parameters as metadata (save in each segment file) std::string conversionParameters = segmentation->SerializeAllConversionParameters(); vtkSmartPointer conversionParametersArray = vtkSmartPointer::New(); conversionParametersArray->SetNumberOfValues(1); conversionParametersArray->SetValue(0,conversionParameters); conversionParametersArray->SetName(GetSegmentationMetaDataKey(KEY_SEGMENTATION_CONVERSION_PARAMETERS).c_str()); currentPolyDataCopy->GetFieldData()->AddArray(conversionParametersArray); // Save contained representation names as metadata (save in each segment file) std::string containedRepresentationNames = this->SerializeContainedRepresentationNames(segmentation); vtkSmartPointer containedRepresentationNamesArray = vtkSmartPointer::New(); containedRepresentationNamesArray->SetNumberOfValues(1); containedRepresentationNamesArray->SetValue(0,containedRepresentationNames); containedRepresentationNamesArray->SetName(GetSegmentationMetaDataKey(KEY_SEGMENTATION_CONTAINED_REPRESENTATION_NAMES).c_str()); currentPolyDataCopy->GetFieldData()->AddArray(containedRepresentationNamesArray); // Set segment poly data to dataset multiBlockDataset->SetBlock(segmentIndex, currentPolyDataCopy); } // Write multiblock dataset to disk vtkSmartPointer writer = vtkSmartPointer::New(); writer->SetInputData(multiBlockDataset); writer->SetFileName(path.c_str()); if (this->UseCompression) { writer->SetDataModeToBinary(); writer->SetCompressorTypeToZLib(); } else { writer->SetDataModeToAscii(); writer->SetCompressorTypeToNone(); } writer->Write(); // Add all files to storage node (multiblock dataset writes segments to individual files in a separate folder) this->AddPolyDataFileNames(path, segmentation); return 1; } //---------------------------------------------------------------------------- void vtkMRMLSegmentationStorageNode::AddPolyDataFileNames(std::string path, vtkSegmentation* segmentation) { if (!segmentation) { vtkErrorMacro(""AddPolyDataFileNames: Invalid segmentation!""); return; } this->AddFileName(path.c_str()); std::string fileNameWithoutExtension = vtksys::SystemTools::GetFilenameWithoutLastExtension(path); std::string parentDirectory = vtksys::SystemTools::GetParentDirectory(path); std::string multiBlockDirectory = parentDirectory + ""/"" + fileNameWithoutExtension; for (int segmentIndex = 0; segmentIndex < segmentation->GetNumberOfSegments(); ++segmentIndex) { std::stringstream ssSegmentFilePath; ssSegmentFilePath << multiBlockDirectory << ""/"" << fileNameWithoutExtension << ""_"" << segmentIndex << "".vtp""; std::string segmentFilePath = ssSegmentFilePath.str(); this->AddFileName(segmentFilePath.c_str()); } } //---------------------------------------------------------------------------- std::string vtkMRMLSegmentationStorageNode::SerializeContainedRepresentationNames(vtkSegmentation* segmentation) { if (!segmentation) { vtkErrorMacro(""SerializeContainedRepresentationNames: Invalid segmentation!""); return """"; } std::stringstream ssRepresentationNames; std::vector containedRepresentationNames; segmentation->GetContainedRepresentationNames(containedRepresentationNames); for (std::vector::iterator reprIt = containedRepresentationNames.begin(); reprIt != containedRepresentationNames.end(); ++reprIt) { ssRepresentationNames << (*reprIt) << SERIALIZATION_SEPARATOR; } return ssRepresentationNames.str(); } //---------------------------------------------------------------------------- void vtkMRMLSegmentationStorageNode::CreateRepresentationsBySerializedNames(vtkSegmentation* segmentation, std::string representationNames) { if (!segmentation) { vtkErrorMacro(""CreateRepresentationsBySerializedNames: Invalid segmentation!""); return; } if (segmentation->GetNumberOfSegments() == 0) { vtkDebugMacro(""CreateRepresentationsBySerializedNames: Segmentation is empty, nothing to do""); return; } if (representationNames.empty()) { vtkDebugMacro(""CreateRepresentationsBySerializedNames: Empty representation names list, nothing to create""); return; } std::string masterRepresentation(segmentation->GetMasterRepresentationName()); size_t separatorPosition = representationNames.find(SERIALIZATION_SEPARATOR); while (separatorPosition != std::string::npos) { std::string representationName = representationNames.substr(0, separatorPosition); // Only create non-master representations if (representationName.compare(masterRepresentation)) { segmentation->CreateRepresentation(representationName); } representationNames = representationNames.substr(separatorPosition+1); separatorPosition = representationNames.find(SERIALIZATION_SEPARATOR); } } //---------------------------------------------------------------------------- bool vtkMRMLSegmentationStorageNode::GetSegmentMetaDataFromDicitionary(std::string& headerValue, itk::MetaDataDictionary dictionary, int segmentIndex, std::string keyName) { if (!dictionary.HasKey(GetSegmentMetaDataKey(segmentIndex, keyName))) { return false; } itk::ExposeMetaData(dictionary, GetSegmentMetaDataKey(segmentIndex, keyName), headerValue); return true; } //---------------------------------------------------------------------------- bool vtkMRMLSegmentationStorageNode::GetSegmentationMetaDataFromDicitionary(std::string& headerValue, itk::MetaDataDictionary dictionary, std::string keyName) { if (!dictionary.HasKey(GetSegmentationMetaDataKey(keyName))) { return false; } itk::ExposeMetaData(dictionary, GetSegmentationMetaDataKey(keyName), headerValue); return true; } //---------------------------------------------------------------------------- std::string vtkMRMLSegmentationStorageNode::GetSegmentMetaDataKey(int segmentIndex, const std::string& keyName) { std::stringstream key; key << ""Segment""; if (segmentIndex != SINGLE_SEGMENT_INDEX) { key << segmentIndex; } key << ""_"" << keyName; return key.str(); } //---------------------------------------------------------------------------- std::string vtkMRMLSegmentationStorageNode::GetSegmentationMetaDataKey(const std::string& keyName) { std::stringstream key; key << ""Segmentation"" << ""_"" << keyName; return key.str(); } //---------------------------------------------------------------------------- std::string vtkMRMLSegmentationStorageNode::GetSegmentTagsAsString(vtkSegment* segment) { std::map tags; if (segment) { segment->GetTags(tags); } std::stringstream ssTagsValue; std::map::iterator tagIt; for (tagIt = tags.begin(); tagIt != tags.end(); ++tagIt) { ssTagsValue << tagIt->first << "":"" << tagIt->second << ""|""; } std::string tagsValue = ssTagsValue.str(); return tagsValue; } //---------------------------------------------------------------------------- void vtkMRMLSegmentationStorageNode::SetSegmentTagsFromString(vtkSegment* segment, std::string tagsValue) { std::string separatorCharacter(""|""); size_t separatorPosition = tagsValue.find(separatorCharacter); while (separatorPosition != std::string::npos) { std::string mapPairStr = tagsValue.substr(0, separatorPosition); size_t colonPosition = mapPairStr.find("":""); if (colonPosition == std::string::npos) { tagsValue = tagsValue.substr(separatorPosition + 1); separatorPosition = tagsValue.find(separatorCharacter); continue; } segment->SetTag(mapPairStr.substr(0, colonPosition), mapPairStr.substr(colonPosition + 1)); tagsValue = tagsValue.substr(separatorPosition + 1); separatorPosition = tagsValue.find(separatorCharacter); } } //---------------------------------------------------------------------------- std::string vtkMRMLSegmentationStorageNode::GetImageExtentAsString(vtkOrientedImageData* image) { int extent[6] = { 0, -1, 0, -1, 0, -1 }; if (image) { image->GetExtent(extent); } return GetImageExtentAsString(extent); } //---------------------------------------------------------------------------- std::string vtkMRMLSegmentationStorageNode::GetImageExtentAsString(int extent[6]) { std::stringstream ssExtentValue; ssExtentValue << extent[0] << "" "" << extent[1] << "" "" << extent[2] << "" "" << extent[3] << "" "" << extent[4] << "" "" << extent[5]; std::string extentValue = ssExtentValue.str(); return extentValue; } //---------------------------------------------------------------------------- void vtkMRMLSegmentationStorageNode::GetImageExtentFromString(int extent[6], std::string extentValue) { std::stringstream ssExtentValue(extentValue); extent[0] = 0; extent[1] = -1; extent[2] = 0; extent[3] = -1; extent[4] = 0; extent[5] = -1; ssExtentValue >> extent[0] >> extent[1] >> extent[2] >> extent[3] >> extent[4] >> extent[5]; } //---------------------------------------------------------------------------- std::string vtkMRMLSegmentationStorageNode::GetSegmentColorAsString(vtkMRMLSegmentationNode* segmentationNode, const std::string& segmentId) { double color[3] = { vtkSegment::SEGMENT_COLOR_INVALID[0], vtkSegment::SEGMENT_COLOR_INVALID[1], vtkSegment::SEGMENT_COLOR_INVALID[2] }; vtkSegment* segment = segmentationNode->GetSegmentation()->GetSegment(segmentId); if (segment) { segment->GetColor(color); } std::stringstream colorStream; colorStream << color[0] << "" "" << color[1] << "" "" << color[2]; return colorStream.str(); } //---------------------------------------------------------------------------- void vtkMRMLSegmentationStorageNode::GetSegmentColorFromString(double color[3], std::string colorString) { std::stringstream colorStream(colorString); color[0] = 0.5; color[1] = 0.5; color[2] = 0.5; colorStream >> color[0] >> color[1] >> color[2]; } ",16279,True,3235.3367719398657,median "pred test80 { some disj BinaryTree0: BinaryTree {some disj Node0: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node0 Node = Node0 left = Node0->Node0 no right elem = Node0->1 }} } run test80 for 4 expect 0 pred test78 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 left = Node1->Node0 no right elem = Node0->7 + Node1->6 Depth[Node1] = 1 }} } run test78 for 4 expect 1 pred test31 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 left = Node1->Node0 no right elem = Node0->6 + Node1->-8 Sorted[] }} } run test31 for 4 expect 0 pred test26 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 left = Node1->Node0 no right elem = Node0->4 + Node1->5 Sorted[] }} } run test26 for 4 expect 1 pred test95 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node0->Node1 right = Node2->Node0 elem = Node0->7 + Node1->6 + Node2->3 }} } run test95 for 4 expect 1 pred test105 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node2->Node0 right = Node0->Node1 + Node2->Node0 elem = Node0->7 + Node1->6 + Node2->5 }} } run test105 for 4 expect 0 pred test94 { some disj BinaryTree0: BinaryTree {some disj Node0: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node0 Node = Node0 no left no right elem = Node0->-4 }} } run test94 for 4 expect 1 pred test44 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 no left right = Node1->Node0 elem = Node0->1 + Node1->1 Sorted[] }} } run test44 for 4 expect 0 pred test29 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2, Node3: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node3 Node = Node0 + Node1 + Node2 + Node3 left = Node0->Node2 + Node1->Node0 right = Node3->Node1 elem = Node0->7 + Node1->6 + Node2->4 + Node3->3 Sorted[] }} } run test29 for 4 expect 0 pred test9 { some disj BinaryTree0: BinaryTree {some disj Node0: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node0 Node = Node0 no left no right no elem }} } run test9 for 4 expect 0 pred test7 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node0->Node1 + Node2->Node0 no right elem = Node0->7 + Node1->3 + Node2->2 }} } run test7 for 4 expect 1 pred test60 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node1->Node0 right = Node2->Node1 elem = Node0->7 + Node1->2 + Node2->1 Balanced[] }} } run test60 for 4 expect 0 pred test91 { some disj BinaryTree0: BinaryTree {some disj Node0: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node0 Node = Node0 no left right = Node0->Node0 elem = Node0->-8 }} } run test91 for 4 expect 0 pred test15 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 no left right = Node0->Node1 + Node2->Node0 elem = Node0->4 + Node1->2 + Node2->1 Sorted[] }} } run test15 for 4 expect 0 pred test81 { some disj BinaryTree0: BinaryTree {some disj Node0: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node0 Node = Node0 no left right = Node0->Node0 elem = Node0->-1 }} } run test81 for 4 expect 0 pred test58 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2, Node3: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node3 Node = Node0 + Node1 + Node2 + Node3 left = Node2->Node1 + Node3->Node2 right = Node3->Node0 elem = Node0->7 + Node1->6 + Node2->-7 + Node3->-8 Balanced[] }} } run test58 for 4 expect 1 pred test65 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2, Node3: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node3 Node = Node0 + Node1 + Node2 + Node3 left = Node2->Node1 + Node3->Node2 right = Node3->Node0 elem = Node0->7 + Node1->-6 + Node2->-7 + Node3->-8 Balanced[] }} } run test65 for 4 expect 1 pred test3 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node0 + BinaryTree0->Node1 Node = Node0 + Node1 left = Node0->Node1 no right elem = Node0->7 + Node1->6 }} } run test3 for 4 expect 0 pred test4 { some disj BinaryTree0: BinaryTree { BinaryTree = BinaryTree0 no root no Node no left no right no elem } } run test4 for 4 expect 1 pred test34 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 no left right = Node1->Node0 elem = Node0->-7 + Node1->-8 Sorted[] }} } run test34 for 4 expect 1 pred test77 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node0 Node = Node0 + Node1 no left right = Node0->Node1 elem = Node0->7 + Node1->6 Depth[Node1] = 2 }} } run test77 for 4 expect 1 pred test54 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 left = Node1->Node0 no right elem = Node0->-6 + Node1->-5 HasAtMostOneChild[Node1] }} } run test54 for 4 expect 1 pred test48 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 no left right = Node1->Node0 elem = Node0->-7 + Node1->-8 HasAtMostOneChild[Node1] }} } run test48 for 4 expect 1 pred test66 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2, Node3: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node3 Node = Node0 + Node1 + Node2 + Node3 left = Node2->Node1 + Node3->Node2 right = Node3->Node0 elem = Node0->5 + Node1->3 + Node2->-7 + Node3->-8 Balanced[] }} } run test66 for 4 expect 1 pred test57 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node0->Node1 + Node2->Node0 no right elem = Node0->7 + Node1->1 + Node2->-6 Balanced[] }} } run test57 for 4 expect 0 pred test6 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 no left right = Node2->Node0 + Node2->Node1 elem = Node0->7 + Node1->6 + Node2->-8 }} } run test6 for 4 expect 0 pred test51 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 + Node2 left = Node1->Node2 right = Node2->Node0 elem = Node0->7 + Node1->-8 + Node2->3 HasAtMostOneChild[Node2] }} } run test51 for 4 expect 1 pred test55 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 + Node2 left = Node2->Node0 right = Node1->Node2 elem = Node0->2 + Node1->-8 + Node2->7 HasAtMostOneChild[Node2] }} } run test55 for 4 expect 1 pred test86 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node2->Node0 right = Node0->Node1 + Node2->Node0 elem = Node0->-6 + Node1->-7 + Node2->-8 }} } run test86 for 4 expect 0 pred test76 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 no left right = Node1->Node0 elem = Node0->-5 + Node1->6 Depth[Node1] = 1 }} } run test76 for 4 expect 1 pred test18 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 left = Node1->Node0 no right elem = Node0->4 + Node1->0 Sorted[] }} } run test18 for 4 expect 0 pred test107 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 left = Node1->Node0 no right elem = Node0->7 + Node1->1 }} } run test107 for 4 expect 1 pred test11 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 left = Node1->Node0 no right elem = Node0->4 + Node1->4 Sorted[] }} } run test11 for 4 expect 0 pred test30 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 left = Node1->Node0 no right elem = Node0->2 + Node1->2 Sorted[] }} } run test30 for 4 expect 0 pred test5 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 no left right = Node1->Node0 elem = Node0->7 + Node1->6 }} } run test5 for 4 expect 1 pred test97 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node2->Node0 right = Node2->Node1 elem = Node0->7 + Node1->6 + Node2->2 }} } run test97 for 4 expect 1 pred test36 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 no left right = Node1->Node0 elem = Node0->0 + Node1->-4 Sorted[] }} } run test36 for 4 expect 1 pred test72 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node2->Node1 right = Node2->Node0 elem = Node0->3 + Node1->3 + Node2->2 RepOk[] }} } run test72 for 4 expect 0 pred test2 { some disj BinaryTree0, BinaryTree1: BinaryTree {some disj Node0, Node1, Node2, Node3: Node { BinaryTree = BinaryTree0 + BinaryTree1 root = BinaryTree1->Node3 Node = Node0 + Node1 + Node2 + Node3 left = Node1->Node0 + Node3->Node1 right = Node3->Node2 elem = Node0->6 + Node1->5 + Node2->1 + Node3->-8 }} } run test2 for 4 expect 0 pred test20 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 left = Node1->Node0 no right elem = Node0->-7 + Node1->-4 Sorted[] }} } run test20 for 4 expect 1 pred test53 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node2->Node0 right = Node2->Node1 elem = Node0->2 + Node1->-4 + Node2->-3 HasAtMostOneChild[Node2] }} } run test53 for 4 expect 0 pred test13 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 left = Node1->Node0 no right elem = Node0->3 + Node1->0 Sorted[] }} } run test13 for 4 expect 0 pred test103 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 left = Node1->Node0 no right elem = Node0->7 + Node1->0 }} } run test103 for 4 expect 1 pred test52 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 no left right = Node0->Node1 + Node2->Node0 elem = Node0->7 + Node1->7 + Node2->6 HasAtMostOneChild[Node2] }} } run test52 for 4 expect 1 pred test21 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 left = Node1->Node0 no right elem = Node0->3 + Node1->2 Sorted[] }} } run test21 for 4 expect 0 pred test108 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 left = Node1->Node0 no right elem = Node0->7 + Node1->4 }} } run test108 for 4 expect 1 pred test27 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2, Node3: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node3 Node = Node0 + Node1 + Node2 + Node3 left = Node3->Node2 right = Node1->Node0 + Node2->Node1 elem = Node0->3 + Node1->-1 + Node2->-5 + Node3->2 Sorted[] }} } run test27 for 4 expect 0 pred test82 { some disj BinaryTree0: BinaryTree {some disj Node0: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node0 Node = Node0 no left right = Node0->Node0 elem = Node0->-2 }} } run test82 for 4 expect 0 pred test98 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node2->Node1 right = Node1->Node0 + Node2->Node0 elem = Node0->7 + Node1->7 + Node2->4 }} } run test98 for 4 expect 0 pred test14 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node0->Node1 right = Node2->Node0 elem = Node0->7 + Node1->0 + Node2->-5 Sorted[] }} } run test14 for 4 expect 1 pred test39 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 no left right = Node1->Node0 elem = Node0->-3 + Node1->-2 Sorted[] }} } run test39 for 4 expect 0 pred test68 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2, Node3: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node3 Node = Node0 + Node1 + Node2 + Node3 left = Node2->Node1 + Node3->Node2 right = Node3->Node0 elem = Node0->6 + Node1->3 + Node2->-7 + Node3->-8 Balanced[] }} } run test68 for 4 expect 1 pred test42 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 no left right = Node1->Node0 elem = Node0->7 + Node1->6 Sorted[] }} } run test42 for 4 expect 1 pred test63 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2, Node3: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node3 Node = Node0 + Node1 + Node2 + Node3 left = Node2->Node1 + Node3->Node2 right = Node3->Node0 elem = Node0->7 + Node1->7 + Node2->3 + Node3->-6 Balanced[] }} } run test63 for 4 expect 1 pred test71 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 left = Node1->Node0 no right elem = Node0->7 + Node1->-4 RepOk[] }} } run test71 for 4 expect 0 pred test70 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2, Node3: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node3 Node = Node0 + Node1 + Node2 + Node3 left = Node2->Node1 + Node3->Node2 right = Node3->Node0 elem = Node0->7 + Node1->7 + Node2->-5 + Node3->-8 Balanced[] }} } run test70 for 4 expect 1 pred test96 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 left = Node1->Node0 no right elem = Node0->7 + Node1->5 }} } run test96 for 4 expect 1 pred test61 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2, Node3: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node3 Node = Node0 + Node1 + Node2 + Node3 left = Node2->Node1 + Node3->Node2 right = Node3->Node0 elem = Node0->7 + Node1->-2 + Node2->-4 + Node3->-5 Balanced[] }} } run test61 for 4 expect 1 pred test35 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 no left right = Node1->Node0 elem = Node0->0 + Node1->2 Sorted[] }} } run test35 for 4 expect 0 pred test83 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 left = Node1->Node1 right = Node1->Node0 elem = Node0->-5 + Node1->-6 }} } run test83 for 4 expect 0 pred test62 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2, Node3: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node3 Node = Node0 + Node1 + Node2 + Node3 left = Node2->Node1 + Node3->Node2 right = Node3->Node0 elem = Node0->4 + Node1->4 + Node2->4 + Node3->0 Balanced[] }} } run test62 for 4 expect 1 pred test25 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node2->Node1 right = Node1->Node0 elem = Node0->-3 + Node1->-7 + Node2->-3 Sorted[] }} } run test25 for 4 expect 0 pred test106 { some disj BinaryTree0: BinaryTree {some disj Node0: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node0 Node = Node0 no left no right elem = Node0->-5 }} } run test106 for 4 expect 1 pred test38 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 no left right = Node1->Node0 elem = Node0->-2 + Node1->-3 Sorted[] }} } run test38 for 4 expect 1 pred test17 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 no left right = Node1->Node0 elem = Node0->-3 + Node1->-1 Sorted[] }} } run test17 for 4 expect 0 pred test90 { some disj BinaryTree0: BinaryTree {some disj Node0: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node0 Node = Node0 no left right = Node0->Node0 elem = Node0->-6 }} } run test90 for 4 expect 0 pred test69 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2, Node3: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node3 Node = Node0 + Node1 + Node2 + Node3 left = Node2->Node1 + Node3->Node2 right = Node3->Node0 elem = Node0->7 + Node1->7 + Node2->6 + Node3->-1 Balanced[] }} } run test69 for 4 expect 1 pred test88 { some disj BinaryTree0: BinaryTree {some disj Node0: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node0 Node = Node0 no left no right elem = Node0->-1 }} } run test88 for 4 expect 1 pred test100 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node2->Node0 right = Node1->Node0 + Node2->Node1 elem = Node0->7 + Node1->6 + Node2->5 }} } run test100 for 4 expect 0 pred test109 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node0->Node1 right = Node0->Node1 + Node2->Node0 elem = Node0->7 + Node1->6 + Node2->3 }} } run test109 for 4 expect 0 pred test22 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 left = Node1->Node0 no right elem = Node0->1 + Node1->4 Sorted[] }} } run test22 for 4 expect 1 pred test47 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 no left right = Node1->Node0 elem = Node0->-8 + Node1->5 HasAtMostOneChild[Node1] }} } run test47 for 4 expect 1 pred test73 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2, Node3: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node3 Node = Node0 + Node1 + Node2 + Node3 left = Node2->Node1 + Node3->Node2 right = Node3->Node0 elem = Node0->7 + Node1->5 + Node2->5 + Node3->4 RepOk[] }} } run test73 for 4 expect 0 pred test64 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2, Node3: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node3 Node = Node0 + Node1 + Node2 + Node3 left = Node2->Node1 + Node3->Node2 right = Node3->Node0 elem = Node0->7 + Node1->0 + Node2->-2 + Node3->-5 Balanced[] }} } run test64 for 4 expect 1 pred test84 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 left = Node1->Node1 right = Node1->Node0 elem = Node0->-4 + Node1->-5 }} } run test84 for 4 expect 0 pred test41 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node0->Node1 right = Node2->Node0 elem = Node0->-5 + Node1->-8 + Node2->-8 Sorted[] }} } run test41 for 4 expect 0 pred test43 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2, Node3: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node3 Node = Node0 + Node1 + Node2 + Node3 no left right = Node1->Node2 + Node2->Node0 + Node3->Node1 elem = Node0->7 + Node1->3 + Node2->2 + Node3->-2 Sorted[] }} } run test43 for 4 expect 0 pred test40 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2, Node3: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node3 Node = Node0 + Node1 + Node2 + Node3 left = Node0->Node2 right = Node2->Node1 + Node3->Node0 elem = Node0->7 + Node1->4 + Node2->3 + Node3->5 Sorted[] }} } run test40 for 4 expect 0 pred test37 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2, Node3: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node3 Node = Node0 + Node1 + Node2 + Node3 no left right = Node0->Node1 + Node2->Node0 + Node3->Node2 elem = Node0->6 + Node1->6 + Node2->4 + Node3->-4 Sorted[] }} } run test37 for 4 expect 0 pred test16 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 left = Node1->Node0 no right elem = Node0->5 + Node1->0 Sorted[] }} } run test16 for 4 expect 0 pred test85 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node0->Node1 + Node2->Node0 right = Node2->Node1 elem = Node0->7 + Node1->6 + Node2->5 }} } run test85 for 4 expect 0 pred test92 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node0->Node2 right = Node0->Node1 + Node2->Node0 elem = Node0->7 + Node1->4 + Node2->0 }} } run test92 for 4 expect 0 pred test50 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node2->Node0 right = Node2->Node1 elem = Node0->1 + Node1->-7 + Node2->-6 HasAtMostOneChild[Node2] }} } run test50 for 4 expect 0 pred test75 { some disj BinaryTree0: BinaryTree {some disj Node0: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node0 Node = Node0 no left no right elem = Node0->7 Depth[Node0] = 1 }} } run test75 for 4 expect 1 pred test79 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 no left right = Node0->Node1 + Node2->Node0 elem = Node0->7 + Node1->7 + Node2->6 Depth[Node2] = 1 }} } run test79 for 4 expect 1 pred test102 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1, Node2: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node2 Node = Node0 + Node1 + Node2 left = Node1->Node0 + Node2->Node1 no right elem = Node0->5 + Node1->5 + Node2->-1 }} } run test102 for 4 expect 1 pred test45 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 no left right = Node1->Node0 elem = Node0->5 + Node1->5 Sorted[] }} } run test45 for 4 expect 0 pred test19 { some disj BinaryTree0: BinaryTree {some disj Node0, Node1: Node { BinaryTree = BinaryTree0 root = BinaryTree0->Node1 Node = Node0 + Node1 left = Node1->Node0 no right elem = Node0->1 + Node1->-3 Sorted[] }} } run test19 for 4 expect 0 ",8371,True,3212.4958421210094,median "CLASS zcl_uitb_alv_grid_adapter DEFINITION PUBLIC FINAL CREATE PUBLIC GLOBAL FRIENDS zif_uitb_alv_controller. PUBLIC SECTION. INTERFACES zif_uitb_alv_adpt_selections. METHODS constructor IMPORTING io_controller TYPE REF TO zcl_uitb_alv_controller. METHODS get_metadata. METHODS close. METHODS set_function IMPORTING iv_function TYPE ui_func. METHODS set_metadata IMPORTING is_stable TYPE lvc_s_stbl OPTIONAL if_keep_scroll_position TYPE abap_bool OPTIONAL ir_changelist TYPE REF TO zcl_uitb_alv_changelist OPTIONAL RAISING zcx_uitb_alv_error. METHODS get_grid RETURNING VALUE(result) TYPE REF TO cl_gui_alv_grid. METHODS is_function_call_active RETURNING VALUE(result) TYPE abap_bool. METHODS set_function_call_active IMPORTING value TYPE abap_bool DEFAULT abap_true. METHODS set_focus_to_grid. PROTECTED SECTION. PRIVATE SECTION. TYPES: BEGIN OF ty_s_context_function, function TYPE ui_func, text TYPE string, END OF ty_s_context_function. TYPES: ty_t_context_function TYPE STANDARD TABLE OF ty_s_context_function WITH KEY function. TYPES: BEGIN OF ty_s_internal_ctx_func, functions TYPE ty_t_context_function, insert_before TYPE ui_func, insert_after TYPE ui_func, END OF ty_s_internal_ctx_func. TYPES: ty_t_internal_ctx_func TYPE STANDARD TABLE OF ty_s_internal_ctx_func WITH KEY insert_before insert_after. DATA mo_grid TYPE REF TO cl_gui_alv_grid. DATA mo_current_changelist TYPE REF TO zcl_uitb_alv_changelist. DATA mo_dialog TYPE REF TO if_alv_dialog. DATA ms_stable TYPE lvc_s_stbl. DATA mf_keep_scroll_position TYPE abap_bool. DATA mo_controller TYPE REF TO zcl_uitb_alv_controller. DATA mf_function_call_active TYPE abap_bool. DATA mo_quickfilter_menu TYPE REF TO cl_ctmenu. METHODS get_function_tag IMPORTING iv_user_function TYPE ui_func RETURNING VALUE(result) TYPE string. METHODS on_user_command FOR EVENT user_command OF cl_gui_alv_grid IMPORTING !e_ucomm . METHODS on_before_user_command FOR EVENT before_user_command OF cl_gui_alv_grid IMPORTING !e_ucomm . METHODS on_after_user_command FOR EVENT after_user_command OF cl_gui_alv_grid IMPORTING !e_not_processed !e_saved !e_ucomm . METHODS on_toolbar FOR EVENT toolbar OF cl_gui_alv_grid IMPORTING !e_interactive !e_object . METHODS on_hotspot_click FOR EVENT hotspot_click OF cl_gui_alv_grid IMPORTING es_row_no e_column_id e_row_id. METHODS on_button_click FOR EVENT button_click OF cl_gui_alv_grid IMPORTING es_col_id es_row_no. METHODS on_double_click FOR EVENT double_click OF cl_gui_alv_grid IMPORTING es_row_no e_column e_row. METHODS on_context_menu FOR EVENT context_menu_request OF cl_gui_alv_grid IMPORTING e_object. METHODS on_menu_button FOR EVENT menu_button OF cl_gui_alv_grid IMPORTING e_object e_ucomm. METHODS on_f4 FOR EVENT onf4 OF cl_gui_alv_grid IMPORTING e_fieldname e_fieldvalue es_row_no er_event_data et_bad_cells e_display. METHODS on_data_changed FOR EVENT data_changed OF cl_gui_alv_grid IMPORTING er_data_changed e_onf4 e_onf4_before e_onf4_after e_ucomm. ""!

Deserialize menu from table

METHODS fill_menu_from_serialized IMPORTING it_menu_serialize TYPE sctx_serialize it_additional_functions TYPE ty_t_internal_ctx_func io_menu TYPE REF TO cl_ctmenu. METHODS set_event_handlers. METHODS on_drag FOR EVENT ondrag OF cl_gui_alv_grid IMPORTING es_row_no e_column e_dragdropobj e_row. METHODS on_drop FOR EVENT ondrop OF cl_gui_alv_grid IMPORTING es_row_no e_column e_dragdropobj e_row. METHODS on_drop_complete FOR EVENT ondropcomplete OF cl_gui_alv_grid IMPORTING es_row_no e_column e_dragdropobj e_row. METHODS on_drop_get_flavor FOR EVENT ondropgetflavor OF cl_gui_alv_grid IMPORTING es_row_no e_column e_dragdropobj e_flavors e_row. ENDCLASS. CLASS zcl_uitb_alv_grid_adapter IMPLEMENTATION. METHOD constructor. mo_controller = io_controller. mo_quickfilter_menu = NEW cl_ctmenu( ). mo_quickfilter_menu->add_function( fcode = zif_uitb_c_alv_functions=>quickfilter_exclude text = 'Exclude value' ). *...... initialize dialog for alv display IF mo_controller->mo_model->mv_display_type = zif_uitb_c_alv_display_types=>dialog. mo_dialog = NEW cl_dialog( iv_title = mo_controller->mo_model->get_display_settings( )->get_title( ) io_grid_adapter = me ). ELSEIF mo_controller->mo_model->mv_display_type = zif_uitb_c_alv_display_types=>modal_dialog. mo_dialog = NEW cl_modal_dialog( iv_title = mo_controller->mo_model->get_display_settings( )->get_title( ) io_grid_adapter = me ). ENDIF. ENDMETHOD. METHOD get_function_tag. DATA(lo_functions) = mo_controller->mo_model->get_functions( ). result = VALUE #( lo_functions->mt_function_tag_map[ function = iv_user_function ]-tag OPTIONAL ). ENDMETHOD. METHOD get_grid. result = mo_grid. ENDMETHOD. METHOD get_metadata. CHECK mo_grid IS BOUND. DATA(lo_model) = mo_controller->mo_model. DATA(lo_columns) = lo_model->get_columns( ). DATA(lo_functional_settings) = lo_model->get_functional_settings( ). DATA(lo_display_settings) = lo_model->get_display_settings( ). DATA(lo_selections) = lo_model->get_selections( ). DATA(lo_filters) = lo_model->get_filters( ). DATA(lo_sorting) = lo_model->get_sorting( ). DATA(lo_layout) = lo_model->get_layout( ). mo_grid->get_frontend_fieldcatalog( IMPORTING et_fieldcatalog = DATA(lt_fcat) ). mo_grid->get_frontend_layout( IMPORTING es_layout = DATA(ls_layout) ). mo_grid->get_filter_criteria( IMPORTING et_filter = DATA(lt_filter) ). mo_grid->get_sort_criteria( IMPORTING et_sort = DATA(lt_sort) ). mo_grid->get_variant( IMPORTING es_variant = DATA(ls_variant) ). lo_selections->invalidate_selections( ). zcl_uitb_alv_metadata_util=>get_alv_layout( is_layout = ls_layout io_selections = lo_selections io_display_settings = lo_display_settings io_columns = lo_columns ). zcl_uitb_alv_metadata_util=>get_fieldcatalog( it_fieldcat = lt_fcat io_columns = lo_columns ). zcl_uitb_alv_metadata_util=>get_filters( io_filters = lo_filters it_filter = lt_filter ). zcl_uitb_alv_metadata_util=>get_sorting( io_sorts = lo_sorting it_sorts = lt_sort ). zcl_uitb_alv_metadata_util=>set_variant( is_variant = ls_variant io_layout = lo_layout ). ENDMETHOD. METHOD is_function_call_active. result = mf_function_call_active. ENDMETHOD. METHOD on_after_user_command. set_function_call_active( ). zcl_uitb_alv_evt_controller=>raise_after_function( io_controller = mo_controller iv_function = e_ucomm ). set_function_call_active( abap_false ). ENDMETHOD. METHOD on_before_user_command. set_function_call_active( ). zcl_uitb_alv_evt_controller=>raise_before_function( io_controller = mo_controller iv_function = e_ucomm ). set_function_call_active( abap_false ). ENDMETHOD. METHOD on_button_click. set_function_call_active( ). zcl_uitb_alv_evt_controller=>raise_link_click( io_controller = mo_controller iv_column = es_col_id-fieldname iv_row = es_row_no-row_id ). set_function_call_active( abap_false ). ENDMETHOD. METHOD on_context_menu. DATA: lt_serialized_menu TYPE sctx_serialize. DATA(lo_model) = mo_controller->mo_model. DATA(lo_functions) = lo_model->get_functions( ). IF lo_functions IS BOUND. DATA(lt_disabled) = lo_functions->get_disabled( ). e_object->hide_functions( lt_disabled ). IF lo_functions->mf_quickfilter = abap_true. *...... Recreate menu and add quick filter actions e_object->get_functions( IMPORTING fcodes = DATA(lt_fcodes) ). e_object->if_ctxmnu_internal~serialize_menu( CHANGING menu = lt_serialized_menu ). e_object->clear( ). fill_menu_from_serialized( it_menu_serialize = lt_serialized_menu it_additional_functions = VALUE #( ( insert_after = zif_uitb_c_alv_functions=>filter functions = VALUE #( ( function = zif_uitb_c_alv_functions=>quickfilter text = |{ 'Quickfilter' }| ) ( function = zif_uitb_c_alv_functions=>quickfilter_exclude text = |{ 'Quickfilter (Exclude value)' }| ) ) ) ) io_menu = e_object ). ENDIF. ENDIF. set_function_call_active( ). zcl_uitb_alv_evt_controller=>raise_context_menu( io_controller = mo_controller io_menu = e_object ). set_function_call_active( abap_false ). ENDMETHOD. METHOD on_data_changed. set_function_call_active( ). zcl_uitb_alv_evt_controller=>raise_data_changed( io_controller = mo_controller io_change_protocol = er_data_changed iv_function = e_ucomm if_onf4 = e_onf4 if_onf4_before = e_onf4_before if_onf4_after = e_onf4_after ). set_function_call_active( abap_false ). ENDMETHOD. METHOD on_double_click. set_function_call_active( abap_true ). zcl_uitb_alv_evt_controller=>raise_double_click( io_controller = mo_controller iv_column = e_column-fieldname iv_row = es_row_no-row_id ). set_function_call_active( abap_false ). ENDMETHOD. METHOD on_drag. zcl_uitb_alv_evt_controller=>raise_drag( io_controller = mo_controller iv_row = es_row_no-row_id iv_column = e_column-fieldname is_row_no = es_row_no io_dragdropobj = e_dragdropobj ). ENDMETHOD. METHOD on_drop. zcl_uitb_alv_evt_controller=>raise_drop( io_controller = mo_controller iv_row = es_row_no-row_id iv_column = e_column-fieldname is_row_no = es_row_no io_dragdropobj = e_dragdropobj ). ENDMETHOD. METHOD on_drop_complete. zcl_uitb_alv_evt_controller=>raise_drop_complete( io_controller = mo_controller iv_row = es_row_no-row_id iv_column = e_column-fieldname is_row_no = es_row_no io_dragdropobj = e_dragdropobj ). ENDMETHOD. METHOD on_drop_get_flavor. zcl_uitb_alv_evt_controller=>raise_drop_get_flavor( io_controller = mo_controller iv_row = es_row_no-row_id iv_column = e_column-fieldname is_row_no = es_row_no io_dragdropobj = e_dragdropobj it_flavors = e_flavors ). ENDMETHOD. METHOD on_f4. set_function_call_active( ). zcl_uitb_alv_evt_controller=>raise_f4( io_controller = mo_controller iv_fieldname = e_fieldname iv_fieldvalue = e_fieldvalue is_row_no = es_row_no io_event_data = er_event_data it_bad_cells = et_bad_cells if_display = e_display ). set_function_call_active( abap_false ). ENDMETHOD. METHOD on_hotspot_click. set_function_call_active( ). zcl_uitb_alv_evt_controller=>raise_link_click( io_controller = mo_controller iv_column = e_column_id-fieldname iv_row = es_row_no-row_id ). set_function_call_active( abap_false ). ENDMETHOD. METHOD on_menu_button. ENDMETHOD. METHOD on_toolbar. DATA: lt_disabled_selopt TYPE RANGE OF ui_func. DATA(lo_model) = mo_controller->mo_model. DATA(lo_functions) = lo_model->get_functions( ). IF lo_functions IS NOT BOUND. RETURN. ENDIF. DATA(lt_disabled) = lo_functions->get_disabled( ). IF lt_disabled IS NOT INITIAL. lt_disabled_selopt = VALUE #( LET i = 'I' eq = 'EQ' IN FOR IN lt_disabled ( sign = i option = eq low = ) ). DELETE e_object->mt_toolbar WHERE function IN lt_disabled_selopt. ENDIF. *.. Insert toolbar functions at start IF lo_functions->mt_buttons_front IS NOT INITIAL. LOOP AT lo_functions->mt_buttons_front ASSIGNING FIELD-SYMBOL(). INSERT CORRESPONDING #( ) INTO e_object->mt_toolbar INDEX 1. ENDLOOP. ENDIF. *.. append toolbar buttons at the end e_object->mt_toolbar = VALUE #( BASE e_object->mt_toolbar ( LINES OF CORRESPONDING #( lo_functions->mt_buttons ) ) ). IF lo_functions->mt_menus IS NOT INITIAL. e_object->mt_btnmnu = VALUE #( BASE e_object->mt_btnmnu ( LINES OF CORRESPONDING #( lo_functions->mt_menus ) ) ). ENDIF. *.. add quickfilter if set inside functions IF lo_functions->mf_quickfilter = abap_true. "" try to find filter function DATA(lv_index) = line_index( e_object->mt_toolbar[ function = zif_uitb_c_alv_functions=>filter_menu ] ). DATA(lf_add_quickfilter) = abap_false. IF lv_index = 0. lv_index = line_index( e_object->mt_toolbar[ function = zif_uitb_c_alv_functions=>filter ] ). IF lv_index <> 0. lf_add_quickfilter = abap_true. ENDIF. ELSE. lf_add_quickfilter = abap_true. ENDIF. IF lf_add_quickfilter = abap_true. ADD 1 TO lv_index. INSERT VALUE #( butn_type = cntb_btype_dropdown function = zif_uitb_c_alv_functions=>quickfilter_menu icon = icon_select_with_condition quickinfo = 'Quickfilter...' ) INTO e_object->mt_toolbar INDEX lv_index. e_object->mt_btnmnu = VALUE #( BASE e_object->mt_btnmnu ( function = zif_uitb_c_alv_functions=>quickfilter_menu ctmenu = mo_quickfilter_menu ) ). ENDIF. ENDIF. ENDMETHOD. METHOD on_user_command. set_function_call_active( ). *.. Catch quick filter event IF e_ucomm = zif_uitb_c_alv_functions=>quickfilter_exclude OR e_ucomm = zif_uitb_c_alv_functions=>quickfilter_menu OR e_ucomm = zif_uitb_c_alv_functions=>quickfilter. zcl_uitb_alv_evt_controller=>handle_before_event( io_controller = mo_controller ). mo_controller->mo_model->perform_quick_filter( if_exclude = COND #( WHEN e_ucomm = zif_uitb_c_alv_functions=>quickfilter_exclude THEN abap_true ) ). zcl_uitb_alv_evt_controller=>handle_after_event( io_controller = mo_controller ). ELSE. zcl_uitb_alv_evt_controller=>raise_function_chosen( io_controller = mo_controller iv_function = e_ucomm iv_tag = get_function_tag( iv_user_function = e_ucomm ) ). ENDIF. set_function_call_active( abap_false ). ENDMETHOD. METHOD fill_menu_from_serialized. FIELD-SYMBOLS: LIKE LINE OF it_menu_serialize. DEFINE add_serialized_function. io_menu->add_function( fcode = -fcode text = -text disabled = -disabled checked = -checked accelerator = -accelerator ). END-OF-DEFINITION. LOOP AT it_menu_serialize ASSIGNING . IF -type = sctx_c_type_separator. io_menu->add_separator( ). ELSEIF -type = sctx_c_type_function. *..... Check if an additional function should be inserted before or after LOOP AT it_additional_functions ASSIGNING FIELD-SYMBOL() WHERE insert_after = -fcode OR insert_before = -fcode. ENDLOOP. IF sy-subrc = 0. IF -insert_after IS NOT INITIAL. add_serialized_function. io_menu->add_separator( ). ENDIF. LOOP AT -functions ASSIGNING FIELD-SYMBOL(). io_menu->add_function( fcode = -function text = |{ -text }| ). ENDLOOP. IF -insert_before = abap_true. io_menu->add_separator( ). add_serialized_function. ENDIF. ELSE. add_serialized_function. ENDIF. ENDIF. ENDLOOP. ENDMETHOD. METHOD set_event_handlers. SET HANDLER: on_user_command FOR mo_grid, on_before_user_command FOR mo_grid, on_after_user_command FOR mo_grid, on_toolbar FOR mo_grid, on_menu_button FOR mo_grid, on_button_click FOR mo_grid, on_hotspot_click FOR mo_grid, on_double_click FOR mo_grid, on_context_menu FOR mo_grid, on_menu_button FOR mo_grid, on_f4 FOR mo_grid, on_data_changed FOR mo_grid, on_drag FOR mo_grid, on_drop FOR mo_grid, on_drop_get_flavor FOR mo_grid, on_drop_complete FOR mo_grid . ENDMETHOD. METHOD set_focus_to_grid. CHECK mo_grid IS BOUND. cl_gui_control=>set_focus( mo_grid ). ENDMETHOD. METHOD close. CHECK mo_dialog IS BOUND. mo_dialog->zif_uitb_gui_screen~leave_screen( ). ENDMETHOD. METHOD set_function. CHECK mo_grid IS BOUND. sy-ucomm = iv_function. mo_grid->fcode_bouncer( ). CLEAR sy-ucomm. mo_grid->set_user_command( space ). ENDMETHOD. METHOD set_function_call_active. mf_function_call_active = value. ENDMETHOD. METHOD set_metadata. DATA: ls_layout TYPE lvc_s_layo, lt_excluded TYPE ui_functions, ls_variant TYPE disvariant. FIELD-SYMBOLS: TYPE STANDARD TABLE. DATA(lo_model) = mo_controller->mo_model. DATA(lo_data_changes) = lo_model->get_data_changes( ). ms_stable = is_stable. mf_keep_scroll_position = if_keep_scroll_position. IF ir_changelist IS SUPPLIED. mo_current_changelist = ir_changelist. ENDIF. IF mo_grid IS INITIAL. IF mo_dialog IS BOUND. IF mo_dialog->mf_visible = abap_false. mo_dialog->show( iv_top = lo_model->ms_popup_dimensions-top iv_left = lo_model->ms_popup_dimensions-left iv_width = lo_model->ms_popup_dimensions-width iv_height = lo_model->ms_popup_dimensions-height ). IF mo_dialog->mf_modal = abap_true. RETURN. ENDIF. ENDIF. mo_grid = mo_dialog->mo_gui_alv_grid. ELSE. "" initialize grid mo_grid = NEW cl_gui_alv_grid( i_parent = lo_model->mr_container i_lifetime = lo_model->mr_container->lifetime i_fcat_complete = abap_true i_appl_events = abap_true i_applogparent = lo_data_changes->mo_applog_container ). ENDIF. "" register event handlers set_event_handlers( ). ENDIF. DATA(lo_columns) = lo_model->get_columns( ). DATA(lo_functional_settings) = lo_model->get_functional_settings( ). DATA(lo_dropdowns) = lo_functional_settings->get_dropdowns( ). DATA(lo_display_settings) = lo_model->get_display_settings( ). DATA(lo_functions) = lo_model->get_functions( ). DATA(lo_layout) = lo_model->get_layout( ). DATA(lo_filters) = lo_model->get_filters( ). DATA(lo_sorting) = lo_model->get_sorting( ). DATA(lo_selections) = lo_model->get_selections( ). IF mo_current_changelist->has_metadata_changed( ) OR mo_current_changelist->is_new_data_requested( ). "" get grid metadata for both new data and changed metadata zcl_uitb_alv_metadata_util=>set_alv_layout( EXPORTING ir_selections = lo_selections ir_display_settings = lo_display_settings ir_columns = lo_columns CHANGING cs_layout = ls_layout ). IF mo_controller->mo_model->mv_display_type <> zif_uitb_c_alv_display_types=>embedded. CLEAR ls_layout-grid_title. ENDIF. DATA(lt_fieldcat) = zcl_uitb_alv_metadata_util=>set_fieldcatalog( ir_display_settings = lo_display_settings ir_columns = lo_columns ). DATA(lt_sort) = zcl_uitb_alv_metadata_util=>set_sorting( ir_sorts = lo_sorting ). DATA(lt_filters) = zcl_uitb_alv_metadata_util=>set_filters( ir_filters = lo_filters ). DATA(lt_f4) = zcl_uitb_alv_metadata_util=>set_f4_registrations( ir_columns = lo_columns ). mo_grid->register_f4_for_fields( lt_f4 ). IF lo_display_settings->is_editable( ). mo_grid->set_ready_for_input( 1 ). ELSE. mo_grid->set_ready_for_input( 0 ). ENDIF. mo_grid->process_ucomm_on_invalid_input( lo_functions->mt_func_on_invalid_input ). ENDIF. CASE mo_current_changelist->is_new_data_requested( ). WHEN abap_false. IF mo_current_changelist->has_metadata_changed( ). IF mo_current_changelist->is_filters_only_change( ). mo_grid->set_filter_criteria( lt_filters ). ELSEIF mo_current_changelist->is_layout_only_change( ). mo_grid->set_frontend_layout( ls_layout ). ELSE. mo_grid->set_frontend_fieldcatalog( lt_fieldcat ). mo_grid->set_filter_criteria( lt_filters ). mo_grid->set_frontend_layout( ls_layout ). mo_grid->set_sort_criteria( lt_sort ). mo_grid->set_drop_down_table( it_drop_down_alias = zcl_uitb_alv_metadata_util=>get_dropdowns( lo_dropdowns ) ). ENDIF. ENDIF. IF lo_display_settings->is_editable( ). mo_grid->register_edit_event( lo_data_changes->mv_edit_event ). ENDIF. IF mo_current_changelist->get_refresh_mode( ) <> zif_uitb_c_alv_refresh=>none. IF mf_keep_scroll_position = abap_true. DATA(lf_update_scroll_position) = abap_true. mo_grid->get_scroll_info_via_id( IMPORTING es_row_no = DATA(ls_row_no) es_col_info = DATA(ls_col_info) ). ENDIF. ENDIF. CASE mo_current_changelist->get_refresh_mode( ). WHEN zif_uitb_c_alv_refresh=>full. mo_grid->refresh_table_display( is_stable = ms_stable ). WHEN zif_uitb_c_alv_refresh=>soft. mo_grid->refresh_table_display( is_stable = ms_stable i_soft_refresh = abap_true ). ENDCASE. WHEN abap_true. mo_grid->set_drop_down_table( it_drop_down_alias = zcl_uitb_alv_metadata_util=>get_dropdowns( lo_dropdowns ) ). ASSIGN lo_model->mr_data->* TO . IF lo_display_settings->is_editable( ). mo_grid->register_edit_event( lo_data_changes->mv_edit_event ). ENDIF. DATA(lf_variant_default) = zcl_uitb_alv_metadata_util=>get_variant_default( lo_layout ). DATA(lv_variant_save) = zcl_uitb_alv_metadata_util=>get_variant_save( lo_layout ). zcl_uitb_alv_metadata_util=>get_variant( EXPORTING ir_layout = lo_layout CHANGING cs_variant = ls_variant ). mo_grid->set_table_for_first_display( EXPORTING is_layout = ls_layout is_variant = ls_variant i_save = lv_variant_save i_default = lf_variant_default it_toolbar_excluding = lo_functions->get_disabled( ) CHANGING it_outtab = it_fieldcatalog = lt_fieldcat it_filter = lt_filters it_sort = lt_sort EXCEPTIONS invalid_parameter_combination = 1 program_error = 2 too_many_lines = 3 OTHERS = 4 ). IF sy-subrc <> 0. RAISE EXCEPTION TYPE zcx_uitb_alv_error EXPORTING textid = VALUE scx_t100key( msgid = sy-msgid msgno = sy-msgno attr1 = 'MSGV1' attr2 = 'MSGV2' attr3 = 'MSGV3' attr4 = 'MSGV4' ) msgv1 = sy-msgv1 msgv2 = sy-msgv2 msgv3 = sy-msgv3 msgv4 = sy-msgv4. ENDIF. ENDCASE. zcl_uitb_alv_selction_ctrller=>set_selections( mo_controller ). IF lf_update_scroll_position = abap_true. mo_grid->set_scroll_info_via_id( is_col_info = ls_col_info is_row_no = ls_row_no ). ENDIF. cl_gui_cfw=>flush( ). ENDMETHOD. METHOD zif_uitb_alv_adpt_selections~get_current_cell. CHECK mo_grid IS BOUND. DATA(lo_model) = mo_controller->mo_model. zcl_uitb_alv_metadata_util=>get_current_cell( ir_grid = mo_grid ir_selections = lo_model->mo_selections ). ENDMETHOD. METHOD zif_uitb_alv_adpt_selections~get_selected_cells. CHECK mo_grid IS BOUND. DATA(lo_model) = mo_controller->mo_model. zcl_uitb_alv_metadata_util=>get_selected_cells( ir_grid = mo_grid ir_selections = lo_model->mo_selections ). ENDMETHOD. METHOD zif_uitb_alv_adpt_selections~get_selected_columns. CHECK mo_grid IS BOUND. DATA(lo_model) = mo_controller->mo_model. zcl_uitb_alv_metadata_util=>get_selected_columns( ir_grid = mo_grid ir_selections = lo_model->mo_selections ). ENDMETHOD. METHOD zif_uitb_alv_adpt_selections~get_selected_rows. CHECK mo_grid IS BOUND. DATA(lo_model) = mo_controller->mo_model. zcl_uitb_alv_metadata_util=>get_selected_rows( ir_grid = mo_grid ir_selections = lo_model->mo_selections ). ENDMETHOD. METHOD zif_uitb_alv_adpt_selections~set_current_cell. CHECK mo_grid IS BOUND. DATA(lo_model) = mo_controller->mo_model. zcl_uitb_alv_metadata_util=>set_current_cell( ir_grid = mo_grid ir_selections = lo_model->mo_selections ). ENDMETHOD. METHOD zif_uitb_alv_adpt_selections~set_selected_cells. CHECK mo_grid IS BOUND. DATA(lo_model) = mo_controller->mo_model. zcl_uitb_alv_metadata_util=>set_selected_cells( ir_grid = mo_grid ir_selections = lo_model->mo_selections ). ENDMETHOD. METHOD zif_uitb_alv_adpt_selections~set_selected_columns. CHECK mo_grid IS BOUND. DATA(lo_model) = mo_controller->mo_model. zcl_uitb_alv_metadata_util=>set_selected_cols( ir_grid = mo_grid ir_selections = lo_model->mo_selections ). ENDMETHOD. METHOD zif_uitb_alv_adpt_selections~set_selected_rows. CHECK mo_grid IS BOUND. DATA(lo_model) = mo_controller->mo_model. zcl_uitb_alv_metadata_util=>set_selected_rows( ir_grid = mo_grid ir_selections = lo_model->mo_selections ). ENDMETHOD. ENDCLASS. ",7001,False,1523.7660388731504,median "[.configuration-legend] icon:lock[title=Fixed at build time] Configuration property fixed at build time - All other configuration properties are overridable at runtime [.configuration-reference.searchable, cols=""80,.^10,.^10""] |=== h|[[quarkus-oidc_configuration]]link:#quarkus-oidc_configuration[Configuration property] h|Type h|Default a|icon:lock[title=Fixed at build time] [[quarkus-oidc_quarkus.oidc.enabled]]`link:#quarkus-oidc_quarkus.oidc.enabled[quarkus.oidc.enabled]` [.description] -- If the OIDC extension is enabled. --|boolean |`true` a| [[quarkus-oidc_quarkus.oidc.tenant-id]]`link:#quarkus-oidc_quarkus.oidc.tenant-id[quarkus.oidc.tenant-id]` [.description] -- A unique tenant identifier. It must be set by `TenantConfigResolver` providers which resolve the tenant configuration dynamically and is optional in all other cases. --|string | a| [[quarkus-oidc_quarkus.oidc.tenant-enabled]]`link:#quarkus-oidc_quarkus.oidc.tenant-enabled[quarkus.oidc.tenant-enabled]` [.description] -- If this tenant configuration is enabled. --|boolean |`true` a| [[quarkus-oidc_quarkus.oidc.application-type]]`link:#quarkus-oidc_quarkus.oidc.application-type[quarkus.oidc.application-type]` [.description] -- The application type, which can be one of the following values from enum `ApplicationType`. --|`web-app`, `service`, `hybrid` |`service` a| [[quarkus-oidc_quarkus.oidc.auth-server-url]]`link:#quarkus-oidc_quarkus.oidc.auth-server-url[quarkus.oidc.auth-server-url]` [.description] -- The base URL of the OpenID Connect (OIDC) server, for example, 'https://host:port/auth'. OIDC discovery endpoint will be called by default by appending a '.well-known/openid-configuration' path to this URL. Note if you work with Keycloak OIDC server, make sure the base URL is in the following format: 'https://host:port/auth/realms/++{++realm++}++' where '++{++realm++}++' has to be replaced by the name of the Keycloak realm. --|string | a| [[quarkus-oidc_quarkus.oidc.discovery-enabled]]`link:#quarkus-oidc_quarkus.oidc.discovery-enabled[quarkus.oidc.discovery-enabled]` [.description] -- Enables OIDC discovery. If the discovery is disabled then the following properties must be configured: - 'authorization-path' and 'token-path' for the 'web-app' applications - 'jwks-path' or 'introspection-path' for both the 'web-app' and 'service' applications 'web-app' applications may also have 'user-info-path' and 'end-session-path' properties configured. --|boolean |`true` a| [[quarkus-oidc_quarkus.oidc.authorization-path]]`link:#quarkus-oidc_quarkus.oidc.authorization-path[quarkus.oidc.authorization-path]` [.description] -- Relative path of the OIDC authorization endpoint which authenticates the users. This property must be set for the 'web-app' applications if OIDC discovery is disabled. This property will be ignored if the discovery is enabled. --|string | a| [[quarkus-oidc_quarkus.oidc.token-path]]`link:#quarkus-oidc_quarkus.oidc.token-path[quarkus.oidc.token-path]` [.description] -- Relative path of the OIDC token endpoint which issues ID, access and refresh tokens. This property must be set for the 'web-app' applications if OIDC discovery is disabled. This property will be ignored if the discovery is enabled. --|string | a| [[quarkus-oidc_quarkus.oidc.user-info-path]]`link:#quarkus-oidc_quarkus.oidc.user-info-path[quarkus.oidc.user-info-path]` [.description] -- Relative path of the OIDC userinfo endpoint. This property must only be set for the 'web-app' applications if OIDC discovery is disabled and 'authentication.user-info-required' property is enabled. This property will be ignored if the discovery is enabled. --|string | a| [[quarkus-oidc_quarkus.oidc.introspection-path]]`link:#quarkus-oidc_quarkus.oidc.introspection-path[quarkus.oidc.introspection-path]` [.description] -- Relative path of the OIDC RFC7662 introspection endpoint which can introspect both opaque and JWT tokens. This property must be set if OIDC discovery is disabled and 1) the opaque bearer access tokens have to be verified or 2) JWT tokens have to be verified while the cached JWK verification set with no matching JWK is being refreshed. This property will be ignored if the discovery is enabled. --|string | a| [[quarkus-oidc_quarkus.oidc.jwks-path]]`link:#quarkus-oidc_quarkus.oidc.jwks-path[quarkus.oidc.jwks-path]` [.description] -- Relative path of the OIDC JWKS endpoint which returns a JSON Web Key Verification Set. This property should be set if OIDC discovery is disabled and the local JWT verification is required. This property will be ignored if the discovery is enabled. --|string | a| [[quarkus-oidc_quarkus.oidc.end-session-path]]`link:#quarkus-oidc_quarkus.oidc.end-session-path[quarkus.oidc.end-session-path]` [.description] -- Relative path of the OIDC end_session_endpoint. This property must be set if OIDC discovery is disabled and RP Initiated Logout support for the 'web-app' applications is required. This property will be ignored if the discovery is enabled. --|string | a| [[quarkus-oidc_quarkus.oidc.connection-delay]]`link:#quarkus-oidc_quarkus.oidc.connection-delay[quarkus.oidc.connection-delay]` [.description] -- The maximum amount of time the adapter will try connecting to the currently unavailable OIDC server for. For example, setting it to '20S' will let the adapter keep requesting the connection for up to 20 seconds. --|link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html[Duration] link:#duration-note-anchor[icon:question-circle[], title=More information about the Duration format] | a| [[quarkus-oidc_quarkus.oidc.public-key]]`link:#quarkus-oidc_quarkus.oidc.public-key[quarkus.oidc.public-key]` [.description] -- Public key for the local JWT token verification. OIDC server connection will not be created when this property is set. --|string | a| [[quarkus-oidc_quarkus.oidc.client-id]]`link:#quarkus-oidc_quarkus.oidc.client-id[quarkus.oidc.client-id]` [.description] -- The client-id of the application. Each application has a client-id that is used to identify the application --|string | a| [[quarkus-oidc_quarkus.oidc.roles.role-claim-path]]`link:#quarkus-oidc_quarkus.oidc.roles.role-claim-path[quarkus.oidc.roles.role-claim-path]` [.description] -- Path to the claim containing an array of groups. It starts from the top level JWT JSON object and can contain multiple segments where each segment represents a JSON object name only, example: ""realm/groups"". Use double quotes with the namespace qualified claim names. This property can be used if a token has no 'groups' claim but has the groups set in a different claim. --|string | a| [[quarkus-oidc_quarkus.oidc.roles.role-claim-separator]]`link:#quarkus-oidc_quarkus.oidc.roles.role-claim-separator[quarkus.oidc.roles.role-claim-separator]` [.description] -- Separator for splitting a string which may contain multiple group values. It will only be used if the ""role-claim-path"" property points to a custom claim whose value is a string. A single space will be used by default because the standard 'scope' claim may contain a space separated sequence. --|string | a| [[quarkus-oidc_quarkus.oidc.roles.source]]`link:#quarkus-oidc_quarkus.oidc.roles.source[quarkus.oidc.roles.source]` [.description] -- Source of the principal roles. --|`idtoken`, `accesstoken`, `userinfo` | a| [[quarkus-oidc_quarkus.oidc.token.issuer]]`link:#quarkus-oidc_quarkus.oidc.token.issuer[quarkus.oidc.token.issuer]` [.description] -- Expected issuer 'iss' claim value. --|string | a| [[quarkus-oidc_quarkus.oidc.token.audience]]`link:#quarkus-oidc_quarkus.oidc.token.audience[quarkus.oidc.token.audience]` [.description] -- Expected audience 'aud' claim value which may be a string or an array of strings. --|list of string | a| [[quarkus-oidc_quarkus.oidc.token.token-type]]`link:#quarkus-oidc_quarkus.oidc.token.token-type[quarkus.oidc.token.token-type]` [.description] -- Expected token type --|string | a| [[quarkus-oidc_quarkus.oidc.token.lifespan-grace]]`link:#quarkus-oidc_quarkus.oidc.token.lifespan-grace[quarkus.oidc.token.lifespan-grace]` [.description] -- Life span grace period in seconds. When checking token expiry, current time is allowed to be later than token expiration time by at most the configured number of seconds. When checking token issuance, current time is allowed to be sooner than token issue time by at most the configured number of seconds. --|int | a| [[quarkus-oidc_quarkus.oidc.token.principal-claim]]`link:#quarkus-oidc_quarkus.oidc.token.principal-claim[quarkus.oidc.token.principal-claim]` [.description] -- Name of the claim which contains a principal name. By default, the 'upn', 'preferred_username' and `sub` claims are checked. --|string | a| [[quarkus-oidc_quarkus.oidc.token.refresh-expired]]`link:#quarkus-oidc_quarkus.oidc.token.refresh-expired[quarkus.oidc.token.refresh-expired]` [.description] -- Refresh expired ID tokens. If this property is enabled then a refresh token request will be performed if the ID token has expired and, if successful, the local session will be updated with the new set of tokens. Otherwise, the local session will be invalidated and the user redirected to the OpenID Provider to re-authenticate. In this case the user may not be challenged again if the OIDC provider session is still active. For this option be effective the `authentication.session-age-extension` property should also be set to a non-zero value since the refresh token is currently kept in the user session. This option is valid only when the application is of type `ApplicationType++#++WEB_APP`++}++. --|boolean |`false` a| [[quarkus-oidc_quarkus.oidc.token.auto-refresh-interval]]`link:#quarkus-oidc_quarkus.oidc.token.auto-refresh-interval[quarkus.oidc.token.auto-refresh-interval]` [.description] -- Token auto-refresh interval in seconds during the user re-authentication. If this option is set then the valid ID token will be refreshed if it will expire in less than a number of minutes set by this option. The user will still be authenticated if the ID token can no longer be refreshed but is still valid. This option will be ignored if the 'refresh-expired' property is not enabled. --|link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html[Duration] link:#duration-note-anchor[icon:question-circle[], title=More information about the Duration format] | a| [[quarkus-oidc_quarkus.oidc.token.forced-jwk-refresh-interval]]`link:#quarkus-oidc_quarkus.oidc.token.forced-jwk-refresh-interval[quarkus.oidc.token.forced-jwk-refresh-interval]` [.description] -- Forced JWK set refresh interval in minutes. --|link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html[Duration] link:#duration-note-anchor[icon:question-circle[], title=More information about the Duration format] |`10M` a| [[quarkus-oidc_quarkus.oidc.token.header]]`link:#quarkus-oidc_quarkus.oidc.token.header[quarkus.oidc.token.header]` [.description] -- Custom HTTP header that contains a bearer token. This option is valid only when the application is of type `ApplicationType++#++SERVICE`++}++. --|string | a| [[quarkus-oidc_quarkus.oidc.credentials.secret]]`link:#quarkus-oidc_quarkus.oidc.credentials.secret[quarkus.oidc.credentials.secret]` [.description] -- Client secret which is used for a 'client_secret_basic' authentication method. Note that a 'client-secret.value' can be used instead but both properties are mutually exclusive. --|string | a| [[quarkus-oidc_quarkus.oidc.credentials.client-secret.value]]`link:#quarkus-oidc_quarkus.oidc.credentials.client-secret.value[quarkus.oidc.credentials.client-secret.value]` [.description] -- The client secret --|string | a| [[quarkus-oidc_quarkus.oidc.credentials.client-secret.method]]`link:#quarkus-oidc_quarkus.oidc.credentials.client-secret.method[quarkus.oidc.credentials.client-secret.method]` [.description] -- Authentication method. --|`basic`, `post` | a| [[quarkus-oidc_quarkus.oidc.credentials.jwt.secret]]`link:#quarkus-oidc_quarkus.oidc.credentials.jwt.secret[quarkus.oidc.credentials.jwt.secret]` [.description] -- client_secret_jwt: JWT which includes client id as one of its claims is signed by the client secret and is submitted as a 'client_assertion' form parameter, while 'client_assertion_type' parameter is set to ""urn:ietf:params:oauth:client-assertion-type:jwt-bearer"". --|string | a| [[quarkus-oidc_quarkus.oidc.credentials.jwt.lifespan]]`link:#quarkus-oidc_quarkus.oidc.credentials.jwt.lifespan[quarkus.oidc.credentials.jwt.lifespan]` [.description] -- JWT life-span in seconds. It will be added to the time it was issued at to calculate the expiration time. --|int |`10` a| [[quarkus-oidc_quarkus.oidc.proxy.host]]`link:#quarkus-oidc_quarkus.oidc.proxy.host[quarkus.oidc.proxy.host]` [.description] -- The host (name or IP address) of the Proxy. Note: If OIDC adapter needs to use a Proxy to talk with OIDC server (Provider), then at least the ""host"" config item must be configured to enable the usage of a Proxy. --|string | a| [[quarkus-oidc_quarkus.oidc.proxy.port]]`link:#quarkus-oidc_quarkus.oidc.proxy.port[quarkus.oidc.proxy.port]` [.description] -- The port number of the Proxy. Default value is 80. --|int |`80` a| [[quarkus-oidc_quarkus.oidc.proxy.username]]`link:#quarkus-oidc_quarkus.oidc.proxy.username[quarkus.oidc.proxy.username]` [.description] -- The username, if Proxy needs authentication. --|string | a| [[quarkus-oidc_quarkus.oidc.proxy.password]]`link:#quarkus-oidc_quarkus.oidc.proxy.password[quarkus.oidc.proxy.password]` [.description] -- The password, if Proxy needs authentication. --|string | a| [[quarkus-oidc_quarkus.oidc.authentication.redirect-path]]`link:#quarkus-oidc_quarkus.oidc.authentication.redirect-path[quarkus.oidc.authentication.redirect-path]` [.description] -- Relative path for calculating a ""redirect_uri"" query parameter. It has to start from a forward slash and will be appended to the request URI's host and port. For example, if the current request URI is 'https://localhost:8080/service' then a 'redirect_uri' parameter will be set to 'https://localhost:8080/' if this property is set to '/' and be the same as the request URI if this property has not been configured. Note the original request URI will be restored after the user has authenticated. --|string | a| [[quarkus-oidc_quarkus.oidc.authentication.restore-path-after-redirect]]`link:#quarkus-oidc_quarkus.oidc.authentication.restore-path-after-redirect[quarkus.oidc.authentication.restore-path-after-redirect]` [.description] -- If this property is set to 'true' then the original request URI which was used before the authentication will be restored after the user has been redirected back to the application. --|boolean |`true` a| [[quarkus-oidc_quarkus.oidc.authentication.remove-redirect-parameters]]`link:#quarkus-oidc_quarkus.oidc.authentication.remove-redirect-parameters[quarkus.oidc.authentication.remove-redirect-parameters]` [.description] -- Remove the query parameters such as 'code' and 'state' set by the OIDC server on the redirect URI after the user has authenticated by redirecting a user to the same URI but without the query parameters. --|boolean |`true` a| [[quarkus-oidc_quarkus.oidc.authentication.verify-access-token]]`link:#quarkus-oidc_quarkus.oidc.authentication.verify-access-token[quarkus.oidc.authentication.verify-access-token]` [.description] -- Both ID and access tokens are fetched from the OIDC provider as part of the authorization code flow. ID token is always verified on every user request as the primary token which is used to represent the principal and extract the roles. Access token is not verified by default since it is meant to be propagated to the downstream services. The verification of the access token should be enabled if it is injected as a JWT token. Access tokens obtained as part of the code flow will always be verified if `quarkus.oidc.roles.source` property is set to `accesstoken` which means the authorization decision will be based on the roles extracted from the access token. Bearer access tokens are always verified. --|boolean |`false` a| [[quarkus-oidc_quarkus.oidc.authentication.force-redirect-https-scheme]]`link:#quarkus-oidc_quarkus.oidc.authentication.force-redirect-https-scheme[quarkus.oidc.authentication.force-redirect-https-scheme]` [.description] -- Force 'https' as the 'redirect_uri' parameter scheme when running behind an SSL terminating reverse proxy. This property, if enabled, will also affect the logout `post_logout_redirect_uri` and the local redirect requests. --|boolean |`false` a| [[quarkus-oidc_quarkus.oidc.authentication.scopes]]`link:#quarkus-oidc_quarkus.oidc.authentication.scopes[quarkus.oidc.authentication.scopes]` [.description] -- List of scopes --|list of string | a| [[quarkus-oidc_quarkus.oidc.authentication.cookie-path]]`link:#quarkus-oidc_quarkus.oidc.authentication.cookie-path[quarkus.oidc.authentication.cookie-path]` [.description] -- Cookie path parameter value which, if set, will be used for the session, state and post logout cookies. It may need to be set when the redirect path has a root different to that of the original request URL. --|string | a| [[quarkus-oidc_quarkus.oidc.authentication.cookie-domain]]`link:#quarkus-oidc_quarkus.oidc.authentication.cookie-domain[quarkus.oidc.authentication.cookie-domain]` [.description] -- Cookie domain parameter value which, if set, will be used for the session, state and post logout cookies. --|string | a| [[quarkus-oidc_quarkus.oidc.authentication.user-info-required]]`link:#quarkus-oidc_quarkus.oidc.authentication.user-info-required[quarkus.oidc.authentication.user-info-required]` [.description] -- If this property is set to 'true' then an OIDC UserInfo endpoint will be called --|boolean |`false` a| [[quarkus-oidc_quarkus.oidc.authentication.session-age-extension]]`link:#quarkus-oidc_quarkus.oidc.authentication.session-age-extension[quarkus.oidc.authentication.session-age-extension]` [.description] -- Session age extension in minutes. The user session age property is set to the value of the ID token life-span by default and the user will be redirected to the OIDC provider to re-authenticate once the session has expired. If this property is set to a non-zero value then the expired ID token can be refreshed before the session has expired. This property will be ignored if the `token.refresh-expired` property has not been enabled. --|link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html[Duration] link:#duration-note-anchor[icon:question-circle[], title=More information about the Duration format] |`5M` a| [[quarkus-oidc_quarkus.oidc.authentication.java-script-auto-redirect]]`link:#quarkus-oidc_quarkus.oidc.authentication.java-script-auto-redirect[quarkus.oidc.authentication.java-script-auto-redirect]` [.description] -- If this property is set to 'true' then a normal 302 redirect response will be returned if the request was initiated via JavaScript API such as XMLHttpRequest or Fetch and the current user needs to be (re)authenticated which may not be desirable for Single Page Applications since it automatically following the redirect may not work given that OIDC authorization endpoints typically do not support CORS. If this property is set to `false` then a status code of '499' will be returned to allow the client to handle the redirect manually --|boolean |`true` a| [[quarkus-oidc_quarkus.oidc.tls.verification]]`link:#quarkus-oidc_quarkus.oidc.tls.verification[quarkus.oidc.tls.verification]` [.description] -- Certificate validation and hostname verification, which can be one of the following values from enum `Verification`. Default is required. --|`required`, `none` |`required` a| [[quarkus-oidc_quarkus.oidc.logout.path]]`link:#quarkus-oidc_quarkus.oidc.logout.path[quarkus.oidc.logout.path]` [.description] -- The relative path of the logout endpoint at the application. If provided, the application is able to initiate the logout through this endpoint in conformance with the OpenID Connect RP-Initiated Logout specification. --|string | a| [[quarkus-oidc_quarkus.oidc.logout.post-logout-path]]`link:#quarkus-oidc_quarkus.oidc.logout.post-logout-path[quarkus.oidc.logout.post-logout-path]` [.description] -- Relative path of the application endpoint where the user should be redirected to after logging out from the OpenID Connect Provider. This endpoint URI must be properly registered at the OpenID Connect Provider as a valid redirect URI. --|string | a| [[quarkus-oidc_quarkus.oidc.token-state-manager.strategy]]`link:#quarkus-oidc_quarkus.oidc.token-state-manager.strategy[quarkus.oidc.token-state-manager.strategy]` [.description] -- Default TokenStateManager strategy. --|`keep-all-tokens`, `id-token` |`keep-all-tokens` a| [[quarkus-oidc_quarkus.oidc.token-state-manager.split-tokens]]`link:#quarkus-oidc_quarkus.oidc.token-state-manager.split-tokens[quarkus.oidc.token-state-manager.split-tokens]` [.description] -- Default TokenStateManager keeps all tokens (ID, access and refresh) returned in the authorization code grant response in a single session cookie by default. Enable this property to minimize a session cookie size --|boolean |`false` a| [[quarkus-oidc_quarkus.oidc.authentication.extra-params-extra-params]]`link:#quarkus-oidc_quarkus.oidc.authentication.extra-params-extra-params[quarkus.oidc.authentication.extra-params]` [.description] -- Additional properties which will be added as the query parameters to the authentication redirect URI. --|`Map` | h|[[quarkus-oidc_quarkus.oidc.named-tenants-additional-named-tenants]]link:#quarkus-oidc_quarkus.oidc.named-tenants-additional-named-tenants[Additional named tenants] h|Type h|Default a| [[quarkus-oidc_quarkus.oidc.-tenant-.tenant-id]]`link:#quarkus-oidc_quarkus.oidc.-tenant-.tenant-id[quarkus.oidc.""tenant"".tenant-id]` [.description] -- A unique tenant identifier. It must be set by `TenantConfigResolver` providers which resolve the tenant configuration dynamically and is optional in all other cases. --|string | a| [[quarkus-oidc_quarkus.oidc.-tenant-.tenant-enabled]]`link:#quarkus-oidc_quarkus.oidc.-tenant-.tenant-enabled[quarkus.oidc.""tenant"".tenant-enabled]` [.description] -- If this tenant configuration is enabled. --|boolean |`true` a| [[quarkus-oidc_quarkus.oidc.-tenant-.application-type]]`link:#quarkus-oidc_quarkus.oidc.-tenant-.application-type[quarkus.oidc.""tenant"".application-type]` [.description] -- The application type, which can be one of the following values from enum `ApplicationType`. --|`web-app`, `service`, `hybrid` |`service` a| [[quarkus-oidc_quarkus.oidc.-tenant-.auth-server-url]]`link:#quarkus-oidc_quarkus.oidc.-tenant-.auth-server-url[quarkus.oidc.""tenant"".auth-server-url]` [.description] -- The base URL of the OpenID Connect (OIDC) server, for example, 'https://host:port/auth'. OIDC discovery endpoint will be called by default by appending a '.well-known/openid-configuration' path to this URL. Note if you work with Keycloak OIDC server, make sure the base URL is in the following format: 'https://host:port/auth/realms/++{++realm++}++' where '++{++realm++}++' has to be replaced by the name of the Keycloak realm. --|string | a| [[quarkus-oidc_quarkus.oidc.-tenant-.discovery-enabled]]`link:#quarkus-oidc_quarkus.oidc.-tenant-.discovery-enabled[quarkus.oidc.""tenant"".discovery-enabled]` [.description] -- Enables OIDC discovery. If the discovery is disabled then the following properties must be configured: - 'authorization-path' and 'token-path' for the 'web-app' applications - 'jwks-path' or 'introspection-path' for both the 'web-app' and 'service' applications 'web-app' applications may also have 'user-info-path' and 'end-session-path' properties configured. --|boolean |`true` a| [[quarkus-oidc_quarkus.oidc.-tenant-.authorization-path]]`link:#quarkus-oidc_quarkus.oidc.-tenant-.authorization-path[quarkus.oidc.""tenant"".authorization-path]` [.description] -- Relative path of the OIDC authorization endpoint which authenticates the users. This property must be set for the 'web-app' applications if OIDC discovery is disabled. This property will be ignored if the discovery is enabled. --|string | a| [[quarkus-oidc_quarkus.oidc.-tenant-.token-path]]`link:#quarkus-oidc_quarkus.oidc.-tenant-.token-path[quarkus.oidc.""tenant"".token-path]` [.description] -- Relative path of the OIDC token endpoint which issues ID, access and refresh tokens. This property must be set for the 'web-app' applications if OIDC discovery is disabled. This property will be ignored if the discovery is enabled. --|string | a| [[quarkus-oidc_quarkus.oidc.-tenant-.user-info-path]]`link:#quarkus-oidc_quarkus.oidc.-tenant-.user-info-path[quarkus.oidc.""tenant"".user-info-path]` [.description] -- Relative path of the OIDC userinfo endpoint. This property must only be set for the 'web-app' applications if OIDC discovery is disabled and 'authentication.user-info-required' property is enabled. This property will be ignored if the discovery is enabled. --|string | a| [[quarkus-oidc_quarkus.oidc.-tenant-.introspection-path]]`link:#quarkus-oidc_quarkus.oidc.-tenant-.introspection-path[quarkus.oidc.""tenant"".introspection-path]` [.description] -- Relative path of the OIDC RFC7662 introspection endpoint which can introspect both opaque and JWT tokens. This property must be set if OIDC discovery is disabled and 1) the opaque bearer access tokens have to be verified or 2) JWT tokens have to be verified while the cached JWK verification set with no matching JWK is being refreshed. This property will be ignored if the discovery is enabled. --|string | a| [[quarkus-oidc_quarkus.oidc.-tenant-.jwks-path]]`link:#quarkus-oidc_quarkus.oidc.-tenant-.jwks-path[quarkus.oidc.""tenant"".jwks-path]` [.description] -- Relative path of the OIDC JWKS endpoint which returns a JSON Web Key Verification Set. This property should be set if OIDC discovery is disabled and the local JWT verification is required. This property will be ignored if the discovery is enabled. --|string | a| [[quarkus-oidc_quarkus.oidc.-tenant-.end-session-path]]`link:#quarkus-oidc_quarkus.oidc.-tenant-.end-session-path[quarkus.oidc.""tenant"".end-session-path]` [.description] -- Relative path of the OIDC end_session_endpoint. This property must be set if OIDC discovery is disabled and RP Initiated Logout support for the 'web-app' applications is required. This property will be ignored if the discovery is enabled. --|string | a| [[quarkus-oidc_quarkus.oidc.-tenant-.connection-delay]]`link:#quarkus-oidc_quarkus.oidc.-tenant-.connection-delay[quarkus.oidc.""tenant"".connection-delay]` [.description] -- The maximum amount of time the adapter will try connecting to the currently unavailable OIDC server for. For example, setting it to '20S' will let the adapter keep requesting the connection for up to 20 seconds. --|link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html[Duration] link:#duration-note-anchor[icon:question-circle[], title=More information about the Duration format] | a| [[quarkus-oidc_quarkus.oidc.-tenant-.public-key]]`link:#quarkus-oidc_quarkus.oidc.-tenant-.public-key[quarkus.oidc.""tenant"".public-key]` [.description] -- Public key for the local JWT token verification. OIDC server connection will not be created when this property is set. --|string | a| [[quarkus-oidc_quarkus.oidc.-tenant-.client-id]]`link:#quarkus-oidc_quarkus.oidc.-tenant-.client-id[quarkus.oidc.""tenant"".client-id]` [.description] -- The client-id of the application. Each application has a client-id that is used to identify the application --|string | a| [[quarkus-oidc_quarkus.oidc.-tenant-.roles.role-claim-path]]`link:#quarkus-oidc_quarkus.oidc.-tenant-.roles.role-claim-path[quarkus.oidc.""tenant"".roles.role-claim-path]` [.description] -- Path to the claim containing an array of groups. It starts from the top level JWT JSON object and can contain multiple segments where each segment represents a JSON object name only, example: ""realm/groups"". Use double quotes with the namespace qualified claim names. This property can be used if a token has no 'groups' claim but has the groups set in a different claim. --|string | a| [[quarkus-oidc_quarkus.oidc.-tenant-.roles.role-claim-separator]]`link:#quarkus-oidc_quarkus.oidc.-tenant-.roles.role-claim-separator[quarkus.oidc.""tenant"".roles.role-claim-separator]` [.description] -- Separator for splitting a string which may contain multiple group values. It will only be used if the ""role-claim-path"" property points to a custom claim whose value is a string. A single space will be used by default because the standard 'scope' claim may contain a space separated sequence. --|string | a| [[quarkus-oidc_quarkus.oidc.-tenant-.roles.source]]`link:#quarkus-oidc_quarkus.oidc.-tenant-.roles.source[quarkus.oidc.""tenant"".roles.source]` [.description] -- Source of the principal roles. --|`idtoken`, `accesstoken`, `userinfo` | a| [[quarkus-oidc_quarkus.oidc.-tenant-.token.issuer]]`link:#quarkus-oidc_quarkus.oidc.-tenant-.token.issuer[quarkus.oidc.""tenant"".token.issuer]` [.description] -- Expected issuer 'iss' claim value. --|string | a| [[quarkus-oidc_quarkus.oidc.-tenant-.token.audience]]`link:#quarkus-oidc_quarkus.oidc.-tenant-.token.audience[quarkus.oidc.""tenant"".token.audience]` [.description] -- Expected audience 'aud' claim value which may be a string or an array of strings. --|list of string | a| [[quarkus-oidc_quarkus.oidc.-tenant-.token.token-type]]`link:#quarkus-oidc_quarkus.oidc.-tenant-.token.token-type[quarkus.oidc.""tenant"".token.token-type]` [.description] -- Expected token type --|string | a| [[quarkus-oidc_quarkus.oidc.-tenant-.token.lifespan-grace]]`link:#quarkus-oidc_quarkus.oidc.-tenant-.token.lifespan-grace[quarkus.oidc.""tenant"".token.lifespan-grace]` [.description] -- Life span grace period in seconds. When checking token expiry, current time is allowed to be later than token expiration time by at most the configured number of seconds. When checking token issuance, current time is allowed to be sooner than token issue time by at most the configured number of seconds. --|int | a| [[quarkus-oidc_quarkus.oidc.-tenant-.token.principal-claim]]`link:#quarkus-oidc_quarkus.oidc.-tenant-.token.principal-claim[quarkus.oidc.""tenant"".token.principal-claim]` [.description] -- Name of the claim which contains a principal name. By default, the 'upn', 'preferred_username' and `sub` claims are checked. --|string | a| [[quarkus-oidc_quarkus.oidc.-tenant-.token.refresh-expired]]`link:#quarkus-oidc_quarkus.oidc.-tenant-.token.refresh-expired[quarkus.oidc.""tenant"".token.refresh-expired]` [.description] -- Refresh expired ID tokens. If this property is enabled then a refresh token request will be performed if the ID token has expired and, if successful, the local session will be updated with the new set of tokens. Otherwise, the local session will be invalidated and the user redirected to the OpenID Provider to re-authenticate. In this case the user may not be challenged again if the OIDC provider session is still active. For this option be effective the `authentication.session-age-extension` property should also be set to a non-zero value since the refresh token is currently kept in the user session. This option is valid only when the application is of type `ApplicationType++#++WEB_APP`++}++. --|boolean |`false` a| [[quarkus-oidc_quarkus.oidc.-tenant-.token.auto-refresh-interval]]`link:#quarkus-oidc_quarkus.oidc.-tenant-.token.auto-refresh-interval[quarkus.oidc.""tenant"".token.auto-refresh-interval]` [.description] -- Token auto-refresh interval in seconds during the user re-authentication. If this option is set then the valid ID token will be refreshed if it will expire in less than a number of minutes set by this option. The user will still be authenticated if the ID token can no longer be refreshed but is still valid. This option will be ignored if the 'refresh-expired' property is not enabled. --|link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html[Duration] link:#duration-note-anchor[icon:question-circle[], title=More information about the Duration format] | a| [[quarkus-oidc_quarkus.oidc.-tenant-.token.forced-jwk-refresh-interval]]`link:#quarkus-oidc_quarkus.oidc.-tenant-.token.forced-jwk-refresh-interval[quarkus.oidc.""tenant"".token.forced-jwk-refresh-interval]` [.description] -- Forced JWK set refresh interval in minutes. --|link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html[Duration] link:#duration-note-anchor[icon:question-circle[], title=More information about the Duration format] |`10M` a| [[quarkus-oidc_quarkus.oidc.-tenant-.token.header]]`link:#quarkus-oidc_quarkus.oidc.-tenant-.token.header[quarkus.oidc.""tenant"".token.header]` [.description] -- Custom HTTP header that contains a bearer token. This option is valid only when the application is of type `ApplicationType++#++SERVICE`++}++. --|string | a| [[quarkus-oidc_quarkus.oidc.-tenant-.credentials.secret]]`link:#quarkus-oidc_quarkus.oidc.-tenant-.credentials.secret[quarkus.oidc.""tenant"".credentials.secret]` [.description] -- Client secret which is used for a 'client_secret_basic' authentication method. Note that a 'client-secret.value' can be used instead but both properties are mutually exclusive. --|string | a| [[quarkus-oidc_quarkus.oidc.-tenant-.credentials.client-secret.value]]`link:#quarkus-oidc_quarkus.oidc.-tenant-.credentials.client-secret.value[quarkus.oidc.""tenant"".credentials.client-secret.value]` [.description] -- The client secret --|string | a| [[quarkus-oidc_quarkus.oidc.-tenant-.credentials.client-secret.method]]`link:#quarkus-oidc_quarkus.oidc.-tenant-.credentials.client-secret.method[quarkus.oidc.""tenant"".credentials.client-secret.method]` [.description] -- Authentication method. --|`basic`, `post` | a| [[quarkus-oidc_quarkus.oidc.-tenant-.credentials.jwt.secret]]`link:#quarkus-oidc_quarkus.oidc.-tenant-.credentials.jwt.secret[quarkus.oidc.""tenant"".credentials.jwt.secret]` [.description] -- client_secret_jwt: JWT which includes client id as one of its claims is signed by the client secret and is submitted as a 'client_assertion' form parameter, while 'client_assertion_type' parameter is set to ""urn:ietf:params:oauth:client-assertion-type:jwt-bearer"". --|string | a| [[quarkus-oidc_quarkus.oidc.-tenant-.credentials.jwt.lifespan]]`link:#quarkus-oidc_quarkus.oidc.-tenant-.credentials.jwt.lifespan[quarkus.oidc.""tenant"".credentials.jwt.lifespan]` [.description] -- JWT life-span in seconds. It will be added to the time it was issued at to calculate the expiration time. --|int |`10` a| [[quarkus-oidc_quarkus.oidc.-tenant-.proxy.host]]`link:#quarkus-oidc_quarkus.oidc.-tenant-.proxy.host[quarkus.oidc.""tenant"".proxy.host]` [.description] -- The host (name or IP address) of the Proxy. Note: If OIDC adapter needs to use a Proxy to talk with OIDC server (Provider), then at least the ""host"" config item must be configured to enable the usage of a Proxy. --|string | a| [[quarkus-oidc_quarkus.oidc.-tenant-.proxy.port]]`link:#quarkus-oidc_quarkus.oidc.-tenant-.proxy.port[quarkus.oidc.""tenant"".proxy.port]` [.description] -- The port number of the Proxy. Default value is 80. --|int |`80` a| [[quarkus-oidc_quarkus.oidc.-tenant-.proxy.username]]`link:#quarkus-oidc_quarkus.oidc.-tenant-.proxy.username[quarkus.oidc.""tenant"".proxy.username]` [.description] -- The username, if Proxy needs authentication. --|string | a| [[quarkus-oidc_quarkus.oidc.-tenant-.proxy.password]]`link:#quarkus-oidc_quarkus.oidc.-tenant-.proxy.password[quarkus.oidc.""tenant"".proxy.password]` [.description] -- The password, if Proxy needs authentication. --|string | a| [[quarkus-oidc_quarkus.oidc.-tenant-.authentication.redirect-path]]`link:#quarkus-oidc_quarkus.oidc.-tenant-.authentication.redirect-path[quarkus.oidc.""tenant"".authentication.redirect-path]` [.description] -- Relative path for calculating a ""redirect_uri"" query parameter. It has to start from a forward slash and will be appended to the request URI's host and port. For example, if the current request URI is 'https://localhost:8080/service' then a 'redirect_uri' parameter will be set to 'https://localhost:8080/' if this property is set to '/' and be the same as the request URI if this property has not been configured. Note the original request URI will be restored after the user has authenticated. --|string | a| [[quarkus-oidc_quarkus.oidc.-tenant-.authentication.restore-path-after-redirect]]`link:#quarkus-oidc_quarkus.oidc.-tenant-.authentication.restore-path-after-redirect[quarkus.oidc.""tenant"".authentication.restore-path-after-redirect]` [.description] -- If this property is set to 'true' then the original request URI which was used before the authentication will be restored after the user has been redirected back to the application. --|boolean |`true` a| [[quarkus-oidc_quarkus.oidc.-tenant-.authentication.remove-redirect-parameters]]`link:#quarkus-oidc_quarkus.oidc.-tenant-.authentication.remove-redirect-parameters[quarkus.oidc.""tenant"".authentication.remove-redirect-parameters]` [.description] -- Remove the query parameters such as 'code' and 'state' set by the OIDC server on the redirect URI after the user has authenticated by redirecting a user to the same URI but without the query parameters. --|boolean |`true` a| [[quarkus-oidc_quarkus.oidc.-tenant-.authentication.verify-access-token]]`link:#quarkus-oidc_quarkus.oidc.-tenant-.authentication.verify-access-token[quarkus.oidc.""tenant"".authentication.verify-access-token]` [.description] -- Both ID and access tokens are fetched from the OIDC provider as part of the authorization code flow. ID token is always verified on every user request as the primary token which is used to represent the principal and extract the roles. Access token is not verified by default since it is meant to be propagated to the downstream services. The verification of the access token should be enabled if it is injected as a JWT token. Access tokens obtained as part of the code flow will always be verified if `quarkus.oidc.roles.source` property is set to `accesstoken` which means the authorization decision will be based on the roles extracted from the access token. Bearer access tokens are always verified. --|boolean |`false` a| [[quarkus-oidc_quarkus.oidc.-tenant-.authentication.force-redirect-https-scheme]]`link:#quarkus-oidc_quarkus.oidc.-tenant-.authentication.force-redirect-https-scheme[quarkus.oidc.""tenant"".authentication.force-redirect-https-scheme]` [.description] -- Force 'https' as the 'redirect_uri' parameter scheme when running behind an SSL terminating reverse proxy. This property, if enabled, will also affect the logout `post_logout_redirect_uri` and the local redirect requests. --|boolean |`false` a| [[quarkus-oidc_quarkus.oidc.-tenant-.authentication.scopes]]`link:#quarkus-oidc_quarkus.oidc.-tenant-.authentication.scopes[quarkus.oidc.""tenant"".authentication.scopes]` [.description] -- List of scopes --|list of string | a| [[quarkus-oidc_quarkus.oidc.-tenant-.authentication.extra-params-extra-params]]`link:#quarkus-oidc_quarkus.oidc.-tenant-.authentication.extra-params-extra-params[quarkus.oidc.""tenant"".authentication.extra-params]` [.description] -- Additional properties which will be added as the query parameters to the authentication redirect URI. --|`Map` | a| [[quarkus-oidc_quarkus.oidc.-tenant-.authentication.cookie-path]]`link:#quarkus-oidc_quarkus.oidc.-tenant-.authentication.cookie-path[quarkus.oidc.""tenant"".authentication.cookie-path]` [.description] -- Cookie path parameter value which, if set, will be used for the session, state and post logout cookies. It may need to be set when the redirect path has a root different to that of the original request URL. --|string | a| [[quarkus-oidc_quarkus.oidc.-tenant-.authentication.cookie-domain]]`link:#quarkus-oidc_quarkus.oidc.-tenant-.authentication.cookie-domain[quarkus.oidc.""tenant"".authentication.cookie-domain]` [.description] -- Cookie domain parameter value which, if set, will be used for the session, state and post logout cookies. --|string | a| [[quarkus-oidc_quarkus.oidc.-tenant-.authentication.user-info-required]]`link:#quarkus-oidc_quarkus.oidc.-tenant-.authentication.user-info-required[quarkus.oidc.""tenant"".authentication.user-info-required]` [.description] -- If this property is set to 'true' then an OIDC UserInfo endpoint will be called --|boolean |`false` a| [[quarkus-oidc_quarkus.oidc.-tenant-.authentication.session-age-extension]]`link:#quarkus-oidc_quarkus.oidc.-tenant-.authentication.session-age-extension[quarkus.oidc.""tenant"".authentication.session-age-extension]` [.description] -- Session age extension in minutes. The user session age property is set to the value of the ID token life-span by default and the user will be redirected to the OIDC provider to re-authenticate once the session has expired. If this property is set to a non-zero value then the expired ID token can be refreshed before the session has expired. This property will be ignored if the `token.refresh-expired` property has not been enabled. --|link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html[Duration] link:#duration-note-anchor[icon:question-circle[], title=More information about the Duration format] |`5M` a| [[quarkus-oidc_quarkus.oidc.-tenant-.authentication.java-script-auto-redirect]]`link:#quarkus-oidc_quarkus.oidc.-tenant-.authentication.java-script-auto-redirect[quarkus.oidc.""tenant"".authentication.java-script-auto-redirect]` [.description] -- If this property is set to 'true' then a normal 302 redirect response will be returned if the request was initiated via JavaScript API such as XMLHttpRequest or Fetch and the current user needs to be (re)authenticated which may not be desirable for Single Page Applications since it automatically following the redirect may not work given that OIDC authorization endpoints typically do not support CORS. If this property is set to `false` then a status code of '499' will be returned to allow the client to handle the redirect manually --|boolean |`true` a| [[quarkus-oidc_quarkus.oidc.-tenant-.tls.verification]]`link:#quarkus-oidc_quarkus.oidc.-tenant-.tls.verification[quarkus.oidc.""tenant"".tls.verification]` [.description] -- Certificate validation and hostname verification, which can be one of the following values from enum `Verification`. Default is required. --|`required`, `none` |`required` a| [[quarkus-oidc_quarkus.oidc.-tenant-.logout.path]]`link:#quarkus-oidc_quarkus.oidc.-tenant-.logout.path[quarkus.oidc.""tenant"".logout.path]` [.description] -- The relative path of the logout endpoint at the application. If provided, the application is able to initiate the logout through this endpoint in conformance with the OpenID Connect RP-Initiated Logout specification. --|string | a| [[quarkus-oidc_quarkus.oidc.-tenant-.logout.post-logout-path]]`link:#quarkus-oidc_quarkus.oidc.-tenant-.logout.post-logout-path[quarkus.oidc.""tenant"".logout.post-logout-path]` [.description] -- Relative path of the application endpoint where the user should be redirected to after logging out from the OpenID Connect Provider. This endpoint URI must be properly registered at the OpenID Connect Provider as a valid redirect URI. --|string | a| [[quarkus-oidc_quarkus.oidc.-tenant-.token-state-manager.strategy]]`link:#quarkus-oidc_quarkus.oidc.-tenant-.token-state-manager.strategy[quarkus.oidc.""tenant"".token-state-manager.strategy]` [.description] -- Default TokenStateManager strategy. --|`keep-all-tokens`, `id-token` |`keep-all-tokens` a| [[quarkus-oidc_quarkus.oidc.-tenant-.token-state-manager.split-tokens]]`link:#quarkus-oidc_quarkus.oidc.-tenant-.token-state-manager.split-tokens[quarkus.oidc.""tenant"".token-state-manager.split-tokens]` [.description] -- Default TokenStateManager keeps all tokens (ID, access and refresh) returned in the authorization code grant response in a single session cookie by default. Enable this property to minimize a session cookie size --|boolean |`false` |=== ifndef::no-duration-note[] [NOTE] [[duration-note-anchor]] .About the Duration format ==== The format for durations uses the standard `java.time.Duration` format. You can learn more about it in the link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html#parse-java.lang.CharSequence-[Duration#parse() javadoc]. You can also provide duration values starting with a number. In this case, if the value consists only of a number, the converter treats the value as seconds. Otherwise, `PT` is implicitly prepended to the value to obtain a standard `java.time.Duration` format. ==== endif::no-duration-note[] ",12256,True,3701.0588401625682,median "CLASS z2mse_extr3_classes DEFINITION PUBLIC INHERITING FROM z2mse_extr3_elements FINAL CREATE PUBLIC . PUBLIC SECTION. CONSTANTS: is_class_type TYPE seoclstype VALUE 0, interface_type TYPE seoclstype VALUE 1, attribute_type TYPE seocmptype VALUE 0, method_type TYPE seocmptype VALUE 1, event_type TYPE seocmptype VALUE 2. TYPES: BEGIN OF ty_class_component, clsname TYPE string, cmpname TYPE string, cmptype TYPE seocmptype, mtdtype TYPE seomtdtype, END OF ty_class_component. TYPES ty_class_components TYPE STANDARD TABLE OF ty_class_component WITH KEY clsname cmpname. DATA: class_components TYPE ty_class_components. CLASS-METHODS clear. CLASS-METHODS get_instance IMPORTING element_manager TYPE REF TO z2mse_extr3_element_manager RETURNING VALUE(r_instance) TYPE REF TO z2mse_extr3_classes. METHODS add IMPORTING class TYPE string EXPORTING VALUE(is_added) TYPE abap_bool VALUE(new_element_id) TYPE z2mse_extr3_element_manager=>element_id_type VALUE(class_components) TYPE ty_class_components. METHODS add_component IMPORTING clsname TYPE string cmpname TYPE string is_specific TYPE abap_bool EXPORTING VALUE(is_added) TYPE abap_bool VALUE(new_element_id) TYPE z2mse_extr3_element_manager=>element_id_type. METHODS class_name IMPORTING element_id TYPE i EXPORTING VALUE(class_name) TYPE string VALUE(clstype) TYPE seoclstype VALUE(exists) TYPE abap_bool. METHODS comp_name IMPORTING element_id TYPE i EXPORTING VALUE(class_name) TYPE string VALUE(cmpname) TYPE string VALUE(cmptype) TYPE seocmptype VALUE(exists) TYPE abap_bool. METHODS is_redefinition_of_method IMPORTING invoced_element_id1 TYPE i invocing_element_id2 TYPE i RETURNING VALUE(r_result) TYPE abap_bool. METHODS make_model REDEFINITION. METHODS name REDEFINITION. METHODS collect_infos REDEFINITION. PROTECTED SECTION. PRIVATE SECTION. CLASS-DATA instance TYPE REF TO z2mse_extr3_classes. TYPES: BEGIN OF element_type, element_id TYPE z2mse_extr3_element_manager=>element_id_type, class_name TYPE string, clstype TYPE seoclstype, adt_link TYPE string, END OF element_type. DATA elements_element_id TYPE HASHED TABLE OF element_type WITH UNIQUE KEY element_id. DATA elements_class_name TYPE HASHED TABLE OF element_type WITH UNIQUE KEY class_name. TYPES: BEGIN OF element_comp_type, element_id TYPE z2mse_extr3_element_manager=>element_id_type, clsname TYPE string, cmpname TYPE string, cmptype TYPE seocmptype, mtdtype TYPE seomtdtype, adt_link TYPE string, END OF element_comp_type. DATA elements_comp_element_id TYPE HASHED TABLE OF element_comp_type WITH UNIQUE KEY element_id. DATA elements_comp_clsname_cmpname TYPE SORTED TABLE OF element_comp_type WITH UNIQUE KEY clsname cmpname. TYPES: BEGIN OF element_metarel_type, element_id TYPE z2mse_extr3_element_manager=>element_id_type, refclsname TYPE string, reltype TYPE seoreltype, END OF element_metarel_type. DATA elements_metarel_element_id TYPE HASHED TABLE OF element_metarel_type WITH UNIQUE KEY element_id. DATA elements_metarel_refclsname TYPE HASHED TABLE OF element_metarel_type WITH UNIQUE KEY refclsname. TYPES: BEGIN OF redefined_type, clsname TYPE seoclsname, refclsname TYPE seoclsname, mtdname TYPE seocpdname, END OF redefined_type. TYPES: BEGIN OF redefined_method_type, clsname TYPE seoclsname, defined_in_clsname TYPE seoclsname, method TYPE seocpdname, END OF redefined_method_type. DATA redefined_methods TYPE HASHED TABLE OF redefined_method_type WITH UNIQUE KEY method clsname defined_in_clsname. METHODS _add_component IMPORTING clsname TYPE string cmpname TYPE string EXPORTING VALUE(is_added) TYPE abap_bool VALUE(is_added_now) TYPE abap_bool VALUE(new_element_id) TYPE z2mse_extr3_element_manager=>element_id_type. METHODS _add_metarel IMPORTING clsname TYPE string. ""! Call me only after checking that the component to be added is not already added. METHODS _add_single_component_to_class IMPORTING i_found_class_name TYPE string i_found_cmpname TYPE string i_found_cmptype TYPE seocmptype i_found_mtdtype TYPE seomtdtype RETURNING VALUE(r_new_element_id) TYPE z2mse_extr3_element_manager=>element_id_type. METHODS _get_redefined IMPORTING class TYPE string RETURNING VALUE(r_result) TYPE z2mse_extr3_classes=>ty_class_components. ENDCLASS. CLASS z2mse_extr3_classes IMPLEMENTATION. METHOD add. DATA: element TYPE element_type, element_comp TYPE element_comp_type. READ TABLE elements_class_name INTO element WITH KEY class_name = class. IF sy-subrc EQ 0. is_added = abap_true. new_element_id = element-element_id. LOOP AT elements_comp_clsname_cmpname INTO element_comp WHERE clsname = class. DATA class_component TYPE z2mse_extr3_classes=>ty_class_component. class_component-clsname = element_comp-clsname. class_component-cmpname = element_comp-cmpname. class_component-cmptype = element_comp-cmptype. class_component-mtdtype = element_comp-mtdtype. INSERT class_component INTO TABLE class_components. ENDLOOP. ELSE. "" Does table exists? DATA: found_class_name TYPE seoclsname, found_class_type TYPE seoclstype. TEST-SEAM seoclass. "" No blank between ( and found... to be 7.02 compatible SELECT SINGLE clsname clstype FROM seoclass INTO (found_class_name , found_class_type ) WHERE clsname = class. END-TEST-SEAM. IF found_class_name IS NOT INITIAL. is_added = abap_true. ENDIF. IF is_added EQ abap_true. new_element_id = element_manager->add_element( element = me is_specific = abap_false ). element-element_id = new_element_id. element-class_name = class. element-clstype = found_class_type. INSERT element INTO TABLE elements_element_id. INSERT element INTO TABLE elements_class_name. ENDIF. TEST-SEAM seocompo_2. SELECT clsname cmpname cmptype mtdtype FROM seocompo INTO CORRESPONDING FIELDS OF TABLE class_components WHERE cmptype <> 3 "" A type AND clsname = class. END-TEST-SEAM. DATA: redefined_class_components TYPE ty_class_components, redefined_class_component TYPE ty_class_component. redefined_class_components = _get_redefined( class ). * DATA: redefined_components TYPE STANDARD TABLE OF redefined_type WITH DEFAULT KEY, * redefined_component TYPE redefined_type. * * TEST-SEAM seoredef. * * SELECT clsname refclsname mtdname FROM seoredef INTO TABLE redefined_components * WHERE clsname = class * AND version = 1. * * END-TEST-SEAM. * * IF sy-subrc EQ 0. * * DATA: referenced_class_component TYPE z2mse_extr3_classes=>ty_class_component. * * LOOP AT redefined_components INTO redefined_component. * * TEST-SEAM seocompo_3. * * SELECT SINGLE clsname cmpname cmptype mtdtype * FROM seocompo * INTO CORRESPONDING FIELDS OF referenced_class_component * WHERE cmptype <> 3 "" A type * AND clsname = class * AND cmpname = redefined_component-mtdname. * * END-TEST-SEAM. * * IF sy-subrc <> 0. * ""Inconsistency * ELSE. * INSERT referenced_class_component INTO TABLE class_components. * ASSERT sy-subrc EQ 0. * ENDIF. * * ENDLOOP. * * ENDIF. LOOP AT redefined_class_components INTO redefined_class_component. INSERT redefined_class_component INTO TABLE class_components. ENDLOOP. LOOP AT class_components INTO class_component. _add_component( EXPORTING clsname = class_component-clsname cmpname = class_component-cmpname ). ENDLOOP. _add_metarel( clsname = class ). ENDIF. ENDMETHOD. METHOD add_component. DATA: is_added_now TYPE abap_bool. add( EXPORTING class = clsname IMPORTING is_added = is_added ). IF is_added EQ abap_true. _add_component( EXPORTING clsname = clsname cmpname = cmpname IMPORTING is_added = is_added new_element_id = new_element_id is_added_now = is_added_now ). IF is_specific EQ abap_true AND new_element_id IS NOT INITIAL. element_manager->model_builder->new_element_id( EXPORTING i_element_id = new_element_id i_is_specific = abap_true ). ENDIF. ENDIF. ENDMETHOD. METHOD class_name. DATA element TYPE element_type. READ TABLE elements_element_id INTO element WITH TABLE KEY element_id = element_id. IF sy-subrc EQ 0. class_name = element-class_name. clstype = element-clstype. exists = abap_true. ENDIF. ENDMETHOD. METHOD clear. CLEAR instance. ENDMETHOD. METHOD collect_infos. DATA: part1 TYPE string, part2_classes TYPE string, part2_interfaces TYPE string, name TYPE string, part3 TYPE string. "" Get ADT Link to class or interface CONCATENATE 'adt://' sysid '/sap/bc/adt/oo/' INTO part1. part2_classes = 'classes/'. part2_interfaces = 'interfaces/'. part3 = '/source/main'. FIELD-SYMBOLS: TYPE element_type. LOOP AT elements_element_id ASSIGNING . name = -class_name. TRANSLATE name TO LOWER CASE. IF -clstype EQ is_class_type. CONCATENATE part1 part2_classes name part3 INTO -adt_link. ELSEIF -clstype EQ interface_type. CONCATENATE part1 part2_interfaces name part3 INTO -adt_link. ELSE. ASSERT 1 = 2. ENDIF. "" Get ADT Link to components DATA: cifkey TYPE seoclskey, cifref TYPE REF TO if_oo_clif_incl_naming, clsref TYPE REF TO if_oo_class_incl_naming, intref TYPE REF TO if_oo_interface_incl_naming, source TYPE seop_source_string, source_protected TYPE seop_source_string, source_private TYPE seop_source_string, source_line TYPE LINE OF seop_source_string. cifkey-clsname = -class_name. CLEAR source. CLEAR source_protected. CLEAR source_private. CALL METHOD cl_oo_include_naming=>get_instance_by_cifkey EXPORTING cifkey = cifkey RECEIVING cifref = cifref EXCEPTIONS OTHERS = 1. IF sy-subrc <> 0. "" :-( ELSE. CASE cifref->clstype. WHEN seoc_clstype_class. clsref ?= cifref. READ REPORT clsref->public_section INTO source. READ REPORT clsref->protected_section INTO source_protected. READ REPORT clsref->private_section INTO source_private. WHEN seoc_clstype_interface. intref ?= cifref. READ REPORT intref->public_section INTO source. WHEN OTHERS. "" What is to be done? ENDCASE. ENDIF. APPEND LINES OF source_protected TO source. APPEND LINES OF source_private TO source. DATA: line_no TYPE i, line TYPE string. line_no = 0. * LOOP AT source INTO source_line. * add 1 to line_no. * line = source_line. * condense line. * split line at ' ' into * ENDLOOP. DATA: tokens TYPE STANDARD TABLE OF stokes, token LIKE LINE OF tokens, next_component TYPE seocmptype, next_line TYPE i. DATA statements TYPE STANDARD TABLE OF sstmnt. SCAN ABAP-SOURCE source TOKENS INTO tokens STATEMENTS INTO statements. LOOP AT tokens INTO token. ADD 1 TO line_no. IF line_no EQ next_line. DATA: element_comp TYPE element_comp_type. READ TABLE elements_comp_clsname_cmpname INTO element_comp WITH TABLE KEY clsname = -class_name cmpname = token-str. IF sy-subrc <> 0. "" What to do? ELSE. FIELD-SYMBOLS TYPE element_comp_type. READ TABLE elements_comp_element_id ASSIGNING WITH TABLE KEY element_id = element_comp-element_id. IF sy-subrc <> 0. "" What to do? ELSE. DATA: row TYPE string. row = token-row. DATA: adt_link TYPE string. CONCATENATE -adt_link '#start=' row ',1' INTO adt_link. CONDENSE adt_link NO-GAPS. IF -adt_link IS INITIAL. "" Are there further hits? -adt_link = adt_link. ENDIF. ENDIF. ENDIF. ELSE. CLEAR next_line. CLEAR next_component. CASE token-str. WHEN 'CLASS-DATA' OR 'DATA'. next_component = attribute_type. next_line = line_no + 1. WHEN 'CLASS-METHODS' OR 'METHODS'. next_component = method_type. next_line = line_no + 1. WHEN 'CLASS-EVENTS' OR 'EVENTS'. next_component = event_type. next_line = line_no + 1. ENDCASE. ENDIF. ENDLOOP. ENDLOOP. ENDMETHOD. METHOD comp_name. DATA element_comp TYPE element_comp_type. READ TABLE elements_comp_element_id INTO element_comp WITH KEY element_id = element_id. IF sy-subrc EQ 0. class_name = element_comp-clsname. cmpname = element_comp-cmpname. cmptype = element_comp-cmptype. exists = abap_true. ENDIF. ENDMETHOD. METHOD get_instance. IF instance IS NOT BOUND. CREATE OBJECT instance EXPORTING i_element_manager = element_manager. ENDIF. instance->type = class_type. r_instance = instance. ENDMETHOD. METHOD make_model. DATA element TYPE element_type. READ TABLE elements_element_id INTO element WITH TABLE KEY element_id = element_id. IF sy-subrc EQ 0. DATA: last_id TYPE i, file_anchor_id TYPE i. IF element-clstype EQ is_class_type. "" SAP_2_FAMIX_59 Mark the FAMIX Class with the attribute modifiers = 'ABAPGlobalClass' "" SAP_2_FAMIX_6 Map ABAP classes to FAMIX.Class element_manager->famix_class->add( EXPORTING name_group = ng_abap_class name = element-class_name modifiers = z2mse_extract3=>modifier_abapglobalclass IMPORTING id = last_id ). IF element-adt_link IS NOT INITIAL. element_manager->famix_file_anchor->add( EXPORTING element_id = last_id "" Required for Moose 6.1 file_name = element-adt_link IMPORTING id = file_anchor_id ). IF file_anchor_id IS NOT INITIAL. element_manager->famix_class->set_source_anchor_by_id( EXPORTING element_id = last_id source_anchor_id = file_anchor_id ). ENDIF. ENDIF. ELSEIF element-clstype EQ interface_type. "" SAP_2_FAMIX_60 Mark the FAMIX Class with the attribute modifiers = 'ABAPGlobalInterface' "" SAP_2_FAMIX_7 Map ABAP Interfaces to FAMIX.Class element_manager->famix_class->add( EXPORTING name_group = ng_abap_class name = element-class_name modifiers = z2mse_extract3=>modifier_abapglobalinterface IMPORTING id = last_id ). "" SAP_2_FAMIX_8 Set the attribute isInterface in case of ABAP Interfaces element_manager->famix_class->is_interface( element_id = last_id ). IF element-adt_link IS NOT INITIAL. element_manager->famix_file_anchor->add( EXPORTING element_id = last_id "" Required for Moose 6.1 file_name = element-adt_link IMPORTING id = file_anchor_id ). IF file_anchor_id IS NOT INITIAL. element_manager->famix_class->set_source_anchor_by_id( EXPORTING element_id = last_id source_anchor_id = file_anchor_id ). ENDIF. ENDIF. ELSE. ASSERT 1 = 2. ENDIF. DATA association TYPE z2mse_extr3_element_manager=>association_type. LOOP AT associations INTO association WHERE element_id1 = element_id AND association->type = z2mse_extr3_association=>parent_package_ass. DATA package TYPE REF TO z2mse_extr3_packages. package ?= element_manager->get_element( i_element_id = association-element_id2 ). element_manager->famix_class->set_parent_package( element_id = last_id parent_package = package->devclass( i_element_id = association-element_id2 ) parent_package_name_group = ng_abap_package ). ENDLOOP. ELSE. DATA element_comp TYPE element_comp_type. READ TABLE elements_comp_element_id INTO element_comp WITH KEY element_id = element_id. ASSERT sy-subrc EQ 0. CASE element_comp-cmptype. WHEN attribute_type. * DATA last_id TYPE i.! element_manager->famix_attribute->add( EXPORTING name = element_comp-cmpname IMPORTING id = last_id ). element_manager->famix_attribute->set_parent_type( EXPORTING element_id = last_id parent_element = 'FAMIX.Class' parent_name_group = ng_abap_class parent_name = element_comp-clsname ). IF element_comp-adt_link IS NOT INITIAL. element_manager->famix_file_anchor->add( EXPORTING element_id = last_id "" Required for Moose 6.1 file_name = element_comp-adt_link IMPORTING id = file_anchor_id ). IF file_anchor_id IS NOT INITIAL. element_manager->famix_attribute->set_source_anchor_by_id( EXPORTING element_id = last_id source_anchor_id = file_anchor_id ). ENDIF. ENDIF. element_manager->famix_attribute->store_id( EXPORTING name_group = ng_abap_class class = element_comp-clsname attribute = element_comp-cmpname ). * sap_attribute->add( EXPORTING class = class-clsname * attribute = component-cmpname ). WHEN method_type OR event_type. "" SAP_2_FAMIX_15 Map methods of classes to FAMIX.Method "" SAP_2_FAMIX_16 Map methods of interfaces to FAMIX.Method element_manager->famix_method->add( EXPORTING name = element_comp-cmpname IMPORTING id = last_id ). "" SAP_2_FAMIX_41 Fill the attribut signature of FAMIX.METHOD with the name of the method "" SAP_2_FAMIX_42 Fill the attribut signature of FAMIX.METHOD with the name of the method element_manager->famix_method->set_signature( element_id = last_id signature = element_comp-cmpname ). element_manager->famix_method->set_parent_type( EXPORTING element_id = last_id parent_element = 'FAMIX.Class' parent_name_group = ng_abap_class parent_name = element_comp-clsname ). IF element_comp-adt_link IS NOT INITIAL. element_manager->famix_file_anchor->add( EXPORTING element_id = last_id "" Required for Moose 6.1 file_name = element_comp-adt_link IMPORTING id = file_anchor_id ). IF file_anchor_id IS NOT INITIAL. element_manager->famix_method->set_source_anchor_by_id( EXPORTING element_id = last_id source_anchor_id = file_anchor_id ). ENDIF. ENDIF. element_manager->famix_method->store_id( EXPORTING class_name_group = ng_abap_class class = element_comp-clsname method_name_group = ng_abap_method method = element_comp-cmpname ). * sap_method->add( EXPORTING class = class-clsname * method = component-cmpname ). WHEN OTHERS. ASSERT 1 = 2. ENDCASE. ENDIF. ENDMETHOD. METHOD name. DATA: class_name TYPE string, clstype TYPE seoclstype, exists TYPE abap_bool. class_name( EXPORTING element_id = element_id IMPORTING class_name = class_name clstype = clstype exists = exists ). IF exists EQ abap_true. CASE clstype. WHEN is_class_type. element_type = |ABAPClass|. WHEN interface_type. element_type = |ABAPInterface|. WHEN OTHERS. ASSERT 1 = 2. ENDCASE. parent_name = ||. name = class_name. ELSE. DATA: cmpname TYPE string, cmptype TYPE seocmptype. comp_name( EXPORTING element_id = element_id IMPORTING class_name = class_name cmpname = cmpname cmptype = cmptype exists = exists ). ASSERT exists EQ abap_true. DATA element TYPE element_type. READ TABLE elements_class_name INTO element WITH KEY class_name = class_name. ASSERT sy-subrc EQ 0. clstype = element-clstype. CASE clstype. WHEN is_class_type. CASE cmptype. WHEN attribute_type. element_type = |ABAPClassAttribute|. WHEN method_type. element_type = |ABAPClassMethod|. WHEN event_type. element_type = |ABAPClassEvent|. WHEN OTHERS. ASSERT 1 = 2. ENDCASE. WHEN interface_type. CASE cmptype. WHEN attribute_type. element_type = |ABAPInterfaceAttribute|. WHEN method_type. element_type = |ABAPInterfaceMethod|. WHEN event_type. element_type = |ABAPInterfaceEvent|. WHEN OTHERS. ASSERT 1 = 2. ENDCASE. WHEN OTHERS. ASSERT 1 = 2. ENDCASE. parent_name = class_name. name = cmpname. ENDIF. ENDMETHOD. METHOD _add_component. DATA element_comp TYPE element_comp_type. READ TABLE elements_comp_clsname_cmpname INTO element_comp WITH KEY clsname = clsname cmpname = cmpname. IF sy-subrc EQ 0. is_added = abap_true. new_element_id = element_comp-element_id. ELSE. "" Does component exists? DATA: found_class_name TYPE string, found_cmpname TYPE string, found_cmptype TYPE seocmptype, found_mtdtype TYPE seomtdtype. TEST-SEAM seocompo. SELECT SINGLE clsname cmpname cmptype mtdtype FROM seocompo INTO (found_class_name, found_cmpname, found_cmptype, found_mtdtype ) WHERE clsname = clsname AND cmpname = cmpname. END-TEST-SEAM. IF found_class_name IS NOT INITIAL. is_added = abap_true. IF found_cmptype EQ 3. "" Is type RAISE EXCEPTION TYPE ZCX_2MSE_EXTR3_CLASSES_WR_TYPE. ENDIF. ELSE. DATA: redefined_class_components TYPE ty_class_components, redefined_class_component TYPE ty_class_component. redefined_class_components = _get_redefined( clsname ). READ TABLE redefined_class_components INTO redefined_class_component WITH KEY clsname = clsname cmpname = cmpname. IF sy-subrc EQ 0. found_class_name = redefined_class_component-clsname. found_cmpname = redefined_class_component-cmpname. found_cmptype = redefined_class_component-cmptype. found_mtdtype = redefined_class_component-mtdtype. is_added = abap_true. ENDIF. ENDIF. IF is_added EQ abap_true. new_element_id = _add_single_component_to_class( i_found_class_name = found_class_name i_found_cmpname = found_cmpname i_found_cmptype = found_cmptype i_found_mtdtype = found_mtdtype ). is_added_now = abap_true. ENDIF. ENDIF. ENDMETHOD. METHOD _add_metarel. DATA: relation TYPE seometarel, relations TYPE STANDARD TABLE OF seometarel, element_metarel TYPE element_metarel_type, is_added TYPE abap_bool, new_element_id TYPE i. DATA access TYPE REF TO z2mse_extr3_access. access = z2mse_extr3_access=>get_instance( i_element_manager = element_manager ). DATA invocation TYPE REF TO z2mse_extr3_invocation. invocation = z2mse_extr3_invocation=>get_instance( i_element_manager = element_manager ). TEST-SEAM seometarel. SELECT * FROM seometarel INTO TABLE relations WHERE clsname = clsname AND version = 1 AND state = 1. END-TEST-SEAM. LOOP AT relations INTO relation WHERE reltype = 1 OR reltype = 2. element_metarel-element_id = new_element_id. element_metarel-refclsname = relation-refclsname. element_metarel-reltype = relation-reltype. INSERT element_metarel INTO TABLE elements_metarel_element_id. INSERT element_metarel INTO TABLE elements_metarel_refclsname. IF relation-reltype EQ 1. "" Interface DATA: interface_class_components TYPE ty_class_components, interface_class_component TYPE ty_class_component, reclsname_string TYPE string. reclsname_string = relation-refclsname. me->add( EXPORTING class = reclsname_string IMPORTING is_added = is_added new_element_id = new_element_id class_components = interface_class_components ). LOOP AT interface_class_components INTO interface_class_component. new_element_id = _add_single_component_to_class( i_found_class_name = clsname i_found_cmpname = |{ interface_class_component-clsname }~{ interface_class_component-cmpname }| i_found_cmptype = interface_class_component-cmptype i_found_mtdtype = interface_class_component-mtdtype ). DATA interface_element_id TYPE z2mse_extr3_element_manager=>element_id_type . me->add_component( EXPORTING clsname = interface_class_component-clsname cmpname = interface_class_component-cmpname is_specific = abap_false IMPORTING ""* is_added = new_element_id = interface_element_id ). IF interface_class_component-cmptype EQ attribute_type. "" Connections between attributes are not expressible in FAMIX, or? * access->add( EXPORTING accessed_element_id1 = new_element_id * accessing_element_id2 = interface_element_id ). ELSE. invocation->add( EXPORTING invoced_element_id1 = new_element_id invocing_element_id2 = interface_element_id ). ENDIF. ENDLOOP. ENDIF. ENDLOOP. ENDMETHOD. METHOD _add_single_component_to_class. "" Add single component to class DATA element_comp2 TYPE element_comp_type. ASSERT i_found_cmpname IS NOT INITIAL. r_new_element_id = element_manager->add_element( element = me is_specific = abap_false ). element_comp2-element_id = r_new_element_id. element_comp2-clsname = i_found_class_name. element_comp2-cmpname = i_found_cmpname. element_comp2-cmptype = i_found_cmptype. element_comp2-mtdtype = i_found_mtdtype. INSERT element_comp2 INTO TABLE elements_comp_element_id . INSERT element_comp2 INTO TABLE elements_comp_clsname_cmpname . ENDMETHOD. METHOD _get_redefined. DATA: redefined_components TYPE STANDARD TABLE OF redefined_type WITH DEFAULT KEY, redefined_component TYPE redefined_type, found TYPE abap_bool, superclass TYPE seoclsname, component TYPE z2mse_extr3_classes=>ty_class_component. TEST-SEAM seoredef. SELECT * FROM seoredef INTO CORRESPONDING FIELDS OF TABLE redefined_components WHERE clsname = class AND version = 1. END-TEST-SEAM. LOOP AT redefined_components INTO redefined_component. superclass = redefined_component-refclsname. found = ''. WHILE found EQ ''. CLEAR component. TEST-SEAM seocompo_3. SELECT SINGLE clsname cmpname cmptype mtdtype FROM seocompo INTO component WHERE cmptype <> 3 "" A type AND clsname = superclass AND cmpname = redefined_component-mtdname. END-TEST-SEAM. IF sy-subrc EQ 0. found = 'X'. DATA redefined_method TYPE redefined_method_type. redefined_method-method = component-cmpname. redefined_method-clsname = class. redefined_method-defined_in_clsname = component-clsname. INSERT redefined_method INTO TABLE redefined_methods. ""Allow duplicate inserting here component-clsname = class . INSERT component INTO TABLE r_result. ELSE. "" Find next superclass TEST-SEAM seometarel_2. SELECT SINGLE refclsname FROM seometarel INTO superclass WHERE clsname = superclass AND version = 1. END-TEST-SEAM. IF sy-subrc <> 0. found = 'X'. "" Nothing found ENDIF. ENDIF. ENDWHILE. ENDLOOP. ENDMETHOD. METHOD is_redefinition_of_method. DATA: invoced TYPE element_comp_type, invocing TYPE element_comp_type. READ TABLE elements_comp_element_id INTO invoced WITH KEY element_id = invoced_element_id1. IF sy-subrc <> 0. RETURN. ENDIF. READ TABLE elements_comp_element_id INTO invocing WITH KEY element_id = invocing_element_id2. IF sy-subrc <> 0. RETURN. ENDIF. IF invoced-cmpname <> invocing-cmpname. RETURN. ENDIF. DATA: r TYPE redefined_method_type. READ TABLE redefined_methods INTO r WITH TABLE KEY method = invocing-cmpname clsname = invocing-clsname defined_in_clsname = invoced-clsname. IF sy-subrc EQ 0. r_result = 'X'. ENDIF. ENDMETHOD. ENDCLASS. ",7296,False,1576.6323544624577,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. * * This file is an adaptation of Presto's presto-parser/src/main/antlr4/com/facebook/presto/sql/parser/SqlBase.g4 grammar. */ grammar SqlBase; @members { /** * Verify whether current token is a valid decimal token (which contains dot). * Returns true if the character that follows the token is not a digit or letter or underscore. * * For example: * For char stream ""2.3"", ""2."" is not a valid decimal token, because it is followed by digit '3'. * For char stream ""2.3_"", ""2.3"" is not a valid decimal token, because it is followed by '_'. * For char stream ""2.3W"", ""2.3"" is not a valid decimal token, because it is followed by 'W'. * For char stream ""12.0D 34.E2+0.12 "" 12.0D is a valid decimal token because it is folllowed * by a space. 34.E2 is a valid decimal token because it is followed by symbol '+' * which is not a digit or letter or underscore. */ public boolean isValidDecimal() { int nextChar = _input.LA(1); if (nextChar >= 'A' && nextChar <= 'Z' || nextChar >= '0' && nextChar <= '9' || nextChar == '_') { return false; } else { return true; } } } tokens { DELIMITER } singleStatement : statement EOF ; singleExpression : namedExpression EOF ; singleTableIdentifier : tableIdentifier EOF ; singleFunctionIdentifier : functionIdentifier EOF ; singleDataType : dataType EOF ; singleTableSchema : colTypeList EOF ; statement : query #statementDefault | USE db=identifier #use | CREATE DATABASE (IF NOT EXISTS)? identifier (COMMENT comment=STRING)? locationSpec? (WITH DBPROPERTIES tablePropertyList)? #createDatabase | ALTER DATABASE identifier SET DBPROPERTIES tablePropertyList #setDatabaseProperties | DROP DATABASE (IF EXISTS)? identifier (RESTRICT | CASCADE)? #dropDatabase | createTableHeader ('(' colTypeList ')')? tableProvider (OPTIONS options=tablePropertyList)? (PARTITIONED BY partitionColumnNames=identifierList)? bucketSpec? locationSpec? (COMMENT comment=STRING)? (TBLPROPERTIES tableProps=tablePropertyList)? (AS? query)? #createTable | createTableHeader ('(' columns=colTypeList ')')? (COMMENT comment=STRING)? (PARTITIONED BY '(' partitionColumns=colTypeList ')')? bucketSpec? skewSpec? rowFormat? createFileFormat? locationSpec? (TBLPROPERTIES tablePropertyList)? (AS? query)? #createHiveTable | CREATE TABLE (IF NOT EXISTS)? target=tableIdentifier LIKE source=tableIdentifier locationSpec? #createTableLike | ANALYZE TABLE tableIdentifier partitionSpec? COMPUTE STATISTICS (identifier | FOR COLUMNS identifierSeq)? #analyze | ALTER TABLE tableIdentifier ADD COLUMNS '(' columns=colTypeList ')' #addTableColumns | ALTER (TABLE | VIEW) from=tableIdentifier RENAME TO to=tableIdentifier #renameTable | ALTER (TABLE | VIEW) tableIdentifier SET TBLPROPERTIES tablePropertyList #setTableProperties | ALTER (TABLE | VIEW) tableIdentifier UNSET TBLPROPERTIES (IF EXISTS)? tablePropertyList #unsetTableProperties | ALTER TABLE tableIdentifier partitionSpec? CHANGE COLUMN? identifier colType colPosition? #changeColumn | ALTER TABLE tableIdentifier (partitionSpec)? SET SERDE STRING (WITH SERDEPROPERTIES tablePropertyList)? #setTableSerDe | ALTER TABLE tableIdentifier (partitionSpec)? SET SERDEPROPERTIES tablePropertyList #setTableSerDe | ALTER TABLE tableIdentifier ADD (IF NOT EXISTS)? partitionSpecLocation+ #addTablePartition | ALTER VIEW tableIdentifier ADD (IF NOT EXISTS)? partitionSpec+ #addTablePartition | ALTER TABLE tableIdentifier from=partitionSpec RENAME TO to=partitionSpec #renameTablePartition | ALTER TABLE tableIdentifier DROP (IF EXISTS)? partitionSpec (',' partitionSpec)* PURGE? #dropTablePartitions | ALTER VIEW tableIdentifier DROP (IF EXISTS)? partitionSpec (',' partitionSpec)* #dropTablePartitions | ALTER TABLE tableIdentifier partitionSpec? SET locationSpec #setTableLocation | ALTER TABLE tableIdentifier RECOVER PARTITIONS #recoverPartitions | DROP TABLE (IF EXISTS)? tableIdentifier PURGE? #dropTable | DROP VIEW (IF EXISTS)? tableIdentifier #dropTable | CREATE (OR REPLACE)? (GLOBAL? TEMPORARY)? VIEW (IF NOT EXISTS)? tableIdentifier identifierCommentList? (COMMENT STRING)? (PARTITIONED ON identifierList)? (TBLPROPERTIES tablePropertyList)? AS query #createView | CREATE (OR REPLACE)? GLOBAL? TEMPORARY VIEW tableIdentifier ('(' colTypeList ')')? tableProvider (OPTIONS tablePropertyList)? #createTempViewUsing | ALTER VIEW tableIdentifier AS? query #alterViewQuery | CREATE (OR REPLACE)? TEMPORARY? FUNCTION (IF NOT EXISTS)? qualifiedName AS className=STRING (USING resource (',' resource)*)? #createFunction | DROP TEMPORARY? FUNCTION (IF EXISTS)? qualifiedName #dropFunction | EXPLAIN (LOGICAL | FORMATTED | EXTENDED | CODEGEN | COST)? statement #explain | SHOW TABLES ((FROM | IN) db=identifier)? (LIKE? pattern=STRING)? #showTables | SHOW TABLE EXTENDED ((FROM | IN) db=identifier)? LIKE pattern=STRING partitionSpec? #showTable | SHOW DATABASES (LIKE pattern=STRING)? #showDatabases | SHOW TBLPROPERTIES table=tableIdentifier ('(' key=tablePropertyKey ')')? #showTblProperties | SHOW COLUMNS (FROM | IN) tableIdentifier ((FROM | IN) db=identifier)? #showColumns | SHOW PARTITIONS tableIdentifier partitionSpec? #showPartitions | SHOW identifier? FUNCTIONS (LIKE? (qualifiedName | pattern=STRING))? #showFunctions | SHOW CREATE TABLE tableIdentifier #showCreateTable | (DESC | DESCRIBE) FUNCTION EXTENDED? describeFuncName #describeFunction | (DESC | DESCRIBE) DATABASE EXTENDED? identifier #describeDatabase | (DESC | DESCRIBE) TABLE? option=(EXTENDED | FORMATTED)? tableIdentifier partitionSpec? describeColName? #describeTable | REFRESH TABLE tableIdentifier #refreshTable | REFRESH (STRING | .*?) #refreshResource | CACHE LAZY? TABLE tableIdentifier (AS? query)? #cacheTable | UNCACHE TABLE (IF EXISTS)? tableIdentifier #uncacheTable | CLEAR CACHE #clearCache | LOAD DATA LOCAL? INPATH path=STRING OVERWRITE? INTO TABLE tableIdentifier partitionSpec? #loadData | TRUNCATE TABLE tableIdentifier partitionSpec? #truncateTable | MSCK REPAIR TABLE tableIdentifier #repairTable | op=(ADD | LIST) identifier .*? #manageResource | SET ROLE .*? #failNativeCommand | SET .*? #setConfiguration | RESET #resetConfiguration | unsupportedHiveNativeCommands .*? #failNativeCommand ; unsupportedHiveNativeCommands : kw1=CREATE kw2=ROLE | kw1=DROP kw2=ROLE | kw1=GRANT kw2=ROLE? | kw1=REVOKE kw2=ROLE? | kw1=SHOW kw2=GRANT | kw1=SHOW kw2=ROLE kw3=GRANT? | kw1=SHOW kw2=PRINCIPALS | kw1=SHOW kw2=ROLES | kw1=SHOW kw2=CURRENT kw3=ROLES | kw1=EXPORT kw2=TABLE | kw1=IMPORT kw2=TABLE | kw1=SHOW kw2=COMPACTIONS | kw1=SHOW kw2=CREATE kw3=TABLE | kw1=SHOW kw2=TRANSACTIONS | kw1=SHOW kw2=INDEXES | kw1=SHOW kw2=LOCKS | kw1=CREATE kw2=INDEX | kw1=DROP kw2=INDEX | kw1=ALTER kw2=INDEX | kw1=LOCK kw2=TABLE | kw1=LOCK kw2=DATABASE | kw1=UNLOCK kw2=TABLE | kw1=UNLOCK kw2=DATABASE | kw1=CREATE kw2=TEMPORARY kw3=MACRO | kw1=DROP kw2=TEMPORARY kw3=MACRO | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=CLUSTERED | kw1=ALTER kw2=TABLE tableIdentifier kw3=CLUSTERED kw4=BY | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=SORTED | kw1=ALTER kw2=TABLE tableIdentifier kw3=SKEWED kw4=BY | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=SKEWED | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=STORED kw5=AS kw6=DIRECTORIES | kw1=ALTER kw2=TABLE tableIdentifier kw3=SET kw4=SKEWED kw5=LOCATION | kw1=ALTER kw2=TABLE tableIdentifier kw3=EXCHANGE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=ARCHIVE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=UNARCHIVE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=TOUCH | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=COMPACT | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=CONCATENATE | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=SET kw4=FILEFORMAT | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=REPLACE kw4=COLUMNS | kw1=START kw2=TRANSACTION | kw1=COMMIT | kw1=ROLLBACK | kw1=DFS | kw1=DELETE kw2=FROM ; createTableHeader : CREATE TEMPORARY? EXTERNAL? TABLE (IF NOT EXISTS)? tableIdentifier ; bucketSpec : CLUSTERED BY identifierList (SORTED BY orderedIdentifierList)? INTO INTEGER_VALUE BUCKETS ; skewSpec : SKEWED BY identifierList ON (constantList | nestedConstantList) (STORED AS DIRECTORIES)? ; locationSpec : LOCATION STRING ; query : ctes? queryNoWith ; insertInto : INSERT OVERWRITE TABLE tableIdentifier (partitionSpec (IF NOT EXISTS)?)? | INSERT INTO TABLE? tableIdentifier partitionSpec? ; partitionSpecLocation : partitionSpec locationSpec? ; partitionSpec : PARTITION '(' partitionVal (',' partitionVal)* ')' ; partitionVal : identifier (EQ constant)? ; describeFuncName : qualifiedName | STRING | comparisonOperator | arithmeticOperator | predicateOperator ; describeColName : identifier ('.' (identifier | STRING))* ; ctes : WITH namedQuery (',' namedQuery)* ; namedQuery : name=identifier AS? '(' query ')' ; tableProvider : USING qualifiedName ; tablePropertyList : '(' tableProperty (',' tableProperty)* ')' ; tableProperty : key=tablePropertyKey (EQ? value=tablePropertyValue)? ; tablePropertyKey : identifier ('.' identifier)* | STRING ; tablePropertyValue : INTEGER_VALUE | DECIMAL_VALUE | booleanValue | STRING ; constantList : '(' constant (',' constant)* ')' ; nestedConstantList : '(' constantList (',' constantList)* ')' ; createFileFormat : STORED AS fileFormat | STORED BY storageHandler ; fileFormat : INPUTFORMAT inFmt=STRING OUTPUTFORMAT outFmt=STRING #tableFileFormat | identifier #genericFileFormat ; storageHandler : STRING (WITH SERDEPROPERTIES tablePropertyList)? ; resource : identifier STRING ; queryNoWith : insertInto? queryTerm queryOrganization #singleInsertQuery | fromClause multiInsertQueryBody+ #multiInsertQuery ; queryOrganization : (ORDER BY order+=sortItem (',' order+=sortItem)*)? (CLUSTER BY clusterBy+=expression (',' clusterBy+=expression)*)? (DISTRIBUTE BY distributeBy+=expression (',' distributeBy+=expression)*)? (SORT BY sort+=sortItem (',' sort+=sortItem)*)? windows? (LIMIT (ALL | limit=expression))? ; multiInsertQueryBody : insertInto? querySpecification queryOrganization ; queryTerm : queryPrimary #queryTermDefault | left=queryTerm operator=(INTERSECT | UNION | EXCEPT | SETMINUS) setQuantifier? right=queryTerm #setOperation ; queryPrimary : querySpecification #queryPrimaryDefault | TABLE tableIdentifier #table | inlineTable #inlineTableDefault1 | '(' queryNoWith ')' #subquery ; sortItem : expression ordering=(ASC | DESC)? (NULLS nullOrder=(LAST | FIRST))? ; querySpecification : (((SELECT kind=TRANSFORM '(' namedExpressionSeq ')' | kind=MAP namedExpressionSeq | kind=REDUCE namedExpressionSeq)) inRowFormat=rowFormat? (RECORDWRITER recordWriter=STRING)? USING script=STRING (AS (identifierSeq | colTypeList | ('(' (identifierSeq | colTypeList) ')')))? outRowFormat=rowFormat? (RECORDREADER recordReader=STRING)? fromClause? (WHERE where=booleanExpression)?) | ((kind=SELECT (hints+=hint)* setQuantifier? namedExpressionSeq fromClause? | fromClause (kind=SELECT setQuantifier? namedExpressionSeq)?) lateralView* (WHERE where=booleanExpression)? aggregation? (HAVING having=booleanExpression)? windows?) ; hint : '/*+' hintStatements+=hintStatement (','? hintStatements+=hintStatement)* '*/' ; hintStatement : hintName=identifier | hintName=identifier '(' parameters+=primaryExpression (',' parameters+=primaryExpression)* ')' ; fromClause : FROM relation (',' relation)* lateralView* ; aggregation : GROUP BY groupingExpressions+=expression (',' groupingExpressions+=expression)* ( WITH kind=ROLLUP | WITH kind=CUBE | kind=GROUPING SETS '(' groupingSet (',' groupingSet)* ')')? ; groupingSet : '(' (expression (',' expression)*)? ')' | expression ; lateralView : LATERAL VIEW (OUTER)? qualifiedName '(' (expression (',' expression)*)? ')' tblName=identifier (AS? colName+=identifier (',' colName+=identifier)*)? ; setQuantifier : DISTINCT | ALL ; relation : relationPrimary joinRelation* ; joinRelation : (joinType) JOIN right=relationPrimary joinCriteria? | NATURAL joinType JOIN right=relationPrimary ; joinType : INNER? | CROSS | LEFT OUTER? | LEFT SEMI | RIGHT OUTER? | FULL OUTER? | LEFT? ANTI ; joinCriteria : ON booleanExpression | USING '(' identifier (',' identifier)* ')' ; sample : TABLESAMPLE '(' ( (negativeSign=MINUS? percentage=(INTEGER_VALUE | DECIMAL_VALUE) sampleType=PERCENTLIT) | (expression sampleType=ROWS) | sampleType=BYTELENGTH_LITERAL | (sampleType=BUCKET numerator=INTEGER_VALUE OUT OF denominator=INTEGER_VALUE (ON (identifier | qualifiedName '(' ')'))?)) ')' ; identifierList : '(' identifierSeq ')' ; identifierSeq : identifier (',' identifier)* ; orderedIdentifierList : '(' orderedIdentifier (',' orderedIdentifier)* ')' ; orderedIdentifier : identifier ordering=(ASC | DESC)? ; identifierCommentList : '(' identifierComment (',' identifierComment)* ')' ; identifierComment : identifier (COMMENT STRING)? ; relationPrimary : tableIdentifier sample? tableAlias #tableName | '(' queryNoWith ')' sample? tableAlias #aliasedQuery | '(' relation ')' sample? tableAlias #aliasedRelation | inlineTable #inlineTableDefault2 | functionTable #tableValuedFunction ; inlineTable : VALUES expression (',' expression)* tableAlias ; functionTable : identifier '(' (expression (',' expression)*)? ')' tableAlias ; tableAlias : (AS? strictIdentifier identifierList?)? ; rowFormat : ROW FORMAT SERDE name=STRING (WITH SERDEPROPERTIES props=tablePropertyList)? #rowFormatSerde | ROW FORMAT DELIMITED (FIELDS TERMINATED BY fieldsTerminatedBy=STRING (ESCAPED BY escapedBy=STRING)?)? (COLLECTION ITEMS TERMINATED BY collectionItemsTerminatedBy=STRING)? (MAP KEYS TERMINATED BY keysTerminatedBy=STRING)? (LINES TERMINATED BY linesSeparatedBy=STRING)? (NULL DEFINED AS nullDefinedAs=STRING)? #rowFormatDelimited ; tableIdentifier : (db=identifier '.')? table=identifier ; functionIdentifier : (db=identifier '.')? function=identifier ; namedExpression : expression (AS? (identifier | identifierList))? ; namedExpressionSeq : namedExpression (',' namedExpression)* ; expression : booleanExpression ; booleanExpression : NOT booleanExpression #logicalNot | EXISTS '(' query ')' #exists | predicated #booleanDefault | left=booleanExpression operator=AND right=booleanExpression #logicalBinary | left=booleanExpression operator=OR right=booleanExpression #logicalBinary ; // workaround for: // https://github.com/antlr/antlr4/issues/780 // https://github.com/antlr/antlr4/issues/781 predicated : valueExpression predicate? ; predicate : NOT? kind=BETWEEN lower=valueExpression AND upper=valueExpression | NOT? kind=IN '(' expression (',' expression)* ')' | NOT? kind=IN '(' query ')' | NOT? kind=(RLIKE | LIKE) pattern=valueExpression | IS NOT? kind=NULL | IS NOT? kind=DISTINCT FROM right=valueExpression ; valueExpression : primaryExpression #valueExpressionDefault | operator=(MINUS | PLUS | TILDE) valueExpression #arithmeticUnary | left=valueExpression operator=(ASTERISK | SLASH | PERCENT | DIV) right=valueExpression #arithmeticBinary | left=valueExpression operator=(PLUS | MINUS | CONCAT_PIPE) right=valueExpression #arithmeticBinary | left=valueExpression operator=AMPERSAND right=valueExpression #arithmeticBinary | left=valueExpression operator=HAT right=valueExpression #arithmeticBinary | left=valueExpression operator=PIPE right=valueExpression #arithmeticBinary | left=valueExpression comparisonOperator right=valueExpression #comparison ; primaryExpression : name=(CURRENT_DATE | CURRENT_TIMESTAMP) #timeFunctionCall | CASE whenClause+ (ELSE elseExpression=expression)? END #searchedCase | CASE value=expression whenClause+ (ELSE elseExpression=expression)? END #simpleCase | CAST '(' expression AS dataType ')' #cast | STRUCT '(' (argument+=namedExpression (',' argument+=namedExpression)*)? ')' #struct | FIRST '(' expression (IGNORE NULLS)? ')' #first | LAST '(' expression (IGNORE NULLS)? ')' #last | POSITION '(' substr=valueExpression IN str=valueExpression ')' #position | constant #constantDefault | ASTERISK #star | qualifiedName '.' ASTERISK #star | '(' namedExpression (',' namedExpression)+ ')' #rowConstructor | '(' query ')' #subqueryExpression | qualifiedName '(' (setQuantifier? argument+=expression (',' argument+=expression)*)? ')' (OVER windowSpec)? #functionCall | value=primaryExpression '[' index=valueExpression ']' #subscript | identifier #columnReference | base=primaryExpression '.' fieldName=identifier #dereference | '(' expression ')' #parenthesizedExpression ; constant : NULL #nullLiteral | interval #intervalLiteral | identifier STRING #typeConstructor | number #numericLiteral | booleanValue #booleanLiteral | STRING+ #stringLiteral ; comparisonOperator : EQ | NEQ | NEQJ | LT | LTE | GT | GTE | NSEQ ; arithmeticOperator : PLUS | MINUS | ASTERISK | SLASH | PERCENT | DIV | TILDE | AMPERSAND | PIPE | CONCAT_PIPE | HAT ; predicateOperator : OR | AND | IN | NOT ; booleanValue : TRUE | FALSE ; interval : INTERVAL intervalField* ; intervalField : value=intervalValue unit=identifier (TO to=identifier)? ; intervalValue : (PLUS | MINUS)? (INTEGER_VALUE | DECIMAL_VALUE) | STRING ; colPosition : FIRST | AFTER identifier ; dataType : complex=ARRAY '<' dataType '>' #complexDataType | complex=MAP '<' dataType ',' dataType '>' #complexDataType | complex=STRUCT ('<' complexColTypeList? '>' | NEQ) #complexDataType | identifier ('(' INTEGER_VALUE (',' INTEGER_VALUE)* ')')? #primitiveDataType ; colTypeList : colType (',' colType)* ; colType : identifier dataType (COMMENT STRING)? ; complexColTypeList : complexColType (',' complexColType)* ; complexColType : identifier ':' dataType (COMMENT STRING)? ; whenClause : WHEN condition=expression THEN result=expression ; windows : WINDOW namedWindow (',' namedWindow)* ; namedWindow : identifier AS windowSpec ; windowSpec : name=identifier #windowRef | '(' ( CLUSTER BY partition+=expression (',' partition+=expression)* | ((PARTITION | DISTRIBUTE) BY partition+=expression (',' partition+=expression)*)? ((ORDER | SORT) BY sortItem (',' sortItem)*)?) windowFrame? ')' #windowDef ; windowFrame : frameType=RANGE start=frameBound | frameType=ROWS start=frameBound | frameType=RANGE BETWEEN start=frameBound AND end=frameBound | frameType=ROWS BETWEEN start=frameBound AND end=frameBound ; frameBound : UNBOUNDED boundType=(PRECEDING | FOLLOWING) | boundType=CURRENT ROW | expression boundType=(PRECEDING | FOLLOWING) ; qualifiedName : identifier ('.' identifier)* ; identifier : strictIdentifier | ANTI | FULL | INNER | LEFT | SEMI | RIGHT | NATURAL | JOIN | CROSS | ON | UNION | INTERSECT | EXCEPT | SETMINUS ; strictIdentifier : IDENTIFIER #unquotedIdentifier | quotedIdentifier #quotedIdentifierAlternative | nonReserved #unquotedIdentifier ; quotedIdentifier : BACKQUOTED_IDENTIFIER ; number : MINUS? DECIMAL_VALUE #decimalLiteral | MINUS? INTEGER_VALUE #integerLiteral | MINUS? BIGINT_LITERAL #bigIntLiteral | MINUS? SMALLINT_LITERAL #smallIntLiteral | MINUS? TINYINT_LITERAL #tinyIntLiteral | MINUS? DOUBLE_LITERAL #doubleLiteral | MINUS? BIGDECIMAL_LITERAL #bigDecimalLiteral ; nonReserved : SHOW | TABLES | COLUMNS | COLUMN | PARTITIONS | FUNCTIONS | DATABASES | ADD | OVER | PARTITION | RANGE | ROWS | PRECEDING | FOLLOWING | CURRENT | ROW | LAST | FIRST | AFTER | MAP | ARRAY | STRUCT | LATERAL | WINDOW | REDUCE | TRANSFORM | SERDE | SERDEPROPERTIES | RECORDREADER | DELIMITED | FIELDS | TERMINATED | COLLECTION | ITEMS | KEYS | ESCAPED | LINES | SEPARATED | EXTENDED | REFRESH | CLEAR | CACHE | UNCACHE | LAZY | GLOBAL | TEMPORARY | OPTIONS | GROUPING | CUBE | ROLLUP | EXPLAIN | FORMAT | LOGICAL | FORMATTED | CODEGEN | COST | TABLESAMPLE | USE | TO | BUCKET | PERCENTLIT | OUT | OF | SET | RESET | VIEW | REPLACE | IF | POSITION | NO | DATA | START | TRANSACTION | COMMIT | ROLLBACK | IGNORE | SORT | CLUSTER | DISTRIBUTE | UNSET | TBLPROPERTIES | SKEWED | STORED | DIRECTORIES | LOCATION | EXCHANGE | ARCHIVE | UNARCHIVE | FILEFORMAT | TOUCH | COMPACT | CONCATENATE | CHANGE | CASCADE | RESTRICT | BUCKETS | CLUSTERED | SORTED | PURGE | INPUTFORMAT | OUTPUTFORMAT | DBPROPERTIES | DFS | TRUNCATE | COMPUTE | LIST | STATISTICS | ANALYZE | PARTITIONED | EXTERNAL | DEFINED | RECORDWRITER | REVOKE | GRANT | LOCK | UNLOCK | MSCK | REPAIR | RECOVER | EXPORT | IMPORT | LOAD | VALUES | COMMENT | ROLE | ROLES | COMPACTIONS | PRINCIPALS | TRANSACTIONS | INDEX | INDEXES | LOCKS | OPTION | LOCAL | INPATH | ASC | DESC | LIMIT | RENAME | SETS | AT | NULLS | OVERWRITE | ALL | ALTER | AS | BETWEEN | BY | CREATE | DELETE | DESCRIBE | DROP | EXISTS | FALSE | FOR | GROUP | IN | INSERT | INTO | IS |LIKE | NULL | ORDER | OUTER | TABLE | TRUE | WITH | RLIKE | AND | CASE | CAST | DISTINCT | DIV | ELSE | END | FUNCTION | INTERVAL | MACRO | OR | STRATIFY | THEN | UNBOUNDED | WHEN | DATABASE | SELECT | FROM | WHERE | HAVING | TO | TABLE | WITH | NOT | CURRENT_DATE | CURRENT_TIMESTAMP ; SELECT: 'SELECT'; FROM: 'FROM'; ADD: 'ADD'; AS: 'AS'; ALL: 'ALL'; DISTINCT: 'DISTINCT'; WHERE: 'WHERE'; GROUP: 'GROUP'; BY: 'BY'; GROUPING: 'GROUPING'; SETS: 'SETS'; CUBE: 'CUBE'; ROLLUP: 'ROLLUP'; ORDER: 'ORDER'; HAVING: 'HAVING'; LIMIT: 'LIMIT'; AT: 'AT'; OR: 'OR'; AND: 'AND'; IN: 'IN'; NOT: 'NOT' | '!'; NO: 'NO'; EXISTS: 'EXISTS'; BETWEEN: 'BETWEEN'; LIKE: 'LIKE'; RLIKE: 'RLIKE' | 'REGEXP'; IS: 'IS'; NULL: 'NULL'; TRUE: 'TRUE'; FALSE: 'FALSE'; NULLS: 'NULLS'; ASC: 'ASC'; DESC: 'DESC'; FOR: 'FOR'; INTERVAL: 'INTERVAL'; CASE: 'CASE'; WHEN: 'WHEN'; THEN: 'THEN'; ELSE: 'ELSE'; END: 'END'; JOIN: 'JOIN'; CROSS: 'CROSS'; OUTER: 'OUTER'; INNER: 'INNER'; LEFT: 'LEFT'; SEMI: 'SEMI'; RIGHT: 'RIGHT'; FULL: 'FULL'; NATURAL: 'NATURAL'; ON: 'ON'; LATERAL: 'LATERAL'; WINDOW: 'WINDOW'; OVER: 'OVER'; PARTITION: 'PARTITION'; RANGE: 'RANGE'; ROWS: 'ROWS'; UNBOUNDED: 'UNBOUNDED'; PRECEDING: 'PRECEDING'; FOLLOWING: 'FOLLOWING'; CURRENT: 'CURRENT'; FIRST: 'FIRST'; AFTER: 'AFTER'; LAST: 'LAST'; ROW: 'ROW'; WITH: 'WITH'; VALUES: 'VALUES'; CREATE: 'CREATE'; TABLE: 'TABLE'; VIEW: 'VIEW'; REPLACE: 'REPLACE'; INSERT: 'INSERT'; DELETE: 'DELETE'; INTO: 'INTO'; DESCRIBE: 'DESCRIBE'; EXPLAIN: 'EXPLAIN'; FORMAT: 'FORMAT'; LOGICAL: 'LOGICAL'; CODEGEN: 'CODEGEN'; COST: 'COST'; CAST: 'CAST'; SHOW: 'SHOW'; TABLES: 'TABLES'; COLUMNS: 'COLUMNS'; COLUMN: 'COLUMN'; USE: 'USE'; PARTITIONS: 'PARTITIONS'; FUNCTIONS: 'FUNCTIONS'; DROP: 'DROP'; UNION: 'UNION'; EXCEPT: 'EXCEPT'; SETMINUS: 'MINUS'; INTERSECT: 'INTERSECT'; TO: 'TO'; TABLESAMPLE: 'TABLESAMPLE'; STRATIFY: 'STRATIFY'; ALTER: 'ALTER'; RENAME: 'RENAME'; ARRAY: 'ARRAY'; MAP: 'MAP'; STRUCT: 'STRUCT'; COMMENT: 'COMMENT'; SET: 'SET'; RESET: 'RESET'; DATA: 'DATA'; START: 'START'; TRANSACTION: 'TRANSACTION'; COMMIT: 'COMMIT'; ROLLBACK: 'ROLLBACK'; MACRO: 'MACRO'; IGNORE: 'IGNORE'; IF: 'IF'; POSITION: 'POSITION'; EQ : '=' | '=='; NSEQ: '<=>'; NEQ : '<>'; NEQJ: '!='; LT : '<'; LTE : '<=' | '!>'; GT : '>'; GTE : '>=' | '!<'; PLUS: '+'; MINUS: '-'; ASTERISK: '*'; SLASH: '/'; PERCENT: '%'; DIV: 'DIV'; TILDE: '~'; AMPERSAND: '&'; PIPE: '|'; CONCAT_PIPE: '||'; HAT: '^'; PERCENTLIT: 'PERCENT'; BUCKET: 'BUCKET'; OUT: 'OUT'; OF: 'OF'; SORT: 'SORT'; CLUSTER: 'CLUSTER'; DISTRIBUTE: 'DISTRIBUTE'; OVERWRITE: 'OVERWRITE'; TRANSFORM: 'TRANSFORM'; REDUCE: 'REDUCE'; USING: 'USING'; SERDE: 'SERDE'; SERDEPROPERTIES: 'SERDEPROPERTIES'; RECORDREADER: 'RECORDREADER'; RECORDWRITER: 'RECORDWRITER'; DELIMITED: 'DELIMITED'; FIELDS: 'FIELDS'; TERMINATED: 'TERMINATED'; COLLECTION: 'COLLECTION'; ITEMS: 'ITEMS'; KEYS: 'KEYS'; ESCAPED: 'ESCAPED'; LINES: 'LINES'; SEPARATED: 'SEPARATED'; FUNCTION: 'FUNCTION'; EXTENDED: 'EXTENDED'; REFRESH: 'REFRESH'; CLEAR: 'CLEAR'; CACHE: 'CACHE'; UNCACHE: 'UNCACHE'; LAZY: 'LAZY'; FORMATTED: 'FORMATTED'; GLOBAL: 'GLOBAL'; TEMPORARY: 'TEMPORARY' | 'TEMP'; OPTIONS: 'OPTIONS'; UNSET: 'UNSET'; TBLPROPERTIES: 'TBLPROPERTIES'; DBPROPERTIES: 'DBPROPERTIES'; BUCKETS: 'BUCKETS'; SKEWED: 'SKEWED'; STORED: 'STORED'; DIRECTORIES: 'DIRECTORIES'; LOCATION: 'LOCATION'; EXCHANGE: 'EXCHANGE'; ARCHIVE: 'ARCHIVE'; UNARCHIVE: 'UNARCHIVE'; FILEFORMAT: 'FILEFORMAT'; TOUCH: 'TOUCH'; COMPACT: 'COMPACT'; CONCATENATE: 'CONCATENATE'; CHANGE: 'CHANGE'; CASCADE: 'CASCADE'; RESTRICT: 'RESTRICT'; CLUSTERED: 'CLUSTERED'; SORTED: 'SORTED'; PURGE: 'PURGE'; INPUTFORMAT: 'INPUTFORMAT'; OUTPUTFORMAT: 'OUTPUTFORMAT'; DATABASE: 'DATABASE' | 'SCHEMA'; DATABASES: 'DATABASES' | 'SCHEMAS'; DFS: 'DFS'; TRUNCATE: 'TRUNCATE'; ANALYZE: 'ANALYZE'; COMPUTE: 'COMPUTE'; LIST: 'LIST'; STATISTICS: 'STATISTICS'; PARTITIONED: 'PARTITIONED'; EXTERNAL: 'EXTERNAL'; DEFINED: 'DEFINED'; REVOKE: 'REVOKE'; GRANT: 'GRANT'; LOCK: 'LOCK'; UNLOCK: 'UNLOCK'; MSCK: 'MSCK'; REPAIR: 'REPAIR'; RECOVER: 'RECOVER'; EXPORT: 'EXPORT'; IMPORT: 'IMPORT'; LOAD: 'LOAD'; ROLE: 'ROLE'; ROLES: 'ROLES'; COMPACTIONS: 'COMPACTIONS'; PRINCIPALS: 'PRINCIPALS'; TRANSACTIONS: 'TRANSACTIONS'; INDEX: 'INDEX'; INDEXES: 'INDEXES'; LOCKS: 'LOCKS'; OPTION: 'OPTION'; ANTI: 'ANTI'; LOCAL: 'LOCAL'; INPATH: 'INPATH'; CURRENT_DATE: 'CURRENT_DATE'; CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'; STRING : '\\'' ( ~('\\''|'\\\\') | ('\\\\' .) )* '\\'' | '""' ( ~('""'|'\\\\') | ('\\\\' .) )* '""' ; BIGINT_LITERAL : DIGIT+ 'L' ; SMALLINT_LITERAL : DIGIT+ 'S' ; TINYINT_LITERAL : DIGIT+ 'Y' ; BYTELENGTH_LITERAL : DIGIT+ ('B' | 'K' | 'M' | 'G') ; INTEGER_VALUE : DIGIT+ ; DECIMAL_VALUE : DIGIT+ EXPONENT | DECIMAL_DIGITS EXPONENT? {isValidDecimal()}? ; DOUBLE_LITERAL : DIGIT+ EXPONENT? 'D' | DECIMAL_DIGITS EXPONENT? 'D' {isValidDecimal()}? ; BIGDECIMAL_LITERAL : DIGIT+ EXPONENT? 'BD' | DECIMAL_DIGITS EXPONENT? 'BD' {isValidDecimal()}? ; IDENTIFIER : (LETTER | DIGIT | '_')+ ; BACKQUOTED_IDENTIFIER : '`' ( ~'`' | '``' )* '`' ; fragment DECIMAL_DIGITS : DIGIT+ '.' DIGIT* | '.' DIGIT+ ; fragment EXPONENT : 'E' [+-]? DIGIT+ ; fragment DIGIT : [0-9] ; fragment LETTER : [A-Z] ; SIMPLE_COMMENT : '--' ~[\\r\\n]* '\\r'? '\\n'? -> channel(HIDDEN) ; BRACKETED_EMPTY_COMMENT : '/**/' -> channel(HIDDEN) ; BRACKETED_COMMENT : '/*' ~[+] .*? '*/' -> channel(HIDDEN) ; WS : [ \\r\\n\\t]+ -> channel(HIDDEN) ; // Catch-all for anything we can't recognize. // We use this to be able to ignore and recover all the text // when splitting statements with DelimiterLexer UNRECOGNIZED : . ; ",8263,False,1578.390123317058,median