text:
<?php
/**
 * @author Gabriel Zerbib <gabriel@figdice.org>
 * @package FigDice
 */

namespace figdice;

use figdice\classes\AutoloadFeedFactory;
use figdice\classes\Context;
use figdice\classes\MagicReflector;
use figdice\classes\NativeFunctionFactory;
use figdice\classes\TagFig;
use figdice\classes\tags\TagFigCdata;
use figdice\classes\tags\TagFigDictionary;
use figdice\classes\tags\TagFigFeed;
use figdice\classes\tags\TagFigInclude;
use figdice\classes\tags\TagFigMount;
use figdice\classes\tags\TagFigParam;
use figdice\classes\tags\TagFigTrans;
use figdice\classes\tags\TagFigAttr;
use figdice\classes\tags\TagFigVal;
use figdice\classes\ViewElementContainer;
use figdice\classes\ViewElementTag;
use figdice\exceptions\FeedClassNotFoundException;
use figdice\exceptions\FileNotFoundException;
use figdice\exceptions\RequiredAttributeException;
use figdice\exceptions\TagRenderingException;
use figdice\exceptions\XMLParsingException;

use figdice\exceptions\RenderingException;
use figdice\classes\XMLEntityTransformer;

/**
 * Main component of the FigDice library.
 * The View object represents the transform lifecycle from a template into a rendered document.
 *
 * After creating a View instance, you may register one or more {@link FeedFactory} objects
 * (see {@see registerFeedFactory}),
 * and you may register one or more {@link FunctionFactory} object (see {@see registerFunctionFactory})
 * and one {@see FilterFactory} (see {@see setFilterFactory}).
 *
 * Then you would {@see loadFile} an XML source file, and finally {@see render} it to obtain its final
 * result (which you would typically output to the browser).
 */
class View implements \Serializable {

	const GLOBAL_PLUGS = 'GLOBAL_PLUGS';

	/** @var bool Indicates whether this object was retrieved by unserializing */
	private $unserialized = false;

	/**
	 * Textual source of the transformation.
	 *
	 * @var string
	 */
	private $source;

	/**
	 * The source filename.
	 * @var string
	 */
	private $filename;

	/**
	 * The directory where to store temporary files (results of compilation).
	 * @var string
	 */
	private $cachePath;

	/**
     * The root folder for the templates, from which to derive the filenames of cached views.
     * @var string
     */
	private $templatesRoot;

	/**
	 * The Filter Factory instance.
     * If no factory is defined, the View will consider that the filter class are already
     * (or auto-) loaded, or PHP will raise the usual class not found exception.
     * Also, without a factory, the filter instance is constructed with no arguments.
	 * @var FilterFactory
	 */
	private $filterFactory;
	/**
	 * The path where to find the language packs.
	 * They are organized in the following tree:
	 * <code>
	 *   <translationPath>/<languageCode>/...(the dictionary files, named the same in every languageCode)
	 * </code>
	 * @var string
	 */
	private $translationPath;
	/**
	 * The language in which to translate the view,
	 * using fig:trans tags.
	 * @var string
	 */
	private $language;

	/**
	 * Depth stack used at parse time.
	 *
	 * @var ViewElementTag[]|ViewElementContainer[]
	 */
	private $stack;

	/**
	 * Topmost node of the tree after successful parsing.
	 *
	 * @var ViewElementTag
	 */
	private $rootNode;

	/**
	 * @var boolean
	 */
	private $replacements = true;

	/**
	 * Indicates whether the source file was successfully parsed.
	 * @var boolean
	 */
	private $bParsed;

	/**
	 * XML parser resource (domxml)
	 *
	 * @var resource
	 */
	private $xmlParser;

	/**
	 * Associative array of the named macros.
	 * A Macro is a ViewElementTag that is rendered
	 * only upon calling from within another element.
	 *
	 * @var ViewElementTag[]
	 */
	public $macros;

	/**
	 * Used internally at parse-time to determine whether when the very
	 * first tag opening occurs.
	 * @var boolean
	 */
	private $firstOpening;

	/**
	 * Cache of Lexers.
	 * @var array of Lexer
	 */
	public $lexers;

	/**
	 * The FeedFactory objects passed by the caller of the view,
	 * which are used to instanciate the feeds.
	 * @var FeedFactory[]
	 */
	public $feedFactories = array();

	/**
	 * Cache mechanism for feed instanciation.
	 * @var FeedFactory[] classname => factory object
	 */
	private $feedFactoryForClass = array();

	/**
	 * The data available to the FIG tags, arranged in stack
	 * of called macros. The head element si the top-level universe.
	 *
	 * @var array
	 */
	private $callStackData;

	/**
	 * Array of FunctionFactory, used to generate the Function handlers in the Lexer.
	 *
	 * @var FunctionFactory[]
	 */
	private $functionFactories;

	/**
	 * Can be overridden with xmlns:XYZ="http://www.figdice.org/"
	 * @var string
	 */
	public $figNamespace = 'fig:';

    /**
     * The default value for omitted "source" attribute on a fig:trans tag.
     * Defined per template.
     * @var string
     */
	public $defaultTransSource = null;

	private $options = [];

    /**
     * Used during parsing, to keep track of the last CData piece that was processed just before opening a tag.
     * @var string
     */
    private $previousCData = null;

    /**
	 * View constructor.
	 * @param array $options Optional indexed array of options, for specific behavior of the library.
	 * Introduced in 2.3 for the remodeling of the plug execution context.
	 */
	public function __construct(array $options = []) {
		$this->options = $options;
		$this->source = '';
		$this->rootNode = null;
		$this->stack = array();
		$this->lexers = array();
		$this->callStackData = array(array());
		$this->functionFactories = array(new NativeFunctionFactory());
		$this->language = null;
		$this->filename = null;
	}

	/**
	 * Checks whether the View has the specified option configured at construction.
	 * @param $option
	 * @return bool
	 */
	public function hasOption($option)
	{
		return in_array($option, $this->options);
	}

	/**
	 *
	 * Specifies the target language code in which you wish to translate
	 * the fig:trans tags or your templates.
	 * This language code must correspond to a subfolder of the Translation Path
	 * Set to null in order to specify that the view should not try any translation.
	 * @param $language string
	 */
	public function setLanguage($language) {
		$this->language = $language;
	}
	/**
	 * Returns the language in which the view is to be translated
	 * if any fig: translation resources are specified.
	 * @return string
	 */
	public function getLanguage() {
		return $this->language;
	}

	/**
	 * Register a new Function Factory instance,
	 * that the Lexer will use in order to load a function handler class.
	 *
	 * @param FunctionFactory $factory
	 */
	public function registerFunctionFactory(FunctionFactory $factory) {
		array_unshift($this->functionFactories, $factory);
	}
	/**
	 * Returns the registered Function Factories.
	 *
	 * @return FunctionFactory[]
	 */
	public function getFunctionFactories() {
		return $this->functionFactories;
	}
	/**
	 * Register a new Feed Factory instance.
	 *
	 * @param FeedFactory $factory
	 */
	public function registerFeedFactory(FeedFactory $factory) {
		$this->feedFactories []= $factory;
	}

	/**
	 * Load from source file.
	 *
   * @param string $filename
   * @throws FileNotFoundException
   */
	public function loadFile($filename) {
		$this->filename = $filename;

		// If a cache directory was specified,
        // try to load from it
		if ($this->cachePath) {
		    if (! $this->templatesRoot) {
		        $this->templatesRoot = dirname($filename);
            }
		    $cacheFile = $this->makeCacheFilename($this->cachePath, $this->templatesRoot, $this->filename);
            if ( file_exists($cacheFile)
                 && (! file_exists($this->filename) || (filemtime($this->filename) < filemtime($cacheFile)) )
            ) {
                $this->loadFromSerialized(file_get_contents($cacheFile));
                return;
            }
        }

		if(file_exists($filename)) {
			$this->source = file_get_contents($filename);
		} else {
			$message = "File not found: $filename";
			throw new FileNotFoundException($message, $filename);
		}
	}

	/**
	 * Instead of loading a file, you can load a string.
	 * Includes and cdata files are taken relative to the working directory.
	 * @param string $string
	 */
	public function loadString($string) {
	  $this->filename = null;
	  $this->source = $string;
	}
	/**
	 * @return ViewElementTag
	 */
	public function getRootNode() {
		return $this->rootNode;
	}

	/**
	 * Specifies whether the View should replace
	 * the standard HTML entities with their special character equivalelent
	 * in source before parsing. Default: true
	 * You should not have to turn off the replacements, unless
	 * working in HHVM and intending to produce non-HTML output, from a
	 * source text which still contains HTML escape sequences (like ä)
	 * @param boolean $bool
	 */
	public function setReplacements($bool) {
	    $this->replacements = $bool;
	}

    /**
     * Parse source.
     * @throws RequiredAttributeException
     * @throws XMLParsingException
     */
	public function parse() {
		if($this->bParsed) {
			return;
		}

		if ($this->replacements) {
            // We cannot rely of html_entity_decode,
            // because it would replace & and < as well,
            // whereas we need to keep them unmodified.
            // We must do it manually, with a modified hardcopy
            // of PHP 5.4+ 's get_html_translation_table(ENT_XHTML)
            $this->source = XMLEntityTransformer::replace($this->source);
		}

		$this->xmlParser = xml_parser_create('UTF-8');
		xml_parser_set_option($this->xmlParser, XML_OPTION_CASE_FOLDING, false);
		xml_set_object($this->xmlParser, $this);
		xml_set_element_handler($this->xmlParser, 'openTagHandler', 'closeTagHandler');
		xml_set_character_data_handler($this->xmlParser,'cdataHandler');

		//Prepare the detection of the very first tag, in order to compute
		//the offset in XML string as regarded by the parser.
		$this->firstOpening = true;

		try {
            $bSuccess = xml_parse($this->xmlParser, $this->source);
        } catch (RequiredAttributeException $ex) {
		    throw $ex->setFile($this->filename);
        }

        if ($bSuccess) {
            $errMsg = '';
            $lineNumber = 0;
        } else {
			$errMsg = xml_error_string(xml_get_error_code($this->xmlParser));
			$lineNumber = xml_get_current_line_number($this->xmlParser);
			if(count($this->stack)) {
				$lastElement = $this->stack[count($this->stack) - 1];
				if($lastElement instanceof ViewElementTag) {
					$errMsg .= '. Last element: ' . $lastElement->getTagName() . '(' . $lineNumber . ')';
				}
			}
		}

		xml_parser_free($this->xmlParser);
		$this->bParsed = $bSuccess;

		if(! $bSuccess ) {
			throw new XMLParsingException(
					$errMsg,
					$lineNumber);
		}

		// Store a serialized version of the parsed tree, if successfully parsed,
        // and if we've got a cache path.
        if ( ($this->cachePath) && ($this->filename !== null) && (! $this->unserialized) ) {
            $cacheFile = $this->makeCacheFilename($this->cachePath, $this->templatesRoot, $this->filename, true);
            file_put_contents($cacheFile, serialize($this));
        }

    }

    /**
     * The compiled file is at the same subfolder location as the source file,
     * relative to the templatesRoot directory, but under the tempPath directory.
     * In other words, tempPath and templatesRoot correspond together.
     *
     * Example: if  cachePath is      /tmp/figdice
     *          and templatesRoot is  /var/www/html/app/templates
     *          and filename is       /var/www/html/app/templates/sub/footer.html
     *
     * then     cacheFile is          /tmp/figdice/figs/sub/footer.html.fig
     *
     * CAUTION: Relative path for the initial template file, is converted to absolute
     * using the current working directory (the way file_get_contents works).
     *
     * You can work with exotic files (non local filesystem) provided that they are specified
     * with full (valid) scheme. @see http://php.net/manual/en/function.parse-url.php
     * @param string $cachePath
     * @param string $templatesRoot
     * @param string $filename
     * @param bool $mkdir Whether to create the intermediate folder structure
     * @return string
     */
    private function makeCacheFilename($cachePath, $templatesRoot, $filename, $mkdir = false)
    {
        // If the template filename is relative (ie. not starting by / and not specifying a scheme)
        // then we first prefis it with the current working directory. And then we continue as if
        // absolute.
        if ( (substr($filename, 0, 1) != '/')  && ! parse_url($filename, PHP_URL_SCHEME)) {
            $filename = getcwd() . '/' . $filename;
        }

        $cacheFile = str_replace($templatesRoot, $cachePath . '/figs', $filename) . '.fig';
        if ($mkdir) {
            // Create the intermediary folders if not exist.
            $intermed = dirname($cacheFile);
            if (! file_exists($intermed)) {
                // In case of permission problems, or file already exists (and is not a directory),
                // the regular PHP warnings will be issued.
                mkdir($intermed, 0700, true);
            }
        }
        return $cacheFile;
    }

    /**
     * Process parsed source and render view,
     * using the data universe.
     * @return string
     * @throws FeedClassNotFoundException
     * @throws RenderingException
     * @throws RequiredAttributeException
     * @throws XMLParsingException
     */
	public function render() {
		if(! $this->bParsed) {
			$this->parse();
		}

		if (! $this->rootNode) {
			throw new XMLParsingException('No template file loaded', 0);
		}

        $context = new Context($this);

		// DOCTYPE
        // The doctype is necessarily on the root tag, declared as an attribute, example:
        //   fig:doctype="html"
        // However, it can be on the root node of an included template (when using the reverse plug/slot pattern)
        if ($this->rootNode instanceof ViewElementTag) {
            $context->setDoctype($this->rootNode->getAttribute($this->figNamespace . 'doctype'));
        }

        try {
            $result = $this->rootNode->render($context);
        } catch (RequiredAttributeException $ex) {
            throw $ex->setFile($context->getFilename());
        } catch (TagRenderingException $ex) {
            throw new RenderingException($ex->getTag(), $context->getFilename(), $ex->getLine(), $ex->getMessage(), $ex);
        } catch (FeedClassNotFoundException $ex) {
            throw $ex->setFile($context->getFilename());
        }

		$result = $this->plugIntoSlots($context, $result);

		// Take care of the doctype at top of output
		if ($context->getDoctype()) {
			$result = '<!doctype ' . $context->getDoctype() . '>' . "\n" . $result;
		}

		return $result;
	}

    /**
     * Specifies the folder in which the engine will be able to produce
     * temporary files, for JIT-compilation and caching purposes. The engine will
     * not attempt to use cache-based optimization features if you leave
     * this property blank.
     *
     * @param string $path
     * @param string $templatesRoot
     */
	public function setCachePath($path, $templatesRoot = null) {
	    // Suppress the trailing slash
		$this->cachePath = preg_replace('#/+$#', '', $path);
		$this->templatesRoot = preg_replace('#/+$#', '', $templatesRoot);
	}
	/**
	 * The folder in which FigDice can store its cache
	 * (currently only Dictionary cache)
	 * @return string
	 */
	public function getCachePath() {
		return $this->cachePath;
	}
	/**
     * The absolute root of all the tree of templates.
     * This value is important when deriving the filename for the cache of a template or
     * its sub-templates (included).
     * The cache directory contains a tree similar to that of the source templates,
     * and you must indicate what source root dir corresponds to the root cache dir.
     * @return string
     */
	public function getTemplatesRoot()
    {
	    return $this->templatesRoot;
    }
	/**
	 * Returns the Filter Factory instance attachted to the view.
	 *
	 * @return FilterFactory
	 */
	public function getFilterFactory() {
		return $this->filterFactory;
	}
	/**
	 * Sets the Filter Factory instance.
	 *
	 * @param FilterFactory $filterFactory
	 */
	public function setFilterFactory(FilterFactory $filterFactory) {
		$this->filterFactory = $filterFactory;
	}

	/**
	 * Specify rendering data by name.
	 * Can be used in replacement to the fig:feed tag and its Feed class.
	 * Always mounts the data at the root level of the universe.
	 *
	 * @param string $mountingName
	 * @param mixed $data
	 */
	public function mount($mountingName, $data) {
		$this->callStackData[0][$mountingName] = $data;
	}

    /**
     * Returns an assoc array of the universe data.
     * During view rendering, the unvierse is made of layers, along the iterations and macro calls etc.
     * One same key can exist in a lower layer and in another layer above it,
     * in which case the upper version is used in priority.
     * This method merges top-bottom (the upper key overwrites the lower one).
     * @return mixed
     */
	public function getMergedData()
    {
        $result = [];
        foreach ($this->callStackData as $layer) {
            $result = array_merge($layer, $result);
        }
        return $result;
    }

    /**
     * @param $xmlParser
     * @param $tagName
     * @param $attributes
     *
     * @throws RequiredAttributeException
     */
    private function openTagHandler($xmlParser, $tagName, $attributes) {
		if($this->firstOpening) {
			$this->firstOpening = false;

			//Position the namespace:
			$matches = null;
			foreach($attributes as $attrName => $attrValue) {
				if(preg_match('/figdice/', $attrValue) &&
					 preg_match('/xmlns:(.+)/', $attrName, $matches)) {
					$this->figNamespace = $matches[1] . ':';
					break;
				}
			}

            // Remove the fig xmlns directive from the list of attributes of the opening root tag
            // (as it should not be rendered)
            unset($attributes['xmlns:' . substr($this->figNamespace, 0, strlen($this->figNamespace) - 1)]);

			// Consume optional fig:trans directive
            if (isset($attributes[$this->figNamespace.'trans'])) {
                $this->defaultTransSource = $attributes[$this->figNamespace.'trans'];
                // Remove the attribute from the list of attributes of the opening root tag
                unset($attributes[$this->figNamespace.'trans']);
            }
        }

		$lineNumber = xml_get_current_line_number($xmlParser);

		//
		// Detect special tags
        //
		if($tagName == $this->figNamespace . TagFigAttr::TAGNAME) {
			$newElement = new TagFigAttr($tagName, $lineNumber);
		} else if ($tagName == $this->figNamespace . TagFigCdata::TAGNAME) {
            $newElement = new TagFigCdata($tagName, $lineNumber);
        } else if ($tagName == $this->figNamespace . TagFigDictionary::TAGNAME) {
            $newElement = new TagFigDictionary($tagName, $lineNumber);
        } else if ($tagName == $this->figNamespace . TagFigFeed::TAGNAME) {
		    $newElement = new TagFigFeed($tagName, $lineNumber);
        } else if ($tagName == $this->figNamespace . TagFigInclude::TAGNAME) {
		    $newElement = new TagFigInclude($tagName, $lineNumber);
        } else if ($tagName == $this->figNamespace . TagFigMount::TAGNAME) {
		    $newElement = new TagFigMount($tagName, $lineNumber);
        } else if ($tagName == $this->figNamespace . TagFigParam::TAGNAME) {
		    $newElement = new TagFigParam($tagName, $lineNumber);
        } else if ($tagName == $this->figNamespace . TagFigTrans::TAGNAME) {
		    $newElement = new TagFigTrans($tagName, $lineNumber);
        } else if ($tagName == $this->figNamespace . TagFigVal::TAGNAME) {
		    $newElement = new TagFigVal($tagName, $lineNumber);
        } else {
			$newElement = new ViewElementTag($tagName, $lineNumber, $this->previousCData);
		}

		$this->previousCData = null;

		$newElement->setAttributes($this->figNamespace, $attributes);

		if($this->rootNode) {
            /** @var ViewElementTag $parentElement */
			$parentElement = & $this->stack[count($this->stack)-1];
			$newElement->parent = &$parentElement;

			//Since the new element has a parent, then the parent is not autoclose.
			$newElement->parent->autoclose = false;

			$parentElement->appendChild($newElement);
		} else
		{
			//If there no root node yet, then this new element is actually
			//the root element for the view.
			$this->rootNode = &$newElement;
		}

		$this->stack[] = & $newElement;
	}
	public function closeTagHandler($xmlParser, $tagName) {
	    /** @var ViewElementTag $element */
		$element = & $this->stack[count($this->stack) - 1];
		array_pop($this->stack);

		//$element->autoclose is set to true at creation of the tag,
		//and then is invalidated as the tag gets inner contents.
		//If the flag is still true here, it means that it has no inner contents.
		//So we might have a chance to find the /> sequence right before current byte position.
		if( $element->autoclose ) {
			$pos = xml_get_current_byte_index($xmlParser);
			//The /> sequence as the previous 2 chars of current position
			//works on Windows XP Pro 32bits with libxml 2.6.26.
			if(substr($this->source, $pos - 2, 2) != '/>') {
                //Find the opening bracket < of the closing tag:
                $latestOpeningBracket = strrpos(substr($this->source, 0, $pos + 1), '<');
                if (!preg_match('#^<[^>]+/>#', substr($this->source, $latestOpeningBracket))) {
                    $element->autoclose = false;
                }
            }
		}

		// Optimization
		$this->tentativeSquashInertTree($element);

	}

	private function tentativeSquashInertTree(ViewElementTag $element)
    {
        // We will now try to perform optimization on the tag that was just closed.
        // If it is not a fig tag, nor contains any fig directive attributes,
        // and none of its plain attribute contains adhoc parts,
        // and all of its children are plain ViewElementCData,
        // then we can turn the whole island into plain CData.
        if ( ! $element instanceof TagFig) {
            $squashedElement = $element->makeSquashedElement( $this->isFigPrefix($element->getTagName()) /*envelope yes or no*/);
            if (null != $squashedElement) {

                // Replate the last child of parent (because it changed nature)
                if ( $element->parent ) {
                    $element->parent->replaceLastChild($squashedElement);
                } // Or if there is no parent, we're the root tag!
                else {
                    $this->rootNode = $squashedElement;
                }
            }
        }
    }

    /**
	 * XML parser handler for CDATA
	 *
	 * @param resource $xmlParser
	 * @param string $cdata
	 */
	private function cdataHandler($xmlParser, $cdata) {
		//Last element in stack = parent element of the CDATA.
		$currentElement = $this->stack[count($this->stack)-1];
		$currentElement->appendCDataChild($cdata);

		// hhvm invokes several cdata chunks if they contain \n
        $this->previousCData .= $cdata;
	}

    /**
     * Inject the content of the fig:plug nodes
     * into the corresponding slots.
     *
     * @param Context $context
     * @param string $input
     * @return string
     */
	private function plugIntoSlots(Context $context, $input) {
	    $slots = $context->getSlots();
		if(count($slots) == 0) {
			// Nothing to do.
			return $input;
		}

		$result = $input;

		foreach($slots as $slotName => $slot) {
			$plugOutput = '';
			$slotPos = strpos($result, $slot->getAnchorString());

            $plugsForSlot = $context->getPlugs($slotName);

			if( null != $plugsForSlot ) {

				foreach ($plugsForSlot as $plug) {

					if ($this->hasOption(self::GLOBAL_PLUGS)) {
						$plugElement = $plug->getTag();
						$plugElement->clearAttribute($this->figNamespace . 'plug');

						$plugRender = $plugElement->render($context);

						if ($plugElement->evalFigAttribute($context, 'append')) {
							$plugOutput .= $plugRender;
						} else {
							$plugOutput = $plugRender;
						}

						$plugElement->setAttribute($this->figNamespace . 'plug', $slotName);
					} else {
						$plugRender = $plug->getRenderedString();
						if ($plug->isAppend()) {
							$plugOutput .= $plugRender;
						} else {
							$plugOutput = $plugRender;
						}
					}

				}
				$result = substr_replace( $result, $plugOutput, $slotPos, strlen($slot->getAnchorString()) + $slot->getLength() );
			} else {
			  // If a slot did not receive any plugged content, we use its
			  // hardcoded template content as default. But we still need
			  // to clear the placeholder that was used during slots/plugs reconciliation!
				$result = substr_replace( $result, $plugOutput, $slotPos, strlen($slot->getAnchorString()) );
			}
			$slot->setLength(strlen($plugOutput));

		}
		return $result;
	}

    /**
     * @internal
     * @param $data
     */
	public function pushStackData($data) {
		array_push($this->callStackData, $data);
	}

    /**
     * @internal
     */
    public function popStackData() {
		array_pop($this->callStackData);
	}
	public function fetchData($name) {
		if($name == '/') {
			return $this->callStackData[0];

		}
		if($name == '.') {
			return $this->callStackData[count($this->callStackData) - 1];
		}
		if($name == '..') {
			return $this->callStackData[count($this->callStackData) - 2];
		}

		$stackDepth = count($this->callStackData);
		for($i = $stackDepth - 1; $i >= 0; --$i) {

			//If the piece of data is actually an object, rather than an array,
			//then try to apply a Get method on the name of the property (a la Java Bean).
			//If the object does not expose such method, try to obtain the object's property directly.
			if(is_object($this->callStackData[$i])) {
				$getter = 'get' . ucfirst($name);
				if(method_exists($this->callStackData[$i], $getter)) {
									return $this->callStackData[$i]->$getter();
				} else {
					$objectVars = get_object_vars($this->callStackData[$i]);
					if(array_key_exists($name, $objectVars)) {
						return $objectVars[$name];
					} else {
                        return MagicReflector::invoke($this->callStackData[$i], $getter);
                    }
				}
			} else {
				if(is_array($this->callStackData[$i]) && array_key_exists($name, $this->callStackData[$i])) {
									return $this->callStackData[$i][$name];
				}
			}

		}
		return null;
	}

	/**
	 * @return string
	 */
	public function getFilename() {
		return $this->filename;
	}
	/**
	 * @return string
	 */
	public function getTranslationPath() {
		return $this->translationPath;
	}
	/**
	 * @param string $path
	 */
	public function setTranslationPath($path) {
		$this->translationPath = $path;
	}

	/**
	 * Called by the ViewElementTag::fig_feed method,
	 * to instantiate a feed by its class name.
	 *
	 * @param string $classname
	 * @param array $attributes associative array of the extended parameters
	 * @return Feed null if no factory handles specified class.
	 */
	public function createFeed($classname, array $attributes) {
		if(in_array($classname, $this->feedFactoryForClass)) {
			$feedFactory = $this->feedFactoryForClass[$classname];
			return $feedFactory->create($classname, $attributes);
		} else {
			// If no factory is registered,
      // let's use at least the Autoload factory
      if (0 == count($this->feedFactories)) {
        $this->registerFeedFactory(new AutoloadFeedFactory());
      }

			foreach ($this->feedFactories as $factory) {
				if(null != ($feedInstance = $factory->create($classname, $attributes))) {
					$this->feedFactoryForClass[$classname] = $factory;
					return $feedInstance;
				}
			}
			return null;
		}
	}

	/**
	 * Checks whether specified attribute name is in the fig namespace
	 * (whose prefix can be overridden by xmlns declaration).
	 * @param string $attribute
	 * @return boolean
	 */
	public function isFigPrefix($attribute) {
		return (substr($attribute, 0, strlen($this->figNamespace)) == $this->figNamespace);
	}

  public function serialize()
  {
      if (! $this->bParsed) {
          $this->parse();
      }

      return serialize([
          'f' => $this->getFilename(),
          'ns' => $this->figNamespace,
          'trans' => $this->defaultTransSource,
          'root' => $this->rootNode
      ]);
  }
  public function unserialize($serialized)
  {
      $data = unserialize($serialized);

      $this->bParsed = true;
      $this->filename = $data['f'];
      $this->figNamespace = $data['ns'];
      $this->defaultTransSource = isset($data['trans']) ? $data['trans'] : null;
      $this->rootNode = $data['root'];

      $this->unserialized = true;
  }

    private function loadFromSerialized($data)
    {
        /** @var View $view */
        $view = unserialize($data);

        $this->bParsed = true;
        $this->filename = $view->filename;
        $this->figNamespace = $view->figNamespace;
        $this->defaultTransSource = $view->defaultTransSource;
        $this->rootNode = $view->rootNode;

        $this->unserialized = true;
    }
}


text:
package com.navercorp.pinpoint.profiler.instrument;

import com.navercorp.pinpoint.bootstrap.config.ProfilerConfig;
import com.navercorp.pinpoint.bootstrap.context.TraceContext;
import com.navercorp.pinpoint.bootstrap.instrument.ClassFilters;
import com.navercorp.pinpoint.bootstrap.instrument.InstrumentContext;
import com.navercorp.pinpoint.bootstrap.instrument.InstrumentMethod;
import com.navercorp.pinpoint.bootstrap.instrument.MethodFilters;
import com.navercorp.pinpoint.bootstrap.plugin.RequestRecorderFactory;
import com.navercorp.pinpoint.bootstrap.plugin.uri.UriStatRecorderFactory;
import com.navercorp.pinpoint.profiler.context.monitor.DataSourceMonitorRegistryService;
import com.navercorp.pinpoint.profiler.context.monitor.metric.CustomMetricRegistryService;
import com.navercorp.pinpoint.profiler.instrument.interceptor.InterceptorDefinitionFactory;
import com.navercorp.pinpoint.profiler.instrument.mock.BaseAnnotationInterceptor;
import com.navercorp.pinpoint.profiler.instrument.mock.BaseGetter;
import com.navercorp.pinpoint.profiler.instrument.mock.BaseSetter;
import com.navercorp.pinpoint.profiler.instrument.mock.accessor.IntAccessor;
import com.navercorp.pinpoint.profiler.instrument.mock.accessor.IntArrayAccessor;
import com.navercorp.pinpoint.profiler.instrument.mock.accessor.IntArraysAccessor;
import com.navercorp.pinpoint.profiler.instrument.mock.accessor.ObjectAccessor;
import com.navercorp.pinpoint.profiler.instrument.mock.accessor.ObjectArrayAccessor;
import com.navercorp.pinpoint.profiler.instrument.mock.accessor.ObjectArraysAccessor;
import com.navercorp.pinpoint.profiler.instrument.mock.accessor.PublicStrAccessor;
import com.navercorp.pinpoint.profiler.instrument.mock.accessor.ThrowExceptionAccessor;
import com.navercorp.pinpoint.profiler.instrument.mock.getter.FieldDefaultStaticFinalStrGetter;
import com.navercorp.pinpoint.profiler.instrument.mock.getter.FieldDefaultStaticStrGetter;
import com.navercorp.pinpoint.profiler.instrument.mock.getter.FieldDefaultStrGetter;
import com.navercorp.pinpoint.profiler.instrument.mock.getter.FieldEnumGetter;
import com.navercorp.pinpoint.profiler.instrument.mock.getter.FieldIntArrayGetter;
import com.navercorp.pinpoint.profiler.instrument.mock.getter.FieldIntGetter;
import com.navercorp.pinpoint.profiler.instrument.mock.getter.FieldMapGetter;
import com.navercorp.pinpoint.profiler.instrument.mock.getter.FieldObjectArrayGetter;
import com.navercorp.pinpoint.profiler.instrument.mock.getter.FieldObjectArraysGetter;
import com.navercorp.pinpoint.profiler.instrument.mock.getter.FieldObjectGetter;
import com.navercorp.pinpoint.profiler.instrument.mock.getter.FieldObjectMapGetter;
import com.navercorp.pinpoint.profiler.instrument.mock.getter.FieldPrivateStaticFinalStrGetter;
import com.navercorp.pinpoint.profiler.instrument.mock.getter.FieldPrivateStaticStrGetter;
import com.navercorp.pinpoint.profiler.instrument.mock.getter.FieldPrivateStrGetter;
import com.navercorp.pinpoint.profiler.instrument.mock.getter.FieldProtectedStaticFinalStrGetter;
import com.navercorp.pinpoint.profiler.instrument.mock.getter.FieldProtectedStaticStrGetter;
import com.navercorp.pinpoint.profiler.instrument.mock.getter.FieldProtectedStrGetter;
import com.navercorp.pinpoint.profiler.instrument.mock.getter.FieldPublicStaticFinalStrGetter;
import com.navercorp.pinpoint.profiler.instrument.mock.getter.FieldPublicStaticStrGetter;
import com.navercorp.pinpoint.profiler.instrument.mock.getter.FieldPublicStrGetter;
import com.navercorp.pinpoint.profiler.instrument.mock.getter.FieldStrMapGetter;
import com.navercorp.pinpoint.profiler.instrument.mock.getter.FieldTransientIntGetter;
import com.navercorp.pinpoint.profiler.instrument.mock.getter.FieldVolatileIntGetter;
import com.navercorp.pinpoint.profiler.instrument.mock.getter.FieldWildcardMapGetter;
import com.navercorp.pinpoint.profiler.instrument.mock.setter.FieldDefaultFinalStrSetter;
import com.navercorp.pinpoint.profiler.instrument.mock.setter.FieldDefaultStaticStrSetter;
import com.navercorp.pinpoint.profiler.instrument.mock.setter.FieldDefaultStrSetter;
import com.navercorp.pinpoint.profiler.instrument.mock.setter.FieldEnumSetter;
import com.navercorp.pinpoint.profiler.instrument.mock.setter.FieldIntArraySetter;
import com.navercorp.pinpoint.profiler.instrument.mock.setter.FieldIntSetter;
import com.navercorp.pinpoint.profiler.instrument.mock.setter.FieldMapSetter;
import com.navercorp.pinpoint.profiler.instrument.mock.setter.FieldObjectArraySetter;
import com.navercorp.pinpoint.profiler.instrument.mock.setter.FieldObjectArraysSetter;
import com.navercorp.pinpoint.profiler.instrument.mock.setter.FieldObjectMapSetter;
import com.navercorp.pinpoint.profiler.instrument.mock.setter.FieldObjectSetter;
import com.navercorp.pinpoint.profiler.instrument.mock.setter.FieldPrivateStrSetter;
import com.navercorp.pinpoint.profiler.instrument.mock.setter.FieldProtectedStrSetter;
import com.navercorp.pinpoint.profiler.instrument.mock.setter.FieldPublicFinalStrSetter;
import com.navercorp.pinpoint.profiler.instrument.mock.setter.FieldPublicStrSetter;
import com.navercorp.pinpoint.profiler.instrument.mock.setter.FieldStrMapSetter;
import com.navercorp.pinpoint.profiler.instrument.mock.setter.FieldTransientIntSetter;
import com.navercorp.pinpoint.profiler.instrument.mock.setter.FieldVolatileIntSetter;
import com.navercorp.pinpoint.profiler.instrument.mock.setter.FieldWildcardMapSetter;
import com.navercorp.pinpoint.profiler.interceptor.factory.ExceptionHandlerFactory;
import com.navercorp.pinpoint.profiler.interceptor.registry.DefaultInterceptorRegistryBinder;
import com.navercorp.pinpoint.profiler.interceptor.registry.InterceptorRegistryBinder;
import com.navercorp.pinpoint.profiler.metadata.ApiMetaDataService;
import com.navercorp.pinpoint.profiler.objectfactory.ObjectBinderFactory;

import com.google.inject.Provider;
import com.google.inject.util.Providers;
import org.junit.Before;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.objectweb.asm.tree.ClassNode;

import java.io.InputStream;
import java.util.List;

import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

/**
 * @author jaehong.kim
 */
public class ASMClassTest {
    private final InterceptorRegistryBinder interceptorRegistryBinder = new DefaultInterceptorRegistryBinder();

    private final ProfilerConfig profilerConfig = mock(ProfilerConfig.class);
    private final Provider<TraceContext> traceContextProvider = Providers.of(mock(TraceContext.class));
    private final DataSourceMonitorRegistryService dataSourceMonitorRegistryService = mock(DataSourceMonitorRegistryService.class);
    private final CustomMetricRegistryService customMetricRegistryService = mock(CustomMetricRegistryService.class);
    private final Provider<ApiMetaDataService> apiMetaDataService = Providers.of(mock(ApiMetaDataService.class));

    private final InstrumentContext pluginContext = mock(InstrumentContext.class);

    private final ExceptionHandlerFactory exceptionHandlerFactory = new ExceptionHandlerFactory(false);
    private final RequestRecorderFactory requestRecorderFactory = mock(RequestRecorderFactory.class);
    private final Provider<UriStatRecorderFactory> uriStatRecorderFactoryProvider = Providers.of(mock(UriStatRecorderFactory.class));

    private final ObjectBinderFactory objectBinderFactory = new ObjectBinderFactory(profilerConfig, traceContextProvider, dataSourceMonitorRegistryService,
            customMetricRegistryService, apiMetaDataService, exceptionHandlerFactory,
            requestRecorderFactory, uriStatRecorderFactoryProvider);
    private final ScopeFactory scopeFactory = new ScopeFactory();
    private final InterceptorDefinitionFactory interceptorDefinitionFactory = new InterceptorDefinitionFactory();

    private final EngineComponent engineComponent = new DefaultEngineComponent(objectBinderFactory, interceptorRegistryBinder, interceptorDefinitionFactory, apiMetaDataService, scopeFactory);

    @Before
    public void setUp() {

        when(pluginContext.injectClass(any(ClassLoader.class), any(String.class))).thenAnswer(new Answer<Class<?>>() {

            @Override
            public Class<?> answer(InvocationOnMock invocation) throws Throwable {
                ClassLoader loader = (ClassLoader) invocation.getArguments()[0];
                String name = (String) invocation.getArguments()[1];

                return loader.loadClass(name);
            }

        });
        when(pluginContext.getResourceAsStream(any(ClassLoader.class), any(String.class))).thenAnswer(new Answer<InputStream>() {

            @Override
            public InputStream answer(InvocationOnMock invocation) throws Throwable {
                ClassLoader loader = (ClassLoader) invocation.getArguments()[0];
                String name = (String) invocation.getArguments()[1];
                if(loader == null) {
                    loader = ClassLoader.getSystemClassLoader();
                }

                return loader.getResourceAsStream(name);
            }
        });
    }

    @Test
    public void getSuperClass() throws Exception {
        ASMClass clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.BaseClass");
        assertEquals("java.lang.Object", clazz.getSuperClass());

        clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.ExtendedClass");
        assertEquals("com.navercorp.pinpoint.profiler.instrument.mock.BaseClass", clazz.getSuperClass());

        clazz = getClass("java.lang.Object");
        assertEquals(null, clazz.getSuperClass());
    }

    @Test
    public void isInterface() throws Exception {
        ASMClass clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.BaseClass");
        assertEquals(false, clazz.isInterface());

        clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.BaseInterface");
        assertEquals(true, clazz.isInterface());
    }

    @Test
    public void getName() throws Exception {
        ASMClass clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.BaseClass");
        assertEquals("com.navercorp.pinpoint.profiler.instrument.mock.BaseClass", clazz.getName());
    }

    @Test
    public void getInterfaces() throws Exception {
        ASMClass clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.BaseClass");
        assertEquals(0, clazz.getInterfaces().length);

        clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.BaseInterface");
        assertEquals(0, clazz.getInterfaces().length);

        clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.BaseImplementClass");
        assertEquals(1, clazz.getInterfaces().length);
        assertEquals("com.navercorp.pinpoint.profiler.instrument.mock.BaseInterface", clazz.getInterfaces()[0]);
    }

    @Test
    public void getDeclaredMethod() throws Exception {
        ASMClass clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.ArgsClass");
        assertNull(clazz.getDeclaredMethod("notExists"));

        assertNotNull(clazz.getDeclaredMethod("arg"));
        assertNotNull(clazz.getDeclaredMethod("argByteType", "byte"));
        assertNotNull(clazz.getDeclaredMethod("argShortType", "short"));
        assertNotNull(clazz.getDeclaredMethod("argIntType", "int"));
        assertNotNull(clazz.getDeclaredMethod("argFloatType", "float"));
        assertNotNull(clazz.getDeclaredMethod("argDoubleType", "double"));
        assertNotNull(clazz.getDeclaredMethod("argBooleanType", "boolean"));
        assertNotNull(clazz.getDeclaredMethod("argCharType", "char"));
        assertNotNull(clazz.getDeclaredMethod("argByteArrayType", "byte[]"));
        assertNotNull(clazz.getDeclaredMethod("argShortArrayType", "short[]"));
        assertNotNull(clazz.getDeclaredMethod("argIntArrayType", "int[]"));
        assertNotNull(clazz.getDeclaredMethod("argFloatArrayType", "float[]"));
        assertNotNull(clazz.getDeclaredMethod("argDoubleArrayType", "double[]"));
        assertNotNull(clazz.getDeclaredMethod("argBooleanArrayType", "boolean[]"));
        assertNotNull(clazz.getDeclaredMethod("argCharArrayType", "char[]"));

        assertNotNull(clazz.getDeclaredMethod("argByteArraysType", "byte[][]"));
        assertNotNull(clazz.getDeclaredMethod("argShortArraysType", "short[][]"));
        assertNotNull(clazz.getDeclaredMethod("argIntArraysType", "int[][]"));
        assertNotNull(clazz.getDeclaredMethod("argFloatArraysType", "float[][]"));
        assertNotNull(clazz.getDeclaredMethod("argDoubleArraysType", "double[][]"));
        assertNotNull(clazz.getDeclaredMethod("argBooleanArraysType", "boolean[][]"));
        assertNotNull(clazz.getDeclaredMethod("argCharArraysType", "char[][]"));

        assertNotNull(clazz.getDeclaredMethod("argAllType", "byte", "short", "int", "float", "double", "boolean", "char", "byte[]", "short[]", "int[]", "float[]", "double[]", "boolean[]", "char[]", "byte[][]", "short[][]", "int[][]", "float[][]", "double[][]", "boolean[][]", "char[][]"));
        assertNotNull(clazz.getDeclaredMethod("argObject", "java.lang.String", "java.lang.Object", "java.lang.Byte", "java.lang.Short", "java.lang.Integer", "java.lang.Long", "java.lang.Float", "java.lang.Double", "java.lang.Boolean", "java.lang.Character", "java.lang.String[]", "java.lang.Object[]", "java.lang.Byte[]", "java.lang.Short[]", "java.lang.Integer[]", "java.lang.Long[]", "java.lang.Float[]", "java.lang.Double[]", "java.lang.Boolean[]", "java.lang.Character[]", "java.lang.String[][]", "java.lang.Object[][]", "java.lang.Byte[][]", "java.lang.Short[][]", "java.lang.Integer[][]", "java.lang.Long[][]", "java.lang.Float[][]", "java.lang.Double[][]", "java.lang.Boolean[][]", "java.lang.Character[][]"));
        assertNotNull(clazz.getDeclaredMethod("argArgs", "java.lang.Object[]"));

        assertNotNull(clazz.getDeclaredMethod("argInterface", "java.util.Map", "java.util.Map", "java.util.Map"));
        assertNotNull(clazz.getDeclaredMethod("argEnum", "java.lang.Enum"));
        assertNotNull(clazz.getDeclaredMethod("argEnumArray", "java.lang.Enum[]"));
        assertNotNull(clazz.getDeclaredMethod("argEnumArrays", "java.lang.Enum[][]"));

        // find super's method.
        clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.ExtendedClass");
        assertNull(clazz.getDeclaredMethod("base"));
    }

    @Test
    public void getDeclaredMethods() throws Exception {
        ASMClass clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.ArgsClass");
        List<InstrumentMethod> methods = clazz.getDeclaredMethods();
        assertNotNull(methods);

        methods = clazz.getDeclaredMethods(MethodFilters.name("arg"));
        assertEquals(1, methods.size());
        assertEquals("arg", methods.get(0).getName());
    }

    @Test
    public void getDeclaredConstructors() throws Exception {
        ASMClass clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.ArgsClass");
        List<InstrumentMethod> constructors = clazz.getDeclaredConstructors();
        assertNotNull(constructors);
        assertEquals(2, constructors.size());
        assertEquals("ArgsClass", constructors.get(0).getName());

        assertEquals("ArgsClass", constructors.get(1).getName());
        assertArrayEquals(new String[] {"int"}, constructors.get(1).getParameterTypes());
    }

    @Test
    public void hasDeclaredMethod() throws Exception {
        ASMClass clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.ArgsClass");
        assertFalse(clazz.hasDeclaredMethod("notExists"));

        assertTrue(clazz.hasDeclaredMethod("arg"));
        assertTrue(clazz.hasDeclaredMethod("argByteType", "byte"));

        // find super's method.
        clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.ExtendedClass");
        assertFalse(clazz.hasDeclaredMethod("base"));
    }

    @Test
    public void hasMethod() throws Exception {
        // find not exists method.
        ASMClass clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.ArgsClass");
        assertFalse(clazz.hasMethod("notExists"));

        // find method.
        assertTrue(clazz.hasMethod("arg"));
        assertTrue(clazz.hasMethod("argByteType", "byte"));

        // find super's method.
        clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.ExtendedClass");
        assertTrue(clazz.hasMethod("base"));
    }

    @Test
    public void hasEnclosingMethod() throws Exception {
        ASMClass clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.BaseClass");
        assertFalse(clazz.hasEnclosingMethod("notExists"));

        clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.NestedClass$3LocalInner");
        assertTrue(clazz.hasEnclosingMethod("enclosingMethod", "java.lang.String", "int"));
    }

    @Test
    public void hasConstructor() throws Exception {
        ASMClass clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.BaseClass");
        assertTrue(clazz.hasConstructor());

        clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.ExtendedClass");
        assertTrue(clazz.hasConstructor());
        assertTrue(clazz.hasConstructor("java.lang.String"));
        assertFalse(clazz.hasConstructor("java.lang.String", "int", "byte"));
    }

    @Test
    public void hasField() throws Exception {
        ASMClass clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.BaseClass");
        assertTrue(clazz.hasField("s"));
        assertFalse(clazz.hasField("notExists"));

        assertTrue(clazz.hasField("b", "boolean"));
        assertTrue(clazz.hasField("s", "java.lang.String"));

        clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.ExtendedClass");
        assertTrue(clazz.hasField("s"));
        assertTrue(clazz.hasField("e"));

        clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.FieldClass");
        assertTrue(clazz.hasField("b"));
        assertTrue(clazz.hasField("s"));
        assertTrue(clazz.hasField("i"));
        assertTrue(clazz.hasField("l"));
        assertTrue(clazz.hasField("f"));
        assertTrue(clazz.hasField("d"));
        assertTrue(clazz.hasField("y"));
        assertTrue(clazz.hasField("c"));

        assertTrue(clazz.hasField("bArray"));
        assertTrue(clazz.hasField("sArray"));
        assertTrue(clazz.hasField("iArray"));
        assertTrue(clazz.hasField("lArray"));
        assertTrue(clazz.hasField("fArray"));
        assertTrue(clazz.hasField("dArray"));
        assertTrue(clazz.hasField("yArray"));
        assertTrue(clazz.hasField("cArray"));

        assertTrue(clazz.hasField("bArrays"));
        assertTrue(clazz.hasField("sArrays"));
        assertTrue(clazz.hasField("iArrays"));
        assertTrue(clazz.hasField("lArrays"));
        assertTrue(clazz.hasField("fArrays"));
        assertTrue(clazz.hasField("dArrays"));
        assertTrue(clazz.hasField("yArrays"));
        assertTrue(clazz.hasField("cArrays"));

        assertTrue(clazz.hasField("str"));
        assertTrue(clazz.hasField("object"));

        assertTrue(clazz.hasField("publicStaticFinalStr"));
        assertTrue(clazz.hasField("volatileInt"));
        assertTrue(clazz.hasField("transientInt"));
    }

    @Test
    public void addDelegatorMethod() throws Exception {
        ASMClass clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.ExtendedClass");
        clazz.addDelegatorMethod("base");
        assertNotNull(clazz.getDeclaredMethod("base"));

        // duplicated.
        try {
            clazz.addDelegatorMethod("extended");
            fail("skip throw exception.");
        } catch(Exception ignored) {
        }

        // not exist.
        try {
            clazz.addDelegatorMethod("notExist");
            fail("skip throw exception.");
        } catch(Exception ignored) {
        }

        clazz.addDelegatorMethod("getInstance");
        assertNotNull(clazz.getDeclaredMethod("getInstance"));
    }

    @Test
    public void addField() throws Exception {
        ASMClass clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.BaseClass");
        clazz.addField(IntAccessor.class);
        assertNotNull(clazz.getDeclaredMethod("_$PINPOINT$_setTraceInt", "int"));
        assertNotNull(clazz.getDeclaredMethod("_$PINPOINT$_getTraceInt"));

        clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.BaseClass");
        clazz.addField(IntArrayAccessor.class);
        assertNotNull(clazz.getDeclaredMethod("_$PINPOINT$_setTraceIntArray", "int[]"));
        assertNotNull(clazz.getDeclaredMethod("_$PINPOINT$_getTraceIntArray"));

        clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.BaseClass");
        clazz.addField(IntArraysAccessor.class);
        assertNotNull(clazz.getDeclaredMethod("_$PINPOINT$_setTraceIntArrays", "int[][]"));
        assertNotNull(clazz.getDeclaredMethod("_$PINPOINT$_getTraceIntArrays"));

        clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.BaseClass");
        clazz.addField(ObjectAccessor.class);
        assertNotNull(clazz.getDeclaredMethod("_$PINPOINT$_setTraceObject", "java.lang.Object"));
        assertNotNull(clazz.getDeclaredMethod("_$PINPOINT$_getTraceObject"));

        clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.BaseClass");
        clazz.addField(ObjectArrayAccessor.class);
        assertNotNull(clazz.getDeclaredMethod("_$PINPOINT$_setTraceObjectArray", "java.lang.Object[]"));
        assertNotNull(clazz.getDeclaredMethod("_$PINPOINT$_getTraceObjectArray"));

        clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.BaseClass");
        clazz.addField(ObjectArraysAccessor.class);
        assertNotNull(clazz.getDeclaredMethod("_$PINPOINT$_setTraceObjectArrays", "java.lang.Object[][]"));
        assertNotNull(clazz.getDeclaredMethod("_$PINPOINT$_getTraceObjectArrays"));

        clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.BaseClass");
        clazz.addField(PublicStrAccessor.class);
        assertNotNull(clazz.getDeclaredMethod("_$PINPOINT$_setTracePublicStr", "java.lang.String"));
        assertNotNull(clazz.getDeclaredMethod("_$PINPOINT$_getTracePublicStr"));

        // skip throw exception.
        clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.BaseClass");
        clazz.addField(ThrowExceptionAccessor.class);
        assertNotNull(clazz.getDeclaredMethod("_$PINPOINT$_setTraceDefaultStr", "java.lang.String"));
        assertNotNull(clazz.getDeclaredMethod("_$PINPOINT$_getTraceDefaultStr"));
    }

    @Test
    public void addGetter() throws Exception {
        // TODO super field.
        ASMClass clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.BaseClass");
        clazz.addGetter(BaseGetter.class, "b");
        assertNotNull(clazz.getDeclaredMethod("_$PINPOINT$_isB"));

        clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.FieldClass");
        clazz.addGetter(FieldIntGetter.class, "i");
        assertNotNull(clazz.getDeclaredMethod("_$PINPOINT$_getInt"));

        clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.FieldClass");
        clazz.addGetter(FieldIntArrayGetter.class, "iArray");
        assertNotNull(clazz.getDeclaredMethod("_$PINPOINT$_getIntArray"));

        clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.FieldClass");
        clazz.addGetter(FieldObjectGetter.class, "object");
        assertNotNull(clazz.getDeclaredMethod("_$PINPOINT$_getObject"));

        clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.FieldClass");
        clazz.addGetter(FieldObjectArrayGetter.class, "objectArray");
        assertNotNull(clazz.getDeclaredMethod("_$PINPOINT$_getObjectArray"));

        clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.FieldClass");
        clazz.addGetter(FieldObjectArraysGetter.class, "objectArrays");
        assertNotNull(clazz.getDeclaredMethod("_$PINPOINT$_getObjectArrays"));

        clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.FieldClass");
        clazz.addGetter(FieldEnumGetter.class, "e");
        assertNotNull(clazz.getDeclaredMethod("_$PINPOINT$_getEnum"));

        clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.FieldClass");
        clazz.addGetter(FieldMapGetter.class, "map");
        assertNotNull(clazz.getDeclaredMethod("_$PINPOINT$_getMap"));

        clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.FieldClass");
        clazz.addGetter(FieldStrMapGetter.class, "strMap");
        assertNotNull(clazz.getDeclaredMethod("_$PINPOINT$_getStrMap"));

        clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.FieldClass");
        clazz.addGetter(FieldObjectMapGetter.class, "objectMap");
        assertNotNull(clazz.getDeclaredMethod("_$PINPOINT$_getObjectMap"));

        clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.FieldClass");
        clazz.addGetter(FieldWildcardMapGetter.class, "wildcardMap");
        assertNotNull(clazz.getDeclaredMethod("_$PINPOINT$_getWildcardMap"));

        clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.FieldClass");
        clazz.addGetter(FieldDefaultStrGetter.class, "defaultStr");
        assertNotNull(clazz.getDeclaredMethod("_$PINPOINT$_getDefaultStr"));

        clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.FieldClass");
        clazz.addGetter(FieldDefaultStaticStrGetter.class, "defaultStaticStr");
        assertNotNull(clazz.getDeclaredMethod("_$PINPOINT$_getDefaultStaticStr"));

        clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.FieldClass");
        clazz.addGetter(FieldDefaultStaticFinalStrGetter.class, "defaultStaticFinalStr");
        assertNotNull(clazz.getDeclaredMethod("_$PINPOINT$_getDefaultStaticFinalStr"));

        clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.FieldClass");
        clazz.addGetter(FieldPrivateStrGetter.class, "privateStr");
        assertNotNull(clazz.getDeclaredMethod("_$PINPOINT$_getPrivateStr"));

        clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.FieldClass");
        clazz.addGetter(FieldPrivateStaticStrGetter.class, "privateStaticStr");
        assertNotNull(clazz.getDeclaredMethod("_$PINPOINT$_getPrivateStaticStr"));

        clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.FieldClass");
        clazz.addGetter(FieldPrivateStaticFinalStrGetter.class, "privateStaticFinalStr");
        assertNotNull(clazz.getDeclaredMethod("_$PINPOINT$_getPrivateStaticFinalStr"));

        clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.FieldClass");
        clazz.addGetter(FieldProtectedStrGetter.class, "protectedStr");
        assertNotNull(clazz.getDeclaredMethod("_$PINPOINT$_getProtectedStr"));

        clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.FieldClass");
        clazz.addGetter(FieldProtectedStaticStrGetter.class, "protectedStaticStr");
        assertNotNull(clazz.getDeclaredMethod("_$PINPOINT$_getProtectedStaticStr"));

        clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.FieldClass");
        clazz.addGetter(FieldProtectedStaticFinalStrGetter.class, "protectedStaticFinalStr");
        assertNotNull(clazz.getDeclaredMethod("_$PINPOINT$_getProtectedStaticFinalStr"));

        clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.FieldClass");
        clazz.addGetter(FieldPublicStrGetter.class, "publicStr");
        assertNotNull(clazz.getDeclaredMethod("_$PINPOINT$_getPublicStr"));

        clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.FieldClass");
        clazz.addGetter(FieldPublicStaticStrGetter.class, "publicStaticStr");
        assertNotNull(clazz.getDeclaredMethod("_$PINPOINT$_getPublicStaticStr"));

        clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.FieldClass");
        clazz.addGetter(FieldPublicStaticFinalStrGetter.class, "publicStaticFinalStr");
        assertNotNull(clazz.getDeclaredMethod("_$PINPOINT$_getPublicStaticFinalStr"));

        clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.FieldClass");
        clazz.addGetter(FieldVolatileIntGetter.class, "volatileInt");
        assertNotNull(clazz.getDeclaredMethod("_$PINPOINT$_getVolatileInt"));

        clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.FieldClass");
        clazz.addGetter(FieldTransientIntGetter.class, "transientInt");
        assertNotNull(clazz.getDeclaredMethod("_$PINPOINT$_getTransientInt"));
    }

    @Test
    public void addSetter() throws Exception {
        ASMClass clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.BaseClass");
        clazz.addSetter(BaseSetter.class, "b");
        assertNotNull(clazz.getDeclaredMethod("_$PINPOINT$_setB", "boolean"));

        clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.FieldClass");
        clazz.addSetter(FieldIntSetter.class, "i");
        assertNotNull(clazz.getDeclaredMethod("_$PINPOINT$_setInt", "int"));

        clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.FieldClass");
        clazz.addSetter(FieldIntArraySetter.class, "iArray");
        assertNotNull(clazz.getDeclaredMethod("_$PINPOINT$_setIntArray", "int[]"));

        clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.FieldClass");
        clazz.addSetter(FieldObjectSetter.class, "object");
        assertNotNull(clazz.getDeclaredMethod("_$PINPOINT$_setObject", "java.lang.Object"));

        clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.FieldClass");
        clazz.addSetter(FieldObjectArraySetter.class, "objectArray");
        assertNotNull(clazz.getDeclaredMethod("_$PINPOINT$_setObjectArray", "java.lang.Object[]"));

        clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.FieldClass");
        clazz.addSetter(FieldObjectArraysSetter.class, "objectArrays");
        assertNotNull(clazz.getDeclaredMethod("_$PINPOINT$_setObjectArrays", "java.lang.Object[][]"));

        clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.FieldClass");
        clazz.addSetter(FieldEnumSetter.class, "e");
        assertNotNull(clazz.getDeclaredMethod("_$PINPOINT$_setEnum", "java.lang.Enum"));

        clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.FieldClass");
        clazz.addSetter(FieldMapSetter.class, "map");
        assertNotNull(clazz.getDeclaredMethod("_$PINPOINT$_setMap", "java.util.Map"));

        clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.FieldClass");
        clazz.addSetter(FieldStrMapSetter.class, "strMap");
        assertNotNull(clazz.getDeclaredMethod("_$PINPOINT$_setStrMap", "java.util.Map"));

        clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.FieldClass");
        clazz.addSetter(FieldObjectMapSetter.class, "objectMap");
        assertNotNull(clazz.getDeclaredMethod("_$PINPOINT$_setObjectMap", "java.util.Map"));

        clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.FieldClass");
        clazz.addSetter(FieldWildcardMapSetter.class, "wildcardMap");
        assertNotNull(clazz.getDeclaredMethod("_$PINPOINT$_setWildcardMap", "java.util.Map"));

        clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.FieldClass");
        clazz.addSetter(FieldDefaultStrSetter.class, "defaultStr");
        assertNotNull(clazz.getDeclaredMethod("_$PINPOINT$_setDefaultStr", "java.lang.String"));

        try {
            clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.FieldClass");
            clazz.addSetter(FieldDefaultStaticStrSetter.class, "defaultStaticStr");
            assertNotNull(clazz.getDeclaredMethod("_$PINPOINT$_setDefaultStaticStr", "java.lang.String"));
            fail("can't throw exception");
        } catch(Exception ignored) {
        }

        try {
            clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.FieldClass");
            clazz.addSetter(FieldDefaultFinalStrSetter.class, "defaultFinalStr");
            assertNotNull(clazz.getDeclaredMethod("_$PINPOINT$_setDefaultFinalStr", "java.lang.String"));
            fail("can't throw exception");
        } catch(Exception ignored) {
        }

        clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.FieldClass");
        clazz.addSetter(FieldPrivateStrSetter.class, "privateStr");
        assertNotNull(clazz.getDeclaredMethod("_$PINPOINT$_setPrivateStr", "java.lang.String"));

        clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.FieldClass");
        clazz.addSetter(FieldProtectedStrSetter.class, "protectedStr");
        assertNotNull(clazz.getDeclaredMethod("_$PINPOINT$_setProtectedStr", "java.lang.String"));

        clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.FieldClass");
        clazz.addSetter(FieldPublicStrSetter.class, "publicStr");
        assertNotNull(clazz.getDeclaredMethod("_$PINPOINT$_setPublicStr", "java.lang.String"));

        try {
            clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.FieldClass");
            clazz.addSetter(FieldPublicFinalStrSetter.class, "publicFinalStr");
            assertNotNull(clazz.getDeclaredMethod("_$PINPOINT$_setPublicFinalStr", "java.lang.String"));
            fail("can't throw exception");
        } catch(Exception ignored) {
        }

        // removeFinal is true
        clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.FieldClass");
        clazz.addSetter(FieldPublicFinalStrSetter.class, "publicFinalStr", true);
        assertNotNull(clazz.getDeclaredMethod("_$PINPOINT$_setPublicFinalStr", "java.lang.String"));

        clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.FieldClass");
        clazz.addSetter(FieldVolatileIntSetter.class, "volatileInt");
        assertNotNull(clazz.getDeclaredMethod("_$PINPOINT$_setVolatileInt", "int"));

        clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.FieldClass");
        clazz.addSetter(FieldTransientIntSetter.class, "transientInt");
        assertNotNull(clazz.getDeclaredMethod("_$PINPOINT$_setTransientInt", "int"));
    }

    @Test
    public void addInterceptor() throws Exception {
        ASMClass clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.BaseClass");
        clazz.addInterceptor(BaseAnnotationInterceptor.class);
    }

    @Test
    public void getNestedClasses() throws Exception {
        ASMClass clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.NestedClass");

        String targetClassName = "com.navercorp.pinpoint.profiler.instrument.mock.NestedClass$StaticNested";
        assertEquals(1, clazz.getNestedClasses(ClassFilters.name(targetClassName)).size());
        assertEquals(targetClassName, clazz.getNestedClasses(ClassFilters.name(targetClassName)).get(0).getName());

        targetClassName = "com.navercorp.pinpoint.profiler.instrument.mock.NestedClass$InstanceInner";
        assertEquals(1, clazz.getNestedClasses(ClassFilters.name(targetClassName)).size());
        assertEquals(targetClassName, clazz.getNestedClasses(ClassFilters.name(targetClassName)).get(0).getName());

        targetClassName = "com.navercorp.pinpoint.profiler.instrument.mock.NestedClass$1LocalInner";
        assertEquals(1, clazz.getNestedClasses(ClassFilters.name(targetClassName)).size());
        assertEquals(targetClassName, clazz.getNestedClasses(ClassFilters.name(targetClassName)).get(0).getName());

        targetClassName = "com.navercorp.pinpoint.profiler.instrument.mock.NestedClass$1";
        assertEquals(1, clazz.getNestedClasses(ClassFilters.name(targetClassName)).size());
        assertEquals(targetClassName, clazz.getNestedClasses(ClassFilters.name(targetClassName)).get(0).getName());

        // find enclosing method condition.
        assertEquals(2, clazz.getNestedClasses(ClassFilters.enclosingMethod("annonymousInnerClass")).size());

        // find interface condition.
        assertEquals(2, clazz.getNestedClasses(ClassFilters.interfaze("java.util.concurrent.Callable")).size());

        // find enclosing method & interface condition.
        assertEquals(1, clazz.getNestedClasses(ClassFilters.chain(ClassFilters.enclosingMethod("annonymousInnerClass"), ClassFilters.interfaze("java.util.concurrent.Callable"))).size());
    }

    @Test
    public void isInterceptorable() throws Exception {
        ASMClass clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.BaseInterface");
        assertFalse(clazz.isInterceptable());

        clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.BaseClass");
        assertTrue(clazz.isInterceptable());

        clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.BaseEnum");
        assertTrue(clazz.isInterceptable());

        clazz = getClass("com.navercorp.pinpoint.profiler.instrument.mock.BaseEnum");
        assertTrue(clazz.isInterceptable());
    }

    private ASMClass getClass(final String targetClassName) throws Exception {
        ClassNode classNode = ASMClassNodeLoader.get(targetClassName);
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        return new ASMClass(engineComponent, pluginContext, classLoader, getClass().getProtectionDomain(), classNode);
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.sqoop.manager.oracle;

import org.apache.hadoop.conf.Configuration;
import org.apache.sqoop.manager.oracle.OraOopConstants.
           OraOopOracleDataChunkMethod;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

/**
 * Test import data from Oracle.
 */
public class ImportTest extends OraOopTestCase {

  private static final boolean DISABLE_ORACLE_ESCAPING_FLAG = false;

  @Test
  public void testProductImport() throws Exception {
    setSqoopTargetDirectory(getSqoopTargetDirectory() + "tst_product");
    createTable("table_tst_product.xml");

    try {
      int retCode = runImport("TST_PRODUCT", getSqoopConf(), false, DISABLE_ORACLE_ESCAPING_FLAG);
      assertEquals("Return code should be 0", 0, retCode);

    } finally {
      cleanupFolders();
      closeTestEnvConnection();
    }
  }

  @Test
  public void testProductWithWhiteSpaceImport() throws Exception {
    setSqoopTargetDirectory(getSqoopTargetDirectory() + "tst_product");
    createTable("table_tst_product_with_white_space.xml");

    try {
      int retCode = runImport("TST_Pr OdUCT", getSqoopConf(), false, DISABLE_ORACLE_ESCAPING_FLAG);
      assertEquals("Return code should be 0", 0, retCode);

    } finally {
      cleanupFolders();
      closeTestEnvConnection();
    }
  }

  @Test
  public void testProductPartImport() throws Exception {
    setSqoopTargetDirectory(getSqoopTargetDirectory() + "tst_product_part");
    createTable("table_tst_product_part.xml");

    try {
      int retCode = runImport("TST_PRODUCT_PART", getSqoopConf(), false, DISABLE_ORACLE_ESCAPING_FLAG);
      assertEquals("Return code should be 0", 0, retCode);

    } finally {
      cleanupFolders();
      closeTestEnvConnection();
    }
  }

  @Test
  public void testProductPartImportPartitionChunk() throws Exception {
    setSqoopTargetDirectory(getSqoopTargetDirectory() + "tst_product_part");
    createTable("table_tst_product_part.xml");

    Configuration sqoopConf = getSqoopConf();
    sqoopConf.set(OraOopConstants.ORAOOP_ORACLE_DATA_CHUNK_METHOD,
        OraOopConstants.OraOopOracleDataChunkMethod.PARTITION.toString());

    try {
      int retCode = runImport("TST_PRODUCT_PART", sqoopConf, false, DISABLE_ORACLE_ESCAPING_FLAG);
      assertEquals("Return code should be 0", 0, retCode);

    } finally {
      cleanupFolders();
      closeTestEnvConnection();
    }
  }

  @Test
  public void testProductPartImportSubset() throws Exception {
    setSqoopTargetDirectory(getSqoopTargetDirectory() + "tst_product_part");
    createTable("table_tst_product_part.xml");

    Configuration sqoopConf = getSqoopConf();
    sqoopConf.set(OraOopConstants.ORAOOP_ORACLE_DATA_CHUNK_METHOD,
        OraOopOracleDataChunkMethod.ROWID.toString());
    sqoopConf.set(OraOopConstants.ORAOOP_IMPORT_PARTITION_LIST,
        "tst_product_part_1,tst_product_part_2,\"tst_product_pa#rt_6\"");

    try {
      int retCode = runImport("TST_PRODUCT_PART", sqoopConf, false, DISABLE_ORACLE_ESCAPING_FLAG);
      assertEquals("Return code should be 0", 0, retCode);

    } finally {
      cleanupFolders();
      closeTestEnvConnection();
    }
  }

  @Test
  public void testProductPartImportSubsetPartitionChunk() throws Exception {
    setSqoopTargetDirectory(getSqoopTargetDirectory() + "tst_product_part");
    createTable("table_tst_product_part.xml");

    Configuration sqoopConf = getSqoopConf();
    sqoopConf.set(OraOopConstants.ORAOOP_ORACLE_DATA_CHUNK_METHOD,
        OraOopOracleDataChunkMethod.PARTITION.toString());
    sqoopConf
        .set(
            OraOopConstants.ORAOOP_IMPORT_PARTITION_LIST,
            "tst_product_part_1,tst_product_part_2,"
           +"tst_product_part_3,\"tst_product_pa#rt_6\"");

    try {
      int retCode = runImport("TST_PRODUCT_PART", sqoopConf, false, DISABLE_ORACLE_ESCAPING_FLAG);
      assertEquals("Return code should be 0", 0, retCode);

    } finally {
      cleanupFolders();
      closeTestEnvConnection();
    }
  }

  @Test
  public void testProductSubPartImport() throws Exception {
    setSqoopTargetDirectory(getSqoopTargetDirectory() + "tst_product_subpart");
    createTable("table_tst_product_subpart.xml");

    try {
      int retCode = runImport("TST_PRODUCT_SUBPART", getSqoopConf(), false, DISABLE_ORACLE_ESCAPING_FLAG);
      assertEquals("Return code should be 0", 0, retCode);

    } finally {
      cleanupFolders();
      closeTestEnvConnection();
    }
  }

  @Test
  public void testProductSubPartImportPartitionChunk() throws Exception {
    setSqoopTargetDirectory(getSqoopTargetDirectory() + "tst_product_subpart");
    createTable("table_tst_product_subpart.xml");

    Configuration sqoopConf = getSqoopConf();
    sqoopConf.set(OraOopConstants.ORAOOP_ORACLE_DATA_CHUNK_METHOD,
        OraOopConstants.OraOopOracleDataChunkMethod.PARTITION.toString());

    try {
      int retCode = runImport("TST_PRODUCT_SUBPART", sqoopConf, false, DISABLE_ORACLE_ESCAPING_FLAG);
      assertEquals("Return code should be 0", 0, retCode);

    } finally {
      cleanupFolders();
      closeTestEnvConnection();
    }
  }

  @Test
  public void testProductSubPartImportSubset() throws Exception {
    setSqoopTargetDirectory(getSqoopTargetDirectory() + "tst_product_subpart");
    createTable("table_tst_product_subpart.xml");

    Configuration sqoopConf = getSqoopConf();
    sqoopConf.set(OraOopConstants.ORAOOP_ORACLE_DATA_CHUNK_METHOD,
        OraOopOracleDataChunkMethod.ROWID.toString());
    sqoopConf
        .set(OraOopConstants.ORAOOP_IMPORT_PARTITION_LIST,
            "TST_PRODUCT_PART_1,TST_PRODUCT_PART_2,"
           +"TST_PRODUCT_PART_3,TST_PRODUCT_PART_4");

    try {
      int retCode = runImport("TST_PRODUCT_SUBPART", sqoopConf, false, DISABLE_ORACLE_ESCAPING_FLAG);
      assertEquals("Return code should be 0", 0, retCode);

    } finally {
      cleanupFolders();
      closeTestEnvConnection();
    }
  }

  @Test
  public void testProductSubPartImportSubsetPartitionChunk() throws Exception {
    setSqoopTargetDirectory(getSqoopTargetDirectory() + "tst_product_subpart");
    createTable("table_tst_product_subpart.xml");

    Configuration sqoopConf = getSqoopConf();
    sqoopConf.set(OraOopConstants.ORAOOP_ORACLE_DATA_CHUNK_METHOD,
        OraOopConstants.OraOopOracleDataChunkMethod.PARTITION.toString());
    sqoopConf.set(OraOopConstants.ORAOOP_IMPORT_PARTITION_LIST,
        "TST_PRODUCT_PART_1,TST_PRODUCT_PART_2,TST_PRODUCT_PART_3");

    try {
      int retCode = runImport("TST_PRODUCT_SUBPART", sqoopConf, false, DISABLE_ORACLE_ESCAPING_FLAG);
      assertEquals("Return code should be 0", 0, retCode);

    } finally {
      cleanupFolders();
      closeTestEnvConnection();
    }
  }

  @Test
  public void testProductImportConsistentRead() throws Exception {
    setSqoopTargetDirectory(getSqoopTargetDirectory() + "tst_product");
    createTable("table_tst_product.xml");

    // Make sure Oracle SCN has updated since creating table
    Thread.sleep(10000);

    Configuration sqoopConf = getSqoopConf();
    sqoopConf.setBoolean(OraOopConstants.ORAOOP_IMPORT_CONSISTENT_READ, true);

    try {
      int retCode = runImport("TST_PRODUCT", sqoopConf, false, DISABLE_ORACLE_ESCAPING_FLAG);
      assertEquals("Return code should be 0", 0, retCode);

    } finally {
      cleanupFolders();
      closeTestEnvConnection();
    }
  }

  @Test
  public void testProductImportMixedCaseTableName() throws Exception {
    setSqoopTargetDirectory(getSqoopTargetDirectory() + "T5+_Pr#duct");
    createTable("table_tst_product_special_chars.xml");

    try {
      int retCode = runImport("\"\"T5+_Pr#duct\"\"", getSqoopConf(), false, DISABLE_ORACLE_ESCAPING_FLAG);
      assertEquals("Return code should be 0", 0, retCode);

    } finally {
      cleanupFolders();
      closeTestEnvConnection();
    }
  }

  @Test
  public void testProductPartIotImport() throws Exception {
    setSqoopTargetDirectory(getSqoopTargetDirectory() + "tst_product_part");
    createTable("table_tst_product_part_iot.xml");

    Configuration sqoopConf = getSqoopConf();
    sqoopConf.set(OraOopConstants.ORAOOP_ORACLE_DATA_CHUNK_METHOD,
        OraOopConstants.OraOopOracleDataChunkMethod.PARTITION.toString());

    try {
      int retCode = runImport("TST_PRODUCT_PART_IOT", sqoopConf, false, DISABLE_ORACLE_ESCAPING_FLAG);
      assertEquals("Return code should be 0", 0, retCode);

    } finally {
      cleanupFolders();
      closeTestEnvConnection();
    }
  }

}


text:
"""
This is a drop-in replacement for multiprocessing's pool that
plays better with keyboard interrupts.  This implimentation is a modified
version of one originally written by Peter K. G. Williams <peter@newton.cx>
for emcee:

    * `<https://github.com/dfm/emcee/blob/master/emcee/interruptible_pool.py>`_

which was an adaptation of a method written by John Reese, shared as

    * `<https://github.com/jreese/multiprocessing-keyboardinterrupt/>`_
"""

import signal, types, atexit, functools
from multiprocessing.pool import Pool as MPPool
from multiprocessing import TimeoutError

def _initializer_wrapper(initializer, *args):
    """
    Ignore SIGINT. During typical keyboard interrupts, the parent does the
    killing.
    """
    signal.signal(signal.SIGINT, signal.SIG_IGN)
    if initializer is not None:
        initializer(*args)

class Pool(MPPool):
    """
    A modified :class:`multiprocessing.pool.Pool` that handles :exc:`KeyboardInterrupts` in the
    :func:`map` method more gracefully.

    :param processes: (optional)
        The number of processes to use (defaults to number of CPUs).

    :param initializer: (optional)
        A callable to be called by each process when it starts.

    :param initargs: (optional)
        Arguments for *initializer*; called as ``initializer(*initargs)``.

    :param kwargs: (optional)
        Extra arguments. Python 2.7 supports a `maxtasksperchild` parameter.
    """
    def __init__(self, processes=None, initializer=None, initargs=(), **kwargs):
        self._wait_timeout = 3600

        new_initializer = functools.partial(_initializer_wrapper, initializer)
        super(Pool, self).__init__(processes, new_initializer, initargs, **kwargs)

    def map(self, func, items, chunksize=None):
        """
        A replacement for :func:`map` that handles :exc:`KeyboardInterrupt`.

        :param func:
            Function to apply to the items.

        :param items:
            Iterable of items to have `func` applied to.
        """
        # Call r.get() with a timeout, since a Condition.wait() swallows
        # KeyboardInterrupts without a timeout
        r = self.map_async(func, items, chunksize)

        while True:
            try:
                return r.get(self._wait_timeout)
            except TimeoutError:
                pass
            except KeyboardInterrupt:
                self.terminate()
                self.join()
                raise

class SerialPool(object):
    def close(self):
        return

    def map(self, function, tasks, callback=None):
        results = []
        for task in tasks:
            result = function(task)
            if callback is not None:
                callback(result)
            results.append(result)
        return results

"""
This is implemented same as in https://github.com/gwastro/pycbc/pycbc/pool.py

"""

def _dummy_broadcast(self, f, args):
    self.map(f, [args] * self.size)

def choose_pool(processes, mpi=False):
    if mpi:
        try:
            import schwimmbad
            pool = schwimmbad.choose_pool(mpi=mpi, processes=processes)
            pool.broadcast = types.MethodType(_dummy_broadcast, pool)
            atexit.register(pool.close)
        except ImportError:
            raise ValueError("Failed to start up an MPI pool, "
                             "install mpi4py / schwimmbadd")
    elif processes == 1:
        pool = SerialPool()
    else:
        pool = Pool(processes)
    return pool


text:
<?php

class Google_Service_AnalyticsData_DateRange extends Google_Model
{
  public $endDate;
  public $name;
  public $startDate;

  public function setEndDate($endDate)
  {
    $this->endDate = $endDate;
  }
  public function getEndDate()
  {
    return $this->endDate;
  }
  public function setName($name)
  {
    $this->name = $name;
  }
  public function getName()
  {
    return $this->name;
  }
  public function setStartDate($startDate)
  {
    $this->startDate = $startDate;
  }
  public function getStartDate()
  {
    return $this->startDate;
  }
}


text:
external help file: PSDataConduIT-help.xml
Module Name: PSDataConduIT
online version: https://github.com/erwindevreugd/PSDataConduIT
schema: 2.0.0
---

# Set-Visit

## SYNOPSIS
Updates a visit.

## SYNTAX

```
Set-Visit [[-Server] <String>] [[-Credential] <PSCredential>] -VisitID <Int32> -VisitorID <Int32>
 -CardholderID <Int32> [-Hours <Int32>] [-ScheduledTimeIn <DateTime>] [-ScheduledTimeOut <DateTime>]
 [-Purpose <String>] [-EmailList <String>] [<CommonParameters>]
```

## DESCRIPTION
Updates a visit.

If the result returns null, try the parameter "-Verbose" to get more details.

## EXAMPLES

### EXAMPLE 1
```

```

## PARAMETERS

### -Server
The name of the server where the DataConduIT service is running or localhost

```yaml
Type: String
Parameter Sets: (All)
Aliases:

Required: False
Position: 1
Default value: $Script:Server
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### -Credential
The credentials used to authenticate the user to the DataConduIT service

```yaml
Type: PSCredential
Parameter Sets: (All)
Aliases:

Required: False
Position: 2
Default value: $Script:Credential
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### -VisitID
Specifies the id of the visit to update.

```yaml
Type: Int32
Parameter Sets: (All)
Aliases:

Required: True
Position: Named
Default value: 0
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### -VisitorID
Specifies the new id of the visitor to assign to the visit.

```yaml
Type: Int32
Parameter Sets: (All)
Aliases:

Required: True
Position: Named
Default value: 0
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### -CardholderID
Specifies the new id of the cardholder that will host the visit.

```yaml
Type: Int32
Parameter Sets: (All)
Aliases:

Required: True
Position: Named
Default value: 0
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### -Hours
Specifies the new duration of the visit.
If the ScheduledTimeout parameter is specified this parameter is ignored.

```yaml
Type: Int32
Parameter Sets: (All)
Aliases:

Required: False
Position: Named
Default value: 4
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### -ScheduledTimeIn
Specifies the new scheduled starting time of the visit.
The default value is now.

```yaml
Type: DateTime
Parameter Sets: (All)
Aliases:

Required: False
Position: Named
Default value: ([DateTime]::Now)
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### -ScheduledTimeOut
Specifies the new scheduled ending time of the visit.

```yaml
Type: DateTime
Parameter Sets: (All)
Aliases:

Required: False
Position: Named
Default value: ([DateTime]::Now).AddHours($Hours)
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### -Purpose
Specifies the new purpose of the visit.

```yaml
Type: String
Parameter Sets: (All)
Aliases:

Required: False
Position: Named
Default value: None
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### -EmailList
Specifies the new list of email addresses for the visit.

```yaml
Type: String
Parameter Sets: (All)
Aliases:

Required: False
Position: Named
Default value: None
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable.
For more information, see about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216).

## INPUTS

## OUTPUTS

## NOTES

## RELATED LINKS


text:
package com.ltdev.cc.entity;

import com.ltdev.cc.Tile;
import com.ltdev.cc.physics.primitives.Shape;

public abstract class HoldObject extends Entity
{
	private boolean held;

	public HoldObject(Shape shape)
	{
	    super(shape);
		held = false;
	}

	public boolean isHeld()
	{
		return held;
	}

	public void hold()
	{
		held = true;
	}

	public void drop()
	{
		held = false;
	}
}


text:
external help file: Microsoft.Azure.Commands.Network.dll-Help.xml
online version:
schema: 2.0.0
---

# Get-AzureRmVirtualNetworkGatewayLearnedRoute

## SYNOPSIS
Lists routes learned by an Azure virtual network gateway

## SYNTAX

```
Get-AzureRmVirtualNetworkGatewayLearnedRoute -VirtualNetworkGatewayName <String> -ResourceGroupName <String>
 [<CommonParameters>]
```

## DESCRIPTION
Enumerates routes learned by an Azure virtual network gateway from various sources. This includes routes learned over BGP, as well as static routes.

## EXAMPLES

### Example 1
```
PS C:\> Get-AzureRmVirtualNetworkGatewayLearnedRoute -ResourceGroupName resourceGroup -VirtualNetworkGatewayname gatewayName

AsPath       :
LocalAddress : 10.1.0.254
Network      : 10.1.0.0/16
NextHop      :
Origin       : Network
SourcePeer   : 10.1.0.254
Weight       : 32768

AsPath       :
LocalAddress : 10.1.0.254
Network      : 10.0.0.254/32
NextHop      :
Origin       : Network
SourcePeer   : 10.1.0.254
Weight       : 32768

AsPath       : 65515
LocalAddress : 10.1.0.254
Network      : 10.0.0.0/16
NextHop      : 10.0.0.254
Origin       : EBgp
SourcePeer   : 10.0.0.254
Weight       : 32768
```

For the Azure virtual network gateway named gatewayname in resource group resourceGroup, retrieves routes the Azure gateway knows.

The Azure virtual network gateway in this case has two static routes (10.1.0.0/16 and 10.0.0.254/32), as well as one route learned over BGP (10.0.0.0/16).

## PARAMETERS

### -ResourceGroupName
Virtual network gateway resource group's name

```yaml
Type: String
Parameter Sets: (All)
Aliases:

Required: True
Position: Named
Default value: None
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### -VirtualNetworkGatewayName
Virtual network gateway name

```yaml
Type: String
Parameter Sets: (All)
Aliases: ResourceName

Required: True
Position: Named
Default value: None
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216).

## INPUTS

### System.String

## OUTPUTS

### Microsoft.Azure.Commands.Network.Models.PSGatewayRoute[]

## NOTES

## RELATED LINKS


text:
SET(CMAKE_DEPENDS_LANGUAGES
  "CXX"
  )
# The set of files for implicit dependencies of each language:
SET(CMAKE_DEPENDS_CHECK_CXX
  "/home/sumedh/kfs/src/cc/meta/ChildProcessTracker.cc" "/home/sumedh/kfs/src/cc/meta/CMakeFiles/kfsMeta-shared.dir/ChildProcessTracker.o"
  "/home/sumedh/kfs/src/cc/meta/ChunkReplicator.cc" "/home/sumedh/kfs/src/cc/meta/CMakeFiles/kfsMeta-shared.dir/ChunkReplicator.o"
  "/home/sumedh/kfs/src/cc/meta/ChunkServer.cc" "/home/sumedh/kfs/src/cc/meta/CMakeFiles/kfsMeta-shared.dir/ChunkServer.o"
  "/home/sumedh/kfs/src/cc/meta/ChunkServerFactory.cc" "/home/sumedh/kfs/src/cc/meta/CMakeFiles/kfsMeta-shared.dir/ChunkServerFactory.o"
  "/home/sumedh/kfs/src/cc/meta/ClientSM.cc" "/home/sumedh/kfs/src/cc/meta/CMakeFiles/kfsMeta-shared.dir/ClientSM.o"
  "/home/sumedh/kfs/src/cc/meta/LayoutManager.cc" "/home/sumedh/kfs/src/cc/meta/CMakeFiles/kfsMeta-shared.dir/LayoutManager.o"
  "/home/sumedh/kfs/src/cc/meta/LeaseCleaner.cc" "/home/sumedh/kfs/src/cc/meta/CMakeFiles/kfsMeta-shared.dir/LeaseCleaner.o"
  "/home/sumedh/kfs/src/cc/meta/NetDispatch.cc" "/home/sumedh/kfs/src/cc/meta/CMakeFiles/kfsMeta-shared.dir/NetDispatch.o"
  "/home/sumedh/kfs/src/cc/meta/checkpoint.cc" "/home/sumedh/kfs/src/cc/meta/CMakeFiles/kfsMeta-shared.dir/checkpoint.o"
  "/home/sumedh/kfs/src/cc/meta/entry.cc" "/home/sumedh/kfs/src/cc/meta/CMakeFiles/kfsMeta-shared.dir/entry.o"
  "/home/sumedh/kfs/src/cc/meta/kfsops.cc" "/home/sumedh/kfs/src/cc/meta/CMakeFiles/kfsMeta-shared.dir/kfsops.o"
  "/home/sumedh/kfs/src/cc/meta/kfstree.cc" "/home/sumedh/kfs/src/cc/meta/CMakeFiles/kfsMeta-shared.dir/kfstree.o"
  "/home/sumedh/kfs/src/cc/meta/logger.cc" "/home/sumedh/kfs/src/cc/meta/CMakeFiles/kfsMeta-shared.dir/logger.o"
  "/home/sumedh/kfs/src/cc/meta/meta.cc" "/home/sumedh/kfs/src/cc/meta/CMakeFiles/kfsMeta-shared.dir/meta.o"
  "/home/sumedh/kfs/src/cc/meta/replay.cc" "/home/sumedh/kfs/src/cc/meta/CMakeFiles/kfsMeta-shared.dir/replay.o"
  "/home/sumedh/kfs/src/cc/meta/request.cc" "/home/sumedh/kfs/src/cc/meta/CMakeFiles/kfsMeta-shared.dir/request.o"
  "/home/sumedh/kfs/src/cc/meta/restore.cc" "/home/sumedh/kfs/src/cc/meta/CMakeFiles/kfsMeta-shared.dir/restore.o"
  "/home/sumedh/kfs/src/cc/meta/startup.cc" "/home/sumedh/kfs/src/cc/meta/CMakeFiles/kfsMeta-shared.dir/startup.o"
  "/home/sumedh/kfs/src/cc/meta/util.cc" "/home/sumedh/kfs/src/cc/meta/CMakeFiles/kfsMeta-shared.dir/util.o"
  )
SET(CMAKE_CXX_COMPILER_ID "GNU")

# Preprocessor definitions for this target.
SET(CMAKE_TARGET_DEFINITIONS
  "_FILE_OFFSET_BITS=64"
  "_LARGEFILE_SOURCE"
  "_LARGEFILE64_SOURCE"
  "_LARGE_FILES"
  "KFS_OS_NAME_LINUX"
  )

# Targets to which this target links.
SET(CMAKE_TARGET_LINKED_INFO_FILES
  )


text:
<!doctype html>

    <base href="../">
    <title>JSDoc: Source:custom-marker.js</title>
    <link type="text/css" rel="stylesheet" href="css/jsdoc-default.css">
    <link href="css/prettify-tomorrow.css" type="text/css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,400,300,700" rel="stylesheet" type="text/css">
    <link href="css/custom.css" type="text/css" rel="stylesheet">

Index

            module: undefined

          +

                service

              +

                Attr2Options

                GeoCoder

                NavigatorGeolocation

                StreetView

                directive

              +

                bicycling-layer

                cloud-layer

                custom-control

                directions

                drawing-manager

                dynamic-maps-engine-layer

                fusion-tables-layer

                heatmap-layer

                info-window

                kml-layer

                map-data

                map-lazy-load

                map-type

                maps-engine-layer

                marker

                overlay-map-type

                places-auto-complete

                shape

                streetview-panorama

                traffic-layer

                transit-layer

                weather-layer

                controller

              +

                MapController

            module: ngmap

          +

                directive

              +

                custom-marker

            module: ngMap

          +

                directive

              +

                map

        Source:custom-marker.js

/**
 * @ngdoc directive
 * @memberof ngmap
 * @name custom-marker
 * @param Attr2Options {service} convert html attribute to Gogole map api options
 * @param $compile {service} AngularJS $compile service
 * @param $timeout {service} AngularJS $timeout
 * @description
 *   Marker with html
 *   Requires:  map directive
 *   Restrict To:  Element
 *
 * @attr {String} position required, position on map
 * @attr {Number} z-index optional
 * @attr {Boolean} visible optional
 * @example
 *
 * Example:
 *   <map center="41.850033,-87.6500523" zoom="3">
 *     <custom-marker position="41.850033,-87.6500523">
 *       <div>
 *         <b>Home</b>
 *       </div>
 *     </custom-marker>
 *   </map>
 *
 */
(function() {
  'use strict';
  var parser, $compile, $timeout;
  var cAbortEvent = function (e) {
    e.preventDefault && e.preventDefault();
    e.cancelBubble = true;
    e.stopPropagation && e.stopPropagation();
  };
  var CustomMarker = function(options) {
    options = options || {};
    this.el = document.createElement('div');
    this.el.style.display = 'inline-block';
    this.visible = true; for (var key in options) {
     this[key] = options[key];
    }
  };
  var setCustomMarker = function() {
    CustomMarker.prototype = new google.maps.OverlayView();
    CustomMarker.prototype.setContent = function(html, scope) {
      this.html = html;
      if (scope) {
        var compiledEl = $compile(html)(scope);
        var customMarkerEl = compiledEl[0];
        var me = this;
        $timeout(function() {
          me.content = customMarkerEl.innerHTML;
          me.el.innerHTML = me.content;
        });
      } else {
        this.content = html;
        this.el.innerHTML = this.content;
      }
      this.el.style.position = 'relative';
      this.el.className = 'custom-marker';
    };
    CustomMarker.prototype.setPosition = function(position) {
      position && (this.position = position);
      if (this.getProjection() && typeof this.position.lng == 'function') {
        var posPixel = this.getProjection().fromLatLngToDivPixel(this.position);
        var x = Math.round(posPixel.x - (this.el.offsetWidth/2));
        var y = Math.round(posPixel.y - this.el.offsetHeight - 10); // 10px for anchor
        this.el.style.left = x + "px";
        this.el.style.top = y + "px";
      }
    };
    CustomMarker.prototype.setZIndex = function(zIndex) {
      zIndex && (this.zIndex = zIndex);
      this.el.style.zIndex = this.zIndex;
    };
    CustomMarker.prototype.setVisible = function(visible) {
      this.el.style.display = visible ? 'inline-block' : 'none';
      this.visible = visible;
    };
    CustomMarker.prototype.addClass = function(className) {
      var classNames = this.el.className.split(' ');
      (classNames.indexOf(className) == -1) && classNames.push(className);
      this.el.className = classNames.join(' ');
    };
    CustomMarker.prototype.removeClass = function(className) {
      var classNames = this.el.className.split(' ');
      var index = classNames.indexOf(className);
      (index > -1) && classNames.splice(index, 1);
      this.el.className = classNames.join(' ');
    };
    CustomMarker.prototype.onAdd = function() {
      this.getPanes().overlayMouseTarget.appendChild(this.el);
    };
    CustomMarker.prototype.draw = function() {
      this.setPosition();
      this.setZIndex(this.zIndex);
      this.setVisible(this.visible);
    };
    CustomMarker.prototype.onRemove = function() {
      this.el.parentNode.removeChild(this.el);
      this.el = null;
    };
  };
  var customMarkerDirective = function(Attr2Options, _$compile_, _$timeout_)  {
    parser = Attr2Options;
    $compile = _$compile_;
    $timeout = _$timeout_;
    setCustomMarker();
    return {
      restrict: 'E',
      require: '^map',
      link: function(scope, element, attrs, mapController) {
        var orgAttrs = parser.orgAttributes(element);
        var filtered = parser.filter(attrs);
        var options = parser.getOptions(filtered, scope);
        var events = parser.getEvents(scope, filtered);
        /**
         * build a custom marker element
         */
        var removedEl = element[0].parentElement.removeChild(element[0]);
        console.log("custom-marker options", options);
        var customMarker = new CustomMarker(options);
        customMarker.setContent(removedEl.innerHTML, scope);
        console.log('customMarker', customMarker);
        console.log("custom-marker events", "events");
        for (var eventName in events) {
          google.maps.event.addDomListener(
            customMarker.el, eventName, events[eventName]);
        }
        mapController.addObject('customMarkers', customMarker);
        if (!(options.position instanceof google.maps.LatLng)) {
          mapController.getGeoLocation(options.position).then(
            function(latlng) {
              customMarker.setPosition(latlng);
            }
          );
        }
        element.bind('$destroy', function() {
          //Is it required to remove event listeners when DOM is removed?
          mapController.deleteObject('customMarkers', marker);
        });
      } //link
    }; // return
  };// function
  customMarkerDirective.$inject = ['Attr2Options', '$compile', '$timeout'];
  angular.module('ngMap').directive('customMarker', customMarkerDirective);
})();

        Documentation generated by
        JSDoc 3.3.2
        using
        Angular-JSDoc template


text:
namespace blink {

class ComputedStyle;
class NGBreakToken;
class NGConstraintSpace;
class NGFragmentBuilder;
class NGInlineNode;
class NGLineBuilder;

// A class for inline layout (e.g. a anonymous block with inline-level children
// only).
//
// This algorithm may at some point be merged with NGBlockLayoutAlgorithm in
// the future. Currently it exists as its own class to simplify the LayoutNG
// transition period.
class CORE_EXPORT NGInlineLayoutAlgorithm : public NGLayoutAlgorithm {
 public:
  // Default constructor.
  // @param style Style reference of the block that is being laid out.
  // @param first_child Our first child; the algorithm will use its NextSibling
  //                    method to access all the children.
  // @param space The constraint space which the algorithm should generate a
  //              fragment within.
  NGInlineLayoutAlgorithm(PassRefPtr<const ComputedStyle>,
                          NGInlineNode* first_child,
                          NGConstraintSpace* space,
                          NGBreakToken* break_token = nullptr);

  NGLayoutStatus Layout(NGPhysicalFragment*,
                        NGPhysicalFragment**,
                        NGLayoutAlgorithm**) override;

  DECLARE_VIRTUAL_TRACE();

 private:
  // Read-only Getters.
  const ComputedStyle& Style() const { return *style_; }

  bool LayoutCurrentChild();
  NGConstraintSpace* CreateConstraintSpaceForCurrentChild() const;

  enum State { kStateInit, kStateChildLayout, kStateFinalize };
  State state_ = kStateInit;

  RefPtr<const ComputedStyle> style_;
  Member<NGInlineNode> first_child_;
  Member<NGConstraintSpace> constraint_space_;
  Member<NGBreakToken> break_token_;
  Member<NGFragmentBuilder> builder_;
  Member<NGConstraintSpace> space_for_current_child_;
  Member<NGInlineNode> current_child_;
  Member<NGLineBuilder> line_builder_;
};

}  // namespace blink

#endif  // NGInlineLayoutAlgorithm_h