text:
copyright:
  years: 2016, 2017
lastupdated: "2017-02-24"

---

{:new_window: target="_blank"}
{:shortdesc: .shortdesc}
{:screen: .screen}
{:codeblock: .codeblock}
{:pre: .pre}

# Definizione delle politiche
{: #policies}

Le politiche controllano i gate nella tua delivery pipeline continua. Se il tuo codice non soddisfa o supera una politica approvata in un gate particolare, la distribuzione viene arrestata per prevenire che vengano rilasciati dei rischi.
{:shortdesc}

Definisci le politiche in {{site.data.keyword.DRA_short}}. Le politiche sono create nell'organizzazione (org) {{site.data.keyword.Bluemix_notm}} che contiene {{site.data.keyword.DRA_short}}. Tutte le applicazioni nella stessa organizzazione possono utilizzare la politica.

Per definire una politica:

1. Dal menu di navigazione di sinistra, fai clic su **Settings**.

2. Fai clic su **Policy**.

3. Fai clic su **Create Policy** e immetti quindi un nome e una descrizione per la nuova politica.

4. Fai clic su **Next**.

4. Aggiungi almeno una regola alla politica:
  1. Fai clic su **Add Rule to Policy**.
  2. Seleziona il tipo di regola.
  3. Immetti i dettagli e le condizioni per la regola.
  4. Fai clic su **Save**.

5. Quando ha terminato di aggiungere le regole alla politica, fai clic su **Complete**.

## Creazione di regole
{: #criteria}

Le regole definiscono i criteri che le tue politiche utilizzano per valutare un esito positivo o negativo. Potresti creare una politica "Unit Testing and Test Coverage" che contiene una regola di verifica dell'unità che richiede l'80% di esito positivo della verifica dell'unità e una regola di copertura del test che richiede il 100% di copertura di codice. Se aggiungi un gate che fa riferimento a questa regola in una pipeline, il gate previene a tutte le build che non soddisfano entrambe le regole di procedere.

Puoi richiedere l'esito positivo indipendentemente se hai contrassegnato i test come critici. Per creare una regola, seleziona una politica e fai clic su **Add Rule to Policy**.

### Creazione di regole di test di verifica funzionali
{: #criteria_fvt}

1. Immetti un descrizione e seleziona un formato.

2. Specifica la percentuale di scenari di test che deve essere superata per essere considerata con esito positivo.

3. Definisci ogni scenario di test che è critico.

4. Per monitorare le regressioni dello scenario di test, seleziona la casella di spunta **Monitor for test case regression**.

5. Fai clic su **Save**.

### Creazione di regole di verifica dell'unità
{: #criteria_ut}

1. Immetti un descrizione e seleziona un formato.

2. Specifica la percentuale di scenari di test che deve essere superata per essere considerata con esito positivo.

3. Definisci ogni scenario di test che è critico.

4. Per monitorare le regressioni dello scenario di test, seleziona la casella di spunta **Monitor for test case regression**.

5. Fai clic su **Save**.

### Creazione di regole di copertura del codice
{: #criteria_codecoverage}

1. Immetti un descrizione e seleziona un formato.

2. Specifica la percentuale di copertura del codice necessaria per essere considerato con esito positivo.

3. Per monitorare le regressioni di copertura del codice, seleziona la casella di spunta **Monitor for test case regression**.

4. Fai clic su **Save**.

### Creazione di regole di scansione di sicurezza statica
{: #criteria_static}

1. Immetti una descrizione.

2. Specifica i numeri massimi dei problemi di severità bassa, alta e media consentiti dalla regola.

3. Fai clic su **Save**.

### Creazione di regole di scansione di sicurezza dinamica
{: #criteria_dynamic}

1. Immetti una descrizione.

2. Specifica i numeri massimi dei problemi di severità bassa, alta e media consentiti dalla regola.

3. Fai clic su **Save**.

## Verifica strumenti e formati del risultato

{{site.data.keyword.DRA_short}} supporta questi tipi di metriche e formati:

* Test di verifica funzionale (Mocha, xUnit)
* Verifiche di unità (Mocha, xUnit, Karma/Mocha)
* Copertura del codice (Istanbul come formato di riepilogo JSON, Blanket.js)

{{site.data.keyword.DRA_short}} supporta inoltre i test Selenium e Jasmine. Questi test devono essere inclusi negli strumenti supportati ufficiali, come xUnit e Mocha. Per ulteriori informazioni sull'utilizzo contemporaneo di {{site.data.keyword.deliverypipeline}}, {{site.data.keyword.DRA_short}} e Selenium, consulta [Running Selenium tests from the command line on a delivery pipeline](https://developer.ibm.com/devops-services/2016/07/21/running-selenium-tests-command-line-delivery-pipeline/).

Per gli elementi con scenari di test, puoi specificare gli scenari di test critici, che sono test che devono essere superati indipendentemente dalla percentuale accettabile. Il nome degli scenari di test critici devono corrispondere all'attributo `full title` dello scenario di test.
* Per i test Karma/Mocha, le stringhe della descrizione `describe()` e `it()` sono collegate tra loro con gli spazi.
* Per i test xUnit, il nome del pacchetto e della funzione sono collegati tra loro con gli spazi. Ciò è riportato nel seguente esempio:
  ```
  <testsuites package="test">
    <testsuite package="otc-api" name="PUT Service Instances - Test Setup" tests="2" failures="0" errors="0">
      <testcase name="#1 Authorization passed for mock user: idsb3t1@us.ibm.com"/>
      <testcase name="#2 Authorization passed for mock user: idsb3t4@us.ibm.com"/>
    </testsuite>
  </testsuite>
  ```
  Questo esempio produce questi nomi di scenari di test:
  ```
  test otc-api PUT Service Instances - Test Setup #1 Authorization passed for mock user: idsb3t1@us.ibm.com
  test otc-api PUT Service Instances - Test Setup #2 Authorization passed for mock user: idsb3t1@us.ibm.com
  ```

Puoi utilizzare Sauce Labs con {{site.data.keyword.DRA_short}} aggiungendo l'integrazione dello strumento Sauce Labs alla tua pipeline. Quindi, incorpora le variabili di ambiente `SAUCE_USERNAME` e `SAUCE_ACCESS_KEY` nei test Selenium come credenziali.

Puoi visualizzare i titoli completi di tutti i test nei log dopo un'esecuzione.

**Note:**
* {{site.data.keyword.DRA_short}} non supporta i test critici che contengono un trattino nel titolo completo.
* Se modifichi il tuo nome dell'organizzazione, devi ricreare le politiche che sono state associate con il nome precedente. Perderai l'accesso a tutti i report di decisione generati prima della modifica del nome.

## Visualizzazione dei report di decisione
{: #DI_decision_reports}

Dopo aver eseguito una pipeline, {{site.data.keyword.DRA_short}} inizia a raccogliere e analizzare i risultati del test da essa per stabilire una linea di base. I dati di ogni successiva esecuzione sono raccolti e confrontati con i risultati precedenti. I gate di decisione utilizzano questi dati per determinare quando arrestare una distribuzione.

Per visualizzare il report di decisione per un gate dalla pipeline, completa questi passi:

   1. Nella fase che contiene il gate da verificare, fai clic su **Visualizza log e cronologia**.

   2. Dal lavoro che contiene il gate, fai clic sul nome del gate.

   3. Nella vista del log, individua il messaggio `Check {{site.data.keyword.DRA_short}} report here` e fai clic sul link per aprire il report.


text:
package org.apache.lucene.index;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import org.apache.lucene.store.FSDirectory;

/**
 * Command-line tool that enables listing segments in an
 * index, copying specific segments to another index, and
 * deleting segments from an index.
 *
 *
This tool does file-level copying of segments files.
 * This means it's unable to split apart a single segment
 * into multiple segments.  For example if your index is
 * optimized, this tool won't help.  Also, it does basic
 * file-level copying (using simple
 * File{In,Out}putStream) so it will not work with non
 * FSDirectory Directory impls.

 *
 *
NOTE: The tool is experimental and might change
 * in incompatible ways in the next release.  You can easily
 * accidentally remove segments from your index so be
 * careful!
 */
public class IndexSplitter {
  public SegmentInfos infos;

  FSDirectory fsDir;

  File dir;

  /**
   * @param args
   */
  public static void main(String[] args) throws Exception {
    if (args.length < 2) {
      System.err
          .println("Usage: IndexSplitter <srcDir> -l (list the segments and their sizes)");
      System.err.println("IndexSplitter <srcDir> <destDir> <segments>+");
      System.err
          .println("IndexSplitter <srcDir> -d (delete the following segments)");
      return;
    }
    File srcDir = new File(args[0]);
    IndexSplitter is = new IndexSplitter(srcDir);
    if (!srcDir.exists()) {
      throw new Exception("srcdir:" + srcDir.getAbsolutePath()
          + " doesn't exist");
    }
    if (args[1].equals("-l")) {
      is.listSegments();
    } else if (args[1].equals("-d")) {
      List<String> segs = new ArrayList<String>();
      for (int x = 2; x < args.length; x++) {
        segs.add(args[x]);
      }
      is.remove(segs.toArray(new String[0]));
    } else {
      File targetDir = new File(args[1]);
      List<String> segs = new ArrayList<String>();
      for (int x = 2; x < args.length; x++) {
        segs.add(args[x]);
      }
      is.split(targetDir, segs.toArray(new String[0]));
    }
  }

  public IndexSplitter(File dir) throws IOException {
    this.dir = dir;
    fsDir = FSDirectory.open(dir);
    infos = new SegmentInfos();
    infos.read(fsDir);
  }

  public void listSegments() throws IOException {
    DecimalFormat formatter = new DecimalFormat("###,###.###");
    for (int x = 0; x < infos.size(); x++) {
      SegmentInfo info = infos.info(x);
      String sizeStr = formatter.format(info.sizeInBytes());
      System.out.println(info.name + " " + sizeStr);
    }
  }

  private int getIdx(String name) {
    for (int x = 0; x < infos.size(); x++) {
      if (name.equals(infos.info(x).name))
        return x;
    }
    return -1;
  }

  private SegmentInfo getInfo(String name) {
    for (int x = 0; x < infos.size(); x++) {
      if (name.equals(infos.info(x).name))
        return infos.info(x);
    }
    return null;
  }

  public void remove(String[] segs) throws IOException {
    for (String n : segs) {
      int idx = getIdx(n);
      infos.remove(idx);
    }
    infos.commit(fsDir);
  }

  public void split(File destDir, String[] segs) throws IOException {
    destDir.mkdirs();
    FSDirectory destFSDir = FSDirectory.open(destDir);
    SegmentInfos destInfos = new SegmentInfos();
    for (String n : segs) {
      SegmentInfo info = getInfo(n);
      destInfos.add(info);
      // now copy files over
      List<String> files = info.files();
      for (final String srcName : files) {
        File srcFile = new File(dir, srcName);
        File destFile = new File(destDir, srcName);
        copyFile(srcFile, destFile);
      }
    }
    destInfos.commit(destFSDir);
    // System.out.println("destDir:"+destDir.getAbsolutePath());
  }

  private static final byte[] copyBuffer = new byte[32*1024];

  private static void copyFile(File src, File dst) throws IOException {
    InputStream in = new FileInputStream(src);
    OutputStream out = new FileOutputStream(dst);
    int len;
    while ((len = in.read(copyBuffer)) > 0) {
      out.write(copyBuffer, 0, len);
    }
    in.close();
    out.close();
  }
}

redpajama_set_name: RedPajamaGithub


text:
from __future__ import division
from datetime import datetime, timedelta
import hashlib
import logging
import os
import struct

from babelfish import Error as BabelfishError, Language
from enzyme import Error as EnzymeError, MKV
from guessit import guess_episode_info, guess_file_info, guess_movie_info

logger = logging.getLogger(__name__)

#: Video extensions
VIDEO_EXTENSIONS = ('.3g2', '.3gp', '.3gp2', '.3gpp', '.60d', '.ajp', '.asf', '.asx', '.avchd', '.avi', '.bik',
                    '.bix', '.box', '.cam', '.dat', '.divx', '.dmf', '.dv', '.dvr-ms', '.evo', '.flc', '.fli',
                    '.flic', '.flv', '.flx', '.gvi', '.gvp', '.h264', '.m1v', '.m2p', '.m2ts', '.m2v', '.m4e',
                    '.m4v', '.mjp', '.mjpeg', '.mjpg', '.mkv', '.moov', '.mov', '.movhd', '.movie', '.movx', '.mp4',
                    '.mpe', '.mpeg', '.mpg', '.mpv', '.mpv2', '.mxf', '.nsv', '.nut', '.ogg', '.ogm', '.omf', '.ps',
                    '.qt', '.ram', '.rm', '.rmvb', '.swf', '.ts', '.vfw', '.vid', '.video', '.viv', '.vivo', '.vob',
                    '.vro', '.wm', '.wmv', '.wmx', '.wrap', '.wvx', '.wx', '.x264', '.xvid')

#: Subtitle extensions
SUBTITLE_EXTENSIONS = ('.srt', '.sub', '.smi', '.txt', '.ssa', '.ass', '.mpl')

class Video(object):
    """Base class for videos.

    Represent a video, existing or not. Attributes have an associated score based on equations defined in
    :mod:`~subliminal.score`.

    :param str name: name or path of the video.
    :param str format: format of the video (HDTV, WEB-DL, BluRay, ...).
    :param str release_group: release group of the video.
    :param str resolution: resolution of the video stream (480p, 720p, 1080p or 1080i).
    :param str video_codec: codec of the video stream.
    :param str audio_codec: codec of the main audio stream.
    :param int imdb_id: IMDb id of the video.
    :param dict hashes: hashes of the video file by provider names.
    :param int size: size of the video file in bytes.
    :param set subtitle_languages: existing subtitle languages

    """
    #: Score by match property
    scores = {}

    def __init__(self, name, format=None, release_group=None, resolution=None, video_codec=None, audio_codec=None,
                 imdb_id=None, hashes=None, size=None, subtitle_languages=None):
        #: Name or path of the video
        self.name = name

        #: Format of the video (HDTV, WEB-DL, BluRay, ...)
        self.format = format

        #: Release group of the video
        self.release_group = release_group

        #: Resolution of the video stream (480p, 720p, 1080p or 1080i)
        self.resolution = resolution

        #: Codec of the video stream
        self.video_codec = video_codec

        #: Codec of the main audio stream
        self.audio_codec = audio_codec

        #: IMDb id of the video
        self.imdb_id = imdb_id

        #: Hashes of the video file by provider names
        self.hashes = hashes or {}

        #: Size of the video file in bytes
        self.size = size

        #: Existing subtitle languages
        self.subtitle_languages = subtitle_languages or set()

    @property
    def exists(self):
        """Test whether the video exists."""
        return os.path.exists(self.name)

    @property
    def age(self):
        """Age of the video."""
        if self.exists:
            return datetime.utcnow() - datetime.utcfromtimestamp(os.path.getmtime(self.name))

        return timedelta()

    @classmethod
    def fromguess(cls, name, guess):
        """Create an :class:`Episode` or a :class:`Movie` with the given `name` based on the `guess`.

        :param str name: name of the video.
        :param dict guess: guessed data, like a :class:`~guessit.guess.Guess` instance.
        :raise: :class:`ValueError` if the `type` of the `guess` is invalid

        """
        if guess['type'] == 'episode':
            return Episode.fromguess(name, guess)

        if guess['type'] == 'movie':
            return Movie.fromguess(name, guess)

        raise ValueError('The guess must be an episode or a movie guess')

    @classmethod
    def fromname(cls, name):
        """Shortcut for :meth:`fromguess` with a `guess` guessed from the `name`.

        :param str name: name of the video.

        """
        return cls.fromguess(name, guess_file_info(name))

    def __repr__(self):
        return '<%s [%r]>' % (self.__class__.__name__, self.name)

    def __hash__(self):
        return hash(self.name)

class Episode(Video):
    """Episode :class:`Video`.

    Scores are defined by a set of equations, see :func:`~subliminal.score.solve_episode_equations`

    :param str series: series of the episode.
    :param int season: season number of the episode.
    :param int episode: episode number of the episode.
    :param str title: title of the episode.
    :param int year: year of series.
    :param int tvdb_id: TVDB id of the episode

    """
    #: Score by match property
    scores = {'hash': 137, 'imdb_id': 110, 'tvdb_id': 88, 'series': 44, 'year': 44, 'title': 22, 'season': 11,
              'episode': 11, 'release_group': 11, 'format': 6, 'video_codec': 4, 'resolution': 4, 'audio_codec': 2,
              'hearing_impaired': 1}

    def __init__(self, name, series, season, episode, format=None, release_group=None, resolution=None,
                 video_codec=None, audio_codec=None, imdb_id=None, hashes=None, size=None, subtitle_languages=None,
                 title=None, year=None, tvdb_id=None):
        super(Episode, self).__init__(name, format, release_group, resolution, video_codec, audio_codec, imdb_id,
                                      hashes, size, subtitle_languages)
        #: Series of the episode
        self.series = series

        #: Season number of the episode
        self.season = season

        #: Episode number of the episode
        self.episode = episode

        #: Title of the episode
        self.title = title

        #: Year of series
        self.year = year

        #: TVDB id of the episode
        self.tvdb_id = tvdb_id

    @classmethod
    def fromguess(cls, name, guess):
        if guess['type'] != 'episode':
            raise ValueError('The guess must be an episode guess')

        if 'series' not in guess or 'season' not in guess or 'episodeNumber' not in guess:
            raise ValueError('Insufficient data to process the guess')

        return cls(name, guess['series'], guess['season'], guess['episodeNumber'], format=guess.get('format'),
                   release_group=guess.get('releaseGroup'), resolution=guess.get('screenSize'),
                   video_codec=guess.get('videoCodec'), audio_codec=guess.get('audioCodec'),
                   title=guess.get('title'), year=guess.get('year'))

    @classmethod
    def fromname(cls, name):
        return cls.fromguess(name, guess_episode_info(name))

    def __repr__(self):
        if self.year is None:
            return '<%s [%r, %dx%d]>' % (self.__class__.__name__, self.series, self.season, self.episode)

        return '<%s [%r, %d, %dx%d]>' % (self.__class__.__name__, self.series, self.year, self.season, self.episode)

class Movie(Video):
    """Movie :class:`Video`.

    Scores are defined by a set of equations, see :func:`~subliminal.score.solve_movie_equations`

    :param str title: title of the movie.
    :param int year: year of the movie

    """
    #: Score by match property
    scores = {'hash': 62, 'imdb_id': 62, 'title': 23, 'year': 12, 'release_group': 11, 'format': 6, 'video_codec': 4,
              'resolution': 4, 'audio_codec': 2, 'hearing_impaired': 1}

    def __init__(self, name, title, format=None, release_group=None, resolution=None, video_codec=None,
                 audio_codec=None, imdb_id=None, hashes=None, size=None, subtitle_languages=None, year=None):
        super(Movie, self).__init__(name, format, release_group, resolution, video_codec, audio_codec, imdb_id, hashes,
                                    size, subtitle_languages)
        #: Title of the movie
        self.title = title

        #: Year of the movie
        self.year = year

    @classmethod
    def fromguess(cls, name, guess):
        if guess['type'] != 'movie':
            raise ValueError('The guess must be a movie guess')

        if 'title' not in guess:
            raise ValueError('Insufficient data to process the guess')

        return cls(name, guess['title'], format=guess.get('format'), release_group=guess.get('releaseGroup'),
                   resolution=guess.get('screenSize'), video_codec=guess.get('videoCodec'),
                   audio_codec=guess.get('audioCodec'), year=guess.get('year'))

    @classmethod
    def fromname(cls, name):
        return cls.fromguess(name, guess_movie_info(name))

    def __repr__(self):
        if self.year is None:
            return '<%s [%r]>' % (self.__class__.__name__, self.title)

        return '<%s [%r, %d]>' % (self.__class__.__name__, self.title, self.year)

def search_external_subtitles(path, directory=None):
    """Search for external subtitles from a video `path` and their associated language.

    Unless `directory` is provided, search will be made in the same directory as the video file.

    :param str path: path to the video.
    :param str directory: directory to search for subtitles.
    :return: found subtitles with their languages.
    :rtype: dict

    """
    dirpath, filename = os.path.split(path)
    dirpath = dirpath or '.'
    fileroot, fileext = os.path.splitext(filename)
    subtitles = {}
    for p in os.listdir(directory or dirpath):
        # keep only valid subtitle filenames
        if not p.startswith(fileroot) or not p.endswith(SUBTITLE_EXTENSIONS):
            continue

        # extract the potential language code
        language_code = p[len(fileroot):-len(os.path.splitext(p)[1])].replace(fileext, '').replace('_', '-')[1:]

        # default language is undefined
        language = Language('und')

        # attempt to parse
        if language_code:
            try:
                language = Language.fromietf(language_code)
            except ValueError:
                logger.error('Cannot parse language code %r', language_code)

        subtitles[p] = language

    logger.debug('Found subtitles %r', subtitles)

    return subtitles

def scan_video(path, subtitles=True, embedded_subtitles=True, subtitles_dir=None):
    """Scan a video and its subtitle languages from a video `path`.

    :param str path: existing path to the video.
    :param bool subtitles: scan for subtitles with the same name.
    :param bool embedded_subtitles: scan for embedded subtitles.
    :param str subtitles_dir: directory to search for subtitles.
    :return: the scanned video.
    :rtype: :class:`Video`

    """
    # check for non-existing path
    if not os.path.exists(path):
        raise ValueError('Path does not exist')

    # check video extension
    if not path.endswith(VIDEO_EXTENSIONS):
        raise ValueError('%s is not a valid video extension' % os.path.splitext(path)[1])

    dirpath, filename = os.path.split(path)
    logger.info('Scanning video %r in %r', filename, dirpath)

    # guess
    video = Video.fromguess(path, guess_file_info(path))

    # size and hashes
    video.size = os.path.getsize(path)
    if video.size > 10485760:
        logger.debug('Size is %d', video.size)
        video.hashes['opensubtitles'] = hash_opensubtitles(path)
        video.hashes['thesubdb'] = hash_thesubdb(path)
        video.hashes['shooter'] = hash_shooter(path)
        video.hashes['napiprojekt'] = hash_napiprojekt(path)
        logger.debug('Computed hashes %r', video.hashes)
    else:
        logger.warning('Size is lower than 10MB: hashes not computed')

    # external subtitles
    if subtitles:
        video.subtitle_languages |= set(search_external_subtitles(path, directory=subtitles_dir).values())

    # video metadata with enzyme
    try:
        if filename.endswith('.mkv'):
            with open(path, 'rb') as f:
                mkv = MKV(f)

            # main video track
            if mkv.video_tracks:
                video_track = mkv.video_tracks[0]

                # resolution
                if video_track.height in (480, 720, 1080):
                    if video_track.interlaced:
                        video.resolution = '%di' % video_track.height
                    else:
                        video.resolution = '%dp' % video_track.height
                    logger.debug('Found resolution %s with enzyme', video.resolution)

                # video codec
                if video_track.codec_id == 'V_MPEG4/ISO/AVC':
                    video.video_codec = 'h264'
                    logger.debug('Found video_codec %s with enzyme', video.video_codec)
                elif video_track.codec_id == 'V_MPEG4/ISO/SP':
                    video.video_codec = 'DivX'
                    logger.debug('Found video_codec %s with enzyme', video.video_codec)
                elif video_track.codec_id == 'V_MPEG4/ISO/ASP':
                    video.video_codec = 'XviD'
                    logger.debug('Found video_codec %s with enzyme', video.video_codec)
            else:
                logger.warning('MKV has no video track')

            # main audio track
            if mkv.audio_tracks:
                audio_track = mkv.audio_tracks[0]
                # audio codec
                if audio_track.codec_id == 'A_AC3':
                    video.audio_codec = 'AC3'
                    logger.debug('Found audio_codec %s with enzyme', video.audio_codec)
                elif audio_track.codec_id == 'A_DTS':
                    video.audio_codec = 'DTS'
                    logger.debug('Found audio_codec %s with enzyme', video.audio_codec)
                elif audio_track.codec_id == 'A_AAC':
                    video.audio_codec = 'AAC'
                    logger.debug('Found audio_codec %s with enzyme', video.audio_codec)
            else:
                logger.warning('MKV has no audio track')

            # subtitle tracks
            if mkv.subtitle_tracks:
                if embedded_subtitles:
                    embedded_subtitle_languages = set()
                    for st in mkv.subtitle_tracks:
                        if st.language:
                            try:
                                embedded_subtitle_languages.add(Language.fromalpha3b(st.language))
                            except BabelfishError:
                                logger.error('Embedded subtitle track language %r is not a valid language', st.language)
                                embedded_subtitle_languages.add(Language('und'))
                        elif st.name:
                            try:
                                embedded_subtitle_languages.add(Language.fromname(st.name))
                            except BabelfishError:
                                logger.debug('Embedded subtitle track name %r is not a valid language', st.name)
                                embedded_subtitle_languages.add(Language('und'))
                        else:
                            embedded_subtitle_languages.add(Language('und'))
                    logger.debug('Found embedded subtitle %r with enzyme', embedded_subtitle_languages)
                    video.subtitle_languages |= embedded_subtitle_languages
            else:
                logger.debug('MKV has no subtitle track')

    except:
        logger.exception('Parsing video metadata with enzyme failed')

    return video

def scan_videos(path, subtitles=True, embedded_subtitles=True, subtitles_dir=None):
    """Scan `path` for videos and their subtitles.

    :param str path: existing directory path to scan.
    :param bool subtitles: scan for subtitles with the same name.
    :param bool embedded_subtitles: scan for embedded subtitles.
    :param str subtitles_dir: directory to search for subtitles.
    :return: the scanned videos.
    :rtype: list of :class:`Video`

    """
    # check for non-existing path
    if not os.path.exists(path):
        raise ValueError('Path does not exist')

    # check for non-directory path
    if not os.path.isdir(path):
        raise ValueError('Path is not a directory')

    # walk the path
    videos = []
    for dirpath, dirnames, filenames in os.walk(path):
        logger.debug('Walking directory %s', dirpath)

        # remove badly encoded and hidden dirnames
        for dirname in list(dirnames):
            if dirname.startswith('.'):
                logger.debug('Skipping hidden dirname %r in %r', dirname, dirpath)
                dirnames.remove(dirname)

        # scan for videos
        for filename in filenames:
            # filter on videos
            if not filename.endswith(VIDEO_EXTENSIONS):
                continue

            # skip hidden files
            if filename.startswith('.'):
                logger.debug('Skipping hidden filename %r in %r', filename, dirpath)
                continue

            # reconstruct the file path
            filepath = os.path.join(dirpath, filename)

            # skip links
            if os.path.islink(filepath):
                logger.debug('Skipping link %r in %r', filename, dirpath)
                continue

            # scan video
            try:
                video = scan_video(filepath, subtitles=subtitles, embedded_subtitles=embedded_subtitles,
                                   subtitles_dir=subtitles_dir)
            except ValueError:  # pragma: no cover
                logger.exception('Error scanning video')
                continue

            videos.append(video)

    return videos

def hash_opensubtitles(video_path):
    """Compute a hash using OpenSubtitles' algorithm.

    :param str video_path: path of the video.
    :return: the hash.
    :rtype: str

    """
    bytesize = struct.calcsize(b'<q')
    with open(video_path, 'rb') as f:
        filesize = os.path.getsize(video_path)
        filehash = filesize
        if filesize < 65536 * 2:
            return
        for _ in range(65536 // bytesize):
            filebuffer = f.read(bytesize)
            (l_value,) = struct.unpack(b'<q', filebuffer)
            filehash += l_value
            filehash &= 0xFFFFFFFFFFFFFFFF  # to remain as 64bit number
        f.seek(max(0, filesize - 65536), 0)
        for _ in range(65536 // bytesize):
            filebuffer = f.read(bytesize)
            (l_value,) = struct.unpack(b'<q', filebuffer)
            filehash += l_value
            filehash &= 0xFFFFFFFFFFFFFFFF
    returnedhash = '%016x' % filehash

    return returnedhash

def hash_thesubdb(video_path):
    """Compute a hash using TheSubDB's algorithm.

    :param str video_path: path of the video.
    :return: the hash.
    :rtype: str

    """
    readsize = 64 * 1024
    if os.path.getsize(video_path) < readsize:
        return
    with open(video_path, 'rb') as f:
        data = f.read(readsize)
        f.seek(-readsize, os.SEEK_END)
        data += f.read(readsize)

    return hashlib.md5(data).hexdigest()

def hash_shooter(video_path):
    """Compute a hash using Shooter's algorithm

    :param string video_path: path of the video
    :return: the hash
    :rtype: str

    """

    readsize = 4096
    size = os.path.getsize(video_path)
    if size < 8192:
        return None
    with open(video_path, 'rb') as f:
        digest = []
        for offset in [4096, size//3*2, size//3, size - 8192]:
            f.seek(offset,0)
            data = f.read(4096)
            digest.append(hashlib.md5(data).hexdigest())
    return ';'.join(digest)

def hash_napiprojekt(video_path):
    """Compute a hash using NapiProjekt's algorithm.

    :param str video_path: path of the video.
    :return: the hash.
    :rtype: str

    """
    readsize = 1024 * 1024 * 10
    with open(video_path, 'rb') as f:
        data = f.read(readsize)
    return hashlib.md5(data).hexdigest()


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="RuntimeTypeInfo.cs" company="Kephas Software SRL">
//   Copyright (c) Kephas Software SRL. All rights reserved.
//   Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
// <summary>
//   Provides optimized access to methods and properties at runtime.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Kephas.Runtime
{
    using System;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Linq;
    using System.Linq.Expressions;
    using System.Reflection;

    using Kephas.Collections;
    using Kephas.Diagnostics.Contracts;
    using Kephas.Logging;
    using Kephas.Reflection;
    using Kephas.Resources;
    using Kephas.Services;

    /// <summary>
    /// An object activator delegate.
    /// </summary>
    /// <param name="args">A variable-length parameters list containing arguments.</param>
    /// <returns>
    /// An object.
    /// </returns>
    internal delegate object InstanceActivator(params object?[] args);

    /// <summary>
    /// Provides optimized and extensible access to a type's methods and properties at runtime.
    /// </summary>
    public class RuntimeTypeInfo : RuntimeElementInfoBase, IRuntimeTypeInfo, IEquatable<RuntimeTypeInfo>
    {
        private static readonly Type RuntimeFieldInfoGenericType = typeof(RuntimeFieldInfo<,>);
        private static readonly Type RuntimeFieldInfoType = typeof(RuntimeFieldInfo);
        private static readonly Type RuntimePropertyInfoGenericType = typeof(RuntimePropertyInfo<,>);
        private static readonly Type RuntimePropertyInfoType = typeof(RuntimePropertyInfo);

        private IDictionary<string, IRuntimeFieldInfo> fields;
        private IDictionary<string, IRuntimePropertyInfo> properties;
        private IDictionary<string, ICollection<IRuntimeMethodInfo>> methods;
        private IDictionary<string, IRuntimeElementInfo> members;

        /// <summary>
        /// The base <see cref="ITypeInfo"/>s.
        /// </summary>
        private IReadOnlyList<ITypeInfo> baseTypes;

        /// <summary>
        /// The generic type parameters.
        /// </summary>
        private IReadOnlyList<ITypeInfo> genericTypeParameters;

        /// <summary>
        /// The generic type arguments.
        /// </summary>
        private IReadOnlyList<ITypeInfo> genericTypeArguments;

        /// <summary>
        /// The generic type definition.
        /// </summary>
        private ITypeInfo? genericTypeDefinition;

        /// <summary>
        /// The default value.
        /// </summary>
        private object defaultValue;

        /// <summary>
        /// True if default value created.
        /// </summary>
        private bool defaultValueCreated;

        /// <summary>
        /// The instance activator.
        /// </summary>
        private InstanceActivator instanceActivator;

        /// <summary>
        /// The declaring container.
        /// </summary>
        private IRuntimeAssemblyInfo declaringContainer;

        /// <summary>
        /// Initializes a new instance of the <see cref="RuntimeTypeInfo"/> class.
        /// </summary>
        /// <param name="typeRegistry">The container type serviceRegistry.</param>
        /// <param name="typeInfo">The <see cref="TypeInfo"/>.</param>
        /// <param name="logger">Optional. The logger.</param>
        internal RuntimeTypeInfo(IRuntimeTypeRegistry typeRegistry, TypeInfo typeInfo, ILogger? logger = null)
            : this(typeRegistry, typeInfo.AsType(), typeInfo, logger)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="RuntimeTypeInfo"/> class.
        /// </summary>
        /// <param name="typeRegistry">The container type serviceRegistry.</param>
        /// <param name="type">The type.</param>
        /// <param name="logger">Optional. The logger.</param>
        protected internal RuntimeTypeInfo(IRuntimeTypeRegistry typeRegistry, Type type, ILogger? logger = null)
            : this(typeRegistry, type, type.GetTypeInfo(), logger)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="RuntimeTypeInfo"/> class.
        /// </summary>
        /// <param name="typeRegistry">The container type serviceRegistry.</param>
        /// <param name="type">The type.</param>
        /// <param name="typeInfo">The <see cref="TypeInfo"/>.</param>
        /// <param name="logger">The logger.</param>
        private RuntimeTypeInfo(IRuntimeTypeRegistry typeRegistry, Type type, TypeInfo typeInfo, ILogger? logger)
            : base(typeRegistry, logger)
        {
            this.Type = type;
            this.TypeInfo = typeInfo;
            this.Name = type.Name;
            this.FullName = typeInfo.FullName;
            this.Namespace = type.Namespace;
        }

        /// <summary>
        /// Gets the name of the type.
        /// </summary>
        /// <value>
        /// The name of the type.
        /// </value>
        public string Name { get; }

        /// <summary>
        /// Gets the full name of the element.
        /// </summary>
        /// <value>
        /// The full name of the element.
        /// </value>
        public string FullName { get; }

        /// <summary>
        /// Gets the full name qualified with the module where it was defined.
        /// </summary>
        /// <value>
        /// The full name qualified with the module.
        /// </value>
        public string QualifiedFullName => this.TypeInfo.GetQualifiedFullName();

        /// <summary>
        /// Gets the namespace of the type.
        /// </summary>
        /// <value>
        /// The namespace of the type.
        /// </value>
        public string Namespace { get; }

        /// <summary>
        /// Gets the default value of the type.
        /// </summary>
        /// <value>
        /// The default value.
        /// </value>
        public object DefaultValue
        {
            get
            {
                if (!this.defaultValueCreated && this.TypeInfo.IsValueType && this.Type != typeof(void))
                {
                    this.defaultValue = Activator.CreateInstance(this.Type);
                    this.defaultValueCreated = true;
                }

                return this.defaultValue;
            }
        }

        /// <summary>
        /// Gets the runtime type kind.
        /// </summary>
        /// <value>
        /// The runtime type kind.
        /// </value>
        public RuntimeTypeKind Kind => this.TypeInfo.IsClass
                                           ? RuntimeTypeKind.Class
                                           : this.TypeInfo.IsInterface
                                               ? RuntimeTypeKind.Interface
                                               : this.TypeInfo.IsEnum
                                                   ? RuntimeTypeKind.Enum
                                                   : RuntimeTypeKind.Unknown;

        /// <summary>
        /// Gets the bases of this <see cref="ITypeInfo"/>. They include the real base and also the implemented interfaces.
        /// </summary>
        /// <value>
        /// The bases.
        /// </value>
        public IEnumerable<ITypeInfo> BaseTypes => this.baseTypes ??= this.CreateBaseTypes(this.TypeInfo);

        /// <summary>
        /// Gets a read-only list of <see cref="ITypeInfo"/> objects that represent the type parameters of a generic type definition (open generic).
        /// </summary>
        /// <value>
        /// The generic arguments.
        /// </value>
        public IReadOnlyList<ITypeInfo> GenericTypeParameters => this.genericTypeParameters ??= this.CreateGenericTypeParameters(this.TypeInfo);

        /// <summary>
        /// Gets a read-only list of <see cref="ITypeInfo"/> objects that represent the type arguments of a closed generic type.
        /// </summary>
        /// <value>
        /// The generic arguments.
        /// </value>
        public IReadOnlyList<ITypeInfo> GenericTypeArguments => this.genericTypeArguments ??= this.CreateGenericTypeArguments(this.TypeInfo);

        /// <summary>
        /// Gets a <see cref="ITypeInfo"/> object that represents a generic type definition from which the current generic type can be constructed.
        /// </summary>
        /// <value>
        /// The generic type definition.
        /// </value>
        public ITypeInfo? GenericTypeDefinition => this.genericTypeDefinition ??= this.GetGenericTypeDefinition(this.TypeInfo);

        /// <summary>
        /// Gets the enumeration of properties.
        /// </summary>
        IEnumerable<IPropertyInfo> ITypeInfo.Properties => this.Properties.Values;

        /// <summary>
        /// Gets the members.
        /// </summary>
        /// <value>
        /// The members.
        /// </value>
        IEnumerable<IElementInfo> ITypeInfo.Members => this.Members.Values;

        /// <summary>
        /// Gets the container type registry.
        /// </summary>
        ITypeRegistry ITypeInfo.TypeRegistry => this.TypeRegistry;

        /// <summary>
        /// Gets the element annotations.
        /// </summary>
        /// <value>
        /// The element annotations.
        /// </value>
        public IEnumerable<object> Annotations => this.TypeInfo.GetCustomAttributes();

        /// <summary>
        /// Gets the parent element declaring this element.
        /// </summary>
        /// <value>
        /// The declaring element.
        /// </value>
        public IElementInfo DeclaringContainer => this.declaringContainer ??= this.TypeRegistry.GetAssemblyInfo(this.TypeInfo.Assembly);

        /// <summary>
        /// Gets the type.
        /// </summary>
        /// <value>
        /// The type.
        /// </value>
        public Type Type { get; }

        /// <summary>
        /// Gets the underlying <see cref="TypeInfo"/>.
        /// </summary>
        /// <value>
        /// The type.
        /// </value>
        public TypeInfo TypeInfo { get; }

        /// <summary>
        /// Gets the members.
        /// </summary>
        /// <value>
        /// The members.
        /// </value>
        public IDictionary<string, IRuntimeElementInfo> Members => this.GetMembers();

        /// <summary>
        /// Gets the fields.
        /// </summary>
        /// <value>
        /// The fields.
        /// </value>
        public IDictionary<string, IRuntimeFieldInfo> Fields => this.GetFields();

        /// <summary>
        /// Gets the runtime properties.
        /// </summary>
        /// <value>
        /// The runtime properties.
        /// </value>
        public IDictionary<string, IRuntimePropertyInfo> Properties => this.GetProperties();

        /// <summary>
        /// Gets the runtime methods.
        /// </summary>
        /// <value>
        /// The runtime methods.
        /// </value>
        public IDictionary<string, ICollection<IRuntimeMethodInfo>> Methods => this.GetMethods();

        /// <summary>
        /// Determines whether the runtime types are based on the same type.
        /// </summary>
        /// <param name="left">The object on the left side.</param>
        /// <param name="right">The object on the right side.</param>
        /// <returns>True, if both runtime types are based on the same type, otherwise false.</returns>
        public static bool operator ==(RuntimeTypeInfo? left, RuntimeTypeInfo? right)
        {
            return Equals(left, right);
        }

        /// <summary>
        /// Determines whether the runtime types are not based on the same type.
        /// </summary>
        /// <param name="left">The object on the left side.</param>
        /// <param name="right">The object on the right side.</param>
        /// <returns>True, if the runtime types are not based on the same type, otherwise false.</returns>
        public static bool operator !=(RuntimeTypeInfo? left, RuntimeTypeInfo? right)
        {
            return !Equals(left, right);
        }

        /// <summary>
        /// Determines whether this runtime type is equal to the provided one.
        /// </summary>
        /// <param name="other">The other runtime type.</param>
        /// <returns>True, if both runtime types are based on the same type, otherwise false.</returns>
        public bool Equals(RuntimeTypeInfo? other)
        {
            return this.Equals((IRuntimeTypeInfo?) other);
        }

        /// <summary>
        /// Determines whether the runtime types are based on the same type.
        /// </summary>
        /// <param name="other">The other runtime type.</param>
        /// <returns>True, if both runtime types are based on the same type, otherwise false.</returns>
        public bool Equals(IRuntimeTypeInfo? other)
        {
            if (ReferenceEquals(null, other))
            {
                return false;
            }

            if (ReferenceEquals(this, other))
            {
                return true;
            }

            return this.Type == other.Type;
        }

        /// <summary>
        /// Determines whether the runtime types are based on the same type.
        /// </summary>
        /// <param name="obj">The other object to compare with.</param>
        /// <returns>True, if both runtime types are based on the same type, otherwise false.</returns>
        public override bool Equals(object? obj)
        {
            if (ReferenceEquals(null, obj))
            {
                return false;
            }

            return ReferenceEquals(this, obj) || (obj is IRuntimeTypeInfo other && this.Equals(other));
        }

        /// <summary>
        /// Gets a hash code for this object.
        /// </summary>
        /// <returns>The hash code.</returns>
        public override int GetHashCode()
        {
            return this.Type.GetHashCode();
        }

#if NETSTANDARD2_1
#else
        /// <summary>
        /// Gets the display information.
        /// </summary>
        /// <returns>The display information.</returns>
        public virtual IDisplayInfo? GetDisplayInfo() => ElementInfoHelper.GetDisplayInfo(this);
#endif

        /// <summary>
        /// Gets the underlying member information.
        /// </summary>
        /// <returns>
        /// The underlying member information.
        /// </returns>
        public ICustomAttributeProvider GetUnderlyingElementInfo() => this.TypeInfo;

        /// <summary>
        /// Gets a member by the provided name.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="throwIfNotFound">True to throw if the requested member is not found.</param>
        /// <returns>
        /// The requested member, or <c>null</c>.
        /// </returns>
        public IElementInfo? GetMember(string name, bool throwIfNotFound = true)
        {
            if (this.Fields.TryGetValue(name, out IRuntimeFieldInfo fieldInfo))
            {
                return fieldInfo;
            }

            if (this.Properties.TryGetValue(name, out IRuntimePropertyInfo propertyInfo))
            {
                return propertyInfo;
            }

            if (this.Methods.TryGetValue(name, out ICollection<IRuntimeMethodInfo> methodInfos))
            {
                if (methodInfos.Count > 1)
                {
                    throw new AmbiguousMatchException(Strings.RuntimeTypeInfo_AmbiguousMember_Exception.FormatWith(name, this, nameof(this.Methods)));
                }

                return methodInfos.First();
            }

            if (throwIfNotFound)
            {
                throw new KeyNotFoundException(Strings.RuntimeTypeInfo_MemberNotFound_Exception.FormatWith(name, this.Type));
            }

            return null;
        }

        /// <summary>
        /// Gets the value of the property with the specified name.
        /// </summary>
        /// <param name="instance">The instance.</param>
        /// <param name="propertyName">Name of the property.</param>
        /// <returns>
        /// The value of the specified property.
        /// </returns>
        /// <remarks>
        /// If a property with the provided name is not found, an exception occurs.
        /// </remarks>
        public object? GetValue(object? instance, string propertyName)
        {
            var dynamicProperty = this.GetProperty(propertyName);
            return dynamicProperty!.GetValue(instance);
        }

        /// <summary>
        /// Gets the value of the property with the specified name.
        /// </summary>
        /// <param name="instance">The instance.</param>
        /// <param name="propertyName">Name of the property.</param>
        /// <param name="value">The property value.</param>
        /// <returns>
        /// A boolean value indicating whether the property is found.
        /// </returns>
        public bool TryGetValue(object? instance, string propertyName, out object? value)
        {
            Requires.NotNull(instance, nameof(instance));

            var dynamicProperty = this.GetProperty(propertyName, throwOnNotFound: false);
            value = dynamicProperty?.GetValue(instance);
            return dynamicProperty != null;
        }

        /// <summary>
        /// Sets the value of the property with the specified name.
        /// </summary>
        /// <param name="instance">The instance.</param>
        /// <param name="propertyName">Name of the property.</param>
        /// <param name="value">The value.</param>
        /// <remarks>
        /// If a property with the provided name is not found, an exception occurs.
        /// </remarks>
        public void SetValue(object? instance, string propertyName, object? value)
        {
            var dynamicProperty = this.GetProperty(propertyName);
            dynamicProperty!.SetValue(instance, value);
        }

        /// <summary>
        /// Tries to set the value of the property with the specified name.
        /// </summary>
        /// <param name="instance">The instance.</param>
        /// <param name="propertyName">Name of the property.</param>
        /// <param name="value">The value.</param>
        /// <returns>
        ///   <c>true</c> if the value could be set; otherwise <c>false</c>.
        /// </returns>
        /// <remarks>
        /// If a property with the provided name is not found, the method just returns.
        /// </remarks>
        public bool TrySetValue(object? instance, string propertyName, object? value)
        {
            if (instance == null)
            {
                return false;
            }

            var dynamicProperty = this.GetProperty(propertyName, throwOnNotFound: false);
            if (dynamicProperty != null)
            {
                dynamicProperty.SetValue(instance, value);
                return true;
            }

            return false;
        }

        /// <summary>
        /// Invokes the specified method on the provided instance.
        /// </summary>
        /// <param name="instance">The instance.</param>
        /// <param name="methodName">Name of the method.</param>
        /// <param name="args">The arguments.</param>
        /// <returns>
        /// The invocation result.
        /// </returns>
        public object? Invoke(object? instance, string methodName, IEnumerable<object?> args)
        {
            var matchingMethod = this.GetMatchingMethod(methodName, args);
            return matchingMethod!.Invoke(instance, args);
        }

        /// <summary>
        /// Tries to invokes the specified method on the provided instance.
        /// </summary>
        /// <param name="instance">The instance.</param>
        /// <param name="methodName">Name of the method.</param>
        /// <param name="args">The arguments.</param>
        /// <param name="result">The invocation result.</param>
        /// <returns>A boolean value indicating whether the invocation was successful or not.</returns>
        public bool TryInvoke(object? instance, string methodName, IEnumerable<object?> args, out object? result)
        {
            Requires.NotNull(instance, nameof(instance));

            var matchingMethod = this.GetMatchingMethod(methodName, args, throwOnNotFound: false);
            if (matchingMethod == null)
            {
                result = null;
                return false;
            }

            result = matchingMethod.Invoke(instance, args);
            return true;
        }

        /// <summary>
        /// Creates an instance with the provided arguments (if any).
        /// </summary>
        /// <param name="args">The arguments.</param>
        /// <returns>
        /// The new instance.
        /// </returns>
        public virtual object CreateInstance(IEnumerable<object?>? args = null)
        {
            if (this.instanceActivator == null)
            {
                this.instanceActivator = this.CreateInstanceActivator();
            }

            return args == null ? this.instanceActivator() : this.instanceActivator(args.ToArray());
        }

        /// <summary>
        /// Constructs a generic type baed on the provided type arguments.
        /// </summary>
        /// <param name="typeArguments">The type arguments.</param>
        /// <param name="constructionContext">The construction context (optional).</param>
        /// <returns>
        /// A constructed <see cref="ITypeInfo"/>.
        /// </returns>
        public ITypeInfo MakeGenericType(IEnumerable<ITypeInfo> typeArguments, IContext? constructionContext = null)
        {
            var constructedType = this.TypeInfo.MakeGenericType(typeArguments.Cast<IRuntimeTypeInfo>().Select(t => t.Type).ToArray());
            return this.TypeRegistry.GetTypeInfo(constructedType);
        }

        /// <summary>
        /// Returns a string that represents the current object.
        /// </summary>
        /// <returns>
        /// A string that represents the current object.
        /// </returns>
        public override string ToString() => this.Type.ToString();

        /// <summary>
        /// Gets the attribute of the provided type.
        /// </summary>
        /// <typeparam name="TAttribute">Type of the attribute.</typeparam>
        /// <returns>
        /// The attribute of the provided type.
        /// </returns>
        public IEnumerable<TAttribute> GetAttributes<TAttribute>()
            where TAttribute : Attribute
        {
            return this.TypeInfo.GetCustomAttributes<TAttribute>(inherit: true);
        }

        /// <summary>
        /// Gets the type's proper properties: public, non-static, and without parameters.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <returns>An enumeration of property infos.</returns>
        protected internal static IEnumerable<PropertyInfo> GetTypeProperties(Type type)
        {
            return type.GetRuntimeProperties()
                .Where(p => p.GetMethod != null && !p.GetMethod.IsStatic && p.GetMethod.IsPublic
                            && p.GetIndexParameters().Length == 0);
        }

        /// <summary>
        /// Creates the member infos.
        /// </summary>
        /// <param name="membersConfig">Optional. The members configuration.</param>
        /// <returns>
        /// The new member infos.
        /// </returns>
        protected virtual IDictionary<string, IRuntimeElementInfo> CreateMemberInfos(Action<IDictionary<string, IRuntimeElementInfo>>? membersConfig = null)
        {
            return CreateMemberInfos(this.Fields, this.Properties, this.Methods, membersConfig);
        }

        /// <summary>
        /// Creates the members.
        /// </summary>
        /// <typeparam name="TRuntimeMemberInfo">Type of the runtime member.</typeparam>
        /// <typeparam name="TMemberInfo">Type of the member.</typeparam>
        /// <param name="type">The type.</param>
        /// <param name="runtimeMembers">The runtime members.</param>
        /// <param name="memberTypeGetter">The member type getter.</param>
        /// <param name="criteria">Optional. The criteria.</param>
        /// <returns>
        /// A dictionary of members.
        /// </returns>
        protected IDictionary<string, TMemberInfo> CreateMembers<TRuntimeMemberInfo, TMemberInfo>(Type type, IEnumerable<TRuntimeMemberInfo> runtimeMembers, Func<TRuntimeMemberInfo, Type> memberTypeGetter, Func<TRuntimeMemberInfo, bool>? criteria = null)
            where TRuntimeMemberInfo : MemberInfo
        {
            var memberInfos = new Dictionary<string, TMemberInfo>();
            if (criteria != null)
            {
                runtimeMembers = runtimeMembers.Where(criteria);
            }

            var position = 0;
            foreach (var runtimeMemberInfo in runtimeMembers)
            {
                var memberName = runtimeMemberInfo.Name;
                if (memberInfos.ContainsKey(memberName))
                {
                    continue;
                }

                var memberType = memberTypeGetter(runtimeMemberInfo);
                var memberCtor = memberType.GetTypeInfo().DeclaredConstructors.First();
                var memberInfo = (TMemberInfo)memberCtor.Invoke(new object?[] { this.TypeRegistry, runtimeMemberInfo, position++, this.Logger });
                memberInfos.Add(memberName, memberInfo);
            }

            return new ReadOnlyDictionary<string, TMemberInfo>(memberInfos);
        }

        /// <summary>
        /// Creates the fields.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <param name="criteria">Optional. The criteria.</param>
        /// <returns>
        /// A dictionary of fields.
        /// </returns>
        protected virtual IDictionary<string, IRuntimeFieldInfo> CreateFieldInfos(Type type, Func<FieldInfo, bool>? criteria = null)
        {
            var memberTypeGetter = type.GetTypeInfo().ContainsGenericParameters
                                       ? (Func<FieldInfo, Type>)(fieldType => RuntimeFieldInfoType)
                                       : (field => RuntimeFieldInfoGenericType.MakeGenericType(type, field.FieldType));

            var runtimeMembers = type.GetRuntimeFields().Where(f => f.IsPublic);

            return this.CreateMembers<FieldInfo, IRuntimeFieldInfo>(type, runtimeMembers, memberTypeGetter, criteria);
        }

        /// <summary>
        /// Creates the properties.
        /// </summary>
        /// <param name="type">The container type.</param>
        /// <param name="criteria">The criteria.</param>
        /// <returns>
        /// A dictionary of properties.
        /// </returns>
        protected virtual IDictionary<string, IRuntimePropertyInfo> CreatePropertyInfos(Type type, Func<PropertyInfo, bool>? criteria = null)
        {
            var memberTypeGetter = type.GetTypeInfo().ContainsGenericParameters
                                       ? (Func<PropertyInfo, Type>)(prop => RuntimePropertyInfoType)
                                       : (prop => RuntimePropertyInfoGenericType.MakeGenericType(type, prop.PropertyType));

            var runtimeMembers = GetTypeProperties(type);
            return this.CreateMembers<PropertyInfo, IRuntimePropertyInfo>(type, runtimeMembers, memberTypeGetter, criteria);
        }

        private static IDictionary<string, IRuntimeElementInfo> CreateMemberInfos(
            IDictionary<string, IRuntimeFieldInfo> fieldInfos,
            IDictionary<string, IRuntimePropertyInfo> propertyInfos,
            IDictionary<string, ICollection<IRuntimeMethodInfo>> methodInfos,
            Action<IDictionary<string, IRuntimeElementInfo>>? membersConfig)
        {
            var memberInfos = new Dictionary<string, IRuntimeElementInfo>();
            foreach (var kv in fieldInfos)
            {
                memberInfos.Add(kv.Key, kv.Value);
            }

            foreach (var kv in propertyInfos)
            {
                memberInfos.Add(kv.Key, kv.Value);
            }

            foreach (var kv in methodInfos)
            {
                var groupMethodInfos = (IList<IRuntimeMethodInfo>)kv.Value;
                if (groupMethodInfos.Count > 1)
                {
                    for (var i = 0; i < groupMethodInfos.Count; i++)
                    {
                        var methodInfo = groupMethodInfos[i];
                        memberInfos.Add($"{kv.Key}#{i}", methodInfo);
                    }
                }
                else
                {
                    memberInfos.Add(groupMethodInfos[0].Name, groupMethodInfos[0]);
                }
            }

            membersConfig?.Invoke(memberInfos);

            return new ReadOnlyDictionary<string, IRuntimeElementInfo>(memberInfos);
        }

        private IDictionary<string, ICollection<IRuntimeMethodInfo>> CreateMethodInfos(Type type)
        {
            var methodInfos = type.GetRuntimeMethods()
                .Where(mi => !mi.IsStatic && mi.IsPublic)
                .GroupBy(
                    mi => mi.Name,
                    (name, methods)
                        => new KeyValuePair<string, ICollection<IRuntimeMethodInfo>>(
                            name,
                            methods.Select(mi
                                => (IRuntimeMethodInfo)new RuntimeMethodInfo(this.TypeRegistry, mi, this.Logger)).ToList().AsReadOnly()));
            return new ReadOnlyDictionary<string, ICollection<IRuntimeMethodInfo>>(methodInfos.ToDictionary(g => g.Key, g => g.Value));
        }

        private IReadOnlyList<ITypeInfo> CreateBaseTypes(TypeInfo typeInfo)
        {
            var baseTypeInfos = new List<ITypeInfo>();
            if (typeInfo.BaseType != null)
            {
                baseTypeInfos.Add(this.TypeRegistry.GetTypeInfo(typeInfo.BaseType));
            }

            typeInfo.ImplementedInterfaces.ForEach(i => baseTypeInfos.Add(this.TypeRegistry.GetTypeInfo(i)));

            return new ReadOnlyCollection<ITypeInfo>(baseTypeInfos);
        }

        private ITypeInfo? GetGenericTypeDefinition(Type typeInfo)
        {
            if (typeInfo.IsGenericType && !typeInfo.IsGenericTypeDefinition)
            {
                return this.TypeRegistry.GetTypeInfo(typeInfo.GetGenericTypeDefinition());
            }

            return null;
        }

        private IDictionary<string, IRuntimeElementInfo> GetMembers()
        {
            return this.members ??= this.CreateMemberInfos();
        }

        private IDictionary<string, IRuntimeFieldInfo> GetFields()
        {
            return this.fields ??= this.CreateFieldInfos(this.Type);
        }

        private IDictionary<string, IRuntimePropertyInfo> GetProperties()
        {
            return this.properties ??= this.CreatePropertyInfos(this.Type);
        }

        private IDictionary<string, ICollection<IRuntimeMethodInfo>> GetMethods()
        {
            return this.methods ??= this.CreateMethodInfos(this.Type);
        }

        /// <summary>
        /// Creates the generic parameters.
        /// </summary>
        /// <param name="typeInfo">The <see cref="TypeInfo"/>.</param>
        /// <returns>
        /// The new generic arguments.
        /// </returns>
        private IReadOnlyList<ITypeInfo> CreateGenericTypeParameters(TypeInfo typeInfo)
        {
            var args = typeInfo.GenericTypeParameters;
            if (args.Length == 0)
            {
                return Array.Empty<ITypeInfo>();
            }

            return new ReadOnlyCollection<ITypeInfo>(args.Select(a => (ITypeInfo)this.TypeRegistry.GetTypeInfo(a)).ToList());
        }

        /// <summary>
        /// Creates the generic arguments.
        /// </summary>
        /// <param name="typeInfo">The <see cref="TypeInfo"/>.</param>
        /// <returns>
        /// The new generic arguments.
        /// </returns>
        private IReadOnlyList<ITypeInfo> CreateGenericTypeArguments(TypeInfo typeInfo)
        {
            var args = typeInfo.GenericTypeArguments;
            if (args.Length == 0)
            {
                return Array.Empty<ITypeInfo>();
            }

            return new ReadOnlyCollection<ITypeInfo>(args.Select(a => (ITypeInfo)this.TypeRegistry.GetTypeInfo(a)).ToList());
        }

        /// <summary>
        /// Gets the runtime property for the provided property name.
        /// </summary>
        /// <param name="propertyName">Name of the property.</param>
        /// <param name="throwOnNotFound">If set to <c>true</c> an exception is thrown if the property is not found.</param>
        /// <returns>
        /// The runtime property.
        /// </returns>
        private IRuntimePropertyInfo? GetProperty(string propertyName, bool throwOnNotFound = true)
        {
            if (!this.GetProperties().TryGetValue(propertyName, out IRuntimePropertyInfo propertyInfo))
            {
                if (throwOnNotFound)
                {
                    throw new MemberAccessException(string.Format(Strings.RuntimeTypeInfo_PropertyNotFound_Exception, propertyName, this.Type));
                }

                return null;
            }

            return propertyInfo;
        }

        /// <summary>
        /// Gets the runtime methods for the provided method name.
        /// </summary>
        /// <param name="methodName">Name of the property.</param>
        /// <param name="throwOnNotFound">If set to <c>true</c> an exception is thrown if the method is not found.</param>
        /// <returns>
        /// The runtime method.
        /// </returns>
        private IList<IRuntimeMethodInfo>? GetMethods(string methodName, bool throwOnNotFound = true)
        {
            if (!this.GetMethods().TryGetValue(methodName, out ICollection<IRuntimeMethodInfo> methodInfos))
            {
                if (throwOnNotFound)
                {
                    throw new MemberAccessException($"Method {methodName} not found or is not accessible in {this.Type}.");
                }

                return null;
            }

            return (IList<IRuntimeMethodInfo>)methodInfos;
        }

        /// <summary>
        /// Gets the matching method.
        /// </summary>
        /// <param name="methodName">Name of the method.</param>
        /// <param name="args">The arguments.</param>
        /// <param name="throwOnNotFound">If set to <c>true</c> an exception is thrown if the method is not found.</param>
        /// <returns>
        /// A matching method for the provided name and arguments.
        /// </returns>
        private IRuntimeMethodInfo? GetMatchingMethod(string methodName, IEnumerable<object?> args, bool throwOnNotFound = true)
        {
            var methodInfos = this.GetMethods(methodName, throwOnNotFound);
            if (methodInfos == null)
            {
                return null;
            }

            if (methodInfos.Count == 1)
            {
                return methodInfos[0];
            }

            var argsCount = args.Count();
            var matchingMethods = methodInfos.Where(mi => mi.MethodInfo.GetParameters().Length == argsCount)
                                        .Take(2)
                                        .ToList();

            if (matchingMethods.Count > 1)
            {
                // TODO localization
                throw new AmbiguousMatchException($"Multiple methods found with name {methodName} and {argsCount} arguments in {this.Type}.");
            }

            if (matchingMethods.Count == 0)
            {
                if (throwOnNotFound)
                {
                    // TODO localization
                    throw new MemberAccessException($"Method {methodName} with {argsCount} arguments not found or is not accessible in {this.Type}.");
                }

                return null;
            }

            return matchingMethods[0];
        }

        /// <summary>
        /// Creates an optimized instance activator.
        /// </summary>
        /// <returns>
        /// The new instance activator.
        /// </returns>
        private InstanceActivator CreateInstanceActivator()
        {
            var constructors = this.TypeInfo.DeclaredConstructors.ToList();

            if (constructors.Count == 0)
            {
                return args => throw new InvalidOperationException(string.Format(Strings.RuntimeTypeInfo_NoPublicConstructorDefined_Exception, this.Type));
            }

            if (constructors.Count > 1)
            {
                return args => args == null ? Activator.CreateInstance(this.Type) : Activator.CreateInstance(this.Type, args);
            }

            var constructor = constructors[0];
            var parameters = constructor.GetParameters();
            var argsParam = Expression.Parameter(typeof(object[]), "args");

            var exargs = new Expression[parameters.Length];
            for (var i = 0; i < parameters.Length; i++)
            {
                var index = Expression.Constant(i);
                var paramType = parameters[i].ParameterType;
                var accessor = Expression.ArrayIndex(argsParam, index);
                var cast = Expression.Convert(accessor, paramType);
                exargs[i] = cast;
            }

            var newex = Expression.New(constructor, exargs);
            var lambda = Expression.Lambda(typeof(InstanceActivator), newex, argsParam);
            var activator = (InstanceActivator)lambda.Compile();
            return args => parameters.Length == args?.Length
                                        ? activator(args)
                                        : throw new InvalidOperationException($"Mismatched parameter count: expected {parameters.Length}, received {args?.Length}.");
        }
    }
}


text:
#include "berryRegistryToggleState.h"

#include "berryObjects.h"
#include "berryObjectString.h"
#include "berryObjectStringMap.h"

namespace berry {

const QString RegistryToggleState::STATE_ID = "org.blueberry.ui.commands.toggleState";

void RegistryToggleState::SetInitializationData(
    const SmartPointer<IConfigurationElement>& /*configurationElement*/,
    const QString& /*propertyName*/, const Object::Pointer& data)
{
  if (ObjectString::Pointer objStr = data.Cast<ObjectString>())
  {
    // This is the default value.
    ReadDefault(*objStr);
    SetShouldPersist(true);
  }
  else if (ObjectStringMap::Pointer parameters = data.Cast<ObjectStringMap>())
  {
    QString defaultObject = parameters->value("default");
    if (!defaultObject.isNull())
    {
      ReadDefault(defaultObject);
    }

    QString persistedObject = parameters->value("persisted");
    if (!persistedObject.isNull())
    {
      ReadPersisted(persistedObject);
    }
  }
  else
  {
    SetShouldPersist(true);
  }
}

void RegistryToggleState::ReadDefault(const QString& defaultString)
{
  if (defaultString.compare("true", Qt::CaseInsensitive) == 0)
  {
    Object::Pointer newValue(new ObjectBool(true));
    SetValue(newValue);
  }
}

void RegistryToggleState::ReadPersisted(const QString& persistedString)
{
  if (persistedString.compare("false", Qt::CaseInsensitive) == 0)
  {
    SetShouldPersist(false);
  }
  else
  {
    SetShouldPersist(true);
  }
}

}


text: import '../register';


text:
package nl.conspect.eventboot;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

/**
 * @author arnoutvw
 * @since 20/10/14
 */
@SpringBootApplication
public class Application{

	public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
	}

	@Bean
	public CommandLineRunner helloWorldRunner() {
		return args -> System.out.println("Hello World, from Spring Boot!");
	}
}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE190_Integer_Overflow__unsigned_int_rand_multiply_82_bad.cpp
Label Definition File: CWE190_Integer_Overflow.label.xml
Template File: sources-sinks-82_bad.tmpl.cpp
*/
/*
 * @description
 * CWE: 190 Integer Overflow
 * BadSource: rand Set data to result of rand()
 * GoodSource: Set data to a small, non-zero number (two)
 * Sinks: multiply
 *    GoodSink: Ensure there will not be an overflow before multiplying data by 2
 *    BadSink : If data is positive, multiply by 2, which can cause an overflow
 * Flow Variant: 82 Data flow: data passed in a parameter to an virtual method called via a pointer
 *
 * */
#ifndef OMITBAD

#include "std_testcase.h"
#include "CWE190_Integer_Overflow__unsigned_int_rand_multiply_82.h"

namespace CWE190_Integer_Overflow__unsigned_int_rand_multiply_82
{

void CWE190_Integer_Overflow__unsigned_int_rand_multiply_82_bad::action(unsigned int data)
{
    if(data > 0) /* ensure we won't have an underflow */
    {
        /* POTENTIAL FLAW: if (data*2) > UINT_MAX, this will overflow */
        unsigned int result = data * 2;
        printUnsignedLine(result);
    }
}

}
#endif /* OMITBAD */


text:
<?xml version="1.0" encoding="UTF-8"?>

<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
         http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.0.xsd">

	<changeSet id="initial-data-set-roles-and-admin" author="fbristow">
		<!-- insert the initial set of roles -->
		<insert tableName="system_role">
			<column name="name" value="ROLE_USER" />
			<column name="description" value="A basic user in the system." />
		</insert>
		<insert tableName="system_role">
			<column name="name" value="ROLE_ADMIN" />
			<column name="description" value="An administrative user in the system." />
		</insert>
		<insert tableName="system_role">
			<column name="name" value="ROLE_CLIENT" />
			<column name="description" value="A client tool in the system." />
		</insert>
		<insert tableName="system_role">
			<column name="name" value="ROLE_MANAGER" />
			<column name="description" value="A manager role in the system." />
		</insert>

		<!-- insert the initial administrator user -->
		<insert tableName="user">
			<column name="createdDate" valueComputed="NOW()" />
			<column name="modifiedDate" valueComputed="NOW()" />
			<column name="email" value="admin@example.org" />
			<column name="firstName" value="Administrator" />
			<column name="lastName" value="Administrator" />
			<column name="locale" value="en" />
			<column name="password"
				value="$2a$10$yvzFLxWA9m2wNQmHpJtWT.MRZv8qV8Mo3EMB6HTkDnUbi9aBrbWWW" />
			<column name="phoneNumber" value="867-5309" />
			<column name="username" value="admin" />
			<column name="enabled" valueBoolean="true" />
			<column name="system_role" value="2" />
			<column name="credentialsNonExpired" valueBoolean="false" />
		</insert>
	</changeSet>
</databaseChangeLog>


text: PRAGMA recursive_triggers


text:
package org.apache.qpid.jms.transports.netty;

import java.io.IOException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

import org.apache.qpid.jms.transports.TransportListener;
import org.apache.qpid.jms.transports.TransportOptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.http.DefaultHttpHeaders;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestEncoder;
import io.netty.handler.codec.http.HttpResponseDecoder;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
import io.netty.handler.codec.http.websocketx.ContinuationWebSocketFrame;
import io.netty.handler.codec.http.websocketx.PingWebSocketFrame;
import io.netty.handler.codec.http.websocketx.PongWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshaker;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshakerFactory;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketVersion;
import io.netty.util.concurrent.ScheduledFuture;

/**
 * Netty based WebSockets Transport that wraps and extends the TCP Transport.
 */
public class NettyWsTransport extends NettyTcpTransport {

    private static final Logger LOG = LoggerFactory.getLogger(NettyWsTransport.class);
    private static final String AMQP_SUB_PROTOCOL = "amqp";
    private ScheduledFuture<?> handshakeTimeoutFuture;

    /**
     * Create a new transport instance
     *
     * @param remoteLocation
     *        the URI that defines the remote resource to connect to.
     * @param options
     *        the transport options used to configure the socket connection.
     * @param secure
     * 		  should the transport enable an SSL layer.
     */
    public NettyWsTransport(URI remoteLocation, TransportOptions options, boolean secure) {
        this(null, remoteLocation, options, secure);
    }

    /**
     * Create a new transport instance
     *
     * @param listener
     *        the TransportListener that will receive events from this Transport.
     * @param remoteLocation
     *        the URI that defines the remote resource to connect to.
     * @param options
     *        the transport options used to configure the socket connection.
     * @param secure
     * 		  should the transport enable an SSL layer.
     */
    public NettyWsTransport(TransportListener listener, URI remoteLocation, TransportOptions options, boolean secure) {
        super(listener, remoteLocation, options, secure);
    }

    @Override
    public void write(ByteBuf output) throws IOException {
        checkConnected();
        int length = output.readableBytes();
        if (length == 0) {
            return;
        }

        LOG.trace("Attempted write of: {} bytes", length);

        channel.write(new BinaryWebSocketFrame(output), channel.voidPromise());
    }

    @Override
    public void writeAndFlush(ByteBuf output) throws IOException {
        checkConnected();
        int length = output.readableBytes();
        if (length == 0) {
            return;
        }

        LOG.trace("Attempted write and flush of: {} bytes", length);

        channel.writeAndFlush(new BinaryWebSocketFrame(output), channel.voidPromise());
    }

    @Override
    protected ChannelInboundHandlerAdapter createChannelHandler() {
        return new NettyWebSocketTransportHandler();
    }

    @Override
    protected void addAdditionalHandlers(ChannelPipeline pipeline) {
        /*
         * If we use a HttpClientCodec here instead of the HttpRequestEncoder and the HttpResponseDecoder
         * and there is a HttpProxyHandler in the pipeline, that ProxyHandler will add another HttpClientCodec
         * for communication with the proxy. When the WebSocketClientHandshaker tries to exchange the codecs in
         * the pipeline, it will mix up the two HttpRequestEncoders in the pipeline and exchange the wrong one.
         * HttpReqestEncoder and HttpResponseDecoder has precedence over the HttpClientCodec, so the
         * WebSocketClientHandshaker will remove these handlers inserted here and will leave the HttpClientCodec
         * added by the HttpProxyHandler alone.
         */
        pipeline.addLast(new HttpResponseDecoder());
        pipeline.addLast(new HttpRequestEncoder());
        pipeline.addLast(new HttpObjectAggregator(8192));
    }

    @Override
    protected void handleConnected(Channel channel) throws Exception {
        LOG.trace("Channel has become active, awaiting WebSocket handshake! Channel is {}", channel);
    }

    protected void handleChannelInactive(Channel channel) throws Exception {
        try {
            if (handshakeTimeoutFuture != null) {
                handshakeTimeoutFuture.cancel(false);
            }
        } finally {
            super.handleChannelInactive(channel);
        }
    }

    //----- Handle connection events -----------------------------------------//

    private class NettyWebSocketTransportHandler extends NettyDefaultHandler<Object> {

        private final WebSocketClientHandshaker handshaker;

        public NettyWebSocketTransportHandler() {
            DefaultHttpHeaders headers = new DefaultHttpHeaders();

            getTransportOptions().getHttpHeaders().forEach((key, value) -> {
                headers.set(key, value);
            });

            handshaker = WebSocketClientHandshakerFactory.newHandshaker(
                getRemoteLocation(), WebSocketVersion.V13, AMQP_SUB_PROTOCOL,
                true, headers, getMaxFrameSize());
        }

        @Override
        public void channelActive(ChannelHandlerContext context) throws Exception {
            handshaker.handshake(context.channel());

            handshakeTimeoutFuture = context.executor().schedule(()-> {
                LOG.trace("WebSocket handshake timed out! Channel is {}", context.channel());
                if (!handshaker.isHandshakeComplete()) {
                    NettyWsTransport.super.handleException(channel, new IOException("WebSocket handshake timed out"));
                }
            }, getTransportOptions().getConnectTimeout(), TimeUnit.MILLISECONDS);

            super.channelActive(context);
        }

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, Object message) throws Exception {
            LOG.trace("New data read: incoming: {}", message);

            Channel ch = ctx.channel();
            if (!handshaker.isHandshakeComplete()) {
                handshaker.finishHandshake(ch, (FullHttpResponse) message);
                LOG.trace("WebSocket Client connected! {}", ctx.channel());
                // Now trigger super processing as we are really connected.
                if(handshakeTimeoutFuture.cancel(false)) {
                    NettyWsTransport.super.handleConnected(ch);
                }
                return;
            }

            // We shouldn't get this since we handle the handshake previously.
            if (message instanceof FullHttpResponse) {
                FullHttpResponse response = (FullHttpResponse) message;
                throw new IllegalStateException(
                    "Unexpected FullHttpResponse (getStatus=" + response.status() +
                    ", content=" + response.content().toString(StandardCharsets.UTF_8) + ')');
            }

            WebSocketFrame frame = (WebSocketFrame) message;
            if (frame instanceof TextWebSocketFrame) {
                TextWebSocketFrame textFrame = (TextWebSocketFrame) frame;
                LOG.warn("WebSocket Client received message: " + textFrame.text());
                ctx.fireExceptionCaught(new IOException("Received invalid frame over WebSocket."));
            } else if (frame instanceof BinaryWebSocketFrame) {
                BinaryWebSocketFrame binaryFrame = (BinaryWebSocketFrame) frame;
                LOG.trace("WebSocket Client received data: {} bytes", binaryFrame.content().readableBytes());
                listener.onData(binaryFrame.content());
            } else if (frame instanceof ContinuationWebSocketFrame) {
                ContinuationWebSocketFrame continuationFrame = (ContinuationWebSocketFrame) frame;
                LOG.trace("WebSocket Client received data continuation: {} bytes", continuationFrame.content().readableBytes());
                listener.onData(continuationFrame.content());
            } else if (frame instanceof PingWebSocketFrame) {
                LOG.trace("WebSocket Client received ping, response with pong");
                ch.write(new PongWebSocketFrame(frame.content()));
            } else if (frame instanceof CloseWebSocketFrame) {
                LOG.trace("WebSocket Client received closing");
                ch.close();
            }
        }
    }
}