text:
using System;
using System.Collections.Generic;
using System.Linq;
using Content.Server.Administration;
using Content.Server.Interfaces.GameTicking;
using Content.Server.Players;
using Content.Shared.Administration;
using Content.Shared.Maps;
using Content.Shared.Roles;
using Robust.Server.Interfaces.Console;
using Robust.Server.Interfaces.Player;
using Robust.Shared.GameObjects.Components.Transform;
using Robust.Shared.Interfaces.GameObjects;
using Robust.Shared.Interfaces.Map;
using Robust.Shared.IoC;
using Robust.Shared.Map;
using Robust.Shared.Network;
using Robust.Shared.Prototypes;
using Robust.Shared.Utility;

namespace Content.Server.GameTicking
{
    [AdminCommand(AdminFlags.Server)]
    class DelayStartCommand : IClientCommand
    {
        public string Command => "delaystart";
        public string Description => "Delays the round start.";
        public string Help => $"Usage: {Command} <seconds>\nPauses/Resumes the countdown if no argument is provided.";

        public void Execute(IConsoleShell shell, IPlayerSession player, string[] args)
        {
            var ticker = IoCManager.Resolve<IGameTicker>();
            if (ticker.RunLevel != GameRunLevel.PreRoundLobby)
            {
                shell.SendText(player, "This can only be executed while the game is in the pre-round lobby.");
                return;
            }

            if (args.Length == 0)
            {
                var paused = ticker.TogglePause();
                shell.SendText(player, paused ? "Paused the countdown." : "Resumed the countdown.");
                return;
            }

            if (args.Length != 1)
            {
                shell.SendText(player, "Need zero or one arguments.");
                return;
            }

            if (!uint.TryParse(args[0], out var seconds) || seconds == 0)
            {
                shell.SendText(player, $"{args[0]} isn't a valid amount of seconds.");
                return;
            }

            var time = TimeSpan.FromSeconds(seconds);
            if (!ticker.DelayStart(time))
            {
                shell.SendText(player, "An unknown error has occurred.");
            }
        }
    }

    [AdminCommand(AdminFlags.Server)]
    class StartRoundCommand : IClientCommand
    {
        public string Command => "startround";
        public string Description => "Ends PreRoundLobby state and starts the round.";
        public string Help => String.Empty;

        public void Execute(IConsoleShell shell, IPlayerSession player, string[] args)
        {
            var ticker = IoCManager.Resolve<IGameTicker>();

            if (ticker.RunLevel != GameRunLevel.PreRoundLobby)
            {
                shell.SendText(player, "This can only be executed while the game is in the pre-round lobby.");
                return;
            }

            ticker.StartRound();
        }
    }

    [AdminCommand(AdminFlags.Server)]
    class EndRoundCommand : IClientCommand
    {
        public string Command => "endround";
        public string Description => "Ends the round and moves the server to PostRound.";
        public string Help => String.Empty;

        public void Execute(IConsoleShell shell, IPlayerSession player, string[] args)
        {
            var ticker = IoCManager.Resolve<IGameTicker>();

            if (ticker.RunLevel != GameRunLevel.InRound)
            {
                shell.SendText(player, "This can only be executed while the game is in a round.");
                return;
            }

            ticker.EndRound();
        }
    }

    [AdminCommand(AdminFlags.Server)]
    public class NewRoundCommand : IClientCommand
    {
        public string Command => "restartround";
        public string Description => "Moves the server from PostRound to a new PreRoundLobby.";
        public string Help => String.Empty;

        public void Execute(IConsoleShell shell, IPlayerSession player, string[] args)
        {
            var ticker = IoCManager.Resolve<IGameTicker>();
            ticker.RestartRound();
        }
    }

    class RespawnCommand : IClientCommand
    {
        public string Command => "respawn";
        public string Description => "Respawns a player, kicking them back to the lobby.";
        public string Help => "respawn [player]";

        public void Execute(IConsoleShell shell, IPlayerSession player, string[] args)
        {
            if (args.Length > 1)
            {
                shell.SendText(player, "Must provide <= 1 argument.");
                return;
            }

            var playerMgr = IoCManager.Resolve<IPlayerManager>();
            var ticker = IoCManager.Resolve<IGameTicker>();

            NetUserId userId;
            if (args.Length == 0)
            {
                if (player == null)
                {
                    shell.SendText((IPlayerSession)null, "If not a player, an argument must be given.");
                    return;
                }

                userId = player.UserId;
            }
            else if (!playerMgr.TryGetUserId(args[0], out userId))
            {
                shell.SendText(player, "Unknown player");
                return;
            }

            if (!playerMgr.TryGetSessionById(userId, out var targetPlayer))
            {
                if (!playerMgr.TryGetPlayerData(userId, out var data))
                {
                    shell.SendText(player, "Unknown player");
                    return;
                }

                data.ContentData().WipeMind();
                shell.SendText(player,
                    "Player is not currently online, but they will respawn if they come back online");
                return;
            }

            ticker.Respawn(targetPlayer);
        }
    }

    [AnyCommand]
    class ObserveCommand : IClientCommand
    {
        public string Command => "observe";
        public string Description => "";
        public string Help => "";

        public void Execute(IConsoleShell shell, IPlayerSession player, string[] args)
        {
            if (player == null)
            {
                return;
            }

            var ticker = IoCManager.Resolve<IGameTicker>();
            ticker.MakeObserve(player);
        }
    }

    [AnyCommand]
    class JoinGameCommand : IClientCommand
    {
        [Dependency] private readonly IPrototypeManager _prototypeManager = default!;

        public string Command => "joingame";
        public string Description => "";
        public string Help => "";

        public JoinGameCommand()
        {
            IoCManager.InjectDependencies(this);
        }
        public void Execute(IConsoleShell shell, IPlayerSession player, string[] args)
        {
            var output = string.Join(".", args);
            if (player == null)
            {
                return;
            }

            var ticker = IoCManager.Resolve<IGameTicker>();
            if (ticker.RunLevel == GameRunLevel.PreRoundLobby)
            {
                shell.SendText(player, "Round has not started.");
                return;
            }
            else if(ticker.RunLevel == GameRunLevel.InRound)
            {
                string ID = args[0];
                var positions = ticker.GetAvailablePositions();

                if(positions.GetValueOrDefault(ID, 0) == 0) //n < 0 is treated as infinite
                {
                    var jobPrototype = _prototypeManager.Index<JobPrototype>(ID);
                    shell.SendText(player, $"{jobPrototype.Name} has no available slots.");
                    return;
                }
                ticker.MakeJoinGame(player, args[0].ToString());
                return;
            }

            ticker.MakeJoinGame(player, null);
        }
    }

    [AnyCommand]
    class ToggleReadyCommand : IClientCommand
    {
        public string Command => "toggleready";
        public string Description => "";
        public string Help => "";

        public void Execute(IConsoleShell shell, IPlayerSession player, string[] args)
        {
            if (player == null)
            {
                return;
            }

            var ticker = IoCManager.Resolve<IGameTicker>();
            ticker.ToggleReady(player, bool.Parse(args[0]));
        }
    }

    [AdminCommand(AdminFlags.Server)]
    class ToggleDisallowLateJoinCommand: IClientCommand
    {
        public string Command => "toggledisallowlatejoin";
        public string Description => "Allows or disallows latejoining during mid-game.";
        public string Help => $"Usage: {Command} <disallow>";

        public void Execute(IConsoleShell shell, IPlayerSession player, string[] args)
        {
            if (args.Length != 1)
            {
                shell.SendText(player, "Need exactly one argument.");
                return;
            }

            var ticker = IoCManager.Resolve<IGameTicker>();

            if (bool.TryParse(args[0], out var result))
            {
                ticker.ToggleDisallowLateJoin(bool.Parse(args[0]));
                shell.SendText(player, result ? "Late joining has been disabled." : "Late joining has been enabled.");
            }
            else
            {
                shell.SendText(player, "Invalid argument.");
            }
        }
    }

    [AdminCommand(AdminFlags.Server)]
    class SetGamePresetCommand : IClientCommand
    {
        public string Command => "setgamepreset";
        public string Description => "";
        public string Help => "";

        public void Execute(IConsoleShell shell, IPlayerSession player, string[] args)
        {
            if (args.Length != 1)
            {
                shell.SendText(player, "Need exactly one argument.");
                return;
            }

            var ticker = IoCManager.Resolve<IGameTicker>();

            ticker.SetStartPreset(args[0]);
        }
    }

    [AdminCommand(AdminFlags.Server)]
    class ForcePresetCommand : IClientCommand
    {
        public string Command => "forcepreset";
        public string Description => "Forces a specific game preset to start for the current lobby.";
        public string Help => $"Usage: {Command} <preset>";

        public void Execute(IConsoleShell shell, IPlayerSession player, string[] args)
        {
            var ticker = IoCManager.Resolve<IGameTicker>();
            if (ticker.RunLevel != GameRunLevel.PreRoundLobby)
            {
                shell.SendText(player, "This can only be executed while the game is in the pre-round lobby.");
                return;
            }

            if (args.Length != 1)
            {
                shell.SendText(player, "Need exactly one argument.");
                return;
            }

            var name = args[0];
            if (!ticker.TryGetPreset(name, out var type))
            {
                shell.SendText(player, $"No preset exists with name {name}.");
                return;
            }

            ticker.SetStartPreset(type, true);
            shell.SendText(player, $"Forced the game to start with preset {name}.");
        }
    }

    [AdminCommand(AdminFlags.Server | AdminFlags.Mapping)]
    class MappingCommand : IClientCommand
    {
        public string Command => "mapping";
        public string Description => "Creates and teleports you to a new uninitialized map for mapping.";
        public string Help => $"Usage: {Command} <mapname> / {Command} <id> <mapname>";

        public void Execute(IConsoleShell shell, IPlayerSession player, string[] args)
        {
            if (player == null)
            {
                shell.SendText(player, "Only players can use this command");
                return;
            }

            var mapManager = IoCManager.Resolve<IMapManager>();
            int mapId;
            string mapName;

            switch (args.Length)
            {
                case 1:
                    if (player.AttachedEntity == null)
                    {
                        shell.SendText(player, "The map name argument cannot be omitted if you have no entity.");
                        return;
                    }

                    mapId = (int) mapManager.NextMapId();
                    mapName = args[0];
                    break;
                case 2:
                    if (!int.TryParse(args[0], out var id))
                    {
                        shell.SendText(player, $"{args[0]} is not a valid integer.");
                        return;
                    }

                    mapId = id;
                    mapName = args[1];
                    break;
                default:
                    shell.SendText(player, Help);
                    return;
            }

            shell.ExecuteCommand(player, $"addmap {mapId} false");
            shell.ExecuteCommand(player, $"loadbp {mapId} \"{CommandParsing.Escape(mapName)}\"");
            shell.ExecuteCommand(player, "aghost");
            shell.ExecuteCommand(player, $"tp 0 0 {mapId}");

            var newGridId = mapManager.GetAllGrids().Max(g => (int) g.Index);

            shell.SendText(player, $"Created unloaded map from file {mapName} with id {mapId}. Use \"savebp {newGridId} foo.yml\" to save the new grid as a map.");
        }
    }

    [AdminCommand(AdminFlags.Mapping)]
    class TileWallsCommand : IClientCommand
    {
        // ReSharper disable once StringLiteralTypo
        public string Command => "tilewalls";
        public string Description => "Puts an underplating tile below every wall on a grid.";
        public string Help => $"Usage: {Command} <gridId> | {Command}";

        public void Execute(IConsoleShell shell, IPlayerSession player, string[] args)
        {
            GridId gridId;

            switch (args.Length)
            {
                case 0:
                    if (player?.AttachedEntity == null)
                    {
                        shell.SendText((IPlayerSession) null, "Only a player can run this command.");
                        return;
                    }

                    gridId = player.AttachedEntity.Transform.GridID;
                    break;
                case 1:
                    if (!int.TryParse(args[0], out var id))
                    {
                        shell.SendText(player, $"{args[0]} is not a valid integer.");
                        return;
                    }

                    gridId = new GridId(id);
                    break;
                default:
                    shell.SendText(player, Help);
                    return;
            }

            var mapManager = IoCManager.Resolve<IMapManager>();
            if (!mapManager.TryGetGrid(gridId, out var grid))
            {
                shell.SendText(player, $"No grid exists with id {gridId}");
                return;
            }

            var entityManager = IoCManager.Resolve<IEntityManager>();
            if (!entityManager.TryGetEntity(grid.GridEntityId, out var gridEntity))
            {
                shell.SendText(player, $"Grid {gridId} doesn't have an associated grid entity.");
                return;
            }

            var tileDefinitionManager = IoCManager.Resolve<ITileDefinitionManager>();
            var underplating = tileDefinitionManager["underplating"];
            var underplatingTile = new Tile(underplating.TileId);
            var changed = 0;
            foreach (var childUid in gridEntity.Transform.ChildEntityUids)
            {
                if (!entityManager.TryGetEntity(childUid, out var childEntity))
                {
                    continue;
                }

                var prototype = childEntity.Prototype;
                while (true)
                {
                    if (prototype?.Parent == null)
                    {
                        break;
                    }

                    prototype = prototype.Parent;
                }

                if (prototype?.ID != "base_wall")
                {
                    continue;
                }

                if (!childEntity.TryGetComponent(out SnapGridComponent snapGrid))
                {
                    continue;
                }

                var tile = grid.GetTileRef(childEntity.Transform.Coordinates);
                var tileDef = (ContentTileDefinition) tileDefinitionManager[tile.Tile.TypeId];

                if (tileDef.Name == "underplating")
                {
                    continue;
                }

                grid.SetTile(childEntity.Transform.Coordinates, underplatingTile);
                changed++;
            }

            shell.SendText(player, $"Changed {changed} tiles.");
        }
    }
}


text:
import React from 'react'
import PropTypes from './utils/proptypes'
import classnames from 'classnames'
import Spin from './Spin'
import { objectAssign } from './utils/objects'

import _styles from './styles/_mask.scss'

let defaultSpin = <Spin color="#666" size={40} type="fading-circle" />

export default function Mask (props) {
  const { active, children, background, style } = props

  if (!active) return null

  const className = classnames(
    props.className,
    _styles.mask
  )

  return (
    <div className={className} style={objectAssign({}, style, {background})}>
    { children || defaultSpin }
    </div>
  )
}

Mask.propTypes = {
  active: PropTypes.bool,
  background: PropTypes.string,
  children: PropTypes.element,
  className: PropTypes.string,
  style: PropTypes.object
}

Mask.setDefaultSpin = (spin) => {
  defaultSpin = spin
}

redpajama_set_name: RedPajamaGithub


text:
from nova.api.validation import parameter_types

create_backup = {
    'type': 'object',
    'properties': {
        'createBackup': {
            'type': 'object',
            'properties': {
                'name': parameter_types.name,
                'backup_type': {
                    'type': 'string',
                },
                'rotation': {
                    'type': ['integer', 'string'],
                    'pattern': '^[0-9]+$',
                    'minimum': 0,
                },
                'metadata': {
                    'type': 'object',
                }
            },
            'required': ['name', 'backup_type', 'rotation'],
            'additionalProperties': False,
        },
    },
    'required': ['createBackup'],
    'additionalProperties': False,
}


text:
'use strict';

const muk    = require('..');
const assert = require('assert');
const fs     = require('fs');

describe('Mock methods', () => {
  const readFile = fs.readFile;
  const mkdir = fs.mkdir;

  afterEach(muk.restore);

  it('Contains original methods', () => {
    assert.equal(typeof fs.readFile, 'function',
      'fs.readFile is function');
    assert.equal(typeof fs.readFileSync, 'function',
      'fs.readFileSync is function');
  });

  it('Methods are new objects after mocked', () => {
    const readFileMock = (path, callback) => {
      process.nextTick(callback.bind(null, null, 'hello!'));
    };

    const mkdirMock = (path, callback) => {
      process.nextTick(callback.bind(null, null));
    };

    muk(fs, 'readFile', readFileMock);
    muk(fs, 'mkdir', mkdirMock);
    assert.equal(fs.readFile, readFileMock, 'object method is equal to mock');
    assert.equal(fs.mkdir, mkdirMock, 'object method is equal to mock');
  });

  it('No errors calling new mocked methods', (done) => {
    const readFileMock = (path, callback) => {
      process.nextTick(callback.bind(null, null, 'hello!'));
    };
    muk(fs, 'readFile', readFileMock);

    fs.readFile('grimer', (err, data) => {
      assert.ifError(err);
      assert.equal(data, 'hello!', 'data matches');
      done();
    });
  });

  it('Should have original methods after muk.restore()', () => {
    muk.restore();
    assert.equal(fs.readFile, readFile, 'original method is restored');
    assert.equal(fs.mkdir, mkdir, 'original method is restored');

    const readFileMock = (path, callback) => {
      process.nextTick(callback.bind(null, null, 'hello!'));
    };
    muk(fs, 'readFile', readFileMock);
    muk(fs, 'readFile', readFileMock);
    muk.restore();
    assert.equal(fs.readFile, readFile, 'mock twices, original method should be restored too');
  });

  it('Should mock method on prototype', () => {
    const readFile = fs.readFile;
    const newFs = Object.create(fs);
    const readFileMock = (path, callback) => {
      process.nextTick(callback.bind(null, null, 'hello!'));
    };
    muk(newFs, 'readFile', readFileMock);
    assert.equal(newFs.readFile, readFileMock, 'object method is equal to mock');

    muk.restore();
    assert.equal(newFs.readFile, readFile, 'object method is equal to origin');
  });
});

describe('Mock property', () => {
  const config = {
    enableCache: true,
    delay: 10
  };
  const home = process.env.HOME;

  afterEach(muk.restore);

  it('Contains original property', () => {
    assert.equal(config.enableCache, true, 'enableCache is true');
    assert.equal(config.delay, 10, 'delay is 10');
  });

  it('Property are new after mocked', () => {
    muk(config, 'enableCache', false);
    muk(config, 'delay', 0);
    muk(process.env, 'HOME', '/mockhome');

    assert.equal(config.enableCache, false, 'enableCache is false');
    assert.equal(config.delay, 0, 'delay is 0');
    assert.equal(process.env.HOME, '/mockhome', 'process.env.HOME is /mockhome');
  });

  it('Should have original properties after muk.restore()', () => {
    muk(config, 'enableCache', false);
    muk(config, 'enableCache', false);
    muk(config, 'delay', 0);
    muk(process.env, 'HOME', '/mockhome');
    muk(config, 'notExistProp', 'value');
    muk(process.env, 'notExistProp', 0);
    muk.restore();

    assert.equal(config.enableCache, true, 'enableCache is true');
    assert.equal(config.delay, 10, 'delay is 10');
    assert.equal(process.env.HOME, home, 'process.env.HOME is ' + home);
    assert(!config.hasOwnProperty('notExistProp'), 'notExistProp is deleted');
    assert(!process.env.hasOwnProperty('notExistProp'), 'notExistProp is deleted');
  });

  it('Should be undefined when value is not set', () => {
    muk(config, 'enableCache');
    assert.equal(config.enableCache, undefined, 'enableCache is undefined');
  });

  it('Should mock property on prototype', () => {
    const newConfig = Object.create(config);
    muk(newConfig, 'enableCache', false);
    assert.deepEqual(Object.keys(newConfig), ['enableCache'], 'obj should contain properties');
    assert.equal(newConfig.enableCache, false, 'enableCache is false');

    muk.restore();
    assert.equal(newConfig.enableCache, true, 'enableCache is false');
  });
});

describe('Mock getter', () => {
  const obj = {
    get a() {
      return 1;
    }
  };

  afterEach(muk.restore);

  it('Contains original getter', () => {
    assert.equal(obj.a, 1, 'property a of obj is 1');
  });

  it('Methods are new getter after mocked', () => {
    muk(obj, 'a', 2);
    assert.equal(obj.a, 2, 'property a of obj is equal to mock');
  });

  it('Should have original getter after muk.restore()', () => {
    muk(obj, 'a', 2);
    muk.restore();
    assert.equal(obj.a, 1, 'property a of obj is equal to origin');
  });

  it('Should mock property on prototype', () => {
    const newObj = Object.create(obj);
    muk(newObj, 'a', 2);
    assert.deepEqual(Object.keys(newObj), ['a'], 'obj should contain properties');
    assert.equal(newObj.a, 2, 'property a of obj is equal to mock');

    muk.restore();
    assert.equal(newObj.a, 1, 'property a of obj is equal to origin');
  });
});

describe('Mock value with getter', () => {
  const obj = {
    a: 1,
  };

  afterEach(muk.restore);

  it('Value are new getter after mocked', () => {
    muk(obj, 'a', {
      get: () => 2,
    });
    assert.equal(obj.a, 2, 'property a of obj is 2 with getter');
  });

  it('Should throw error when getter', () => {
    muk(obj, 'a', {
      get: () => {
        throw Error('oh no');
      }
    });

    try {
      obj.a;
    } catch (e) {
      assert.equal(e.message, 'oh no');
    }
  });

  it('Should have original getter after muk.restore()', () => {
    muk(obj, 'a', {
      get: () => 2,
    });

    muk.restore();
    assert.equal(obj.a, 1, 'property a of obj is equal to original');
  });
});

describe('Mock value with setter', () => {
  const obj = {
    _a: 1,
  };

  Object.defineProperty(obj, 'a', {
    configurable: true,
    set: (value) => obj._a = value,
    get: () => obj._a,
  });

  afterEach(muk.restore);

  it('Value are new setter after mocked', () => {
    muk(obj, 'a', {
      set: (value) => obj._a = value + 1,
      get: () => obj._a,
    });
    obj.a = 2;
    assert.equal(obj.a, 3, 'property a of obj is 3 with getter');
  });

  it('Should throw error when setter', () => {
    muk(obj, 'a', {
      set: () => {
        throw Error('oh no');
      }
    });

    try {
      obj.a = 2;
    } catch (e) {
      assert.equal(e.message, 'oh no');
    }
  });

  it('Should have original setter after muk.restore()', () => {
    muk(obj, 'a', {
      set: (value) => obj._a = value + 1,
    });

    muk.restore();
    obj.a = 2;
    assert.equal(obj.a, 2, 'property a of obj is equal to original');
  });
});

describe('Mock check', () => {

  afterEach(muk.restore);

  it('Should check whether is mocked', () => {
    const obj = {
      a: 1,
    };
    assert.equal(muk.isMocked(obj, 'a'), false, 'obj should not be mocked');

    muk(obj, 'a', 2);
    assert.ok(muk.isMocked(obj, 'a'), 'obj should be mocked');
  });

  it('Should not be enumerable', () => {
    const obj = {
      a: 1,
    };
    muk(obj, 'a', 2);
    assert.deepEqual(Object.keys(obj), ['a']);

    const keys = [];
    for (let key in obj) {
      keys.push(key);
    }
    assert.deepEqual(keys, ['a']);
  });

  it('Should be restored', () => {
    const obj = {
      a: 1,
    };
    muk(obj, 'a', 2);
    assert.equal(muk.isMocked(obj, 'a'), true);
    muk.restore();
    assert.equal(obj.a, 1);
    assert.equal(muk.isMocked(obj, 'a'), false);
  });

  it('Should check different type', () => {
    const obj = {
      a: 1,
      b: '1',
      c: true,
      d: {},
      get e() {
        return 1;
      },
    };
    muk(obj, 'a', 2);
    assert.ok(muk.isMocked(obj, 'a'));

    muk(obj, 'b', '2');
    assert.ok(muk.isMocked(obj, 'b'));

    muk(obj, 'c', false);
    assert.ok(muk.isMocked(obj, 'c'));

    muk(obj, 'd', { d: 1 });
    assert.ok(muk.isMocked(obj, 'd'));

    muk(obj, 'e', 2);
    assert.ok(muk.isMocked(obj, 'e'));
  });

  it('Should check process.env', () => {
    muk(process.env, 'HOME', '/mockhome');
    assert.equal(process.env.HOME, '/mockhome');
    assert.ok(muk.isMocked(process.env, 'HOME'));
  });
});


text:
{% load blog tagging_tags inlines oembed_tags %}

  #{{ post.id }}

    {% blocktrans with post.author.get_full_name as name and post.publish|date:"SHORT_DATETIME_FORMAT" as date %}Blog post

    by {{ name }}

    on {{ date }}
    {% endblocktrans %}

    {% if post.updated_on > post.pub_date %}

        {% blocktrans with post.updated_on|date:"SHORT_DATETIME_FORMAT" as date %}
        Last updated
 on {{ date }}
        {% endblocktrans %}

    {% endif %}

{{ post.title }}

{{ post.tease|safe }}

  {% oembed %}
    {{ post.body_markup|render_inlines|markdown:"codehilite" }}
  {% endoembed %}


text:
package org.ocpsoft.rewrite.prettyfaces;

import javax.servlet.http.HttpServletRequest;

import org.ocpsoft.rewrite.event.Rewrite;
import org.ocpsoft.rewrite.servlet.http.event.HttpServletRewrite;

public final class PFUtil
{
   private static final String REWRITE_OCCURRED_KEY = InboundRewriteRuleAdaptor.class.getName() + "_REWRITE_OCCURRED";

   public static void setRewriteOccurred(Rewrite event)
   {
      ((HttpServletRewrite) event).getRequest().setAttribute(REWRITE_OCCURRED_KEY, true);
   }

   public static boolean isRewritingEnabled(Rewrite event)
   {
      HttpServletRequest request = ((HttpServletRewrite) event).getRequest();
      Object rewriteOccurred = request.getAttribute(REWRITE_OCCURRED_KEY);
      return rewriteOccurred == null && isMappingEnabled(event);
   }

   public static boolean isMappingEnabled(Rewrite event)
   {
      HttpServletRequest request = ((HttpServletRewrite) event).getRequest();
      Object mappingForwardOccurred = request.getAttribute(UrlMappingRuleAdaptor.REWRITE_MAPPING_ID_KEY);
      return mappingForwardOccurred == null;
   }
}


text:
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

var vanadium = require('vanadium');

module.exports = {
  NamedResource: NamedResource,
  listChildren: listChildren,
  prefixRangeLimit: prefixRangeLimit,
  stringToUTF8Bytes: stringToUTF8Bytes,
  escape: escape,
  unescape: unescape
};

/**
 * NamedResource is a base class for Syncbase layers with names.
 * @param {string} parentFullName Full name of parent layer.
 * @param {string} name Relative name for this layer.
 * @param {string} fullName Full name for this layer.
 */
function NamedResource(parentFullName, name, fullName) {
  if (!(this instanceof NamedResource)) {
    return new NamedResource(parentFullName, name, fullName);
  }

  /**
   * @property _parentFullName
   * @private
   * @type {string}
   */
  Object.defineProperty(this, '_parentFullName', {
    value: parentFullName,
    writable: false,
    enumerable: false
  });

  /**
   * @property name
   * @type {string}
   */
  Object.defineProperty(this, 'name', {
    value: name,
    writable: false,
    enumerable: true
  });

  /**
   * @property fullName
   * @type {string}
   */
  Object.defineProperty(this, 'fullName', {
    value: fullName,
    writable: false,
    enumerable: true
  });
}

/**
 * listChildren returns the relative names of all children of parentFullName.
 * @private
 */
function listChildren(ctx, parentFullName, cb) {
  var rt = vanadium.runtimeForContext(ctx);
  var globPattern = vanadium.naming.join(parentFullName, '*');

  var childNames = [];
  var streamErr = null;
  var stream = rt.getNamespace().glob(ctx, globPattern, function(err) {
    if (err) {
      return cb(err);
    }
    if (streamErr) {
      return cb(streamErr);
    }
    cb(null, childNames);
  }).stream;

  stream.on('data', function(globResult) {
    var fullName = globResult.name;
    var escName = vanadium.naming.basename(fullName);
    // Component names within object names are always escaped. See comment in
    // server/nosql/dispatcher.go for explanation.
    // If unescape throws an exception, there's a bug in the Syncbase server.
    // Glob should return names with escaped components.
    childNames.push(unescape(escName));
  });

  stream.on('error', function(err) {
    console.error('Stream error: ' + JSON.stringify(err));
    streamErr = streamErr || err.error;
  });
}

/**
 * prefixRangeLimit modifies the input bytes to be the limit of the row range
 * for the given prefix.
 * TODO(sadovsky): Why do we modify the input bytes, rather than returning a new
 * byte array?
 * @private
 * @param {Uint8Array} bytes Integer ArrayBuffer to modify.
 */
function prefixRangeLimit(bytes) {
  // bytes can be thought of as a base-256 number. The code below effectively
  // adds 1 to this number, then chops off any trailing \x00 bytes. If the input
  // string consists entirely of \xff bytes, we return an empty string.
  while (bytes.length > 0) {
    var last = bytes.length - 1;
    if (bytes[last] === 255) {
      bytes = bytes.slice(0, last); // chop off trailing \x00
    } else {
      bytes[last] += 1; // add 1
      return; // no carry
    }
  }
}

/**
 * stringToUTF8Bytes converts a JavaScript string to a array of bytes
 * representing the string in UTF8 format.
 * @private
 * @param {string} str String to convert to UTF8 bytes.
 * @return {Uint8Array} UTF8 bytes.
 */
function stringToUTF8Bytes(str) {
  var utf8String = unescape(encodeURIComponent(str)); //jshint ignore:line
  var bytes = new Uint8Array(utf8String.length);

  for (var i = 0; i < utf8String.length; i++) {
    bytes[i] = utf8String.charCodeAt(i);
  }

  return bytes;
}

/**
 * escape escapes a component name for use in a Syncbase object name. In
 * particular, it replaces bytes "%" and "/" with the "%" character followed by
 * the byte's two-digit hex code. Clients using the client library need not
 * escape names themselves; the client library does so on their behalf.
 * @param {string} s String to escape.
 * @return {string} Escaped string.
 */
function escape(s) {
  return vanadium.naming.encodeAsNameElement(s);
}

/**
 * unescape applies the inverse of escape. Throws exception if the given string
 * is not a valid escaped string.
 * @param {string} s String to unescape.
 * @return {string} Unescaped string.
 */
function unescape(s) {
  return vanadium.naming.decodeFromNameElement(s);
}


text:
<?php

namespace Booking\BookingBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints as DoctrineAssert;

/**
 * Cliente
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="Booking\BookingBundle\Entity\ClienteRepository")
 * @DoctrineAssert\UniqueEntity("nombre")
 */
class Cliente
{
    /**
     * @ORM\ManyToMany(targetEntity="Actividad")
     * @ORM\JoinTable(name="cliente_actividad",
     *      joinColumns={@ORM\JoinColumn(name="clienteid", referencedColumnName="id")},
     *      inverseJoinColumns={@ORM\JoinColumn(name="actividadid", referencedColumnName="id")}
     * )
     */

    protected $actividades;
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;
    /**
     * @var string
     * @Assert\Regex(pattern="/[A-Za-z0-9]/")
     * @Assert\Length( min =3 )
     *
     * @ORM\Column(name="nombre", type="string", length=255, nullable=true)
     */
    private $nombre;
    /**
     * @var string
     * @Assert\Regex(pattern="/[A-Za-z0-9]/")     *
     * @ORM\Column(name="referencia", type="string", length=255, nullable=true)
     */
    private $referencia;

    /**
     *
     */
    public function __construct()
    {
        $this->actividades = new ArrayCollection();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Get nombre
     *
     * @return string
     */
    public function getNombre()
    {
        return $this->nombre;
    }

    /**
     * Set nombre
     *
     * @param string $nombre
     * @return Cliente
     */
    public function setNombre($nombre)
    {
        $this->nombre = $nombre;

        return $this;
    }

    /**
     * Get referencia
     *
     * @return string
     */
    public function getReferencia()
    {
        return $this->referencia;
    }

    /**
     * Set referencia
     *
     * @param string $referencia
     * @return Cliente
     */
    public function setReferencia($referencia)
    {
        $this->referencia = $referencia;

        return $this;
    }

    /**
     * Add actividades
     *
     * @param Actividad $actividades
     * @return Cliente
     */
    public function addActividad(Actividad $actividades)
    {
        $this->actividades[] = $actividades;

        return $this;
    }

    /**
     * Remove actividades
     *
     * @param Actividad $actividades
     */
    public function removeActividad(Actividad $actividades)
    {
        $this->actividades->removeElement($actividades);
    }

    /**
     * @return array
     */
    public function toArray()
    {
        return array(
            $this->id,
            $this->nombre,
            $this->referencia,
            $this->getActividades()->toArray()
        );
    }

    /**
     * Get actividades
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getActividades()
    {
        return $this->actividades;
    }
}


text:
#include <aws/networkmanager/model/CreateSiteToSiteVpnAttachmentRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::NetworkManager::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

CreateSiteToSiteVpnAttachmentRequest::CreateSiteToSiteVpnAttachmentRequest() :
    m_coreNetworkIdHasBeenSet(false),
    m_vpnConnectionArnHasBeenSet(false),
    m_tagsHasBeenSet(false),
    m_clientToken(Aws::Utils::UUID::RandomUUID()),
    m_clientTokenHasBeenSet(true)
{
}

Aws::String CreateSiteToSiteVpnAttachmentRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_coreNetworkIdHasBeenSet)
  {
   payload.WithString("CoreNetworkId", m_coreNetworkId);

  }

  if(m_vpnConnectionArnHasBeenSet)
  {
   payload.WithString("VpnConnectionArn", m_vpnConnectionArn);

  }

  if(m_tagsHasBeenSet)
  {
   Array<JsonValue> tagsJsonList(m_tags.size());
   for(unsigned tagsIndex = 0; tagsIndex < tagsJsonList.GetLength(); ++tagsIndex)
   {
     tagsJsonList[tagsIndex].AsObject(m_tags[tagsIndex].Jsonize());
   }
   payload.WithArray("Tags", std::move(tagsJsonList));

  }

  if(m_clientTokenHasBeenSet)
  {
   payload.WithString("ClientToken", m_clientToken);

  }

  return payload.View().WriteReadable();
}


text:
export default function (sequelize, DataTypes) {
  const Company = sequelize.define('company', {
    name: {
      type: DataTypes.STRING,
    },
    code: {
      type: DataTypes.STRING,
      unique: true,
    },
    description: {
      type: DataTypes.STRING,
    }
  }, {
    classMethods: {
      associate: models => {
        Company.belongsTo(models.companyType);
      }
    },
    freezeTableName: true // Model tableName will be the same as the model name
  });

  return Company;
}


text:
package com.rupeng.bookstore.entity;

public class OrdersItem
{
    private Integer id;
    private String ordersId;

    @Override
    public int hashCode()
    {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((id == null) ? 0 : id.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj)
    {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        OrdersItem other = (OrdersItem) obj;
        if (id == null)
        {
            if (other.id != null)
                return false;
        }
        else if (!id.equals(other.id))
            return false;
        return true;
    }

    public Integer getId()
    {
        return id;
    }

    public void setId(Integer id)
    {
        this.id = id;
    }

    public String getOrdersId()
    {
        return ordersId;
    }

    public void setOrdersId(String ordersId)
    {
        this.ordersId = ordersId;
    }

    public int getBookId()
    {
        return bookId;
    }

    public void setBookId(int bookId)
    {
        this.bookId = bookId;
    }

    public String getBookName()
    {
        return bookName;
    }

    public void setBookName(String bookName)
    {
        this.bookName = bookName;
    }

    public double getPrice()
    {
        return price;
    }

    public void setPrice(double price)
    {
        this.price = price;
    }

    public int getCount()
    {
        return count;
    }

    public void setCount(int count)
    {
        this.count = count;
    }

    private int bookId;
    private String bookName;
    private double price;
    private int count;
}


text:
class LibreSTRStyle :
    public StiGame::Gui::Style
{
    public:
        LibreSTRStyle();
        virtual ~LibreSTRStyle();
    protected:
    private:
};

#endif // LIBRESTRSTYLE_H


text:
<?php
/* @var $this SiteController */
/* @var $model ContactForm */
/* @var $form CActiveForm */

$this->pageTitle=Yii::app()->name . ' - Contact Us';
$this->breadcrumbs=array(
	'Contact',
);

?>

Contact Us

<?php if(Yii::app()->user->hasFlash('contact')): ?>

	<?php echo Yii::app()->user->getFlash('contact'); ?>

<?php else: ?>

If you have business inquiries or other questions, please fill out the following form to contact us. Thank you.

<?php $form=$this->beginWidget('CActiveForm', array(
	'id'=>'contact-form',
	'enableClientValidation'=>true,
	'clientOptions'=>array(
		'validateOnSubmit'=>true,
	),
)); ?>

Fields with * are required.

	<?php echo $form->errorSummary($model); ?>

		<?php echo $form->labelEx($model,'name'); ?>

		<?php echo $form->textField($model,'name',array('class'=>'span4')); ?>
		<?php echo $form->error($model,'name'); ?>

		<?php echo $form->labelEx($model,'email'); ?>

		<?php echo $form->textField($model,'email',array('class'=>'span4')); ?>
		<?php echo $form->error($model,'email'); ?>

		<?php echo $form->labelEx($model,'subject'); ?>
		<?php echo $form->textField($model,'subject',array('size'=>60,'maxlength'=>128,'class'=>'span8')); ?>
		<?php echo $form->error($model,'subject'); ?>

		<?php echo $form->labelEx($model,'body'); ?>
		<?php echo $form->textArea($model,'body',array('rows'=>6, 'cols'=>80,'class'=>'span8')); ?>
		<?php echo $form->error($model,'body'); ?>

	<?php if (Yii::app()->user->isGuest and CCaptcha::checkRequirements()): ?>

		<?php echo $form->labelEx($model,'verifyCode'); ?>

		<?php $this->widget('CCaptcha'); ?>
		<?php echo $form->textField($model,'verifyCode'); ?>

Please enter the letters as they are shown in the image above.

Letters are not case-sensitive.

		<?php echo $form->error($model,'verifyCode'); ?>

	<?php endif; ?>

  <?php $this->widget('bootstrap.widgets.TbButton',array(
    'buttonType' => 'submit',
  	'label' => 'Send Message',
  	'size' => 'large',
  	'type'=> 'primary',
  	'url' => array('create')
  )); ?>

<?php $this->endWidget(); ?>

<?php endif; ?>


text:
namespace Dike.Core.Authorization
{
    using Microsoft.AspNetCore.Authentication;
    using Microsoft.AspNetCore.Authentication.Cookies;
    using Microsoft.AspNetCore.Identity;
    using Microsoft.Extensions.Options;
    using System.Threading.Tasks;

    /// <summary>
    /// Provides default implementation of validation functions for security stamps.
    /// </summary>
    /// <typeparam name="TTenant">The type of the tenant.</typeparam>
    /// <typeparam name="TRole">The type of the role.</typeparam>
    /// <typeparam name="TUser">The type of the user.</typeparam>
    /// <seealso cref="Microsoft.AspNetCore.Identity.SecurityStampValidator{TUser}" />
    public class SecurityStampValidator<TTenant, TRole, TUser>
        : SecurityStampValidator<TUser>
        where TTenant : MultiTenancy.Tenant<TUser>
        where TRole : Roles.Role<TUser>, new()
        where TUser : Users.User<TUser>
    {
        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="SecurityStampValidator{TTenant, TRole, TUser}"/> class.
        /// </summary>
        /// <param name="options">The options.</param>
        /// <param name="signInManager">The sign in manager.</param>
        /// <param name="systemClock">The system clock.</param>
        public SecurityStampValidator(
            IOptions<SecurityStampValidatorOptions> options,
            SignInManager<TTenant, TRole, TUser> signInManager,
            ISystemClock systemClock)
            : base(options, signInManager, systemClock)
        {
        }

        #endregion Constructors

        #region Methods

        /// <summary>
        /// Validates a security stamp of an identity as an asynchronous operation, and rebuilds the identity if the validation succeeds, otherwise rejects the identity.
        /// </summary>
        /// <param name="context">The context containing the <see cref="System.Security.Claims.ClaimsPrincipal" />
        /// and <see cref="Microsoft.AspNetCore.Http.Authentication.AuthenticationProperties" /> to validate.</param>
        /// <returns>The <see cref="System.Threading.Tasks.Task" /> that represents the asynchronous validation operation.</returns>
        [Domain.UnitOfWork.UnitOfWork]
        public override Task ValidateAsync(CookieValidatePrincipalContext context)
            => base.ValidateAsync(context);

        #endregion Methods
    }
}


text:
<?php

//Simple facade pattern implemented in order to handle the different type of request made
//when filtering information or erasing it all.

include dirname(__FILE__) . '/Model/bookVO.php';
include dirname(__FILE__) . '/DAO/bookDAO.php';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
	if (!empty($_POST)) {
		$filter = $_POST["filter"];
		$bookDAO = new BookDAO();
		if (strcmp($filter, "0") === 0) {
			echo $bookDAO->getBooks();
		}else if (strcmp($filter, "1") === 0) {
			echo $bookDAO->getByLanguage("Spanish");
		}else if (strcmp($filter, "2") === 0) {
			echo $bookDAO->getByLanguage("French");
		}else if (strcmp($filter, "3") === 0) {
			echo $bookDAO->getByPriceComparison(">=100");
		}else if (strcmp($filter, "4") === 0) {
			echo $bookDAO->getByPriceComparison("<100");
		}else if (strcmp($filter, "5") === 0) {
			echo $bookDAO->dumpTable();
		}else {
			echo "Error";
		}
	}
}
?>


text:
using System;

//Create a console application that calculates and prints the square root of the number 12345.

namespace NumberRaisedByTwo
{
    class SquareRoot
    {
        static void Main()
        {
            int raisedNumber = (int)Math.Pow(12345, 2);
            Console.WriteLine(raisedNumber);
        }
    }
}


text:
package org.camunda.bpm.engine.test.api.runtime.migration;

import static org.camunda.bpm.engine.test.api.runtime.migration.ModifiableBpmnModelInstance.modify;
import static org.camunda.bpm.engine.test.api.runtime.migration.models.ConditionalModels.CONDITION_ID;
import static org.camunda.bpm.engine.test.api.runtime.migration.models.ConditionalModels.CONDITIONAL_PROCESS_KEY;
import static org.camunda.bpm.engine.test.api.runtime.migration.models.ConditionalModels.BOUNDARY_ID;
import static org.camunda.bpm.engine.test.api.runtime.migration.models.EventSubProcessModels.*;
import static org.camunda.bpm.engine.test.util.MigrationPlanAssert.assertThat;
import static org.camunda.bpm.engine.test.util.MigrationPlanAssert.migrate;
import static org.junit.Assert.assertNotNull;

import org.camunda.bpm.engine.migration.MigrationInstructionsBuilder;
import org.camunda.bpm.engine.migration.MigrationPlan;
import org.camunda.bpm.engine.repository.ProcessDefinition;
import org.camunda.bpm.engine.test.ProcessEngineRule;
import org.camunda.bpm.engine.test.api.runtime.migration.models.CallActivityModels;
import org.camunda.bpm.engine.test.api.runtime.migration.models.CompensationModels;
import org.camunda.bpm.engine.test.api.runtime.migration.models.EventBasedGatewayModels;
import org.camunda.bpm.engine.test.api.runtime.migration.models.EventSubProcessModels;
import org.camunda.bpm.engine.test.api.runtime.migration.models.ExternalTaskModels;
import org.camunda.bpm.engine.test.api.runtime.migration.models.GatewayModels;
import org.camunda.bpm.engine.test.api.runtime.migration.models.MessageReceiveModels;
import org.camunda.bpm.engine.test.api.runtime.migration.models.MultiInstanceProcessModels;
import org.camunda.bpm.engine.test.api.runtime.migration.models.ProcessModels;
import org.camunda.bpm.engine.test.api.runtime.migration.models.ServiceTaskModels;
import org.camunda.bpm.engine.test.api.runtime.migration.models.TransactionModels;
import org.camunda.bpm.engine.test.util.MigrationPlanAssert;
import org.camunda.bpm.engine.test.util.ProvidedProcessEngineRule;
import org.camunda.bpm.model.bpmn.Bpmn;
import org.camunda.bpm.model.bpmn.BpmnModelInstance;
import org.camunda.bpm.model.bpmn.instance.UserTask;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.RuleChain;

/**
 * @author Thorben Lindhauer
 *
 */
public class MigrationPlanGenerationTest {

  public static final String MESSAGE_NAME = "Message";
  public static final String SIGNAL_NAME = "Signal";
  public static final String TIMER_DATE = "2016-02-11T12:13:14Z";
  public static final String ERROR_CODE = "Error";
  public static final String ESCALATION_CODE = "Escalation";

  protected ProcessEngineRule rule = new ProvidedProcessEngineRule();
  protected MigrationTestRule testHelper = new MigrationTestRule(rule);

  @Rule
  public RuleChain ruleChain = RuleChain.outerRule(rule).around(testHelper);

  @Test
  public void testMapEqualActivitiesInProcessDefinitionScope() {
    BpmnModelInstance sourceProcess = ProcessModels.ONE_TASK_PROCESS;
    BpmnModelInstance targetProcess = ProcessModels.ONE_TASK_PROCESS;

    assertGeneratedMigrationPlan(sourceProcess, targetProcess)
      .hasInstructions(
        migrate("userTask").to("userTask")
      );
  }

  @Test
  public void testMapEqualActivitiesInSameSubProcessScope() {
    BpmnModelInstance sourceProcess = ProcessModels.SUBPROCESS_PROCESS;
    BpmnModelInstance targetProcess = ProcessModels.SUBPROCESS_PROCESS;

    assertGeneratedMigrationPlan(sourceProcess, targetProcess)
      .hasInstructions(
        migrate("subProcess").to("subProcess"),
        migrate("userTask").to("userTask")
      );

  }

  @Test
  public void testMapEqualActivitiesToSubProcessScope() {
    BpmnModelInstance sourceProcess = ProcessModels.ONE_TASK_PROCESS;
    BpmnModelInstance targetProcess = ProcessModels.SUBPROCESS_PROCESS;

    assertGeneratedMigrationPlan(sourceProcess, targetProcess)
      .hasEmptyInstructions();
  }

  @Test
  public void testMapEqualActivitiesToNestedSubProcessScope() {
    BpmnModelInstance sourceProcess = ProcessModels.SUBPROCESS_PROCESS;
    BpmnModelInstance targetProcess = modify(ProcessModels.DOUBLE_SUBPROCESS_PROCESS)
      .changeElementId("outerSubProcess", "subProcess"); // make ID match with subprocess ID of source definition

    assertGeneratedMigrationPlan(sourceProcess, targetProcess)
      .hasInstructions(
        migrate("subProcess").to("subProcess")
      );
  }

  @Test
  public void testMapEqualActivitiesToSurroundingSubProcessScope() {
    BpmnModelInstance sourceProcess = ProcessModels.SUBPROCESS_PROCESS;
    BpmnModelInstance targetProcess = modify(ProcessModels.DOUBLE_SUBPROCESS_PROCESS)
      .changeElementId("innerSubProcess", "subProcess"); // make ID match with subprocess ID of source definition

    assertGeneratedMigrationPlan(sourceProcess, targetProcess)
      .hasEmptyInstructions();
  }

  @Test
  public void testMapEqualActivitiesToDeeplyNestedSubProcessScope() {
    BpmnModelInstance sourceProcess = ProcessModels.ONE_TASK_PROCESS;
    BpmnModelInstance targetProcess = ProcessModels.DOUBLE_SUBPROCESS_PROCESS;

    assertGeneratedMigrationPlan(sourceProcess, targetProcess)
      .hasEmptyInstructions();
  }

  @Test
  public void testMapEqualActivitiesToSiblingScope() {
    BpmnModelInstance sourceProcess = ProcessModels.PARALLEL_SUBPROCESS_PROCESS;
    BpmnModelInstance targetProcess = modify(ProcessModels.PARALLEL_SUBPROCESS_PROCESS)
      .swapElementIds("userTask1", "userTask2");

    assertGeneratedMigrationPlan(sourceProcess, targetProcess)
      .hasInstructions(
        migrate("subProcess1").to("subProcess1"),
        migrate("subProcess2").to("subProcess2"),
        migrate("fork").to("fork")
      );
  }

  @Test
  public void testMapEqualActivitiesToNestedSiblingScope() {
    BpmnModelInstance sourceProcess = ProcessModels.PARALLEL_DOUBLE_SUBPROCESS_PROCESS;
    BpmnModelInstance targetProcess = modify(ProcessModels.PARALLEL_DOUBLE_SUBPROCESS_PROCESS)
      .swapElementIds("userTask1", "userTask2");

    assertGeneratedMigrationPlan(sourceProcess, targetProcess)
      .hasInstructions(
        migrate("subProcess1").to("subProcess1"),
        migrate("nestedSubProcess1").to("nestedSubProcess1"),
        migrate("subProcess2").to("subProcess2"),
        migrate("nestedSubProcess2").to("nestedSubProcess2"),
        migrate("fork").to("fork")
      );
  }

  @Test
  public void testMapEqualActivitiesWhichBecomeScope() {
    BpmnModelInstance sourceProcess = ProcessModels.ONE_TASK_PROCESS;
    BpmnModelInstance targetProcess = ProcessModels.SCOPE_TASK_PROCESS;

    assertGeneratedMigrationPlan(sourceProcess, targetProcess)
      .hasInstructions(
        migrate("userTask").to("userTask")
      );
  }

  @Test
  public void testMapEqualActivitiesWithParallelMultiInstance() {
    BpmnModelInstance testProcess = modify(ProcessModels.ONE_TASK_PROCESS)
      .<UserTask>getModelElementById("userTask").builder()
        .multiInstance().parallel().cardinality("3").multiInstanceDone().done();

    assertGeneratedMigrationPlan(testProcess, testProcess)
      .hasInstructions(
        migrate("userTask").to("userTask"),
        migrate("userTask#multiInstanceBody").to("userTask#multiInstanceBody"));
  }

  @Test
  public void testMapEqualActivitiesIgnoreUnsupportedActivities() {
    BpmnModelInstance sourceProcess = ProcessModels.UNSUPPORTED_ACTIVITIES;
    BpmnModelInstance targetProcess = ProcessModels.UNSUPPORTED_ACTIVITIES;

    assertGeneratedMigrationPlan(sourceProcess, targetProcess)
      .hasEmptyInstructions();
  }

  @Test
  public void testMapEqualUnsupportedAsyncBeforeActivities() {
    BpmnModelInstance testModel = modify(ProcessModels.UNSUPPORTED_ACTIVITIES)
      .flowNodeBuilder("startEvent").camundaAsyncBefore()
      .moveToNode("decisionTask").camundaAsyncBefore()
      .moveToNode("throwEvent").camundaAsyncAfter()
      .moveToNode("serviceTask").camundaAsyncBefore()
      .moveToNode("sendTask").camundaAsyncBefore()
      .moveToNode("scriptTask").camundaAsyncBefore()
      .moveToNode("endEvent").camundaAsyncBefore()
      .done();

    assertGeneratedMigrationPlan(testModel, testModel)
      .hasInstructions(
        migrate("startEvent").to("startEvent"),
        migrate("decisionTask").to("decisionTask"),
        migrate("throwEvent").to("throwEvent"),
        migrate("serviceTask").to("serviceTask"),
        migrate("sendTask").to("sendTask"),
        migrate("scriptTask").to("scriptTask"),
        migrate("endEvent").to("endEvent")
      );
  }

  @Test
  public void testMapEqualUnsupportedAsyncAfterActivities() {
    BpmnModelInstance testModel = modify(ProcessModels.UNSUPPORTED_ACTIVITIES)
      .flowNodeBuilder("startEvent").camundaAsyncAfter()
      .moveToNode("decisionTask").camundaAsyncAfter()
      .moveToNode("throwEvent").camundaAsyncAfter()
      .moveToNode("serviceTask").camundaAsyncAfter()
      .moveToNode("sendTask").camundaAsyncAfter()
      .moveToNode("scriptTask").camundaAsyncAfter()
      .moveToNode("endEvent").camundaAsyncAfter()
      .done();

    assertGeneratedMigrationPlan(testModel, testModel)
      .hasInstructions(
        migrate("startEvent").to("startEvent"),
        migrate("decisionTask").to("decisionTask"),
        migrate("throwEvent").to("throwEvent"),
        migrate("serviceTask").to("serviceTask"),
        migrate("sendTask").to("sendTask"),
        migrate("scriptTask").to("scriptTask"),
        migrate("endEvent").to("endEvent")
      );
  }

  @Test
  public void testMapEqualActivitiesToParentScope() {
    BpmnModelInstance sourceProcess = modify(ProcessModels.DOUBLE_SUBPROCESS_PROCESS)
      .changeElementId("outerSubProcess", "subProcess");
    BpmnModelInstance targetProcess = ProcessModels.SUBPROCESS_PROCESS;

    assertGeneratedMigrationPlan(sourceProcess, targetProcess)
      .hasInstructions(
        migrate("subProcess").to("subProcess")
      );
  }

  @Test
  public void testMapEqualActivitiesFromScopeToProcessDefinition() {
    BpmnModelInstance sourceProcess = ProcessModels.SUBPROCESS_PROCESS;
    BpmnModelInstance targetProcess = ProcessModels.ONE_TASK_PROCESS;

    assertGeneratedMigrationPlan(sourceProcess, targetProcess)
      .hasEmptyInstructions();
  }

  @Test
  public void testMapEqualActivitiesFromDoubleScopeToProcessDefinition() {
    BpmnModelInstance sourceProcess = ProcessModels.DOUBLE_SUBPROCESS_PROCESS;
    BpmnModelInstance targetProcess = ProcessModels.ONE_TASK_PROCESS;

    assertGeneratedMigrationPlan(sourceProcess, targetProcess)
      .hasEmptyInstructions();
  }

  @Test
  public void testMapEqualActivitiesFromTripleScopeToProcessDefinition() {
    BpmnModelInstance sourceProcess = ProcessModels.TRIPLE_SUBPROCESS_PROCESS;
    BpmnModelInstance targetProcess = ProcessModels.ONE_TASK_PROCESS;

    assertGeneratedMigrationPlan(sourceProcess, targetProcess)
      .hasEmptyInstructions();
  }

  @Test
  public void testMapEqualActivitiesFromTripleScopeToSingleNewScope() {
    BpmnModelInstance sourceProcess = ProcessModels.TRIPLE_SUBPROCESS_PROCESS;
    BpmnModelInstance targetProcess = ProcessModels.SUBPROCESS_PROCESS;

    assertGeneratedMigrationPlan(sourceProcess, targetProcess)
      .hasEmptyInstructions();
  }

  @Test
  public void testMapEqualActivitiesFromTripleScopeToTwoNewScopes() {
    BpmnModelInstance sourceProcess = ProcessModels.TRIPLE_SUBPROCESS_PROCESS;
    BpmnModelInstance targetProcess = ProcessModels.DOUBLE_SUBPROCESS_PROCESS;

    assertGeneratedMigrationPlan(sourceProcess, targetProcess)
      .hasEmptyInstructions();
  }

  @Test
  public void testMapEqualActivitiesToNewScopes() {
    BpmnModelInstance sourceProcess = ProcessModels.DOUBLE_SUBPROCESS_PROCESS;
    BpmnModelInstance targetProcess = modify(ProcessModels.DOUBLE_SUBPROCESS_PROCESS)
      .changeElementId("outerSubProcess", "newOuterSubProcess")
      .changeElementId("innerSubProcess", "newInnerSubProcess");

    assertGeneratedMigrationPlan(sourceProcess, targetProcess)
      .hasEmptyInstructions();
  }

  @Test
  public void testMapEqualActivitiesOutsideOfScope() {
    BpmnModelInstance sourceProcess = ProcessModels.PARALLEL_GATEWAY_SUBPROCESS_PROCESS;
    BpmnModelInstance targetProcess = ProcessModels.PARALLEL_TASK_AND_SUBPROCESS_PROCESS;

    assertGeneratedMigrationPlan(sourceProcess, targetProcess)
      .hasInstructions(
        migrate("subProcess").to("subProcess"),
        migrate("userTask1").to("userTask1")
      );
  }

  @Test
  public void testMapEqualActivitiesToHorizontalScope() {
    BpmnModelInstance sourceProcess = ProcessModels.PARALLEL_TASK_AND_SUBPROCESS_PROCESS;
    BpmnModelInstance targetProcess = ProcessModels.PARALLEL_GATEWAY_SUBPROCESS_PROCESS;

    assertGeneratedMigrationPlan(sourceProcess, targetProcess)
      .hasInstructions(
        migrate("subProcess").to("subProcess"),
        migrate("userTask1").to("userTask1")
      );
  }

  @Test
  public void testMapEqualActivitiesFromTaskWithBoundaryEvent() {
    BpmnModelInstance sourceProcess = modify(ProcessModels.ONE_TASK_PROCESS)
      .activityBuilder("userTask")
        .boundaryEvent(null).message("Message")
      .done();
    BpmnModelInstance targetProcess = ProcessModels.ONE_TASK_PROCESS;

    assertGeneratedMigrationPlan(sourceProcess, targetProcess)
      .hasInstructions(
        migrate("userTask").to("userTask")
      );
  }

  @Test
  public void testMapEqualActivitiesToTaskWithBoundaryEvent() {
    BpmnModelInstance sourceProcess = ProcessModels.ONE_TASK_PROCESS;
    BpmnModelInstance targetProcess = modify(ProcessModels.ONE_TASK_PROCESS)
      .activityBuilder("userTask")
        .boundaryEvent(null).message("Message")
      .done();

    assertGeneratedMigrationPlan(sourceProcess, targetProcess)
      .hasInstructions(
        migrate("userTask").to("userTask")
      );
  }

  @Test
  public void testMapEqualActivitiesWithBoundaryEvent() {
    BpmnModelInstance testProcess = modify(ProcessModels.SUBPROCESS_PROCESS)
      .activityBuilder("subProcess")
        .boundaryEvent("messageBoundary").message(MESSAGE_NAME)
      .moveToActivity("userTask")
        .boundaryEvent("signalBoundary").signal(SIGNAL_NAME)
      .moveToActivity("userTask")
        .boundaryEvent("timerBoundary").timerWithDate(TIMER_DATE)
      .done();

    assertGeneratedMigrationPlan(testProcess, testProcess)
      .hasInstructions(
        migrate("subProcess").to("subProcess"),
        migrate("messageBoundary").to("messageBoundary"),
        migrate("userTask").to("userTask"),
        migrate("signalBoundary").to("signalBoundary"),
        migrate("timerBoundary").to("timerBoundary")
      );
  }

  @Test
  public void testNotMapBoundaryEventsWithDifferentIds() {
    BpmnModelInstance sourceProcess = modify(ProcessModels.ONE_TASK_PROCESS)
      .activityBuilder("userTask")
        .boundaryEvent("message").message(MESSAGE_NAME)
      .done();
    BpmnModelInstance targetProcess = modify(sourceProcess)
      .changeElementId("message", "newMessage");

    assertGeneratedMigrationPlan(sourceProcess, targetProcess)
      .hasInstructions(
        migrate("userTask").to("userTask")
      );
  }

  @Test
  public void testIgnoreNotSupportedBoundaryEvents() {
    BpmnModelInstance testProcess = modify(ProcessModels.SUBPROCESS_PROCESS)
      .activityBuilder("subProcess")
        .boundaryEvent("messageBoundary").message(MESSAGE_NAME)
      .moveToActivity("subProcess")
        .boundaryEvent("errorBoundary").error(ERROR_CODE)
      .moveToActivity("subProcess")
        .boundaryEvent("escalationBoundary").escalation(ESCALATION_CODE)
      .moveToActivity("userTask")
        .boundaryEvent("signalBoundary").signal(SIGNAL_NAME)
      .done();

    assertGeneratedMigrationPlan(testProcess, testProcess)
      .hasInstructions(
        migrate("subProcess").to("subProcess"),
        migrate("messageBoundary").to("messageBoundary"),
        migrate("userTask").to("userTask"),
        migrate("signalBoundary").to("signalBoundary")
      );
  }

  @Test
  public void testNotMigrateBoundaryToParallelActivity() {
    BpmnModelInstance sourceProcess = modify(ProcessModels.PARALLEL_GATEWAY_PROCESS)
      .activityBuilder("userTask1")
        .boundaryEvent("message").message(MESSAGE_NAME)
      .done();
    BpmnModelInstance targetProcess = modify(ProcessModels.PARALLEL_GATEWAY_PROCESS)
      .activityBuilder("userTask2")
        .boundaryEvent("message").message(MESSAGE_NAME)
      .done();

    assertGeneratedMigrationPlan(sourceProcess, targetProcess)
      .hasInstructions(
        migrate("userTask1").to("userTask1"),
        migrate("userTask2").to("userTask2"),
        migrate("fork").to("fork")
      );
  }

  @Test
  public void testNotMigrateBoundaryToChildActivity() {
    BpmnModelInstance sourceProcess = modify(ProcessModels.SUBPROCESS_PROCESS)
      .activityBuilder("subProcess")
        .boundaryEvent("message").message(MESSAGE_NAME)
      .done();
    BpmnModelInstance targetProcess = modify(ProcessModels.SUBPROCESS_PROCESS)
      .activityBuilder("userTask")
        .boundaryEvent("message").message(MESSAGE_NAME)
      .done();

    assertGeneratedMigrationPlan(sourceProcess, targetProcess)
      .hasInstructions(
        migrate("subProcess").to("subProcess"),
        migrate("userTask").to("userTask")
      );
  }

  @Test
  public void testMigrateProcessInstanceWithEventSubProcess() {
    BpmnModelInstance testProcess = modify(ProcessModels.ONE_TASK_PROCESS)
      .addSubProcessTo(ProcessModels.PROCESS_KEY)
      .id("eventSubProcess")
      .triggerByEvent()
      .embeddedSubProcess()
        .startEvent("eventSubProcessStart").message(MESSAGE_NAME)
        .endEvent()
      .subProcessDone()
      .done();

    assertGeneratedMigrationPlan(testProcess, testProcess)
      .hasInstructions(
        migrate("eventSubProcess").to("eventSubProcess"),
        migrate("eventSubProcessStart").to("eventSubProcessStart"),
        migrate("userTask").to("userTask")
      );

    assertGeneratedMigrationPlan(testProcess, ProcessModels.ONE_TASK_PROCESS)
      .hasInstructions(
        migrate("userTask").to("userTask")
      );

    assertGeneratedMigrationPlan(ProcessModels.ONE_TASK_PROCESS, testProcess)
      .hasInstructions(
        migrate("userTask").to("userTask")
      );
  }

  @Test
  public void testMigrateSubProcessWithEventSubProcess() {
    BpmnModelInstance testProcess = modify(ProcessModels.SUBPROCESS_PROCESS)
      .addSubProcessTo("subProcess")
      .id("eventSubProcess")
      .triggerByEvent()
      .embeddedSubProcess()
      .startEvent("eventSubProcessStart").message(MESSAGE_NAME)
      .endEvent()
      .subProcessDone()
      .done();

    assertGeneratedMigrationPlan(testProcess, testProcess)
      .hasInstructions(
        migrate("eventSubProcess").to("eventSubProcess"),
        migrate("eventSubProcessStart").to("eventSubProcessStart"),
        migrate("subProcess").to("subProcess"),
        migrate("userTask").to("userTask")
      );

    assertGeneratedMigrationPlan(testProcess, ProcessModels.SUBPROCESS_PROCESS)
      .hasInstructions(
        migrate("subProcess").to("subProcess"),
        migrate("userTask").to("userTask")
      );

    assertGeneratedMigrationPlan(ProcessModels.SUBPROCESS_PROCESS, testProcess)
      .hasInstructions(
        migrate("subProcess").to("subProcess"),
        migrate("userTask").to("userTask")
      );

  }

  @Test
  public void testMigrateUserTaskInEventSubProcess() {
    BpmnModelInstance testProcess = modify(ProcessModels.SUBPROCESS_PROCESS)
      .addSubProcessTo("subProcess")
      .id("eventSubProcess")
      .triggerByEvent()
      .embeddedSubProcess()
      .startEvent("eventSubProcessStart").message(MESSAGE_NAME)
      .userTask("innerTask")
      .endEvent()
      .subProcessDone()
      .done();

    assertGeneratedMigrationPlan(testProcess, testProcess)
      .hasInstructions(
          migrate("eventSubProcess").to("eventSubProcess"),
          migrate("eventSubProcessStart").to("eventSubProcessStart"),
          migrate("innerTask").to("innerTask"),
          migrate("subProcess").to("subProcess"),
          migrate("userTask").to("userTask")
      );

    assertGeneratedMigrationPlan(testProcess, ProcessModels.SUBPROCESS_PROCESS)
      .hasInstructions(
          migrate("subProcess").to("subProcess"),
          migrate("userTask").to("userTask")
      );

    assertGeneratedMigrationPlan(ProcessModels.SUBPROCESS_PROCESS, testProcess)
    .hasInstructions(
        migrate("subProcess").to("subProcess"),
        migrate("userTask").to("userTask")
    );

  }

  @Test
  public void testNotMigrateActivitiesOfDifferentType() {
    BpmnModelInstance sourceProcess = ProcessModels.ONE_TASK_PROCESS;
    BpmnModelInstance targetProcess = modify(ProcessModels.SUBPROCESS_PROCESS)
      .swapElementIds("userTask", "subProcess");

    assertGeneratedMigrationPlan(sourceProcess, targetProcess)
      .hasEmptyInstructions();
  }

  @Test
  public void testNotMigrateBoundaryEventsOfDifferentType() {
    BpmnModelInstance sourceProcess = modify(ProcessModels.ONE_TASK_PROCESS)
      .activityBuilder("userTask")
        .boundaryEvent("boundary").message(MESSAGE_NAME)
      .done();
    BpmnModelInstance targetProcess = modify(ProcessModels.ONE_TASK_PROCESS)
      .activityBuilder("userTask")
        .boundaryEvent("boundary").signal(SIGNAL_NAME)
      .done();

    assertGeneratedMigrationPlan(sourceProcess, targetProcess)
      .hasInstructions(
        migrate("userTask").to("userTask")
      );
  }

  @Test
  public void testNotMigrateMultiInstanceOfDifferentType() {
    BpmnModelInstance sourceProcess = MultiInstanceProcessModels.SEQ_MI_ONE_TASK_PROCESS;
    BpmnModelInstance targetProcess = MultiInstanceProcessModels.PAR_MI_ONE_TASK_PROCESS;

    assertGeneratedMigrationPlan(sourceProcess, targetProcess)
      .hasEmptyInstructions();
  }

  @Test
  public void testNotMigrateBoundaryEventsWithInvalidEventScopeInstruction() {
    BpmnModelInstance sourceProcess = modify(ProcessModels.ONE_TASK_PROCESS)
        .activityBuilder("userTask")
        .boundaryEvent("boundary")
        .message("foo")
        .done();
    BpmnModelInstance targetProcess = modify(ProcessModels.ONE_RECEIVE_TASK_PROCESS)
        .changeElementId("receiveTask", "userTask")
        .activityBuilder("userTask")
        .boundaryEvent("boundary")
        .message("foo")
        .done();

    assertGeneratedMigrationPlan(sourceProcess, targetProcess)
      .hasEmptyInstructions();
  }

  @Test
  public void testMapReceiveTasks() {
    assertGeneratedMigrationPlan(MessageReceiveModels.ONE_RECEIVE_TASK_PROCESS, MessageReceiveModels.ONE_RECEIVE_TASK_PROCESS)
      .hasInstructions(
        migrate("receiveTask").to("receiveTask"),
        migrate("userTask").to("userTask"));
  }

  @Test
  public void testMapMessageCatchEvents() {
    assertGeneratedMigrationPlan(MessageReceiveModels.ONE_MESSAGE_CATCH_PROCESS, MessageReceiveModels.ONE_MESSAGE_CATCH_PROCESS)
      .hasInstructions(
        migrate("messageCatch").to("messageCatch"),
        migrate("userTask").to("userTask"));
  }

  @Test
  public void testMapCallActivitiesToBpmnTest() {
    assertGeneratedMigrationPlan(CallActivityModels.oneBpmnCallActivityProcess("foo"), CallActivityModels.oneBpmnCallActivityProcess("foo"))
      .hasInstructions(
        migrate("callActivity").to("callActivity"),
        migrate("userTask").to("userTask"));
  }

  @Test
  public void testMapCallActivitiesToCmmnTest() {
    assertGeneratedMigrationPlan(CallActivityModels.oneCmmnCallActivityProcess("foo"), CallActivityModels.oneCmmnCallActivityProcess("foo"))
      .hasInstructions(
        migrate("callActivity").to("callActivity"),
        migrate("userTask").to("userTask"));
  }

  @Test
  public void testMapCallActivitiesFromBpmnToCmmnTest() {
    assertGeneratedMigrationPlan(CallActivityModels.oneBpmnCallActivityProcess("foo"), CallActivityModels.oneCmmnCallActivityProcess("foo"))
      .hasInstructions(
        migrate("callActivity").to("callActivity"),
        migrate("userTask").to("userTask"));
  }

  @Test
  public void testMapCallActivitiesFromCmmnToBpmnTest() {
    assertGeneratedMigrationPlan(CallActivityModels.oneCmmnCallActivityProcess("foo"), CallActivityModels.oneBpmnCallActivityProcess("foo"))
      .hasInstructions(
        migrate("callActivity").to("callActivity"),
        migrate("userTask").to("userTask"));
  }

  @Test
  public void testMapEventBasedGateway() {
    assertGeneratedMigrationPlan(EventBasedGatewayModels.TIMER_EVENT_BASED_GW_PROCESS, EventBasedGatewayModels.SIGNAL_EVENT_BASED_GW_PROCESS)
      .hasInstructions(
        migrate("eventBasedGateway").to("eventBasedGateway"));
  }

  @Test
  public void testMapEventBasedGatewayWithIdenticalFollowingEvents() {
    assertGeneratedMigrationPlan(EventBasedGatewayModels.TIMER_EVENT_BASED_GW_PROCESS, EventBasedGatewayModels.TIMER_EVENT_BASED_GW_PROCESS)
      .hasInstructions(
        migrate("eventBasedGateway").to("eventBasedGateway"),
        migrate("timerCatch").to("timerCatch"),
        migrate("afterTimerCatch").to("afterTimerCatch"));
  }

  // event sub process

  @Test
  public void testMapTimerEventSubProcessAndStartEvent() {
    assertGeneratedMigrationPlan(EventSubProcessModels.TIMER_EVENT_SUBPROCESS_PROCESS, EventSubProcessModels.TIMER_EVENT_SUBPROCESS_PROCESS)
      .hasInstructions(
        migrate("userTask").to("userTask"),
        migrate("eventSubProcess").to("eventSubProcess"),
        migrate("eventSubProcessStart").to("eventSubProcessStart"),
        migrate("eventSubProcessTask").to("eventSubProcessTask"));
  }

  @Test
  public void testMapMessageEventSubProcessAndStartEvent() {
    assertGeneratedMigrationPlan(EventSubProcessModels.MESSAGE_EVENT_SUBPROCESS_PROCESS, EventSubProcessModels.MESSAGE_EVENT_SUBPROCESS_PROCESS)
      .hasInstructions(
        migrate("userTask").to("userTask"),
        migrate("eventSubProcess").to("eventSubProcess"),
        migrate("eventSubProcessStart").to("eventSubProcessStart"),
        migrate("eventSubProcessTask").to("eventSubProcessTask"));
  }

  @Test
  public void testMapSignalEventSubProcessAndStartEvent() {
    assertGeneratedMigrationPlan(EventSubProcessModels.SIGNAL_EVENT_SUBPROCESS_PROCESS, EventSubProcessModels.SIGNAL_EVENT_SUBPROCESS_PROCESS)
      .hasInstructions(
        migrate("userTask").to("userTask"),
        migrate("eventSubProcess").to("eventSubProcess"),
        migrate("eventSubProcessStart").to("eventSubProcessStart"),
        migrate("eventSubProcessTask").to("eventSubProcessTask"));
  }

  @Test
  public void testMapEscalationEventSubProcessAndStartEvent() {
    assertGeneratedMigrationPlan(EventSubProcessModels.ESCALATION_EVENT_SUBPROCESS_PROCESS, EventSubProcessModels.ESCALATION_EVENT_SUBPROCESS_PROCESS)
      .hasInstructions(
        migrate("userTask").to("userTask"),
        migrate("eventSubProcess").to("eventSubProcess"),
        migrate("eventSubProcessTask").to("eventSubProcessTask"));
  }

  @Test
  public void testMapErrorEventSubProcessAndStartEvent() {
    assertGeneratedMigrationPlan(EventSubProcessModels.ERROR_EVENT_SUBPROCESS_PROCESS, EventSubProcessModels.ERROR_EVENT_SUBPROCESS_PROCESS)
      .hasInstructions(
        migrate("userTask").to("userTask"),
        migrate("eventSubProcess").to("eventSubProcess"),
        migrate("eventSubProcessTask").to("eventSubProcessTask"));
  }

  @Test
  public void testMapCompensationEventSubProcessAndStartEvent() {
    assertGeneratedMigrationPlan(EventSubProcessModels.COMPENSATE_EVENT_SUBPROCESS_PROCESS, EventSubProcessModels.COMPENSATE_EVENT_SUBPROCESS_PROCESS)
      .hasInstructions(
        migrate("subProcess").to("subProcess"),
        migrate("userTask").to("userTask"),
        migrate("eventSubProcessStart").to("eventSubProcessStart"));
  }

  @Test
  public void testNotMapEventSubProcessStartEventOfDifferentType() {
    assertGeneratedMigrationPlan(EventSubProcessModels.TIMER_EVENT_SUBPROCESS_PROCESS, EventSubProcessModels.SIGNAL_EVENT_SUBPROCESS_PROCESS)
      .hasInstructions(
        migrate("userTask").to("userTask"),
        migrate("eventSubProcess").to("eventSubProcess"),
        migrate("eventSubProcessTask").to("eventSubProcessTask"));
  }

  @Test
  public void testMapEventSubProcessStartEventWhenSubProcessesAreNotEqual() {
    BpmnModelInstance sourceModel = EventSubProcessModels.TIMER_EVENT_SUBPROCESS_PROCESS;
    BpmnModelInstance targetModel = modify(EventSubProcessModels.TIMER_EVENT_SUBPROCESS_PROCESS)
        .changeElementId("eventSubProcess", "newEventSubProcess");

    assertGeneratedMigrationPlan(sourceModel, targetModel)
      .hasInstructions(
        migrate("userTask").to("userTask"),
        migrate("eventSubProcessStart").to("eventSubProcessStart"));
  }

  @Test
  public void testMapEventSubProcessToEmbeddedSubProcess() {
    BpmnModelInstance sourceModel = modify(EventSubProcessModels.TIMER_EVENT_SUBPROCESS_PROCESS)
        .changeElementId("eventSubProcess", "subProcess");
    BpmnModelInstance targetModel = ProcessModels.SUBPROCESS_PROCESS;

    assertGeneratedMigrationPlan(sourceModel, targetModel)
      .hasInstructions(
        migrate("subProcess").to("subProcess"));
  }

  @Test
  public void testMapEmbeddedSubProcessToEventSubProcess() {
    BpmnModelInstance sourceModel = ProcessModels.SUBPROCESS_PROCESS;
    BpmnModelInstance targetModel = modify(EventSubProcessModels.TIMER_EVENT_SUBPROCESS_PROCESS)
        .changeElementId("eventSubProcess", "subProcess");

    assertGeneratedMigrationPlan(sourceModel, targetModel)
      .hasInstructions(
        migrate("subProcess").to("subProcess"));
  }

  @Test
  public void testMapExternalServiceTask() {
    BpmnModelInstance sourceModel = ExternalTaskModels.ONE_EXTERNAL_TASK_PROCESS;
    BpmnModelInstance targetModel = ExternalTaskModels.ONE_EXTERNAL_TASK_PROCESS;

    assertGeneratedMigrationPlan(sourceModel, targetModel)
      .hasInstructions(
        migrate("externalTask").to("externalTask"));
  }

  @Test
  public void testMapExternalServiceToDifferentType() {
    BpmnModelInstance sourceModel = ExternalTaskModels.ONE_EXTERNAL_TASK_PROCESS;
    BpmnModelInstance targetModel = ProcessModels.newModel()
      .startEvent()
      .sendTask("externalTask")
        .camundaType("external")
        .camundaTopic("foo")
      .endEvent()
      .done();

    assertGeneratedMigrationPlan(sourceModel, targetModel)
      .hasInstructions(
        migrate("externalTask").to("externalTask"));
  }

  @Test
  public void testNotMapExternalToClassDelegateServiceTask() {
    BpmnModelInstance sourceModel = ExternalTaskModels.ONE_EXTERNAL_TASK_PROCESS;
    BpmnModelInstance targetModel = modify(ServiceTaskModels.oneClassDelegateServiceTask("foo.Bar"))
      .changeElementId("serviceTask", "externalTask");

    assertGeneratedMigrationPlan(sourceModel, targetModel)
      .hasEmptyInstructions();
  }

  @Test
  public void testMapParallelGateways() {
    BpmnModelInstance model = GatewayModels.PARALLEL_GW;

    assertGeneratedMigrationPlan(model, model)
      .hasInstructions(
        migrate("fork").to("fork"),
        migrate("join").to("join"),
        migrate("parallel1").to("parallel1"),
        migrate("parallel2").to("parallel2"),
        migrate("afterJoin").to("afterJoin")
      );
  }

  @Test
  public void testMapInclusiveGateways() {
    BpmnModelInstance model = GatewayModels.INCLUSIVE_GW;

    assertGeneratedMigrationPlan(model, model)
      .hasInstructions(
        migrate("fork").to("fork"),
        migrate("join").to("join"),
        migrate("parallel1").to("parallel1"),
        migrate("parallel2").to("parallel2"),
        migrate("afterJoin").to("afterJoin")
      );
  }

  @Test
  public void testNotMapParallelToInclusiveGateway() {

    assertGeneratedMigrationPlan(GatewayModels.PARALLEL_GW, GatewayModels.INCLUSIVE_GW)
      .hasInstructions(
        migrate("parallel1").to("parallel1"),
        migrate("parallel2").to("parallel2"),
        migrate("afterJoin").to("afterJoin")
      );
  }

  @Test
  public void testMapTransaction() {

    assertGeneratedMigrationPlan(TransactionModels.ONE_TASK_TRANSACTION, TransactionModels.ONE_TASK_TRANSACTION)
      .hasInstructions(
        migrate("transaction").to("transaction"),
        migrate("userTask").to("userTask")
      );
  }

  @Test
  public void testMapEmbeddedSubProcessToTransaction() {
    BpmnModelInstance sourceProcess = ProcessModels.SUBPROCESS_PROCESS;
    BpmnModelInstance targetProcess = modify(TransactionModels.ONE_TASK_TRANSACTION)
        .changeElementId("transaction", "subProcess");

    assertGeneratedMigrationPlan(sourceProcess, targetProcess)
      .hasInstructions(
        migrate("subProcess").to("subProcess"),
        migrate("userTask").to("userTask")
      );
  }

  @Test
  public void testMapTransactionToEventSubProcess() {

    BpmnModelInstance sourceProcess = TransactionModels.ONE_TASK_TRANSACTION;
    BpmnModelInstance targetProcess = modify(EventSubProcessModels.MESSAGE_EVENT_SUBPROCESS_PROCESS)
      .changeElementId("eventSubProcess", "transaction")
      .changeElementId("userTask", "foo")
      .changeElementId("eventSubProcessTask", "userTask");

    assertGeneratedMigrationPlan(sourceProcess, targetProcess)
      .hasInstructions(
        migrate("transaction").to("transaction"),
        migrate("userTask").to("userTask")
      );
  }

  @Test
  public void testMapNoUpdateEventTriggers() {
    BpmnModelInstance model = MessageReceiveModels.ONE_MESSAGE_CATCH_PROCESS;

    assertGeneratedMigrationPlan(model, model, false)
      .hasInstructions(
        migrate("userTask").to("userTask").updateEventTrigger(false),
        migrate("messageCatch").to("messageCatch").updateEventTrigger(false)
      );
  }

  @Test
  public void testMapUpdateEventTriggers() {
    BpmnModelInstance model = MessageReceiveModels.ONE_MESSAGE_CATCH_PROCESS;

    assertGeneratedMigrationPlan(model, model, true)
      .hasInstructions(
        migrate("userTask").to("userTask").updateEventTrigger(false),
        migrate("messageCatch").to("messageCatch").updateEventTrigger(true)
      );
  }

  @Test
  public void testMigrationPlanCreationWithEmptyDeploymentCache() {
    // given
    ProcessDefinition sourceDefinition = testHelper.deployAndGetDefinition(ProcessModels.ONE_TASK_PROCESS);
    ProcessDefinition targetDefinition = testHelper.deployAndGetDefinition(ProcessModels.ONE_TASK_PROCESS);
    rule.getProcessEngineConfiguration().getDeploymentCache().discardProcessDefinitionCache();

    // when
    MigrationPlan migrationPlan = rule.getRuntimeService().createMigrationPlan(sourceDefinition.getId(), targetDefinition.getId())
      .mapEqualActivities()
      .build();

    // then
    assertNotNull(migrationPlan);
  }

  @Test
  public void testMapCompensationBoundaryEvents() {

    assertGeneratedMigrationPlan(CompensationModels.ONE_COMPENSATION_TASK_MODEL, CompensationModels.ONE_COMPENSATION_TASK_MODEL, true)
      .hasInstructions(
        migrate("userTask1").to("userTask1").updateEventTrigger(false),
        migrate("userTask2").to("userTask2").updateEventTrigger(false),
        migrate("compensationBoundary").to("compensationBoundary").updateEventTrigger(false)
      );
  }

  @Test
  public void testMapCompensationStartEvents() {
    assertGeneratedMigrationPlan(CompensationModels.COMPENSATION_EVENT_SUBPROCESS_MODEL, CompensationModels.COMPENSATION_EVENT_SUBPROCESS_MODEL, true)
      .hasInstructions(
        migrate("subProcess").to("subProcess").updateEventTrigger(false),
        migrate("userTask1").to("userTask1").updateEventTrigger(false),
        migrate("eventSubProcessStart").to("eventSubProcessStart").updateEventTrigger(false),
        migrate("userTask2").to("userTask2").updateEventTrigger(false),
        migrate("compensationBoundary").to("compensationBoundary").updateEventTrigger(false)
      );

    // should not map eventSubProcess because it active compensation is not supported
  }

  @Test
  public void testMapIntermediateConditionalEvent() {
    BpmnModelInstance sourceProcess = Bpmn.createExecutableProcess(CONDITIONAL_PROCESS_KEY)
      .startEvent()
      .intermediateCatchEvent(CONDITION_ID)
        .condition(VAR_CONDITION)
      .userTask(USER_TASK_ID)
      .endEvent()
      .done();

    assertGeneratedMigrationPlan(sourceProcess, sourceProcess, false)
      .hasInstructions(
        migrate(CONDITION_ID).to(CONDITION_ID).updateEventTrigger(true),
        migrate(USER_TASK_ID).to(USER_TASK_ID).updateEventTrigger(false)
      );
  }

  @Test
  public void testMapConditionalEventSubProcess() {
    assertGeneratedMigrationPlan(EventSubProcessModels.FALSE_CONDITIONAL_EVENT_SUBPROCESS_PROCESS, EventSubProcessModels.CONDITIONAL_EVENT_SUBPROCESS_PROCESS, false)
      .hasInstructions(
        migrate(EVENT_SUB_PROCESS_START_ID).to(EVENT_SUB_PROCESS_START_ID).updateEventTrigger(true),
        migrate(EVENT_SUB_PROCESS_ID).to(EVENT_SUB_PROCESS_ID).updateEventTrigger(false),
        migrate(EVENT_SUB_PROCESS_TASK_ID).to(EVENT_SUB_PROCESS_TASK_ID),
        migrate(USER_TASK_ID).to(USER_TASK_ID)
      );
  }

  @Test
  public void testMapConditionalBoundaryEvents() {
    BpmnModelInstance sourceProcess = modify(ProcessModels.ONE_TASK_PROCESS)
      .activityBuilder(USER_TASK_ID)
      .boundaryEvent(BOUNDARY_ID)
      .condition(VAR_CONDITION)
      .done();

    assertGeneratedMigrationPlan(sourceProcess, sourceProcess, false)
      .hasInstructions(
        migrate(BOUNDARY_ID).to(BOUNDARY_ID).updateEventTrigger(true),
        migrate(USER_TASK_ID).to(USER_TASK_ID).updateEventTrigger(false)
      );
  }

  // helper

  protected MigrationPlanAssert assertGeneratedMigrationPlan(BpmnModelInstance sourceProcess, BpmnModelInstance targetProcess) {
    return assertGeneratedMigrationPlan(sourceProcess, targetProcess, false);
  }

  protected MigrationPlanAssert assertGeneratedMigrationPlan(BpmnModelInstance sourceProcess, BpmnModelInstance targetProcess, boolean updateEventTriggers) {
    ProcessDefinition sourceProcessDefinition = testHelper.deployAndGetDefinition(sourceProcess);
    ProcessDefinition targetProcessDefinition = testHelper.deployAndGetDefinition(targetProcess);

    MigrationInstructionsBuilder migrationInstructionsBuilder = rule.getRuntimeService()
      .createMigrationPlan(sourceProcessDefinition.getId(), targetProcessDefinition.getId())
      .mapEqualActivities();

    if (updateEventTriggers) {
      migrationInstructionsBuilder.updateEventTriggers();
    }

    MigrationPlan migrationPlan = migrationInstructionsBuilder
      .build();

    assertThat(migrationPlan)
      .hasSourceProcessDefinition(sourceProcessDefinition)
      .hasTargetProcessDefinition(targetProcessDefinition);

    return assertThat(migrationPlan);
  }

}