text:
layout: default
permalink: /api/
title: API
---

# API

## General Usage

__Write Files__

~~~ php
$filesystem->write('path/to/file.txt', 'contents');
~~~

__Update Files__

~~~ php
$filesystem->update('path/to/file.txt', 'new contents');
~~~

__Write or Update Files__

~~~ php
$filesystem->put('path/to/file.txt', 'contents');
~~~

__Read Files__

~~~ php
$contents = $filesystem->read('path/to/file.txt');
~~~

__Check if a file exists__

~~~ php
$exists = $filesystem->has('path/to/file.txt');
~~~

__NOTE__: This only has consistent behaviour for files, not directories. Directories
are less important in Flysystem, they're created implicitly and often ignored because
not every adapter (filesystem type) supports directories.

__Delete Files__

~~~ php
$filesystem->delete('path/to/file.txt');
~~~

__Read and Delete__

~~~ php
$contents = $filesystem->readAndDelete('path/to/file.txt');
~~~

__Rename Files__

~~~ php
$filesystem->rename('filename.txt', 'newname.txt');
~~~

__Copy Files__

~~~ php
$filesystem->copy('filename.txt', 'duplicate.txt');
~~~

__Get Mimetypes__

~~~ php
$mimetype = $filesystem->getMimetype('path/to/file.txt');
~~~

__Get Timestamps__

~~~ php
$timestamp = $filesystem->getTimestamp('path/to/file.txt');
~~~

__Get File Sizes__

~~~ php
$size = $filesystem->getSize('path/to/file.txt');
~~~

__Create Directories__

~~~ php
$filesystem->createDir('path/to/nested/directory');
~~~
Directories are also made implicitly when writing to a deeper path

~~~ php
$filesystem->write('path/to/file.txt', 'contents');
~~~

__Delete Directories__

~~~ php
$filesystem->deleteDir('path/to/directory');
~~~
The above method will delete directories recursively

__NOTE__: All paths used by Flysystem API are relative to the adapter root directory.

__Manage Visibility__

Visibility is the abstraction of file permissions across multiple platforms. Visibility can be either public or private.

~~~ php
use League\Flysystem\AdapterInterface;

$filesystem->write('db.backup', $backup, [
    'visibility' => AdapterInterface::VISIBILITY_PRIVATE
]);

// or simply

$filesystem->write('db.backup', $backup, ['visibility' => 'private']);
~~~

You can also change and check visibility of existing files

~~~ php
if ($filesystem->getVisibility('secret.txt') === 'private') {
    $filesystem->setVisibility('secret.txt', 'public');
}
~~~

## Global visibility setting

You can set the visibility as a default, which prevents you from setting it all over the place.

~~~ php
$filesystem = new League\Flysystem\Filesystem($adapter, [
    'visibility' => AdapterInterface::VISIBILITY_PRIVATE
]);
~~~

__List Contents__

~~~ php
$contents = $filemanager->listContents();
~~~

The result of a contents listing is a collection of arrays containing all the metadata the file manager knows at that time. By default you'll receive path info and file type. Additional info could be supplied by default depending on the adapter used.

Example:

~~~ php
foreach ($contents as $object) {
    echo $object['basename'].' is located at'.$object['path'].' and is a '.$object['type'];
}
~~~

By default Flysystem lists the top directory non-recursively. You can supply a directory name and recursive boolean to get more precise results

~~~ php
$contents = $filesystem->listContents('some/dir', true);
~~~

__List paths__

~~~ php
$filesystem->addPlugin(new ListPaths());

$paths = $filesystem->listPaths();

foreach ($paths as $path) {
    echo $path;
}
~~~

__List with ensured presence of specific metadata__

~~~ php
$listing = $filesystem->listWith(['mimetype', 'size', 'timestamp'], 'optional/path/to/dir', true);

foreach ($listing as $object) {
    echo $object['path'].' has mimetype: '.$object['mimetype'];
}
~~~

__Get file into with explicit metadata__

~~~ php
$info = $filesystem->getWithMetadata('path/to/file.txt', ['timestamp', 'mimetype']);
echo $info['mimetype'];
echo $info['timestamp'];
~~~

__NOTE__: This requires the `League\Flysystem\Plugin\GetWithMetadata` plugin.

## Using streams for reads and writes

Some SDK's close streams after consuming them, therefore, before calling fclose on the resource, check if it's still valid using is_resource.

~~~ php
$stream = fopen('/path/to/database.backup', 'r+');
$filesystem->writeStream('backups/'.strftime('%G-%m-%d').'.backup', $stream);

// Using write you can also directly set the visibility
$filesystem->writeStream('backups/'.strftime('%G-%m-%d').'.backup', $stream, [
    'visibility' => AdapterInterface::VISIBILITY_PRIVATE
]);

if (is_resource($stream)) {
    fclose($stream);
}

// Or update a file with stream contents
$filesystem->updateStream('backups/'.strftime('%G-%m-%d').'.backup', $stream);

// Retrieve a read-stream
$stream = $filesystem->readStream('something/is/here.ext');
$contents = stream_get_contents($stream);
fclose($stream);

// Create or overwrite using a stream.
$putStream = tmpfile();
fwrite($putStream, $contents);
rewind($putStream);
$filesystem->putStream('somewhere/here.txt', $putStream);

if (is_resource($putStream)) {
    fclose($putStream);
}
~~~


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE284_Improper_Access_Control__w32_char_CreateWindowStation_05.c
Label Definition File: CWE284_Improper_Access_Control__w32.label.xml
Template File: point-flaw-05.tmpl.c
*/
/*
 * @description
 * CWE: 284 Improper Access Control
 * Sinks: CreateWindowStation
 *    GoodSink: Create a windows station using CreateWindowStationA() without excessive privileges
 *    BadSink : Create a windows station using CreateWindowStationA() with excessive privileges
 * Flow Variant: 05 Control flow: if(staticTrue) and if(staticFalse)
 *
 * */

#include "std_testcase.h"

#include <windows.h>
#pragma comment( lib, "user32" )

/* The two variables below are not defined as "const", but are never
   assigned any other value, so a tool should be able to identify that
   reads of these will always return their initialized values. */
static int staticTrue = 1; /* true */
static int staticFalse = 0; /* false */

#ifndef OMITBAD

void CWE284_Improper_Access_Control__w32_char_CreateWindowStation_05_bad()
{
    if(staticTrue)
    {
        {
            HWINSTA hWinStation;
            char * wStationName = "WindowsStationExample";
            /* FLAW: Call CreateWindowStationA() with GENERIC_ALL as the 3rd parameter */
            hWinStation = CreateWindowStationA(
                              wStationName,
                              0,
                              GENERIC_ALL,
                              NULL);
            if (hWinStation == NULL)
            {
                printLine("Windows station could not be created");
            }
            else
            {
                printLine("Windows Station created successfully");
                CloseWindowStation(hWinStation);
            }
        }
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* good1() uses if(staticFalse) instead of if(staticTrue) */
static void good1()
{
    if(staticFalse)
    {
        /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
        printLine("Benign, fixed string");
    }
    else
    {
        {
            HWINSTA hWinStation;
            char * wStationName = "WindowsStationExample";
            /* FIX: Call CreateWindowStationA() without GENERIC_READ as the 3rd parameter to limit access */
            hWinStation = CreateWindowStationA(
                              wStationName,
                              0,
                              GENERIC_READ,
                              NULL);
            if (hWinStation == NULL)
            {
                printLine("Windows station could not be created");
            }
            else
            {
                printLine("Windows Station created successfully");
                CloseWindowStation(hWinStation);
            }
        }
    }
}

/* good2() reverses the bodies in the if statement */
static void good2()
{
    if(staticTrue)
    {
        {
            HWINSTA hWinStation;
            char * wStationName = "WindowsStationExample";
            /* FIX: Call CreateWindowStationA() without GENERIC_READ as the 3rd parameter to limit access */
            hWinStation = CreateWindowStationA(
                              wStationName,
                              0,
                              GENERIC_READ,
                              NULL);
            if (hWinStation == NULL)
            {
                printLine("Windows station could not be created");
            }
            else
            {
                printLine("Windows Station created successfully");
                CloseWindowStation(hWinStation);
            }
        }
    }
}

void CWE284_Improper_Access_Control__w32_char_CreateWindowStation_05_good()
{
    good1();
    good2();
}

#endif /* OMITGOOD */

/* Below is the main(). It is only used when building this testcase on
   its own for testing or for building a binary to use in testing binary
   analysis tools. It is not used when compiling all the testcases as one
   application, which is how source code analysis tools are tested. */

#ifdef INCLUDEMAIN

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    CWE284_Improper_Access_Control__w32_char_CreateWindowStation_05_good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    CWE284_Improper_Access_Control__w32_char_CreateWindowStation_05_bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif

redpajama_set_name: RedPajamaGithub


text:
package org.apache.cassandra.config;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.google.common.base.Objects;

public class ParameterizedClass
{
    public String class_name;
    public Map<String, String> parameters;

    public ParameterizedClass(String class_name, Map<String, String> parameters)
    {
        this.class_name = class_name;
        this.parameters = parameters;
    }

    @SuppressWarnings("unchecked")
    public ParameterizedClass(LinkedHashMap<String, ?> p)
    {
        this((String)p.get("class_name"),
                p.containsKey("parameters") ? (Map<String, String>)((List<?>)p.get("parameters")).get(0) : null);
    }

    @Override
    public boolean equals(Object that)
    {
        return that instanceof ParameterizedClass && equals((ParameterizedClass) that);
    }

    public boolean equals(ParameterizedClass that)
    {
        return Objects.equal(class_name, that.class_name) && Objects.equal(parameters, that.parameters);
    }

    @Override
    public String toString()
    {
        return class_name + (parameters == null ? "" : parameters.toString());
    }
}


text:
#include "dcmtk/config/osconfig.h"     /* make sure OS specific configuration is included first */

#include "dcmtk/dcmdata/dctk.h"
#include "dcmtk/dcmdata/dcuid.h"       /* for dcmtk version name */
#include "dcmtk/dcmdata/dcddirif.h"    /* for class DicomDirInterface */
#include "dcmtk/ofstd/ofstd.h"         /* for class OFStandard */
#include "dcmtk/ofstd/ofconapp.h"      /* for class OFConsoleApplication */
#include "dcmtk/ofstd/ofcond.h"        /* for class OFCondition */

#ifdef BUILD_DCMGPDIR_AS_DCMMKDIR
#include "dcmtk/dcmimage/diregist.h"   /* include to support color images */
#include "dcmtk/dcmdata/dcrledrg.h"    /* for DcmRLEDecoderRegistration */
#include "dcmtk/dcmjpeg/djdecode.h"    /* for dcmjpeg decoders */
#include "dcmtk/dcmjpeg/dipijpeg.h"    /* for dcmimage JPEG plugin */
#include "dcmtk/dcmjpeg/ddpiimpl.h"    /* for class DicomDirImageImplementation */
#endif

#ifdef WITH_ZLIB
#include <zlib.h>         /* for zlibVersion() */
#endif

#ifdef BUILD_DCMGPDIR_AS_DCMMKDIR
#define OFFIS_CONSOLE_APPLICATION "dcmmkdir"
#define OFFIS_CONSOLE_DESCRIPTION "Create a DICOMDIR file"
#else
#define OFFIS_CONSOLE_APPLICATION "dcmgpdir"
#define OFFIS_CONSOLE_DESCRIPTION "Create a general purpose DICOMDIR"
#endif

#if defined (HAVE_WINDOWS_H) || defined(HAVE_FNMATCH_H)
#define PATTERN_MATCHING_AVAILABLE
#endif

static char rcsid[] = "$dcmtk: " OFFIS_CONSOLE_APPLICATION " v"
  OFFIS_DCMTK_VERSION " " OFFIS_DCMTK_RELEASEDATE " $";

static OFLogger dcmgpdirLogger = OFLog::getLogger("dcmtk.dcmdata." OFFIS_CONSOLE_APPLICATION);

#define SHORTCOL 4
#define LONGCOL 23

// ********************************************

int main(int argc, char *argv[])
{
    OFBool opt_write = OFTrue;
    OFBool opt_append = OFFalse;
    OFBool opt_update = OFFalse;
    OFBool opt_recurse = OFFalse;
    E_EncodingType opt_enctype = EET_ExplicitLength;
    E_GrpLenEncoding opt_glenc = EGL_withoutGL;
    const char *opt_output = DEFAULT_DICOMDIR_NAME;
    const char *opt_fileset = DEFAULT_FILESETID;
    const char *opt_descriptor = NULL;
    const char *opt_charset = DEFAULT_DESCRIPTOR_CHARSET;
    const char *opt_directory = "";
    const char *opt_pattern = "";
    DicomDirInterface::E_ApplicationProfile opt_profile = DicomDirInterface::AP_GeneralPurpose;

#ifdef BUILD_DCMGPDIR_AS_DCMMKDIR
    // register global decompression codecs (no verbose/debug mode set)
    DcmRLEDecoderRegistration::registerCodecs();
    DJDecoderRegistration::registerCodecs();
    // enable the following lines for JPEG 2000 decompression support
/*
    D2JPEG2000Library::initialize();
    D2DecoderRegistration::registerCodecs();
*/
#endif

    /* DICOMDIR interface (checks for JPEG/RLE availability) */
    DicomDirInterface ddir;

    /* set-up command line parameters and options */
    OFConsoleApplication app(OFFIS_CONSOLE_APPLICATION, OFFIS_CONSOLE_DESCRIPTION, rcsid);
    OFCommandLine cmd;
    cmd.setOptionColumns(LONGCOL, SHORTCOL);
    cmd.setParamColumn(LONGCOL + SHORTCOL + 4);

    cmd.addParam("dcmfile-in", "referenced DICOM file (or directory to be scanned)", OFCmdParam::PM_MultiOptional);

    cmd.addGroup("general options:", LONGCOL, SHORTCOL + 2);
     cmd.addOption("--help",                     "-h",     "print this help text and exit", OFCommandLine::AF_Exclusive);
     cmd.addOption("--version",                            "print version information and exit", OFCommandLine::AF_Exclusive);
     OFLog::addOptions(cmd);

    cmd.addGroup("input options:");
      cmd.addSubGroup("DICOMDIR identifiers:");
        cmd.addOption("--fileset-id",            "+F",  1, "[i]d: string (default: " DEFAULT_FILESETID ")",
                                                           "use specific file set ID");
        cmd.addOption("--descriptor",            "+R",  1, "[f]ilename: string",
                                                           "add a file set descriptor file ID\n(e.g. README, default: no descriptor)");
        cmd.addOption("--char-set",              "+C",  1, "[c]harset: string",
                                                           "add a specific character set for descriptor\n(default: \"" DEFAULT_DESCRIPTOR_CHARSET "\" if descriptor present)");
      cmd.addSubGroup("reading:");
        cmd.addOption("--input-directory",       "+id", 1, "[d]irectory: string",
                                                           "read referenced DICOM files from directory d\n(default for --recurse: current directory)");
        cmd.addOption("--keep-filenames",        "-m",     "expect filenames to be in DICOM format (def.)");
        cmd.addOption("--map-filenames",         "+m",     "map to DICOM filenames (lowercase->uppercase,\nand remove trailing period)");
        cmd.addOption("--no-recurse",            "-r",     "do not recurse within directories (default)");
        cmd.addOption("--recurse",               "+r",     "recurse within filesystem directories");
#ifdef PATTERN_MATCHING_AVAILABLE
        cmd.addOption("--pattern",               "+p",  1, "[p]attern: string (only with --recurse)",
                                                           "pattern for filename matching (wildcards)");
#endif
    cmd.addGroup("processing options:");
      cmd.addSubGroup("consistency check:");
        cmd.addOption("--no-consistency-check",  "-W",     "do not check files for consistency");
        cmd.addOption("--warn-inconsist-files",  "+W",     "warn about inconsistent files (default)");
        cmd.addOption("--abort-inconsist-file",  "-a",     "abort on first inconsistent file");
      cmd.addSubGroup("type 1 attributes:");
        cmd.addOption("--strict",                "-I",     "exit with error if DICOMDIR type 1 attributes\nare missing in DICOM file (default)");
        cmd.addOption("--invent",                "+I",     "invent DICOMDIR type 1 attributes\nif missing in DICOM file");
        cmd.addOption("--invent-patient-id",     "+Ipi",   "invent new PatientID in case of inconsistent\nPatientName attributes");
      cmd.addSubGroup("other checks:");
        cmd.addOption("--allow-retired-sop",     "+Nrs",   "allow retired SOP classes defined in previous\neditions of the DICOM standard");
        cmd.addOption("--no-xfer-check",         "-Nxc",   "do not reject images with non-standard\ntransfer syntax (just warn)");
#ifdef BUILD_DCMGPDIR_AS_DCMMKDIR
        cmd.addOption("--no-encoding-check",     "-Nec",   "do not reject images with non-standard\npixel encoding (just warn)");
        cmd.addOption("--no-resolution-check",   "-Nrc",   "do not reject images with non-standard\nspatial resolution (just warn)");
      cmd.addSubGroup("icon images:");
        cmd.addOption("--add-icon-image",        "+X",     "add monochrome icon image on IMAGE level\n(default for cardiac profiles)");
        cmd.addOption("--icon-image-size",       "-Xs", 1, "[s]ize: integer (1..128)",
                                                           "width and height of the icon image (in pixel)\n(fixed: 128 for XA, 64 for CT/MR profile)");
        cmd.addOption("--icon-file-prefix",      "-Xi", 1, "[p]refix: string",
                                                           "use PGM image 'prefix'+'dcmfile-in' as icon\n(default: create icon from DICOM image)");
        cmd.addOption("--default-icon",          "-Xd", 1, "[f]ilename: string",
                                                           "use specified PGM image if icon cannot be\ncreated automatically (default: black image)");
#endif
    cmd.addGroup("output options:");
      cmd.addSubGroup("DICOMDIR file:");
        cmd.addOption("--output-file",           "+D",  1, "[f]ilename: string",
                                                           "generate specific DICOMDIR file\n(default: " DEFAULT_DICOMDIR_NAME " in current directory)");
#ifdef BUILD_DCMGPDIR_AS_DCMMKDIR
      cmd.addSubGroup("profiles:");
        cmd.addOption("--general-purpose",       "-Pgp",   "General Purpose Interchange on CD-R or\nDVD-RAM Media (STD-GEN-CD/DVD-RAM, default)");
        cmd.addOption("--general-dvd-jpeg",      "-Pdv",   "General Purpose DVD Interchange with JPEG\n(STD-GEN-DVD-JPEG)");
        cmd.addOption("--general-dvd-j2k",       "-Pd2",   "General Purpose DVD Interchange with JPEG\n2000 (STD-GEN-DVD-J2K)");
        cmd.addOption("--general-bd-jpeg",       "-Pbd",   "General Purpose BD Interchange with JPEG\n(STD-GEN-BD-JPEG)");
        cmd.addOption("--general-bd-j2k",        "-Pb2",   "General Purpose BD Interchange with JPEG\n2000 (STD-GEN-BD-J2K)");
        cmd.addOption("--general-bd-mpeg2-mpml", "-Pbm",   "General Purpose BD Interchange with MPEG2\nMP@ML (STD-GEN-BD-MPEG2-MPML)");
        cmd.addOption("--general-bd-mpeg2-mphl", "-Pbh",   "General Purpose BD Interchange with MPEG2\nMP@HL (STD-GEN-BD-MPEG2-MPHL)");
        cmd.addOption("--general-bd-mpeg4-hp",   "-Pba",   "General Purpose BD Interchange with MPEG-4\nAVC/H.264 HiP@Level4.1\n(STD-GEN-BD-MPEG4-HPLV41)");
        cmd.addOption("--general-bd-mpeg4-hpbd", "-Pbb",   "General Purpose BD Interchange with MPEG-4\nAVC/H.264 BD-Compatible HiP@Level4.1\n(STD-GEN-BD-MPEG4-HPLV41BD)");
        cmd.addOption("--usb-and-flash-jpeg",    "-Pfl",   "General Purpose USB/Flash Memory Interchange\nwith JPEG (STD-GEN-USB/MMC/CF/SD-JPEG)");
        cmd.addOption("--usb-and-flash-j2k",     "-Pf2",   "General Purpose USB/Flash Memory Interchange\nwith JPEG 2000 (STD-GEN-USB/MMC/CF/SD-J2K)");
        cmd.addOption("--general-mime",          "-Pmi",   "General Purpose MIME Interchange\n(STD-GEN-MIME)");
        cmd.addOption("--mpeg2-mpml-dvd",        "-Pmp",   "DVD Interchange with MPEG2 Main Profile @\nMain Level (STD-DVD-MPEG2-MPML)");
        cmd.addOption("--basic-cardiac",         "-Pbc",   "Basic Cardiac X-Ray Angiographic Studies on\nCD-R Media (STD-XABC-CD)");
        cmd.addOption("--xray-angiographic",     "-Pxa",   "1024 X-Ray Angiographic Studies on CD-R Media\n(STD-XA1K-CD)");
        cmd.addOption("--xray-angiographic-dvd", "-Pxd",   "1024 X-Ray Angiographic Studies on DVD Media\n(STD-XA1K-DVD)");
        cmd.addOption("--dental-radiograph",     "-Pde",   "Dental Radiograph Interchange (STD-DEN-CD)");
        cmd.addOption("--ct-and-mr",             "-Pcm",   "CT/MR Studies (STD-CTMR-xxxx)");
        cmd.addOption("--ultrasound-id-sf",      "-Pus",   "Ultrasound Single Frame for Image Display\n(STD-US-ID-SF-xxxx)");
        cmd.addOption("--ultrasound-sc-sf",                "Ultrasound Single Frame with Spatial\nCalibration (STD-US-SC-SF-xxxx)");
        cmd.addOption("--ultrasound-cc-sf",                "Ultrasound Single Frame with Combined\nCalibration (STD-US-CC-SF-xxxx)");
        cmd.addOption("--ultrasound-id-mf",      "-Pum",   "Ultrasound Single & Multi-Frame for Image\nDisplay (STD-US-ID-MF-xxxx)");
        cmd.addOption("--ultrasound-sc-mf",                "Ultrasound Single & Multi-Frame with Spatial\nCalibration (STD-UD-SC-MF-xxxx)");
        cmd.addOption("--ultrasound-cc-mf",                "Ultrasound Single & Multi-Frame with Combined\nCalibration (STD-UD-CC-MF-xxxx)");
        cmd.addOption("--12-lead-ecg",           "-Pec",   "12-lead ECG Interchange on Diskette\n(STD-WVFM-ECG-FD)");
        cmd.addOption("--hemodynamic-waveform",  "-Phd",   "Hemodynamic Waveform Interchange on Diskette\n(STD-WVFM-HD-FD)");
#endif
      cmd.addSubGroup("writing:");
        cmd.addOption("--replace",               "-A",     "replace existing DICOMDIR (default)");
        cmd.addOption("--append",                "+A",     "append to existing DICOMDIR");
        cmd.addOption("--update",                "+U",     "update existing DICOMDIR");
        cmd.addOption("--discard",               "-w",     "do not write out DICOMDIR");
        cmd.addOption("--no-backup",             "-nb",    "do not create a backup of existing DICOMDIR");
      cmd.addSubGroup("post-1993 value representations:");
        cmd.addOption("--enable-new-vr",         "+u",     "enable support for new VRs (UN/UT) (default)");
        cmd.addOption("--disable-new-vr",        "-u",     "disable support for new VRs, convert to OB");
      cmd.addSubGroup("group length encoding:");
        cmd.addOption("--group-length-remove",   "-g",     "write without group length elements (default)");
        cmd.addOption("--group-length-create",   "+g",     "write with group length elements");
      cmd.addSubGroup("length encoding in sequences and items:");
        cmd.addOption("--length-explicit",       "+e",     "write with explicit lengths (default)");
        cmd.addOption("--length-undefined",      "-e",     "write with undefined lengths");

    /* evaluate command line */
    prepareCmdLineArgs(argc, argv, OFFIS_CONSOLE_APPLICATION);
    if (app.parseCommandLine(cmd, argc, argv))
    {
        /* print help text and exit */
        if (cmd.getArgCount() == 0)
            app.printUsage();

        /* check exclusive options first */
        if (cmd.hasExclusiveOption())
        {
            if (cmd.findOption("--version"))
            {
                app.printHeader(OFTrue /*print host identifier*/);
                COUT << OFendl << "External libraries used:";
#if !defined(WITH_ZLIB) && !defined(BUILD_DCMGPDIR_AS_DCMMKDIR)
                COUT << " none" << OFendl;
#else
                COUT << OFendl;
#endif
#ifdef WITH_ZLIB
                COUT << "- ZLIB, Version " << zlibVersion() << OFendl;
#endif
#ifdef BUILD_DCMGPDIR_AS_DCMMKDIR
                COUT << "- " << DiJPEGPlugin::getLibraryVersionString() << OFendl;
#endif
                return 0;
            }
        }

        /* general options */
        OFLog::configureFromCommandLine(cmd, app);

        /* input options */
        if (cmd.findOption("--fileset-id"))
            app.checkValue(cmd.getValue(opt_fileset));
        if (cmd.findOption("--descriptor"))
            app.checkValue(cmd.getValue(opt_descriptor));
        if (cmd.findOption("--char-set"))
            app.checkValue(cmd.getValue(opt_charset));

        if (cmd.findOption("--input-directory"))
            app.checkValue(cmd.getValue(opt_directory));

        cmd.beginOptionBlock();
        if (cmd.findOption("--keep-filenames"))
            ddir.enableMapFilenamesMode(OFFalse);
        if (cmd.findOption("--map-filenames"))
            ddir.enableMapFilenamesMode(OFTrue);
        cmd.endOptionBlock();

        cmd.beginOptionBlock();
        if (cmd.findOption("--no-recurse"))
            opt_recurse = OFFalse;
        if (cmd.findOption("--recurse"))
        {
            opt_recurse = OFTrue;
            if ((opt_directory == NULL) || (strlen(opt_directory) == 0))
                opt_directory = ".";
        }
        cmd.endOptionBlock();

#ifdef PATTERN_MATCHING_AVAILABLE
        if (cmd.findOption("--pattern"))
        {
            app.checkDependence("--pattern", "--recurse", opt_recurse);
            app.checkValue(cmd.getValue(opt_pattern));
        }
#endif

        /* processing options */
        cmd.beginOptionBlock();
        if (cmd.findOption("--no-consistency-check"))
            ddir.disableConsistencyCheck();
        if (cmd.findOption("--warn-inconsist-files"))
            ddir.enableAbortMode(OFFalse);
        if (cmd.findOption("--abort-inconsist-file"))
            ddir.enableAbortMode(OFTrue);
        cmd.endOptionBlock();

        cmd.beginOptionBlock();
        if (cmd.findOption("--strict"))
            ddir.enableInventMode(OFFalse);
        if (cmd.findOption("--invent"))
            ddir.enableInventMode(OFTrue);
        cmd.endOptionBlock();

        if (cmd.findOption("--invent-patient-id"))
            ddir.enableInventPatientIDMode();

        if (cmd.findOption("--allow-retired-sop"))
            ddir.enableRetiredSOPClassSupport();
        if (cmd.findOption("--no-xfer-check"))
            ddir.disableTransferSyntaxCheck();

#ifdef BUILD_DCMGPDIR_AS_DCMMKDIR
        if (cmd.findOption("--no-encoding-check"))
            ddir.disableEncodingCheck();
        if (cmd.findOption("--no-resolution-check"))
            ddir.disableResolutionCheck();
        if (cmd.findOption("--add-icon-image"))
            ddir.enableIconImageMode();
        if (cmd.findOption("--icon-image-size"))
        {
            OFCmdUnsignedInt iconSize = 0;
            app.checkValue(cmd.getValueAndCheckMinMax(iconSize, 1, 128));
            ddir.setIconSize(OFstatic_cast(unsigned int, iconSize));
        }
        if (cmd.findOption("--icon-file-prefix"))
        {
            const char *iconPrefix = NULL;
            app.checkValue(cmd.getValue(iconPrefix));
            ddir.setIconPrefix(iconPrefix);
        }
        if (cmd.findOption("--default-icon"))
        {
            const char *defaultIcon = NULL;
            app.checkValue(cmd.getValue(defaultIcon));
            ddir.setDefaultIcon(defaultIcon);
        }
#endif

        /* output options */
        if (cmd.findOption("--output-file"))
            app.checkValue(cmd.getValue(opt_output));

#ifdef BUILD_DCMGPDIR_AS_DCMMKDIR
        cmd.beginOptionBlock();
        if (cmd.findOption("--general-purpose"))
            opt_profile = DicomDirInterface::AP_GeneralPurpose;
        if (cmd.findOption("--general-dvd-jpeg"))
            opt_profile = DicomDirInterface::AP_GeneralPurposeDVDJPEG;
        if (cmd.findOption("--general-dvd-j2k"))
            opt_profile = DicomDirInterface::AP_GeneralPurposeDVDJPEG2000;
        if (cmd.findOption("--general-bd-jpeg"))
            opt_profile = DicomDirInterface::AP_GeneralPurposeBDJPEG;
        if (cmd.findOption("--general-bd-j2k"))
            opt_profile = DicomDirInterface::AP_GeneralPurposeBDJPEG2000;
        if (cmd.findOption("--general-bd-mpeg2-mpml"))
            opt_profile = DicomDirInterface::AP_GeneralPurposeBDMPEG2MPatML;
        if (cmd.findOption("--general-bd-mpeg2-mphl"))
            opt_profile = DicomDirInterface::AP_GeneralPurposeBDMPEG2MPatHL;
        if (cmd.findOption("--general-bd-mpeg4-hp"))
            opt_profile = DicomDirInterface::AP_GeneralPurposeBDMPEG4HPatLV41;
        if (cmd.findOption("--general-bd-mpeg4-hpbd"))
            opt_profile = DicomDirInterface::AP_GeneralPurposeBDMPEG4HPatLV41BD;
        if (cmd.findOption("--usb-and-flash-jpeg"))
            opt_profile = DicomDirInterface::AP_USBandFlashJPEG;
        if (cmd.findOption("--usb-and-flash-j2k"))
            opt_profile = DicomDirInterface::AP_USBandFlashJPEG2000;
        if (cmd.findOption("--general-mime"))
            opt_profile = DicomDirInterface::AP_GeneralPurposeMIME;
        if (cmd.findOption("--mpeg2-mpml-dvd"))
            opt_profile = DicomDirInterface::AP_MPEG2MPatMLDVD;
        if (cmd.findOption("--basic-cardiac"))
            opt_profile = DicomDirInterface::AP_BasicCardiac;
        if (cmd.findOption("--xray-angiographic"))
            opt_profile = DicomDirInterface::AP_XrayAngiographic;
        if (cmd.findOption("--xray-angiographic-dvd"))
            opt_profile = DicomDirInterface::AP_XrayAngiographicDVD;
        if (cmd.findOption("--dental-radiograph"))
            opt_profile = DicomDirInterface::AP_DentalRadiograph;
        if (cmd.findOption("--ct-and-mr"))
            opt_profile = DicomDirInterface::AP_CTandMR;
        if (cmd.findOption("--ultrasound-id-sf"))
            opt_profile = DicomDirInterface::AP_UltrasoundIDSF;
        if (cmd.findOption("--ultrasound-sc-sf"))
            opt_profile = DicomDirInterface::AP_UltrasoundSCSF;
        if (cmd.findOption("--ultrasound-cc-sf"))
            opt_profile = DicomDirInterface::AP_UltrasoundCCSF;
        if (cmd.findOption("--ultrasound-id-mf"))
            opt_profile = DicomDirInterface::AP_UltrasoundIDMF;
        if (cmd.findOption("--ultrasound-sc-mf"))
            opt_profile = DicomDirInterface::AP_UltrasoundSCMF;
        if (cmd.findOption("--ultrasound-cc-mf"))
            opt_profile = DicomDirInterface::AP_UltrasoundCCMF;
        if (cmd.findOption("--12-lead-ecg"))
            opt_profile = DicomDirInterface::AP_TwelveLeadECG;
        if (cmd.findOption("--hemodynamic-waveform"))
            opt_profile = DicomDirInterface::AP_HemodynamicWaveform;
        cmd.endOptionBlock();
#endif

        cmd.beginOptionBlock();
        if (cmd.findOption("--replace"))
        {
            opt_write = OFTrue;
            opt_append = OFFalse;
            opt_update = OFFalse;
        }
        if (cmd.findOption("--append"))
        {
            opt_write = OFTrue;
            opt_append = OFTrue;
            opt_update = OFFalse;
        }
        if (cmd.findOption("--update"))
        {
            opt_write = OFTrue;
            opt_append = OFFalse;
            opt_update = OFTrue;
        }
        if (cmd.findOption("--discard"))
        {
            opt_write = OFFalse;
            opt_append = OFFalse;
            opt_update = OFFalse;
        }
        cmd.endOptionBlock();
        if (cmd.findOption("--no-backup"))
            ddir.disableBackupMode();

        cmd.beginOptionBlock();
        if (cmd.findOption("--enable-new-vr"))
        {
            dcmEnableUnknownVRGeneration.set(OFTrue);
            dcmEnableUnlimitedTextVRGeneration.set(OFTrue);
        }
        if (cmd.findOption("--disable-new-vr"))
        {
            dcmEnableUnknownVRGeneration.set(OFFalse);
            dcmEnableUnlimitedTextVRGeneration.set(OFFalse);
        }
        cmd.endOptionBlock();

        cmd.beginOptionBlock();
        if (cmd.findOption("--group-length-create"))
            opt_glenc = EGL_withGL;
        if (cmd.findOption("--group-length-remove"))
            opt_glenc = EGL_withoutGL;
        cmd.endOptionBlock();

        cmd.beginOptionBlock();
        if (cmd.findOption("--length-explicit"))
            opt_enctype = EET_ExplicitLength;
        if (cmd.findOption("--length-undefined"))
            opt_enctype = EET_UndefinedLength;
        cmd.endOptionBlock();

        /* post check */
        if ((opt_profile == DicomDirInterface::AP_BasicCardiac) ||
            (opt_profile == DicomDirInterface::AP_XrayAngiographic) ||
            (opt_profile == DicomDirInterface::AP_CTandMR))
        {
            app.checkConflict("--icon-image-size", "--basic-cardiac, --xray-angiographic or --ct-and-mr", cmd.findOption("--icon-image-size"));
        }
    }

    /* print resource identifier */
    OFLOG_DEBUG(dcmgpdirLogger, rcsid << OFendl);

    /* make sure data dictionary is loaded */
    if (!dcmDataDict.isDictionaryLoaded())
    {
        OFLOG_FATAL(dcmgpdirLogger, "no data dictionary loaded, check environment variable: "
            << DCM_DICT_ENVIRONMENT_VARIABLE);
        return 1;  /* DcmDicomDir class dumps core when no data dictionary present */
    }

    /* make sure input directory exists (if specified) */
    if ((opt_directory != NULL) && (strlen(opt_directory) > 0))
    {
        if (!OFStandard::dirExists(opt_directory))
        {
            OFLOG_FATAL(dcmgpdirLogger, "specified input directory does not exist");
            return 1;
        }
    }

    /* create list of input files */
    OFList<OFString> fileNames;
    OFString pathname;
    const char *param = NULL;
    const int count = cmd.getParamCount();
    if (opt_recurse)
        OFLOG_INFO(dcmgpdirLogger, "determining input files ...");
    /* no parameters? */
    if (count == 0)
    {
        if (opt_recurse)
            OFStandard::searchDirectoryRecursively("", fileNames, opt_pattern, opt_directory);
        else {
            OFLOG_FATAL(dcmgpdirLogger, "missing parameter dcmfile-in");
            return 1;
        }
    } else {
        /* iterate over all input filenames */
        for (int i = 1; i <= count; i++)
        {
            cmd.getParam(i, param);
            /* add input directory */
            OFStandard::combineDirAndFilename(pathname, opt_directory, param, OFTrue /*allowEmptyDirName*/);
            /* search directory recursively (if required) */
            if (OFStandard::dirExists(pathname))
            {
                if (opt_recurse)
                    OFStandard::searchDirectoryRecursively(param, fileNames, opt_pattern, opt_directory);
                else
                    OFLOG_WARN(dcmgpdirLogger, "ignoring directory because option --recurse is not set: " << param);
            } else
                fileNames.push_back(param);
        }
    }
    /* check whether there are any input files */
    if (fileNames.empty())
    {
        OFLOG_FATAL(dcmgpdirLogger, "no input files: DICOMDIR not created");
        return 1;
    }

#ifdef BUILD_DCMGPDIR_AS_DCMMKDIR
    // add image support to DICOMDIR class
    DicomDirImageImplementation imagePlugin;
    ddir.addImageSupport(&imagePlugin);
#endif

    OFCondition result;
    /* create new general purpose DICOMDIR, append to or update existing one */
    if (opt_append)
        result = ddir.appendToDicomDir(opt_profile, opt_output);
    else if (opt_update)
        result = ddir.updateDicomDir(opt_profile, opt_output);
    else
        result = ddir.createNewDicomDir(opt_profile, opt_output, opt_fileset);
    if (result.good())
    {
        /* set fileset descriptor and character set */
        result = ddir.setFilesetDescriptor(opt_descriptor, opt_charset);
        if (result.good())
        {
            /* collect 'bad' files */
            OFList<OFString> badFiles;
            unsigned int goodFiles = 0;
            OFListIterator(OFString) iter = fileNames.begin();
            OFListIterator(OFString) last = fileNames.end();
            /* iterate over all input filenames */
            while ((iter != last) && result.good())
            {
                /* add files to the DICOMDIR */
                result = ddir.addDicomFile((*iter).c_str(), opt_directory);
                if (result.bad())
                {
                    badFiles.push_back(*iter);
                    if (!ddir.abortMode())
                    {
                        /* ignore inconsistent file, just warn (already done inside "ddir") */
                        result = EC_Normal;
                    }
                } else
                    ++goodFiles;
                ++iter;
            }
            /* evaluate result of file checking/adding procedure */
            if (goodFiles == 0)
            {
                OFLOG_ERROR(dcmgpdirLogger, "no good files: DICOMDIR not created");
                result = EC_IllegalCall;
            }
            else if (!badFiles.empty())
            {
                OFOStringStream oss;
                oss << badFiles.size() << " file(s) cannot be added to DICOMDIR: ";
                iter = badFiles.begin();
                last = badFiles.end();
                while (iter != last)
                {
                    oss << OFendl << "  " << (*iter);
                    ++iter;
                }
                oss << OFStringStream_ends;
                OFSTRINGSTREAM_GETSTR(oss, tmpString)
                OFLOG_WARN(dcmgpdirLogger, tmpString);
                OFSTRINGSTREAM_FREESTR(tmpString)
            }
            /* write DICOMDIR file */
            if (result.good() && opt_write)
                result = ddir.writeDicomDir(opt_enctype, opt_glenc);
        }
    }

#ifdef BUILD_DCMGPDIR_AS_DCMMKDIR
    // deregister global decompression codecs
    DcmRLEDecoderRegistration::cleanup();
    DJDecoderRegistration::cleanup();
    // enable the following lines for JPEG 2000 decompression support
/*
    D2DecoderRegistration::cleanup();
    D2JPEG2000Library::cleanup();
*/
#endif

#ifdef DEBUG
    dcmDataDict.clear();  /* useful for debugging with dmalloc */
#endif

    return result.status();
}


text:
using System;
using Microsoft.AspNet.Mvc;
using WhatNow.Data.Ef;
using WhatNow.Ui.Web.Api.Models;

namespace WhatNow.Ui.Web.Api.Controllers
{
	[Route("api/[controller]")]
	public class LogsController : Controller
	{
		private readonly WhatNowDataEntities _dbContext;

		public LogsController(WhatNowDataEntities dbContext)
		{
			_dbContext = dbContext;
		}

		// POST api/values
		[HttpPost]
		public void Post([FromBody] LogRequest value)
		{
			var log = new Log
			{
				ItemId = value.ItemId,
				UserId = 1,
				Logged = value.DateTimeOverride ?? DateTime.UtcNow,
				CreateDate = DateTime.UtcNow
			};

			foreach (var controlLog in value.ControlLogs)
			{
				log.ControlLogs.Add(new ControlLog
				{
					ControlId = controlLog.ControlId,
					ControlOptionId = controlLog.ControlOptionId,
					Value = controlLog.Value
				});
			}

			_dbContext.Logs.Add(log);
			_dbContext.SaveChanges();
		}
	}
}


text:
#include <boost/detail/lightweight_test.hpp>
#include <boost/spirit/home/x3.hpp>

#include <iostream>
#include "test.hpp"

int
main()
{
    using spirit_test::test;
    using boost::spirit::x3::eps;
    using boost::spirit::x3::unused_type;

    {
        BOOST_SPIRIT_ASSERT_CONSTEXPR_CTORS(eps);
        BOOST_TEST((test("", eps)));
        BOOST_TEST((test("xxx", eps, false)));
        //~ BOOST_TEST((!test("", !eps))); // not predicate $$$ Implement me! $$$
    }

    {   // test non-lazy semantic predicate

        BOOST_SPIRIT_ASSERT_CONSTEXPR_CTORS(eps(true));
        BOOST_TEST((test("", eps(true))));
        BOOST_TEST((!test("", eps(false))));
        BOOST_TEST((test("", !eps(false))));
    }

    {   // test lazy semantic predicate

        auto true_ = [](unused_type) { return true; };
        auto false_ = [](unused_type) { return false; };

        // cannot use lambda in constant expression before C++17
        BOOST_SPIRIT_ASSERT_CONSTEXPR_CTORS(eps(std::true_type{}));
        BOOST_TEST((test("", eps(true_))));
        BOOST_TEST((!test("", eps(false_))));
        BOOST_TEST((test("", !eps(false_))));
    }

    return boost::report_errors();
}


text:
<sidebar></sidebar>

        <router-outlet></router-outlet>

    Copyright © 2016 Barsounds. All rights reserved.


text:
using System.Collections.Generic;
using System.ComponentModel.Composition;

namespace Utilities.DomainCommands
{
    [InheritedExport]
    public interface IValidationHandler<in TCommand>
    {
        IEnumerable<ValidationResult> Validate(TCommand command);
    }
}


text:
Bug #42976 (Crash when constructor for newInstance() or newInstanceArgs() fails)
--FILE--
<?php

Class C {
	function __construct(&$x) {
		$x = "x.changed";
	}
}

$x = "x.original";
new C($x); // OK
var_dump($x);

$rc = new ReflectionClass('C');
$x = "x.original";
$rc->newInstance($x); // causes crash
var_dump($x);
$x = "x.original";
$rc->newInstanceArgs(array($x)); // causes crash
var_dump($x);

echo "Done\n";
?>
--EXPECTF--
string(9) "x.changed"

Warning: Parameter 1 to C::__construct() expected to be a reference, value given in %sbug42976.php on line 15

Warning: ReflectionClass::newInstance(): Invocation of C's constructor failed in %sbug42976.php on line 15
string(10) "x.original"

Warning: Parameter 1 to C::__construct() expected to be a reference, value given in %sbug42976.php on line 18

Warning: ReflectionClass::newInstanceArgs(): Invocation of C's constructor failed in %sbug42976.php on line 18
string(10) "x.original"
Done


text:
package me.lorenc.dreadlogs.captor.log4j.functional;

import static me.lorenc.dreadlogs.captor.log4j.Log4jMatchers.hasLog;
import static me.lorenc.dreadlogs.captor.log4j.Log4jMatchers.noLog;
import static org.apache.log4j.Level.*;
import static org.junit.Assert.assertThat;

import org.apache.log4j.Logger;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;

import me.lorenc.dreadlogs.captor.log4j.Log4jCaptor;

public class Log4jCaptorLogLevelFilteringFunctionalTest {

    private static final String LOGGER_NAME = "me.lorenc.dreadlogs.some.package";

    private Logger logger;

    @Rule
    public Log4jCaptor captor = new Log4jCaptor(LOGGER_NAME);

    @Before
    public void before() throws Exception {
        logger = Logger.getLogger(LOGGER_NAME);
    }

    @Test
    public void shouldCaptureFatalLog() throws Exception {

        logger.fatal("fatal message");

        assertThat(captor, hasLog(FATAL, "fatal message"));
    }

    @Test
    public void shouldCaptureErrorLog() throws Exception {

        logger.error("error message");

        assertThat(captor, hasLog(ERROR, "error message"));
    }

    @Test
    public void shouldCaptureWarnLog() throws Exception {

        logger.warn("warn message");

        assertThat(captor, hasLog(WARN, "warn message"));
    }

    @Test
    public void shouldCaptureInfoLog() throws Exception {

        logger.info("info message");

        assertThat(captor, hasLog(INFO, "info message"));
    }

    @Test
    public void shouldCaptureDebugLog() throws Exception {

        logger.debug("debug message");

        assertThat(captor, hasLog(DEBUG, "debug message"));
    }

    @Test
    public void shouldCaptureTraceLog() throws Exception {

        logger.trace("trace message");

        assertThat(captor, hasLog(TRACE, "trace message"));
    }

    @Test
    public void shouldNotFindLogsOnOtherLevels() throws Exception {

        logger.info("a message");

        assertThat(captor, hasLog(INFO, "a message"));

        assertThat(captor, noLog(FATAL, "a message"));
        assertThat(captor, noLog(ERROR, "a message"));
        assertThat(captor, noLog(WARN, "a message"));
        assertThat(captor, noLog(DEBUG, "a message"));
        assertThat(captor, noLog(TRACE, "a message"));
    }

    @Test
    public void shouldNotCaptureFatalLogIfLevelDisabled() throws Exception {
        Log4jCaptor captor = new Log4jCaptor(LOGGER_NAME, OFF);

        logger.fatal("fatal message");

        assertThat(captor, noLog("fatal message"));
    }

    @Test
    public void shouldNotCaptureErrorLogIfLevelDisabled() throws Exception {
        Log4jCaptor captor = new Log4jCaptor(LOGGER_NAME, FATAL);

        logger.error("error message");

        assertThat(captor, noLog("error message"));
    }

    @Test
    public void shouldNotCaptureInfoLogIfLevelDisabled() throws Exception {
        Log4jCaptor captor = new Log4jCaptor(LOGGER_NAME, WARN);

        logger.info("info message");

        assertThat(captor, noLog("info message"));
    }

    @Test
    public void shouldNotCaptureDebugLogIfLevelDisabled() throws Exception {
        Log4jCaptor captor = new Log4jCaptor(LOGGER_NAME, INFO);

        logger.debug("debug message");

        assertThat(captor, noLog("debug message"));
    }

    @Test
    public void shouldNotCaptureTraceLogIfLevelDisabled() throws Exception {
        Log4jCaptor captor = new Log4jCaptor(LOGGER_NAME, DEBUG);

        logger.trace("trace message");

        assertThat(captor, noLog("trace message"));
    }

}


text:
<component name="libraryTable">
  <library name="Maven: org.infinispan:infinispan-server-core:test-jar:tests:7.0.1-SNAPSHOT">
    <CLASSES>
      <root url="jar://$MAVEN_REPOSITORY$/org/infinispan/infinispan-server-core/7.0.1-SNAPSHOT/infinispan-server-core-7.0.1-SNAPSHOT-tests.jar!/" />
    </CLASSES>
    <JAVADOC>
      <root url="jar://$MAVEN_REPOSITORY$/org/infinispan/infinispan-server-core/7.0.1-SNAPSHOT/infinispan-server-core-7.0.1-SNAPSHOT-test-javadoc.jar!/" />
    </JAVADOC>
    <SOURCES>
      <root url="jar://$MAVEN_REPOSITORY$/org/infinispan/infinispan-server-core/7.0.1-SNAPSHOT/infinispan-server-core-7.0.1-SNAPSHOT-test-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
using System.Collections.Generic;

namespace DynThings.WebAPI.Models
{
    public class APIAppThingExtension
    {
        public long ID { get; set; }
        public System.Guid GUID { get; set; }
        public string Code { get; set; }
        public string Title { get; set; }
        public long AppId { get; set; }
        public string ThingTypeCode { get; set; }
        public APIDataType DataType { get; set; }
        public bool IsList { get; set; }

    }
}


text:
<!DOCTYPE html>

        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

PieChart3DDemo1

            A pie chart showing a breakdown of export data by product category
            for New Zealand exports in 2012.  The source of the data is
            http://www.stats.govt.nz/browse_for_stats/snapshots-of-nz/nz-in-profile-2013.aspx.


text:
title: Debugging Virtual Machines
description: Describes tools and techniques to diagnose issues with Virtual Machines.
weight: 80
keywords: [debug,virtual-machines,envoy]
owner: istio/wg-environments-maintainers
test: n/a
---

This page describes how to troubleshoot issues with Istio deployed to Virtual Machines.
Before reading this, you should take the steps in [Virtual Machine Installation](/docs/setup/install/virtual-machine/).
Additionally, [Virtual Machine Architecture](/docs/ops/deployment/vm-architecture/) can help you understand how the components interact.

Troubleshooting an Istio Virtual Machine installation is similar to troubleshooting issues with proxies running inside Kubernetes, but there are some key differences to be aware of.

While much of the same information is available on both platforms, accessing this information differs.

## Monitoring health

The Istio sidecar is typically run as a `systemd` unit. To ensure its running properly, you can check that status:

{{< text bash >}}
$ systemctl status istio
{{< /text  >}}

Additionally, the sidecar health can be programmatically check at its health endpoint:

{{< text bash >}}
$ curl localhost:15021/healthz/ready -I
{{< /text  >}}

## Logs

Logs for the Istio proxy can be found in a few places.

To access the `systemd` logs, which has details about the initialization of the proxy:

{{< text bash >}}
$ journalctl -f -u istio -n 1000
{{< /text  >}}

The proxy will redirect `stderr` and `stdout` to `/var/log/istio/istio.err.log` and  `/var/log/istio/istio.log`, respectively.
To view these in a format similar to `kubectl`:

{{< text bash >}}
$ tail /var/log/istio/istio.err.log /var/log/istio/istio.log -Fq -n 100
{{< /text  >}}

Log levels can be modified by changing the `cluster.env` configuration file. Make sure to restart `istio` if it is already running:

{{< text bash >}}
$ echo "ISTIO_AGENT_FLAGS=\"--log_output_level=dns:debug --proxyLogLevel=debug\"" >> /var/lib/istio/envoy/cluster.env
$ systemctl restart istio
{{< /text  >}}

## Iptables

To ensure `iptables` rules have been successfully applied:

{{< text bash >}}
$ sudo iptables-save
...
-A ISTIO_OUTPUT -d 127.0.0.1/32 -j RETURN
-A ISTIO_OUTPUT -j ISTIO_REDIRECT
{{< /text  >}}

## Istioctl

Most `istioctl` commands will function properly with virtual machines. For example, `istioctl proxy-status` can be used to view all connected proxies:

{{< text bash >}}
$ istioctl proxy-status
NAME           CDS        LDS        EDS        RDS      ISTIOD                    VERSION
vm-1.default   SYNCED     SYNCED     SYNCED     SYNCED   istiod-789ffff8-f2fkt     {{< istio_full_version >}}
{{< /text  >}}

However, `istioctl proxy-config` relies on functionality in Kubernetes to connect to a proxy, which will not work for virtual machines.
Instead, a file containing the configuration dump from Envoy can be passed. For example:

{{< text bash >}}
$ curl -s localhost:15000/config_dump | istioctl proxy-config clusters --file -
SERVICE FQDN                            PORT      SUBSET  DIRECTION     TYPE
istiod.istio-system.svc.cluster.local   443       -       outbound      EDS
istiod.istio-system.svc.cluster.local   15010     -       outbound      EDS
istiod.istio-system.svc.cluster.local   15012     -       outbound      EDS
istiod.istio-system.svc.cluster.local   15014     -       outbound      EDS
{{< /text  >}}

## Automatic registration

When a virtual machine connects to Istiod, a `WorkloadEntry` will automatically be created. This enables
the virtual machine to become a part of a `Service`, similar to an `Endpoint` in Kubernetes.

To check these are created correctly:

{{< text bash >}}
$ kubectl get workloadentries
NAME             AGE   ADDRESS
vm-10.128.0.50   14m   10.128.0.50
{{< /text  >}}

## Certificates

Virtual machines handle certificates differently than Kubernetes Pods, which use a Kubernetes-provided service account token
to authenticate and renew mTLS certificates. Instead, existing mTLS credentials are used to authenticate with the certificate authority and
renew certificates.

The status of these certificates can be viewed in the same way as in Kubernetes:

{{< text bash >}}
$ curl -s localhost:15000/config_dump | ./istioctl proxy-config secret --file -
RESOURCE NAME     TYPE           STATUS     VALID CERT     SERIAL NUMBER                               NOT AFTER                NOT BEFORE
default           Cert Chain     ACTIVE     true           251932493344649542420616421203546836446     2021-01-29T18:07:21Z     2021-01-28T18:07:21Z
ROOTCA            CA             ACTIVE     true           81663936513052336343895977765039160718      2031-01-26T17:54:44Z     2021-01-28T17:54:44Z
{{< /text  >}}

Additionally, these are persisted to disk to ensure downtime or restarts do not lose state.

{{< text bash >}}
$ ls /etc/certs
cert-chain.pem  key.pem  root-cert.pem
{{< /text  >}}


text:
int main()
{
    {
    std::string_view sv = "12345678901234";
    std::basic_string s1{sv, 23}; // expected-error {{no viable constructor or deduction guide for deduction of template arguments of 'basic_string'}}
    }
}


text:
package com.axellience.vuegwt.core.client.tools;

import static jsinterop.base.Js.uncheckedCast;

import elemental2.core.JsArray;
import java.util.Collection;
import java.util.Map;
import jsinterop.base.JsPropertyMap;

public class JsUtils {

  @SafeVarargs
  public static <T> JsPropertyMap<T> map(JsObjectEntry<T>... entries) {
    JsPropertyMap<T> jsObject = (JsPropertyMap<T>) JsPropertyMap.of();
    for (JsObjectEntry<T> entry : entries) {
      jsObject.set(entry.getKey(), entry.getValue());
    }

    return jsObject;
  }

  public static <T> JsPropertyMap<T> map(String key, T value) {
    return (JsPropertyMap<T>) JsPropertyMap.of(key, value);
  }

  public static <T> JsObjectEntry<T> e(String key, T value) {
    return new JsObjectEntry<>(key, value);
  }

  @SafeVarargs
  public static <T> JsArray<T> array(T... array) {
    return new JsArray<>(array);
  }

  public static <T> JsArray<T> arrayFrom(Collection<T> collection) {
    return new JsArray<>(collection.toArray());
  }

  public static <K, V> JsArray<V> arrayFrom(Map<K, V> map) {
    JsArray<V> arr = new JsArray<>();
    map.values().forEach(arr::push);
    return arr;
  }

  public static <T> JsArray<T> arrayFrom(JsArray<T> array) {
    return array;
  }

  public static <T> JsArray<T> arrayFrom(T[] array) {
    return uncheckedCast(JsArray.from(array));
  }

  public static class JsObjectEntry<T> {

    private String key;
    private T value;

    JsObjectEntry(String key, T value) {
      this.key = key;
      this.value = value;
    }

    public String getKey() {
      return key;
    }

    public T getValue() {
      return value;
    }
  }
}


text:
@charset "utf-8";
/* CSS Document

xAccordion jQuery Plugin
Author: Alexandre Mattos <xandynnn>

*/

.xAccordion{margin-bottom:20px}
.xAccordion > ul{border-bottom:3px solid #d9d9d9;list-style:none;border-top:1px solid #d9d9d9}
.xAccordion > ul > li{padding:20px 10px;border-bottom:1px solid #d9d9d9;}
.xAccordion > ul > li a:link,
.xAccordion > ul > li a:visited{color:#838383;font-family:"GothamMedium", Arial, sans-serif;font-size:14px;}
.xAccordion > ul > li a:hover,
.xAccordion > ul > li a:focus{text-decoration:none;}
.xAccordion > ul > li a i{margin-right:12px;}
.xAccordion > ul > li.active a:link,
.xAccordion > ul > li.active a:visited,
.xAccordion > ul > li a:hover,
.xAccordion > ul > li.active a:active{color:#4195d3;text-decoration:none;}
.xAccordion > ul > li > div.contentSlider{padding:20px 0 20px 20px;}
.xAccordion > ul > li > div.contentSlider ul{list-style:circle;margin-bottom:10px;}
.xAccordion > ul > li > div.contentSlider ul > li{}
.xAccordion > ul > li > div.contentSlider p{color:#2f2f2f;font-family:"Arial", sans-serif;font-size:13px;margin:0 0 10px 0;}
.xAccordion > ul > li > div.contentSlider p.noMargin{margin:0;}

/* Botoes Ativo*/
.xAccordion > ul > li i.fa-angle-down{display:inline-block;}
.xAccordion > ul > li i.fa-angle-up{display:none;}
.xAccordion > ul > li.active i.fa-angle-down{display:none;}
.xAccordion > ul > li.active i.fa-angle-up{display:inline-block;}


text:
package org.jsondoc.springmvc.controller;

import java.util.List;

import org.jsondoc.core.pojo.JSONDoc;
import org.jsondoc.core.pojo.JSONDoc.MethodDisplay;
import org.jsondoc.core.scanner.JSONDocScanner;
import org.jsondoc.springmvc.scanner.Spring3JSONDocScanner;
import org.springframework.core.SpringVersion;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class JSONDocController {
	private String version;
	private String basePath;
	private List<String> packages;
	private JSONDocScanner jsondocScanner;
	private boolean playgroundEnabled = true;
	private MethodDisplay displayMethodAs = MethodDisplay.URI;

	public final static String JSONDOC_DEFAULT_PATH = "/jsondoc";

	public JSONDocController(String version, String basePath, List<String> packages) {
		this.version = version;
		this.basePath = basePath;
		this.packages = packages;
		String springVersion = SpringVersion.getVersion();
		if(springVersion != null && !springVersion.isEmpty()) {
			Integer majorSpringVersion = Integer.parseInt(springVersion.split("\\.")[0]);
			this.jsondocScanner = new Spring3JSONDocScanner();
		} else {
			this.jsondocScanner = new Spring3JSONDocScanner();
		}
	}

	public boolean isPlaygroundEnabled() {
		return playgroundEnabled;
	}

	public void setPlaygroundEnabled(boolean playgroundEnabled) {
		this.playgroundEnabled = playgroundEnabled;
	}

	public MethodDisplay getDisplayMethodAs() {
		return displayMethodAs;
	}

	public void setDisplayMethodAs(MethodDisplay displayMethodAs) {
		this.displayMethodAs = displayMethodAs;
	}

	@RequestMapping(value = JSONDocController.JSONDOC_DEFAULT_PATH, method = RequestMethod.GET)
	public @ResponseBody JSONDoc getApi() {
		return jsondocScanner.getJSONDoc(version, basePath, packages, playgroundEnabled, displayMethodAs);
	}

}


text:
WINDOWS BUILD NOTES
===================

Compilers Supported
-------------------
TODO: What works?
Note: releases are cross-compiled using mingw running on Linux.

Dependencies
------------
Libraries you need to download separately and build:

	name            default path               download
	--------------------------------------------------------------------------------------------------------------------
	OpenSSL         \openssl-1.0.1j-mgw        http://www.openssl.org/source/
	Berkeley DB     \db-5.3.28.NC-mgw          http://www.oracle.com/technology/software/products/berkeley-db/index.html
	Boost           \boost-1.57.0-mgw          http://www.boost.org/users/download/
	miniupnpc       \miniupnpc-1.9-mgw         http://miniupnp.tuxfamily.org/files/

Their licenses:

	OpenSSL        Old BSD license with the problematic advertising requirement
	Berkeley DB    New BSD license with additional requirement that linked software must be free open source
	Boost          MIT-like license
	miniupnpc      New (3-clause) BSD license

Versions used in this release:

	OpenSSL      1.0.1j
	Berkeley DB  5.3.28.NC
	Boost        1.57.0
	miniupnpc    1.9

OpenSSL
-------
MSYS shell:

un-tar sources with MSYS 'tar xfz' to avoid issue with symlinks (OpenSSL ticket 2377)
change 'MAKE' env. variable from 'C:\MinGW32\bin\mingw32-make.exe' to '/c/MinGW32/bin/mingw32-make.exe'

	cd /c/openssl-1.0.1j-mgw
	./config
	make

Berkeley DB
-----------
MSYS shell:

	cd /c/db-5.3.28.NC-mgw/build_unix
	sh ../dist/configure --enable-mingw --enable-cxx
	make

Boost
-----
MSYS shell:

	downloaded boost jam 3.1.18
	cd \boost-1.57.0-mgw
	bjam toolset=gcc --build-type=complete stage cxxflags="-std=c++11"

MiniUPnPc
---------
UPnP support is optional, make with `USE_UPNP=` to disable it.

MSYS shell:

	cd /c/miniupnpc-1.9-mgw
	make -f Makefile.mingw
	mkdir miniupnpc
	cp *.h miniupnpc/

Kryptohash
-------
MSYS shell:

	cd \kryptohash
	sh autogen.sh
	sh configure
	mingw32-make
	strip kryptohashd.exe


text:
import {
    Class,
    DefaultLabelStyle,
    Fill,
    Font,
    FontStyle,
    GraphEditorInputMode,
    HorizontalTextAlignment,
    IClipboardHelper,
    IEditLabelHelper,
    INode,
    INodeSizeConstraintProvider,
    IRenderContext,
    Insets,
    InteriorStretchLabelModel,
    InteriorStretchLabelModelPosition,
    ItemClickedEventArgs,
    LabelEditingEventArgs,
    MarkupExtension,
    NodeStyleBase,
    Point,
    Rect,
    ShapeNodeStyle,
    SimpleLabel,
    SimpleNode,
    Size,
    SolidColorFill,
    Stroke,
    SvgVisual,
    TextRenderSupport,
    TypeAttribute,
    VerticalTextAlignment,
    Visual,
    YObject
} from 'yfiles'

import { ModelClassModel } from '../ModelClassModel.js'
import {Attribute} from "../../attributes/Attribute";
import {Method} from "../../methods/Method";

// additional spacing after certain elements
const VERTICAL_SPACING = 2

// empty space before the text elements
const LEFT_SPACING = 25

/**
 * An UML node style that visualizes an ModelClassModel.
 */
export class UMLNodeStyle extends NodeStyleBase {
    /**
     * Returns the background fill.
     * @return {Fill}
     */
    get fill() {
        return this.$fill
    }

    /**
     * Sets the fill for the background.
     * @param {Fill} value
     */
    set fill(value) {
        this.$fill = value
    }

    /**
     * Returns the highlight background fill.
     * @return {Fill}
     */
    get highlightFill() {
        return this.$highlightFill
    }

    /**
     * Sets the fill for the highlight background.
     * @param {Fill} value
     */
    set highlightFill(value) {
        this.$highlightFill = value
    }

    /**
     * Gets the UML data of this style.
     * @returns {ModelClassModel}
     */
    get model() {
        return this.$model
    }

    /**
     * Sets the UML data for this style.
     * @param {ModelClassModel} model
     */
    set model(model) {
        this.$model = model
    }

    /**
     * Creates a new instance of the UML node style.
     * @param {ModelClassModel?} model The UML data that should be visualization by this style
     * @param {Fill?} fill The background fill of the header sections.
     * @param {Fill?} highlightFill The background fill of the selected entry.
     */
    constructor(model, fill, highlightFill) {
        super()
        this.$model = model || new ModelClassModel()
        this.$fill = fill || new SolidColorFill(0x60, 0x7d, 0x8b)
        this.$highlightFill = highlightFill || new SolidColorFill(0xa3, 0xf1, 0xbb)
        this.initializeStyles()
    }

    /**
     * Creates the UML node style visual based on the ModelClassModel.
     * @param {IRenderContext} ctx The render context.
     * @param {INode} node The node to which this style instance is assigned.
     * @returns {Visual}
     */
    createVisual(ctx, node) {
        this.initializeStyles() // fill color might have changed
        const data = this.$model
        const layout = node.layout
        const g = document.createElementNS('http://www.w3.org/2000/svg', 'g')
        g.setAttribute('class', 'uml-node')
        this.dummyNode.layout = new Rect(0, 0, layout.width, layout.height)
        g.appendChild(UMLNodeStyle.getCreator(this.dummyNode).createVisual(ctx).svgElement)

        let yOffset = 0

        // add the class label
        this.stretchLabelModel.insets = new Insets(0, yOffset, 0, 0)
        this.classLabel.text = ''
        g.appendChild(
            UMLNodeStyle.getCreator(this.classLabel, this.backgroundStyle).createVisual(ctx).svgElement
        )
        this.classLabel.text = data.className
        g.appendChild(UMLNodeStyle.getCreator(this.classLabel).createVisual(ctx).svgElement)

        // add stereotype
        if (data.stereotype) {
            this.stretchLabelModel.insets = new Insets(0, 5, 0, 0)
            this.stereotypeLabel.text = `<<${data.stereotype}>>`
            g.appendChild(UMLNodeStyle.getCreator(this.stereotypeLabel).createVisual(ctx).svgElement)
        }

        // add constraint
        if (data.constraint) {
            this.stretchLabelModel.insets = new Insets(0, 5, 0, 0)
            this.constraintLabel.text = `{${data.constraint}}`
            g.appendChild(UMLNodeStyle.getCreator(this.constraintLabel).createVisual(ctx).svgElement)
        }

        yOffset += this.classLabel.preferredSize.height

        let selectedIndex = -1
        if (ctx.canvasComponent.currentItem === node && data.selectedIndex >= 0) {
            selectedIndex = data.selectedIndex
        }

        yOffset += VERTICAL_SPACING
        this.stretchLabelModel.insets = new Insets(0, yOffset, 0, 0)
        this.categoryLabel.text = ''
        const attributesHeaderBackground = UMLNodeStyle.getCreator(
            this.categoryLabel,
            this.backgroundStyle
        ).createVisual(ctx).svgElement
        attributesHeaderBackground.setAttribute('cursor', 'pointer')
        g.appendChild(attributesHeaderBackground)
        this.categoryLabel.text = 'Attributes'
        this.stretchLabelModel.insets = new Insets(LEFT_SPACING, yOffset, 0, 0)
        const attributesTextElement = UMLNodeStyle.getCreator(this.categoryLabel).createVisual(ctx)
            .svgElement
        attributesTextElement.setAttribute('cursor', 'pointer')
        g.appendChild(attributesTextElement)

        yOffset += this.categoryLabel.preferredSize.height
        const attributesHeaderOffset = yOffset

        let counter = 0
        let hasLocalSelection = false
        let hasGlobalSelection = false
        if (data.attributesOpen) {
            for (let i = 0; i < data.attributes.length; i++, counter++) {
                if (counter === selectedIndex) {
                    hasGlobalSelection = true
                    hasLocalSelection = true
                    this.elementLabel.text = ''
                    this.elementLabel.style.backgroundFill = this.$highlightFill
                    this.stretchLabelModel.insets = new Insets(1, yOffset, 1, 0)
                    g.appendChild(UMLNodeStyle.getCreator(this.elementLabel).createVisual(ctx).svgElement)
                }
                if (data.attributes[i] !== null && typeof data.attributes[i] !== 'undefined') {
                    this.elementLabel.text = data.attributes[i].name
                    this.elementLabel.style.backgroundFill = null
                    this.stretchLabelModel.insets = new Insets(LEFT_SPACING, yOffset, 5, 0)
                    g.appendChild(UMLNodeStyle.getCreator(this.elementLabel).createVisual(ctx).svgElement)
                    yOffset += this.elementLabel.preferredSize.height
                }
            }
        } else {
            counter += data.attributes.length
        }
        if (attributesHeaderOffset <= layout.height) {
            this.addControls(
                ctx,
                attributesHeaderBackground,
                layout,
                data.attributesOpen,
                hasLocalSelection
            )
        }

        this.stretchLabelModel.insets = new Insets(0, yOffset, 0, 0)
        this.categoryLabel.text = ''
        const methodsHeaderBackground = UMLNodeStyle.getCreator(
            this.categoryLabel,
            this.backgroundStyle
        ).createVisual(ctx).svgElement
        methodsHeaderBackground.setAttribute('cursor', 'pointer')
        g.appendChild(methodsHeaderBackground)
        this.categoryLabel.text = 'methods'
        this.stretchLabelModel.insets = new Insets(LEFT_SPACING, yOffset, 0, 0)
        const methodsTextElement = UMLNodeStyle.getCreator(this.categoryLabel).createVisual(ctx)
            .svgElement
        methodsTextElement.setAttribute('cursor', 'pointer')
        g.appendChild(methodsTextElement)
        yOffset += this.categoryLabel.preferredSize.height
        const methodsHeaderOffset = yOffset

        hasLocalSelection = false
        if (data.methodsOpen) {
            for (let i = 0; i < data.methods.length; i++, counter++) {
                if (counter === selectedIndex) {
                    hasGlobalSelection = true
                    hasLocalSelection = true
                    this.elementLabel.text = ''
                    this.elementLabel.style.backgroundFill = this.$highlightFill
                    this.stretchLabelModel.insets = new Insets(1, yOffset, 1, 0)
                    g.appendChild(UMLNodeStyle.getCreator(this.elementLabel).createVisual(ctx).svgElement)
                }
                if (data.methods[i] !== null && typeof data.methods[i] !== 'undefined') {
                    this.elementLabel.text = data.methods[i].name
                    this.elementLabel.style.backgroundFill = null
                    this.stretchLabelModel.insets = new Insets(LEFT_SPACING, yOffset, 5, 0)
                    g.appendChild(UMLNodeStyle.getCreator(this.elementLabel).createVisual(ctx).svgElement)
                    yOffset += this.elementLabel.preferredSize.height
                }
            }
        }
        if (methodsHeaderOffset <= layout.height) {
            this.addControls(
                ctx,
                methodsHeaderBackground,
                layout,
                data.methodsOpen,
                hasLocalSelection
            )
        }

        SvgVisual.setTranslate(g, layout.x, layout.y)

        const svgVisual = new SvgVisual(g)
        svgVisual.data = {
            x: layout.x,
            y: layout.y,
            width: layout.width,
            height: layout.height,
            dataModCount: data.modCount,
            hasSelection: hasGlobalSelection,
            fill: this.$fill,
            highlightFill: this.$highlightFill
        }
        return svgVisual
    }

    /**
     * Updates the location of the UML node style. If anything other changed, a new visual is created.
     * @param {IRenderContext} ctx The render context.
     * @param {Visual} oldVisual The visual that has been created in the call to
     *   {@link NodeStyleBase#createVisual}.
     * @param {INode} node The node to which this style instance is assigned.
     * @returns {Visual}
     */
    updateVisual(ctx, oldVisual, node) {
        const layout = node.layout

        const data = oldVisual.data
        const model = this.$model
        if (
            !data ||
            data.dataModCount !== model.modCount ||
            (data.width !== layout.width || data.height !== layout.height) ||
            (data.hasSelection && ctx.canvasComponent.currentItem !== node) ||
            data.fill !== node.style.fill ||
            data.highlightFill !== node.style.highlightFill
        ) {
            return this.createVisual(ctx, node)
        }

        if (data.x !== layout.x || data.y !== layout.y) {
            SvgVisual.setTranslate(oldVisual.svgElement, layout.x, layout.y)
            data.x = layout.x
            data.y = layout.y
        }
        return oldVisual
    }

    /**
     * Return the size of this node considering the associated UML data.
     * @param {INode} node The node of which the size should be determined.
     * @returns {Size} The preferred size of this node.
     */
    getPreferredSize(node) {
        const data = this.$model

        // determine height
        let entries = data.attributesOpen ? data.attributes.length : 0
        entries += data.methodsOpen ? data.methods.length : 0
        const height =
            this.classLabel.preferredSize.height +
            VERTICAL_SPACING + // title section
            this.categoryLabel.preferredSize.height * 2 + // both section titles
            this.elementLabel.preferredSize.height * entries // visible entries

        // determine width
        let width = 125
        const elementFont = this.elementLabel.style.font
        const elements = data.attributes.concat(data.methods)
        elements.forEach(element => {
            const size = TextRenderSupport.measureText(element.name, elementFont)
            width = Math.max(width, size.width + LEFT_SPACING + 5)
        })
        const classNameSize = TextRenderSupport.measureText(data.className, this.classLabel.style.font)
        width = Math.max(width, classNameSize.width)
        const stereotypeSize = TextRenderSupport.measureText(
            data.stereotype,
            this.stereotypeLabel.style.font
        )
        width = Math.max(width, stereotypeSize.width)
        const constraintSize = TextRenderSupport.measureText(
            data.className,
            this.constraintLabel.style.font
        )
        width = Math.max(width, constraintSize.width)

        return new Size(width, height)
    }

    /**
     * Adjusts the size of the given node considering UML data of the node. If the current node layout is bigger than
     * the minimal needed size for the UML data then the current node layout will be used instead.
     * @param {INode} node The node whose size should be adjusted.
     * @param {GraphEditorInputMode} geim The responsible input mode.
     */
    adjustSize(node, geim) {
        const layout = node.layout
        const minSize = this.getPreferredSize(node)
        const width = Math.max(minSize.width, layout.width)
        const height = Math.max(minSize.height, layout.height)
        // GEIM's setNodeLayout handles affected orthogonal edges automatically
        geim.setNodeLayout(node, new Rect(layout.x, layout.y, width, height))
        geim.graphComponent.invalidate()
    }

    /**
     * Adjusts the height of the given node to fit the UML data.
     * @param {INode} node The node whose size should be adjusted.
     * @param {GraphEditorInputMode} geim The responsible input mode.
     * @private
     */
    fitHeight(node, geim) {
        const layout = node.layout
        const newSize = this.getPreferredSize(node)
        // GEIM's setNodeLayout handles affected orthogonal edges automatically
        geim.setNodeLayout(node, new Rect(layout.x, layout.y, layout.width, newSize.height))
        geim.graphComponent.invalidate()
    }

    /**
     * Upon label edit, we check which UML entry was hit and adjust the label edit accordingly. Additionally, we provide
     * an {@link INodeSizeConstraintProvider} to limit the interactive node resizing to the node's size
     * considering the attached UML data.
     * @param {INode} node The node to use for the context lookup.
     * @param {Class} type The type to query.
     * @returns {Object}
     */
    lookup(node, type) {
        const outerThis = this
        if (type === IEditLabelHelper.$class) {
            const oldData = this.$model.clone()
            return new IEditLabelHelper({
                onLabelAdding(evt) {
                    outerThis.editLabel(evt, node, true).then(newData => {
                        outerThis.handleUndo(evt.context.canvasComponent.inputMode, node, newData, oldData)
                    })
                },
                onLabelEditing(evt) {
                    outerThis.editLabel(evt, node, false).then(newData => {
                        outerThis.handleUndo(evt.context.canvasComponent.inputMode, node, newData, oldData)
                    })
                }
            })
        } else if (type === INodeSizeConstraintProvider.$class) {
            return new INodeSizeConstraintProvider({
                getMinimumSize: item => this.getPreferredSize(item),
                getMaximumSize: item => Size.INFINITE,
                getMinimumEnclosedArea: item => Rect.EMPTY
            })
        } else if (type === IClipboardHelper.$class) {
            return new IClipboardHelper({
                shouldCopy: (context, item) => true,
                shouldCut: (context, item) => true,
                shouldPaste: (context, item, userData) => true,
                copy: (context, item) => null,
                cut: (context, item) => null,
                paste: (context, item, userData) => {
                    const style = item.style
                    if (style instanceof UMLNodeStyle) {
                        if (context.targetGraph.foldingView) {
                            context.targetGraph.foldingView.manager.masterGraph.setStyle(item, style.clone())
                        } else {
                            context.targetGraph.setStyle(item, style.clone())
                        }
                    }
                }
            })
        }
        return null
    }

    /**
     * Manages text edits on the {@link UMLNodeStyle} by preconfiguring the {@link TextEditorInputMode}
     * with the text that should be edited and its position such that the label edit text box is opened on top of the
     * clicked text.
     * @param {LabelEditingEventArgs} evt The event args with which the edit label was triggered.
     * @param {INode} node The node whose label should be edited.
     * @param {boolean} adding Whether a new label is added or an existing one should be edited.
     * @return {Promise}
     * @private
     */
    editLabel(evt, node, adding) {
        const data = this.$model
        const index = data.selectedIndex
        const categoryHit = data.selectedCategory
        evt.cancel = true
        evt.handled = true
        const graphComponent = evt.context.canvasComponent
        const editorInputMode = graphComponent.inputMode

        const layout = this.getRelativeSlotLayout(index, node, adding, categoryHit)

        let text = ''
        if (!adding) {
            if (index < 0) {
                text = data.className
            } else if (index >= data.attributes.length) {
                text = data.methods[index - data.attributes.length].name || ''
            } else {
                text = data.attributes[index].name || ''
            }
        } else {
            // we add a dummy entry to make space for the label editing
            // eslint-disable-next-line no-lonely-if
            if (categoryHit === 1) {
                data.attributes.push(new Attribute({name: ""}))
                this.adjustSize(node, editorInputMode)
            } else if (categoryHit === 2) {
                data.methods.push(new Method({name: ""}))
                this.adjustSize(node, editorInputMode)
            }
        }

        editorInputMode.textEditorInputMode.editorText = text
        editorInputMode.textEditorInputMode.upVector = new Point(0, -1)
        const leftPadding = index < 0 ? 0 : LEFT_SPACING
        editorInputMode.textEditorInputMode.location = new Point(
            layout.x + node.layout.x + leftPadding,
            layout.y + node.layout.y + layout.height
        )
        editorInputMode.textEditorInputMode.anchor = new Point(0, 1)

        // actually edit the text and update the UML data model
        return editorInputMode.textEditorInputMode.edit().then(res => {
            if (res !== null) {
                if (index < 0) {
                    data.className = res
                } else if (categoryHit === 1) {
                    if (adding) {
                        data.attributes[data.attributes.length - 1].name = res
                        data.selectedIndex = data.attributes.length - 1
                    } else {
                        data.attributes[index].name = res
                    }
                } else if (categoryHit === 2) {
                    if (adding) {
                        data.methods[data.methods.length - 1].name = res
                        data.selectedIndex = data.attributes.length + (data.methods.length - 1)
                    } else {
                        data.methods[index - data.attributes.length].name = res
                    }
                }
            } else {
                // canceled, maybe remove the dummy entry
                // eslint-disable-next-line no-lonely-if
                if (adding) {
                    if (categoryHit === 1) {
                        data.attributes.splice(data.attributes.length - 1, 1)
                    } else if (categoryHit === 2) {
                        data.methods.splice(data.methods.length - 1, 1)
                    }
                    this.adjustSize(node, editorInputMode)
                }
            }
            data.modify()
            evt.context.canvasComponent.invalidate()
            return data
        })
    }

    /**
     * Clones this style and the associated UML model.
     * @returns {UMLNodeStyle}
     */
    clone() {
        const clone = super.clone()
        clone.model = clone.model.clone()
        return clone
    }

    /**
     * Handles clicks on this style.
     * @param {GraphEditorInputMode} geim
     * @param {ItemClickedEventArgs} args
     */
    nodeClicked(geim, args) {
        const node = args.item
        const data = this.$model
        const location = args.location
        const x = location.x - node.layout.x
        const y = location.y - node.layout.y

        //Todo decide if hard selection or listener. Current Listener: app.js (selectionChangedListener) -> probably better to use in input mode?!
        geim.graphComponent.selection.selectedNodes.clear()
        geim.graphComponent.selection.selectedNodes.setSelected(args.item, true)

        // the vertical relative coordinates of the different interactive parts
        const topAttributesCategory = this.classLabel.preferredSize.height + VERTICAL_SPACING
        const bottomAttributesCategory = topAttributesCategory + this.categoryLabel.preferredSize.height
        let topmethodsCategory = bottomAttributesCategory
        let bottommethodsCategory = topmethodsCategory + this.categoryLabel.preferredSize.height
        if (data.attributesOpen) {
            const attributesHeight = this.elementLabel.preferredSize.height * data.attributes.length
            topmethodsCategory += attributesHeight
            bottommethodsCategory += attributesHeight
        }

        // determine which section or button was clicked
        if (y < topAttributesCategory) {
            if (data.selectedIndex !== -1) {
                data.selectedIndex = -1
            }
            return
        } else if (y >= topAttributesCategory && y <= bottomAttributesCategory) {
            // the attributes header was clicked
            if (x >= 5 && x < node.layout.width - 36) {
                this.toggleOpenState(1, geim, node)
            } else if (x >= node.layout.width - 36 && x <= node.layout.width - 20) {
                this.addLabel(1, geim, node)
            } else if (
                x >= node.layout.width - 18 &&
                x <= node.layout.width - 2 &&
                data.selectedIndex >= 0 &&
                data.selectedIndex <= data.attributes.length - 1
            ) {
                this.removeLabel(1, geim, node)
            } else {
                if (data.selectedIndex !== -1) {
                    data.selectedIndex = -1
                }
                return
            }
        } else if (data.attributesOpen && y > bottomAttributesCategory && y < topmethodsCategory) {
            // an attribute was clicked
            data.selectedCategory = 1
            data.selectedIndex =
                ((y - bottomAttributesCategory) / this.elementLabel.preferredSize.height) | 0
        } else if (y >= topmethodsCategory && y <= bottommethodsCategory) {
            // the methods header was clicked
            if (x >= 5 && x < node.layout.width - 36) {
                this.toggleOpenState(2, geim, node)
            } else if (x >= node.layout.width - 36 && x <= node.layout.width - 20) {
                this.addLabel(2, geim, node)
            } else if (
                x >= node.layout.width - 18 &&
                x <= node.layout.width - 2 &&
                data.selectedIndex >= data.attributes.length &&
                data.selectedIndex <= data.attributes.length + data.methods.length - 1
            ) {
                this.removeLabel(2, geim, node)
            } else {
                if (data.selectedIndex !== -1) {
                    data.selectedIndex = -1
                }
                return
            }
        } else if (y > bottommethodsCategory) {
            // an method was clicked
            data.selectedCategory = 2
            data.selectedIndex =
                (data.attributes.length +
                    (y - (topmethodsCategory + this.categoryLabel.preferredSize.height)) /
                    this.elementLabel.preferredSize.height) |
                0
        } else {
            // a non-interactive part of the style was clicked, just do nothing
            return
        }

        //geim.inputModeContext.canvasComponent.currentItem = node
        geim.inputModeContext.canvasComponent.invalidate()
        args.handled = true
    }

    /**
     * Triggers interactive label adding.
     * @param {number} category 1 represents the attributes section, 2 represents the methods section
     * @param {GraphEditorInputMode} geim
     * @param {INode} node
     * @private
     */
    addLabel(category, geim, node) {
        const data = this.$model
        data.selectedCategory = category
        if (category === 1) {
            data.selectedIndex = Math.max(0, data.attributes.length)
            data.attributesOpen = true
        } else if (category === 2) {
            data.selectedIndex = Math.max(
                data.attributes.length,
                data.attributes.length + data.methods.length
            )
            data.methodsOpen = true
        }
        geim.clickInputMode.preventNextDoubleClick()
        geim.addLabel(node)
    }

    /**
     * Removes the selected label from the node.
     * @param {number} category 1 represents the attributes section, 2 represents the methods section
     * @param {GraphEditorInputMode} geim
     * @param {INode} node
     * @private
     */
    removeLabel(category, geim, node) {
        const data = this.$model
        const oldData = data.clone()
        data.selectedCategory = category
        if (category === 1) {
            data.attributes.splice(data.selectedIndex, 1)
        } else if (category === 2) {
            data.methods.splice(data.selectedIndex - data.attributes.length, 1)
        }
        data.selectedIndex = Math.min(
            data.selectedIndex,
            data.attributes.length + data.methods.length - 1
        )
        data.modify()
        geim.clickInputMode.preventNextDoubleClick()
        this.handleUndo(geim, node, data, oldData)
        this.adjustSize(node, geim)
    }

    /**
     * Toggles the open/closed state of the attributes or methods section.
     * @param {number} category 1 represents the attributes section, 2 represents the methods section
     * @param {GraphEditorInputMode} geim
     * @param {INode} node
     * @private
     */
    toggleOpenState(category, geim, node) {
        const data = this.$model
        if (category === 1) {
            data.attributesOpen = !data.attributesOpen
        } else if (category === 2) {
            data.methodsOpen = !data.methodsOpen
        }
        data.modify()
        this.fitHeight(node, geim)
        geim.clickInputMode.preventNextDoubleClick()
    }

    /**
     * Adds an undo unit to the graphs undo engine which may undo/redo the UML data change.
     * @param {GraphEditorInputMode} geim The responsible input mode.
     * @param {INode} node The node whose data is changed.
     * @param {ModelClassModel} newData The new data.
     * @param {ModelClassModel} oldData The previous data.
     * @private
     */
    handleUndo(geim, node, newData, oldData) {
        const graph = geim.graph
        const edit = graph.beginEdit('AddingLabel', 'AddingLabel')
        graph.addUndoUnit(
            'DataChanged',
            'DataChanged',
            () => {
                this.$model = oldData
                this.adjustSize(node, geim)
            },
            () => {
                this.$model = newData
                this.adjustSize(node, geim)
            }
        )
        edit.commit()
    }

    /**
     * Helper function to return the relative layout of a given slot index. A negative index indicates the class header
     * area.
     * @returns {Rect}
     * @private
     */
    getRelativeSlotLayout(slot, node, isAdding, category) {
        const data = this.$model
        const layout = node.layout

        if (slot < 0) {
            const classNameSize = TextRenderSupport.measureText(
                data.className,
                this.classLabel.style.font
            )
            return new Rect(
                layout.width / 2 - classNameSize.width / 2,
                0,
                layout.width,
                this.classLabel.preferredSize.height - 10
            )
        }

        // determine y-coordinate of the queried slot
        let top =
            this.classLabel.preferredSize.height +
            VERTICAL_SPACING +
            this.categoryLabel.preferredSize.height
        top += slot * this.elementLabel.preferredSize.height
        if ((isAdding && category === 2) || (!isAdding && slot >= data.attributes.length)) {
            // account for the methods category label
            top += this.categoryLabel.preferredSize.height
        }

        return new Rect(0, top, layout.width, this.elementLabel.preferredSize.height)
    }

    /**
     * Helper function to add the control buttons.
     * @private
     */
    addControls(ctx, container, nodeLayout, opened, enableRemoveButton) {
        const openMarker = document.createElementNS('http://www.w3.org/2000/svg', 'polygon')
        openMarker.setAttribute('fill', 'white')
        openMarker.setAttribute('points', opened ? '-5,-3.5 5,-3.5 0,6' : '-3.5,5 6,0 -3.5,-5')
        openMarker.setAttribute('transform', 'translate(12 10)')
        openMarker.setAttribute('class', 'uml-button')
        container.appendChild(openMarker)

        const plusBackground = document.createElementNS('http://www.w3.org/2000/svg', 'rect')
        Fill.setFill(this.$fill, plusBackground, ctx)
        plusBackground.setAttribute('x', `${nodeLayout.width - 37}px`)
        plusBackground.setAttribute('y', '2px')
        plusBackground.setAttribute('width', '16px')
        plusBackground.setAttribute('height', '16px')
        const plusButtonPath = document.createElementNS('http://www.w3.org/2000/svg', 'path')
        plusButtonPath.setAttribute('fill', 'white')
        plusButtonPath.setAttribute(
            'd',
            'M8.5,16.5c-4.418,0-8,3.582-8,8s3.582,8,8,8c4.418,0,8-3.582,8-8S12.918,16.5,8.5,16.5z M13.5,25.5h-4v4h-2v-4h-4v-2h4v-4h2v4h4V25.5z'
        )
        plusButtonPath.setAttribute('transform', `matrix(0.8 0 0 0.8 ${nodeLayout.width - 36} -10)`)
        const plus = document.createElementNS('http://www.w3.org/2000/svg', 'g')
        plus.setAttribute('class', 'uml-button')
        plus.appendChild(plusBackground)
        plus.appendChild(plusButtonPath)
        container.appendChild(plus)

        const minusButtonBackground = document.createElementNS('http://www.w3.org/2000/svg', 'rect')
        Fill.setFill(this.$fill, minusButtonBackground, ctx)
        minusButtonBackground.setAttribute('x', `${nodeLayout.width - 19}px`)
        minusButtonBackground.setAttribute('y', '2px')
        minusButtonBackground.setAttribute('width', '16px')
        minusButtonBackground.setAttribute('height', '16px')
        const minusButtonPath = document.createElementNS('http://www.w3.org/2000/svg', 'path')
        minusButtonPath.setAttribute('fill', 'white')
        minusButtonPath.setAttribute('fill-opacity', enableRemoveButton ? '1' : '0.5')
        minusButtonPath.setAttribute(
            'd',
            'M8.5,16.5c-4.418,0-8,3.582-8,8s3.582,8,8,8c4.418,0,8-3.582,8-8S12.918,16.5,8.5,16.5z M13.5,25.5h-10v-2h10V25.5z'
        )
        minusButtonPath.setAttribute('transform', `matrix(0.8 0 0 0.8 ${nodeLayout.width - 18} -10)`)
        const minus = document.createElementNS('http://www.w3.org/2000/svg', 'g')
        minus.setAttribute('class', enableRemoveButton ? 'uml-button' : 'uml-button disabled')
        minus.appendChild(minusButtonBackground)
        minus.appendChild(minusButtonPath)
        container.appendChild(minus)
    }

    /**
     * Helper method to initialize the dummy styles and label models that are used to build the UML node style.
     * @private
     */
    initializeStyles() {
        this.dummyNode = new SimpleNode()
        const stroke = new Stroke({
            fill: this.$fill,
            thickness: 2
        })
        stroke.freeze()
        this.dummyNode.style = new ShapeNodeStyle({ stroke })

        this.backgroundStyle = new DefaultLabelStyle({
            backgroundFill: this.$fill
        })

        this.stretchLabelModel = new InteriorStretchLabelModel()

        // initialize the category label visualization
        this.categoryLabel = new SimpleLabel(
            this.dummyNode,
            '',
            this.stretchLabelModel.createParameter(InteriorStretchLabelModelPosition.NORTH)
        )
        this.categoryLabel.style = new DefaultLabelStyle({
            textFill: Fill.WHITE,
            verticalTextAlignment: VerticalTextAlignment.CENTER
        })
        this.categoryLabel.preferredSize = new Size(1, 20)

        // initialize the element label visualization
        this.elementLabel = new SimpleLabel(
            this.dummyNode,
            '',
            this.stretchLabelModel.createParameter(InteriorStretchLabelModelPosition.NORTH)
        )
        this.elementLabel.style = new DefaultLabelStyle({
            verticalTextAlignment: VerticalTextAlignment.CENTER
        })
        this.elementLabel.preferredSize = new Size(1, 16)

        // initialize the class label visualization
        this.classLabel = new SimpleLabel(
            this.dummyNode,
            '',
            this.stretchLabelModel.createParameter(InteriorStretchLabelModelPosition.NORTH)
        )
        this.classLabel.style = new DefaultLabelStyle({
            textFill: Fill.WHITE,
            horizontalTextAlignment: HorizontalTextAlignment.CENTER,
            verticalTextAlignment: VerticalTextAlignment.CENTER
        })
        this.classLabel.preferredSize = new Size(1, 50)

        // initialize the stereotype label visualization
        this.stereotypeLabel = new SimpleLabel(
            this.dummyNode,
            '',
            this.stretchLabelModel.createParameter(InteriorStretchLabelModelPosition.NORTH)
        )
        this.stereotypeLabel.style = new DefaultLabelStyle({
            textFill: Fill.WHITE,
            horizontalTextAlignment: HorizontalTextAlignment.CENTER,
            font: new Font({
                fontStyle: FontStyle.ITALIC,
                fontSize: 10
            })
        })

        // initialize the constraint label visualization
        this.constraintLabel = new SimpleLabel(
            this.dummyNode,
            '',
            this.stretchLabelModel.createParameter(InteriorStretchLabelModelPosition.NORTH)
        )
        this.constraintLabel.style = new DefaultLabelStyle({
            textFill: Fill.WHITE,
            horizontalTextAlignment: HorizontalTextAlignment.CENTER,
            verticalTextAlignment: VerticalTextAlignment.BOTTOM,
            font: new Font({
                fontStyle: FontStyle.ITALIC,
                fontSize: 10
            })
        })
    }

    /**
     * Helper function to obtain the visual creator of the item.
     * @param {INode|ILabel} item
     * @param {INodeStyle|ILabelStyle?} itemStyle
     * @private
     */
    static getCreator(item, itemStyle) {
        itemStyle = itemStyle || item.style
        return itemStyle.renderer.getVisualCreator(item, itemStyle)
    }
}

/**
 * Markup extension needed to (de-)serialize the UML style.
 */
export const UMLNodeStyleExtension = Class('UMLNodeStyleExtension', {
    $extends: MarkupExtension,

    $fill: null,
    fill: {
        $meta() {
            return [TypeAttribute(Fill.$class)]
        },
        get() {
            return this.$fill
        },
        set(fill) {
            this.$fill = fill
        }
    },

    $highlightFill: null,
    highlightFill: {
        $meta() {
            return [TypeAttribute(Fill.$class)]
        },
        get() {
            return this.$highlightFill
        },
        set(fill) {
            this.$highlightFill = fill
        }
    },

    $model: null,
    model: {
        $meta() {
            return [TypeAttribute(YObject.$class)]
        },
        get() {
            return this.$model
        },
        set(model) {
            this.$model = model
        }
    },

    provideValue(serviceProvider) {
        return new UMLNodeStyle(this.model, this.fill, this.highlightFill)
    }
})

/**
 * Listener that handles the serialization of the UML style.

export const UMLNodeStyleSerializationListener = (sender, args) => {
    const item = args.item
    if (item instanceof UMLNodeStyle) {
        const umlNodeStyleExtension = new UMLNodeStyleExtension()
        umlNodeStyleExtension.fill = item.fill
        umlNodeStyleExtension.highlightFill = item.highlightFill
        umlNodeStyleExtension.model = item.model
        const context = args.context
        context.serializeReplacement(UMLNodeStyleExtension.$class, item, umlNodeStyleExtension)
        args.handled = true
    }
}

// export a default object to be able to map a namespace to this module for serialization
export default { UMLNodeStyle, UMLNodeStyleExtension }
 */


text:
FROM %%DOCKER_NAMESPACE%%/%%DOCKER_PREFIX%%freeipa-client:%%DOCKER_TAG%%

ENV HARBOR_COMPONENT="marina"

RUN set -e && \
    set -x && \
    dnf install -y \
        pwgen \
        git && \
    dnf clean all && \
    curl -L https://storage.googleapis.com/kubernetes-release/release/${HARBOR_KUBE_RELEASE_VERSION}/bin/linux/amd64/kubectl > /usr/bin/kubectl && \
    chmod +x /usr/bin/kubectl && \
    container-base-systemd-reset.sh

COPY ./common-assets/ /opt/harbor/common-assets

RUN set -e && \
    set -x && \
    cp -rf /opt/harbor/common-assets/* / && \
    rm -rf /opt/harbor/common-assets

LABEL license="Apache-2.0" \
      vendor="Port Direct" \
      url="https://port.direct/" \
      vcs-type="Git" \
      vcs-url="https://github.com/portdirect/harbor" \
      name="%%DOCKER_FULLIMAGE%%" \
      vcs-ref="%%DOCKER_TAG%%" \
      build-date="%%DOCKER_BUILD_DATE%%"