text:
package org.apache.commons.math3.fitting;

import java.util.Arrays;
import java.util.Comparator;
import org.apache.commons.math3.analysis.function.Gaussian;
import org.apache.commons.math3.exception.NullArgumentException;
import org.apache.commons.math3.exception.NumberIsTooSmallException;
import org.apache.commons.math3.exception.OutOfRangeException;
import org.apache.commons.math3.exception.ZeroException;
import org.apache.commons.math3.exception.NotStrictlyPositiveException;
import org.apache.commons.math3.exception.util.LocalizedFormats;
import org.apache.commons.math3.optim.nonlinear.vector.MultivariateVectorOptimizer;
import org.apache.commons.math3.util.FastMath;

/**
 * Fits points to a {@link
 * org.apache.commons.math3.analysis.function.Gaussian.Parametric Gaussian} function.
 *

 * Usage example:
 *

 *   GaussianFitter fitter = new GaussianFitter(
 *     new LevenbergMarquardtOptimizer());
 *   fitter.addObservedPoint(4.0254623,  531026.0);
 *   fitter.addObservedPoint(4.03128248, 984167.0);
 *   fitter.addObservedPoint(4.03839603, 1887233.0);
 *   fitter.addObservedPoint(4.04421621, 2687152.0);
 *   fitter.addObservedPoint(4.05132976, 3461228.0);
 *   fitter.addObservedPoint(4.05326982, 3580526.0);
 *   fitter.addObservedPoint(4.05779662, 3439750.0);
 *   fitter.addObservedPoint(4.0636168,  2877648.0);
 *   fitter.addObservedPoint(4.06943698, 2175960.0);
 *   fitter.addObservedPoint(4.07525716, 1447024.0);
 *   fitter.addObservedPoint(4.08237071, 717104.0);
 *   fitter.addObservedPoint(4.08366408, 620014.0);
 *   double[] parameters = fitter.fit();
 *

 *
 * @since 2.2
 * @version $Id: GaussianFitter.java 1416643 2012-12-03 19:37:14Z tn $
 * @deprecated As of 3.3. Please use {@link GaussianCurveFitter} and
 * {@link WeightedObservedPoints} instead.
 */
@Deprecated
public class GaussianFitter extends CurveFitter<Gaussian.Parametric> {
    /**
     * Constructs an instance using the specified optimizer.
     *
     * @param optimizer Optimizer to use for the fitting.
     */
    public GaussianFitter(MultivariateVectorOptimizer optimizer) {
        super(optimizer);
    }

    /**
     * Fits a Gaussian function to the observed points.
     *
     * @param initialGuess First guess values in the following order:
     *

     *
Norm

     *
Mean

     *
Sigma

     *

     * @return the parameters of the Gaussian function that best fits the
     * observed points (in the same order as above).
     * @since 3.0
     */
    public double[] fit(double[] initialGuess) {
        final Gaussian.Parametric f = new Gaussian.Parametric() {
                @Override
                public double value(double x, double ... p) {
                    double v = Double.POSITIVE_INFINITY;
                    try {
                        v = super.value(x, p);
                    } catch (NotStrictlyPositiveException e) { // NOPMD
                        // Do nothing.
                    }
                    return v;
                }

                @Override
                public double[] gradient(double x, double ... p) {
                    double[] v = { Double.POSITIVE_INFINITY,
                                   Double.POSITIVE_INFINITY,
                                   Double.POSITIVE_INFINITY };
                    try {
                        v = super.gradient(x, p);
                    } catch (NotStrictlyPositiveException e) { // NOPMD
                        // Do nothing.
                    }
                    return v;
                }
            };

        return fit(f, initialGuess);
    }

    /**
     * Fits a Gaussian function to the observed points.
     *
     * @return the parameters of the Gaussian function that best fits the
     * observed points (in the same order as above).
     */
    public double[] fit() {
        final double[] guess = (new ParameterGuesser(getObservations())).guess();
        return fit(guess);
    }

    /**
     * Guesses the parameters {@code norm}, {@code mean}, and {@code sigma}
     * of a {@link org.apache.commons.math3.analysis.function.Gaussian.Parametric}
     * based on the specified observed points.
     */
    public static class ParameterGuesser {
        /** Normalization factor. */
        private final double norm;
        /** Mean. */
        private final double mean;
        /** Standard deviation. */
        private final double sigma;

        /**
         * Constructs instance with the specified observed points.
         *
         * @param observations Observed points from which to guess the
         * parameters of the Gaussian.
         * @throws NullArgumentException if {@code observations} is
         * {@code null}.
         * @throws NumberIsTooSmallException if there are less than 3
         * observations.
         */
        public ParameterGuesser(WeightedObservedPoint[] observations) {
            if (observations == null) {
                throw new NullArgumentException(LocalizedFormats.INPUT_ARRAY);
            }
            if (observations.length < 3) {
                throw new NumberIsTooSmallException(observations.length, 3, true);
            }

            final WeightedObservedPoint[] sorted = sortObservations(observations);
            final double[] params = basicGuess(sorted);

            norm = params[0];
            mean = params[1];
            sigma = params[2];
        }

        /**
         * Gets an estimation of the parameters.
         *
         * @return the guessed parameters, in the following order:
         *

         *
Normalization factor

         *
Mean

         *
Standard deviation

         *

         */
        public double[] guess() {
            return new double[] { norm, mean, sigma };
        }

        /**
         * Sort the observations.
         *
         * @param unsorted Input observations.
         * @return the input observations, sorted.
         */
        private WeightedObservedPoint[] sortObservations(WeightedObservedPoint[] unsorted) {
            final WeightedObservedPoint[] observations = unsorted.clone();
            final Comparator<WeightedObservedPoint> cmp
                = new Comparator<WeightedObservedPoint>() {
                public int compare(WeightedObservedPoint p1,
                                   WeightedObservedPoint p2) {
                    if (p1 == null && p2 == null) {
                        return 0;
                    }
                    if (p1 == null) {
                        return -1;
                    }
                    if (p2 == null) {
                        return 1;
                    }
                    if (p1.getX() < p2.getX()) {
                        return -1;
                    }
                    if (p1.getX() > p2.getX()) {
                        return 1;
                    }
                    if (p1.getY() < p2.getY()) {
                        return -1;
                    }
                    if (p1.getY() > p2.getY()) {
                        return 1;
                    }
                    if (p1.getWeight() < p2.getWeight()) {
                        return -1;
                    }
                    if (p1.getWeight() > p2.getWeight()) {
                        return 1;
                    }
                    return 0;
                }
            };

            Arrays.sort(observations, cmp);
            return observations;
        }

        /**
         * Guesses the parameters based on the specified observed points.
         *
         * @param points Observed points, sorted.
         * @return the guessed parameters (normalization factor, mean and
         * sigma).
         */
        private double[] basicGuess(WeightedObservedPoint[] points) {
            final int maxYIdx = findMaxY(points);
            final double n = points[maxYIdx].getY();
            final double m = points[maxYIdx].getX();

            double fwhmApprox;
            try {
                final double halfY = n + ((m - n) / 2);
                final double fwhmX1 = interpolateXAtY(points, maxYIdx, -1, halfY);
                final double fwhmX2 = interpolateXAtY(points, maxYIdx, 1, halfY);
                fwhmApprox = fwhmX2 - fwhmX1;
            } catch (OutOfRangeException e) {
                // TODO: Exceptions should not be used for flow control.
                fwhmApprox = points[points.length - 1].getX() - points[0].getX();
            }
            final double s = fwhmApprox / (2 * FastMath.sqrt(2 * FastMath.log(2)));

            return new double[] { n, m, s };
        }

        /**
         * Finds index of point in specified points with the largest Y.
         *
         * @param points Points to search.
         * @return the index in specified points array.
         */
        private int findMaxY(WeightedObservedPoint[] points) {
            int maxYIdx = 0;
            for (int i = 1; i < points.length; i++) {
                if (points[i].getY() > points[maxYIdx].getY()) {
                    maxYIdx = i;
                }
            }
            return maxYIdx;
        }

        /**
         * Interpolates using the specified points to determine X at the
         * specified Y.
         *
         * @param points Points to use for interpolation.
         * @param startIdx Index within points from which to start the search for
         * interpolation bounds points.
         * @param idxStep Index step for searching interpolation bounds points.
         * @param y Y value for which X should be determined.
         * @return the value of X for the specified Y.
         * @throws ZeroException if {@code idxStep} is 0.
         * @throws OutOfRangeException if specified {@code y} is not within the
         * range of the specified {@code points}.
         */
        private double interpolateXAtY(WeightedObservedPoint[] points,
                                       int startIdx,
                                       int idxStep,
                                       double y)
            throws OutOfRangeException {
            if (idxStep == 0) {
                throw new ZeroException();
            }
            final WeightedObservedPoint[] twoPoints
                = getInterpolationPointsForY(points, startIdx, idxStep, y);
            final WeightedObservedPoint p1 = twoPoints[0];
            final WeightedObservedPoint p2 = twoPoints[1];
            if (p1.getY() == y) {
                return p1.getX();
            }
            if (p2.getY() == y) {
                return p2.getX();
            }
            return p1.getX() + (((y - p1.getY()) * (p2.getX() - p1.getX())) /
                                (p2.getY() - p1.getY()));
        }

        /**
         * Gets the two bounding interpolation points from the specified points
         * suitable for determining X at the specified Y.
         *
         * @param points Points to use for interpolation.
         * @param startIdx Index within points from which to start search for
         * interpolation bounds points.
         * @param idxStep Index step for search for interpolation bounds points.
         * @param y Y value for which X should be determined.
         * @return the array containing two points suitable for determining X at
         * the specified Y.
         * @throws ZeroException if {@code idxStep} is 0.
         * @throws OutOfRangeException if specified {@code y} is not within the
         * range of the specified {@code points}.
         */
        private WeightedObservedPoint[] getInterpolationPointsForY(WeightedObservedPoint[] points,
                                                                   int startIdx,
                                                                   int idxStep,
                                                                   double y)
            throws OutOfRangeException {
            if (idxStep == 0) {
                throw new ZeroException();
            }
            for (int i = startIdx;
                 idxStep < 0 ? i + idxStep >= 0 : i + idxStep < points.length;
                 i += idxStep) {
                final WeightedObservedPoint p1 = points[i];
                final WeightedObservedPoint p2 = points[i + idxStep];
                if (isBetween(y, p1.getY(), p2.getY())) {
                    if (idxStep < 0) {
                        return new WeightedObservedPoint[] { p2, p1 };
                    } else {
                        return new WeightedObservedPoint[] { p1, p2 };
                    }
                }
            }

            // Boundaries are replaced by dummy values because the raised
            // exception is caught and the message never displayed.
            // TODO: Exceptions should not be used for flow control.
            throw new OutOfRangeException(y,
                                          Double.NEGATIVE_INFINITY,
                                          Double.POSITIVE_INFINITY);
        }

        /**
         * Determines whether a value is between two other values.
         *
         * @param value Value to test whether it is between {@code boundary1}
         * and {@code boundary2}.
         * @param boundary1 One end of the range.
         * @param boundary2 Other end of the range.
         * @return {@code true} if {@code value} is between {@code boundary1} and
         * {@code boundary2} (inclusive), {@code false} otherwise.
         */
        private boolean isBetween(double value,
                                  double boundary1,
                                  double boundary2) {
            return (value >= boundary1 && value <= boundary2) ||
                (value >= boundary2 && value <= boundary1);
        }
    }
}


text:
define([
	"./core",
	"./var/concat",
	"./var/push",
	"./var/deletedIds",
	"./core/access",

	"./manipulation/var/rcheckableType",
	"./manipulation/var/rtagName",
	"./manipulation/var/rscriptType",
	"./manipulation/var/rleadingWhitespace",
	"./manipulation/var/nodeNames",
	"./manipulation/createSafeFragment",
	"./manipulation/wrapMap",
	"./manipulation/getAll",
	"./manipulation/setGlobalEval",
	"./manipulation/buildFragment",
	"./manipulation/support",

	"./core/init",
	"./data/accepts",
	"./traversing",
	"./selector",
	"./event"
], function( jQuery, concat, push, deletedIds, access,
	rcheckableType, rtagName, rscriptType, rleadingWhitespace, nodeNames,
	createSafeFragment, wrapMap, getAll, setGlobalEval,
	buildFragment, support ) {

var rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g,
	rnoshimcache = new RegExp( "<(?:" + nodeNames + ")[\\s/>]", "i" ),
	rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi,
	rnoInnerhtml = /<(?:script|style|link)/i,
	// checked="checked" or checked
	rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
	rscriptTypeMasked = /^true\/(.*)/,
	rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,
	safeFragment = createSafeFragment( document ),
	fragmentDiv = safeFragment.appendChild( document.createElement("div") );

// Manipulating tables requires a tbody
function manipulationTarget( elem, content ) {
	if ( jQuery.nodeName( elem, "table" ) &&
		jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ) {

		return elem.getElementsByTagName( "tbody" )[ 0 ] || elem;
	}

	return elem;
}

// Replace/restore the type attribute of script elements for safe DOM manipulation
function disableScript( elem ) {
	elem.type = (jQuery.find.attr( elem, "type" ) !== null) + "/" + elem.type;
	return elem;
}
function restoreScript( elem ) {
	var match = rscriptTypeMasked.exec( elem.type );
	if ( match ) {
		elem.type = match[1];
	} else {
		elem.removeAttribute("type");
	}
	return elem;
}

function cloneCopyEvent( src, dest ) {
	if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
		return;
	}

	var type, i, l,
		oldData = jQuery._data( src ),
		curData = jQuery._data( dest, oldData ),
		events = oldData.events;

	if ( events ) {
		delete curData.handle;
		curData.events = {};

		for ( type in events ) {
			for ( i = 0, l = events[ type ].length; i < l; i++ ) {
				jQuery.event.add( dest, type, events[ type ][ i ] );
			}
		}
	}

	// make the cloned public data object a copy from the original
	if ( curData.data ) {
		curData.data = jQuery.extend( {}, curData.data );
	}
}

function fixCloneNodeIssues( src, dest ) {
	var nodeName, e, data;

	// We do not need to do anything for non-Elements
	if ( dest.nodeType !== 1 ) {
		return;
	}

	nodeName = dest.nodeName.toLowerCase();

	if ( !support.noCloneEvent && dest[ jQuery.expando ] ) {
		data = jQuery._data( dest );

		for ( e in data.events ) {
			jQuery.removeEvent( dest, e, data.handle );
		}

		// Event data gets referenced instead of copied if the expando gets copied too
		dest.removeAttribute( jQuery.expando );
	}

	// Support: IE<9
	// IE blanks contents when cloning scripts, and tries to evaluate newly-set text
	if ( nodeName === "script" && dest.text !== src.text ) {
		disableScript( dest ).text = src.text;
		restoreScript( dest );

	// Support: IE<9
	// IE8 fails to persist the checked state of a cloned checkbox
	// or radio button.
	} else if ( nodeName === "input" && rcheckableType.test( src.type ) ) {
		dest.checked = src.checked;

	// Support: IE<9
	// IE8 fails to return the selected option to the default selected
	// state when cloning options
	} else if ( nodeName === "option" ) {
		dest.defaultSelected = dest.selected = src.defaultSelected;

	// Support: IE<9
	// IE8 fails to set the defaultValue to the correct value when
	// cloning other types of input fields
	} else if ( nodeName === "input" || nodeName === "textarea" ) {
		dest.defaultValue = src.defaultValue;
	}
}

function domManip( collection, args, callback, ignored ) {

	// Flatten any nested arrays
	args = concat.apply( [], args );

	var first, node, hasScripts,
		scripts, doc, fragment,
		i = 0,
		l = collection.length,
		iNoClone = l - 1,
		value = args[0],
		isFunction = jQuery.isFunction( value );

	// We can't cloneNode fragments that contain checked, in WebKit
	if ( isFunction ||
			( l > 1 && typeof value === "string" &&
				!support.checkClone && rchecked.test( value ) ) ) {
		return collection.each(function( index ) {
			var self = collection.eq( index );
			if ( isFunction ) {
				args[0] = value.call( this, index, self.html() );
			}
			domManip( self, args, callback, ignored );
		});
	}

	if ( l ) {
		fragment = buildFragment( args, collection[ 0 ].ownerDocument, false, collection, ignored );
		first = fragment.firstChild;

		if ( fragment.childNodes.length === 1 ) {
			fragment = first;
		}

		// Require either new content or an interest in ignored elements to invoke the callback
		if ( first || ignored ) {
			scripts = jQuery.map( getAll( fragment, "script" ), disableScript );
			hasScripts = scripts.length;

			// Use the original fragment for the last item
			// instead of the first because it can end up
			// being emptied incorrectly in certain situations (#8070).
			for ( ; i < l; i++ ) {
				node = fragment;

				if ( i !== iNoClone ) {
					node = jQuery.clone( node, true, true );

					// Keep references to cloned scripts for later restoration
					if ( hasScripts ) {
						// Support: Android<4.1, PhantomJS<2
						// push.apply(_, arraylike) throws on ancient WebKit
						jQuery.merge( scripts, getAll( node, "script" ) );
					}
				}

				callback.call( collection[i], node, i );
			}

			if ( hasScripts ) {
				doc = scripts[ scripts.length - 1 ].ownerDocument;

				// Reenable scripts
				jQuery.map( scripts, restoreScript );

				// Evaluate executable scripts on first document insertion
				for ( i = 0; i < hasScripts; i++ ) {
					node = scripts[ i ];
					if ( rscriptType.test( node.type || "" ) &&
						!jQuery._data( node, "globalEval" ) &&
						jQuery.contains( doc, node ) ) {

						if ( node.src ) {
							// Optional AJAX dependency, but won't run scripts if not present
							if ( jQuery._evalUrl ) {
								jQuery._evalUrl( node.src );
							}
						} else {
							jQuery.globalEval(
								( node.text || node.textContent || node.innerHTML || "" )
									.replace( rcleanScript, "" )
							);
						}
					}
				}
			}

			// Fix #11809: Avoid leaking memory
			fragment = first = null;
		}
	}

	return collection;
}

function remove( elem, selector, keepData ) {
	var node,
		elems = selector ? jQuery.filter( selector, elem ) : elem,
		i = 0;

	for ( ; (node = elems[i]) != null; i++ ) {

		if ( !keepData && node.nodeType === 1 ) {
			jQuery.cleanData( getAll( node ) );
		}

		if ( node.parentNode ) {
			if ( keepData && jQuery.contains( node.ownerDocument, node ) ) {
				setGlobalEval( getAll( node, "script" ) );
			}
			node.parentNode.removeChild( node );
		}
	}

	return elem;
}

jQuery.extend({
	htmlPrefilter: function( html ) {
		return html.replace( rxhtmlTag, "<$1></$2>" );
	},

	clone: function( elem, dataAndEvents, deepDataAndEvents ) {
		var destElements, node, clone, i, srcElements,
			inPage = jQuery.contains( elem.ownerDocument, elem );

		if ( support.html5Clone || jQuery.isXMLDoc(elem) ||
			!rnoshimcache.test( "<" + elem.nodeName + ">" ) ) {

			clone = elem.cloneNode( true );

		// IE<=8 does not properly clone detached, unknown element nodes
		} else {
			fragmentDiv.innerHTML = elem.outerHTML;
			fragmentDiv.removeChild( clone = fragmentDiv.firstChild );
		}

		if ( (!support.noCloneEvent || !support.noCloneChecked) &&
				(elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) {

			// We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2
			destElements = getAll( clone );
			srcElements = getAll( elem );

			// Fix all IE cloning issues
			for ( i = 0; (node = srcElements[i]) != null; ++i ) {
				// Ensure that the destination node is not null; Fixes #9587
				if ( destElements[i] ) {
					fixCloneNodeIssues( node, destElements[i] );
				}
			}
		}

		// Copy the events from the original to the clone
		if ( dataAndEvents ) {
			if ( deepDataAndEvents ) {
				srcElements = srcElements || getAll( elem );
				destElements = destElements || getAll( clone );

				for ( i = 0; (node = srcElements[i]) != null; i++ ) {
					cloneCopyEvent( node, destElements[i] );
				}
			} else {
				cloneCopyEvent( elem, clone );
			}
		}

		// Preserve script evaluation history
		destElements = getAll( clone, "script" );
		if ( destElements.length > 0 ) {
			setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
		}

		destElements = srcElements = node = null;

		// Return the cloned set
		return clone;
	},

	cleanData: function( elems, /* internal */ acceptData ) {
		var elem, type, id, data,
			i = 0,
			internalKey = jQuery.expando,
			cache = jQuery.cache,
			attributes = support.attributes,
			special = jQuery.event.special;

		for ( ; (elem = elems[i]) != null; i++ ) {
			if ( acceptData || jQuery.acceptData( elem ) ) {

				id = elem[ internalKey ];
				data = id && cache[ id ];

				if ( data ) {
					if ( data.events ) {
						for ( type in data.events ) {
							if ( special[ type ] ) {
								jQuery.event.remove( elem, type );

							// This is a shortcut to avoid jQuery.event.remove's overhead
							} else {
								jQuery.removeEvent( elem, type, data.handle );
							}
						}
					}

					// Remove cache only if it was not already removed by jQuery.event.remove
					if ( cache[ id ] ) {

						delete cache[ id ];

						// Support: IE<9
						// IE does not allow us to delete expando properties from nodes
						// IE creates expando attributes along with the property
						// IE does not have a removeAttribute function on Document nodes
						if ( !attributes && typeof elem.removeAttribute !== "undefined" ) {
							elem.removeAttribute( internalKey );

						// Webkit & Blink performance suffers when deleting properties
						// from DOM nodes, so set to undefined instead
						// https://code.google.com/p/chromium/issues/detail?id=378607
						} else {
							elem[ internalKey ] = undefined;
						}

						deletedIds.push( id );
					}
				}
			}
		}
	}
});

jQuery.fn.extend({
	detach: function( selector ) {
		return remove( this, selector, true );
	},

	remove: function( selector ) {
		return remove( this, selector );
	},

	text: function( value ) {
		return access( this, function( value ) {
			return value === undefined ?
				jQuery.text( this ) :
				this.empty().append(
					( this[0] && this[0].ownerDocument || document ).createTextNode( value )
				);
		}, null, value, arguments.length );
	},

	append: function() {
		return domManip( this, arguments, function( elem ) {
			if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
				var target = manipulationTarget( this, elem );
				target.appendChild( elem );
			}
		});
	},

	prepend: function() {
		return domManip( this, arguments, function( elem ) {
			if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
				var target = manipulationTarget( this, elem );
				target.insertBefore( elem, target.firstChild );
			}
		});
	},

	before: function() {
		return domManip( this, arguments, function( elem ) {
			if ( this.parentNode ) {
				this.parentNode.insertBefore( elem, this );
			}
		});
	},

	after: function() {
		return domManip( this, arguments, function( elem ) {
			if ( this.parentNode ) {
				this.parentNode.insertBefore( elem, this.nextSibling );
			}
		});
	},

	empty: function() {
		var elem,
			i = 0;

		for ( ; (elem = this[i]) != null; i++ ) {
			// Remove element nodes and prevent memory leaks
			if ( elem.nodeType === 1 ) {
				jQuery.cleanData( getAll( elem, false ) );
			}

			// Remove any remaining nodes
			while ( elem.firstChild ) {
				elem.removeChild( elem.firstChild );
			}

			// If this is a select, ensure that it displays empty (#12336)
			// Support: IE<9
			if ( elem.options && jQuery.nodeName( elem, "select" ) ) {
				elem.options.length = 0;
			}
		}

		return this;
	},

	clone: function( dataAndEvents, deepDataAndEvents ) {
		dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
		deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;

		return this.map(function() {
			return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
		});
	},

	html: function( value ) {
		return access( this, function( value ) {
			var elem = this[ 0 ] || {},
				i = 0,
				l = this.length;

			if ( value === undefined ) {
				return elem.nodeType === 1 ?
					elem.innerHTML.replace( rinlinejQuery, "" ) :
					undefined;
			}

			// See if we can take a shortcut and just use innerHTML
			if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
				( support.htmlSerialize || !rnoshimcache.test( value )  ) &&
				( support.leadingWhitespace || !rleadingWhitespace.test( value ) ) &&
				!wrapMap[ (rtagName.exec( value ) || [ "", "" ])[ 1 ].toLowerCase() ] ) {

				value = jQuery.htmlPrefilter( value );

				try {
					for (; i < l; i++ ) {
						// Remove element nodes and prevent memory leaks
						elem = this[i] || {};
						if ( elem.nodeType === 1 ) {
							jQuery.cleanData( getAll( elem, false ) );
							elem.innerHTML = value;
						}
					}

					elem = 0;

				// If using innerHTML throws an exception, use the fallback method
				} catch ( e ) {}
			}

			if ( elem ) {
				this.empty().append( value );
			}
		}, null, value, arguments.length );
	},

	replaceWith: function() {
		var ignored = [];

		// Make the changes, replacing each non-ignored context element with the new content
		return domManip( this, arguments, function( elem ) {
			var parent = this.parentNode;

			if ( jQuery.inArray( this, ignored ) < 0 ) {
				jQuery.cleanData( getAll( this ) );
				if ( parent ) {
					parent.replaceChild( elem, this );
				}
			}

		// Force callback invocation
		}, ignored );
	}
});

jQuery.each({
	appendTo: "append",
	prependTo: "prepend",
	insertBefore: "before",
	insertAfter: "after",
	replaceAll: "replaceWith"
}, function( name, original ) {
	jQuery.fn[ name ] = function( selector ) {
		var elems,
			i = 0,
			ret = [],
			insert = jQuery( selector ),
			last = insert.length - 1;

		for ( ; i <= last; i++ ) {
			elems = i === last ? this : this.clone(true);
			jQuery( insert[i] )[ original ]( elems );

			// Support: IE<9, Android<4.1, PhantomJS<2
			// .get() because push.apply(_, arraylike) throws on ancient WebKit
			push.apply( ret, elems.get() );
		}

		return this.pushStack( ret );
	};
});

return jQuery;
});

redpajama_set_name: RedPajamaGithub


text:
[Pages](http://botamochi6277.github.io) of
[botamochi6277](http://botamochi6277.github.io)

### License
cardMaker: MIT License

fontBotamochi: [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/)
<!-- ![by-sa](./fontBotamochi/by-sa.png) -->
<img src = "./fontBotamochi/by-sa.png" width=80px>


text:
require 'spec_helper'

describe AuthScope do
  subject{ AuthScope.new(@scope || "user:email") }

  describe '#can?' do
    it 'should authorize for any segment of a chain' do
      @scope = "foo:bar:baz"
      should_authorize "foo"
      should_authorize "foo:bar"
      should_authorize "foo:bar:baz"
    end

    it 'should not work for a non-specified subsegment' do
      @scope = "user:read"
      should_not_authorize "user:write"
    end

    it 'should not work for a deeper namespace' do
      @scope = "user"
      should_not_authorize "user:write"
    end

    it 'should work from multiple defined scopes' do
      @scope = "user apps"
      should_authorize "user"
      should_authorize "apps"
    end

    context 'wildcards' do
      it 'should allow wildcards to represent any scope' do
        @scope = "user:*"
        should_authorize "user:email"
        should_authorize "user:write"
      end

      it 'should not grant multi-level authorization with wildcards' do
        @scope = "user:*"
        should_not_authorize "user:write:another"
      end

      it 'should work with lower namespaces and wildcards' do
        @scope = "user:*:write"
        should_authorize "user:bob:write"
        should_authorize "user:frank:write"
        should_not_authorize "user:bob:read"
      end
    end

    context 'batch delimiter' do
      it 'should work for each specified in the batch' do
        @scope = "user,app:write"
        should_authorize "user:write"
        should_authorize "app:write"
        should_not_authorize "book:write"
      end

      it 'should work on multiple levels' do
        @scope = "user,app:read,write"
        should_authorize "user:write"
        should_authorize "app:read"
      end
    end

    context 'global wildcards' do
      it 'should work for any level of specificity' do
        @scope = "user:**"
        should_authorize "user:abc:write:foo"
      end

      it 'should work as a catch-all if supplied alone' do
        @scope = "**"
        should_authorize "foo:bar:baz"
      end
    end
  end

  describe '#any?' do
    it 'should authorize any of the supplied scopes' do
      @scope = "user:foo:write"
      expect(subject).to be_any('user:foo:write', 'admin')
    end
  end

  describe '#all?' do
    it 'should authorize only with ALL of the supplied scopes' do
      @scope = "user admin"
      expect(subject).to be_all("user", "admin")
      expect(subject).not_to be_all("user", "bork")
    end
  end
end


text:
package eu.dariah.de.colreg.service.base;

import java.util.Map;

public interface EntityService {
	public Map<Integer, String> getOrderedImageMap(Map<Integer, String> imageMap);
}


text:
package org.apache.isis.progmodels.dflt;

import org.apache.isis.core.commons.config.IsisConfiguration;
import org.apache.isis.core.metamodel.facets.actions.action.ActionAnnotationFacetFactory;
import org.apache.isis.core.metamodel.facets.actions.contributing.maxlenannot.MaxLengthFacetOnActionAnnotationFactory;
import org.apache.isis.core.metamodel.facets.actions.contributing.paged.PagedFacetOnActionFactory;
import org.apache.isis.core.metamodel.facets.actions.defaults.method.ActionDefaultsFacetViaMethodFactory;
import org.apache.isis.core.metamodel.facets.actions.exploration.annotation.PrototypeFacetForExplorationAnnotationFactory;
import org.apache.isis.core.metamodel.facets.actions.homepage.annotation.HomePageFacetAnnotationFactory;
import org.apache.isis.core.metamodel.facets.actions.layout.ActionLayoutFacetFactory;
import org.apache.isis.core.metamodel.facets.actions.notcontributed.annotation.NotContributedFacetAnnotationFactory;
import org.apache.isis.core.metamodel.facets.actions.notcontributed.derived.NotContributedFacetDerivedFromDomainServiceFacetFactory;
import org.apache.isis.core.metamodel.facets.actions.notcontributed.derived.NotContributedFacetDerivedFromMixinFacetFactory;
import org.apache.isis.core.metamodel.facets.actions.notinservicemenu.annotation.NotInServiceMenuFacetAnnotationFactory;
import org.apache.isis.core.metamodel.facets.actions.notinservicemenu.derived.NotInServiceMenuFacetDerivedFromDomainServiceFacetFactory;
import org.apache.isis.core.metamodel.facets.actions.notinservicemenu.method.NotInServiceMenuFacetViaMethodFactory;
import org.apache.isis.core.metamodel.facets.actions.validate.method.ActionValidationFacetViaMethodFactory;
import org.apache.isis.core.metamodel.facets.all.i18n.TranslationFacetFactory;
import org.apache.isis.core.metamodel.facets.collections.accessor.CollectionAccessorFacetViaAccessorFactory;
import org.apache.isis.core.metamodel.facets.collections.clear.CollectionClearFacetFactory;
import org.apache.isis.core.metamodel.facets.collections.collection.CollectionAnnotationFacetFactory;
import org.apache.isis.core.metamodel.facets.collections.disabled.fromimmutable.DisabledFacetOnCollectionDerivedFromImmutableFactory;
import org.apache.isis.core.metamodel.facets.collections.javautilcollection.CollectionFacetFactory;
import org.apache.isis.core.metamodel.facets.collections.layout.CollectionLayoutFacetFactory;
import org.apache.isis.core.metamodel.facets.collections.modify.CollectionAddToRemoveFromAndValidateFacetFactory;
import org.apache.isis.core.metamodel.facets.collections.paged.PagedFacetOnCollectionFactory;
import org.apache.isis.core.metamodel.facets.collections.parented.ParentedFacetSinceCollectionFactory;
import org.apache.isis.core.metamodel.facets.collections.sortedby.annotation.SortedByFacetAnnotationFactory;
import org.apache.isis.core.metamodel.facets.fallback.FallbackFacetFactory;
import org.apache.isis.core.metamodel.facets.members.cssclass.annotprop.CssClassFacetOnActionFromConfiguredRegexFactory;
import org.apache.isis.core.metamodel.facets.members.cssclass.annotprop.CssClassFacetOnMemberFactory;
import org.apache.isis.core.metamodel.facets.members.cssclassfa.annotprop.CssClassFaFacetOnMemberFactory;
import org.apache.isis.core.metamodel.facets.members.describedas.annotprop.DescribedAsFacetOnMemberFactory;
import org.apache.isis.core.metamodel.facets.members.describedas.staticmethod.DescribedAsFacetStaticMethodFactory;
import org.apache.isis.core.metamodel.facets.members.disabled.forsession.DisableForSessionFacetViaMethodFactory;
import org.apache.isis.core.metamodel.facets.members.disabled.layout.DisabledFacetOnMemberFromPropertiesFactory;
import org.apache.isis.core.metamodel.facets.members.disabled.method.DisableForContextFacetViaMethodFactory;
import org.apache.isis.core.metamodel.facets.members.disabled.staticmethod.DisabledFacetStaticMethodFacetFactory;
import org.apache.isis.core.metamodel.facets.members.hidden.forsession.HideForSessionFacetViaMethodFactory;
import org.apache.isis.core.metamodel.facets.members.hidden.layout.HiddenFacetOnMemberFromPropertiesFactory;
import org.apache.isis.core.metamodel.facets.members.hidden.method.HideForContextFacetViaMethodFactory;
import org.apache.isis.core.metamodel.facets.members.hidden.staticmethod.HiddenFacetStaticMethodFactory;
import org.apache.isis.core.metamodel.facets.members.named.annotprop.NamedFacetOnMemberFactory;
import org.apache.isis.core.metamodel.facets.members.named.staticmethod.NamedFacetStaticMethodFactory;
import org.apache.isis.core.metamodel.facets.members.order.annotprop.MemberOrderFacetFactory;
import org.apache.isis.core.metamodel.facets.members.render.annotprop.RenderFacetOrResolveFactory;
import org.apache.isis.core.metamodel.facets.object.ViewModelSemanticCheckingFacetFactory;
import org.apache.isis.core.metamodel.facets.object.actionorder.annotation.ActionOrderFacetAnnotationFactory;
import org.apache.isis.core.metamodel.facets.object.audit.markerifc.AuditableFacetMarkerInterfaceFactory;
import org.apache.isis.core.metamodel.facets.object.bookmarkpolicy.bookmarkable.BookmarkPolicyFacetViaBookmarkableAnnotationElseFallbackFactory;
import org.apache.isis.core.metamodel.facets.object.callbacks.CreatedCallbackFacetFactory;
import org.apache.isis.core.metamodel.facets.object.callbacks.LoadCallbackFacetFactory;
import org.apache.isis.core.metamodel.facets.object.callbacks.PersistCallbackFacetFactory;
import org.apache.isis.core.metamodel.facets.object.callbacks.PersistCallbackViaSaveMethodFacetFactory;
import org.apache.isis.core.metamodel.facets.object.callbacks.RemoveCallbackFacetFactory;
import org.apache.isis.core.metamodel.facets.object.callbacks.UpdateCallbackFacetFactory;
import org.apache.isis.core.metamodel.facets.object.choices.boundedmarkerifc.ChoicesFacetFromBoundedMarkerInterfaceFactory;
import org.apache.isis.core.metamodel.facets.object.choices.enums.EnumFacetUsingValueFacetUsingSemanticsProviderFactory;
import org.apache.isis.core.metamodel.facets.object.cssclass.annotation.CssClassFacetOnTypeAnnotationFactory;
import org.apache.isis.core.metamodel.facets.object.cssclass.method.CssClassFacetMethodFactory;
import org.apache.isis.core.metamodel.facets.object.defaults.annotcfg.DefaultedFacetAnnotationElseConfigurationFactory;
import org.apache.isis.core.metamodel.facets.object.describedas.annotation.DescribedAsFacetOnTypeAnnotationFactory;
import org.apache.isis.core.metamodel.facets.object.disabled.method.DisabledObjectFacetViaMethodFactory;
import org.apache.isis.core.metamodel.facets.object.domainobject.DomainObjectAnnotationFacetFactory;
import org.apache.isis.core.metamodel.facets.object.domainobjectlayout.DomainObjectLayoutFacetFactory;
import org.apache.isis.core.metamodel.facets.object.domainservice.annotation.DomainServiceFacetAnnotationFactory;
import org.apache.isis.core.metamodel.facets.object.domainservicelayout.DomainServiceLayoutFacetFactory;
import org.apache.isis.core.metamodel.facets.object.encodeable.annotcfg.EncodableFacetAnnotationElseConfigurationFactory;
import org.apache.isis.core.metamodel.facets.object.facets.annotation.FacetsFacetAnnotationFactory;
import org.apache.isis.core.metamodel.facets.object.fieldorder.annotation.FieldOrderFacetAnnotationFactory;
import org.apache.isis.core.metamodel.facets.object.grid.GridFacetFactory;
import org.apache.isis.core.metamodel.facets.object.hidden.annotation.HiddenFacetOnTypeAnnotationFactory;
import org.apache.isis.core.metamodel.facets.object.hidden.method.HiddenObjectFacetViaMethodFactory;
import org.apache.isis.core.metamodel.facets.object.icon.method.IconFacetMethodFactory;
import org.apache.isis.core.metamodel.facets.object.ignore.annotation.RemoveAnnotatedMethodsFacetFactory;
import org.apache.isis.core.metamodel.facets.object.ignore.datanucleus.RemoveDatanucleusPersistableTypesFacetFactory;
import org.apache.isis.core.metamodel.facets.object.ignore.datanucleus.RemoveDnPrefixedMethodsFacetFactory;
import org.apache.isis.core.metamodel.facets.object.ignore.isis.RemoveStaticGettersAndSettersFacetFactory;
import org.apache.isis.core.metamodel.facets.object.ignore.javalang.IteratorFilteringFacetFactory;
import org.apache.isis.core.metamodel.facets.object.ignore.javalang.RemoveMethodsFacetFactory;
import org.apache.isis.core.metamodel.facets.object.ignore.jdo.RemoveJdoEnhancementTypesFacetFactory;
import org.apache.isis.core.metamodel.facets.object.ignore.jdo.RemoveJdoPrefixedMethodsFacetFactory;
import org.apache.isis.core.metamodel.facets.object.immutable.immutableannot.CopyImmutableFacetOntoMembersFactory;
import org.apache.isis.core.metamodel.facets.object.immutable.immutablemarkerifc.ImmutableFacetMarkerInterfaceFactory;
import org.apache.isis.core.metamodel.facets.object.mask.annotation.MaskFacetOnTypeAnnotationFactory;
import org.apache.isis.core.metamodel.facets.object.maxlen.annotation.MaxLengthFacetOnTypeAnnotationFactory;
import org.apache.isis.core.metamodel.facets.object.membergroups.annotprop.MemberGroupLayoutFacetFactory;
import org.apache.isis.core.metamodel.facets.object.mixin.MixinFacetForMixinAnnotationFactory;
import org.apache.isis.core.metamodel.facets.object.multiline.annotation.MultiLineFacetOnTypeAnnotationFactory;
import org.apache.isis.core.metamodel.facets.object.named.annotation.NamedFacetOnTypeAnnotationFactory;
import org.apache.isis.core.metamodel.facets.object.notpersistable.notpersistableannot.NotPersistableFacetAnnotationFactory;
import org.apache.isis.core.metamodel.facets.object.notpersistable.notpersistablemarkerifc.NotPersistableFacetMarkerInterfaceFactory;
import org.apache.isis.core.metamodel.facets.object.objectspecid.classname.ObjectSpecIdFacetDerivedFromClassNameFactory;
import org.apache.isis.core.metamodel.facets.object.objectvalidprops.impl.ObjectValidPropertiesFacetImplFactory;
import org.apache.isis.core.metamodel.facets.object.paged.annotation.PagedFacetOnTypeAnnotationFactory;
import org.apache.isis.core.metamodel.facets.object.parented.aggregated.AggregatedAnnotationFactory;
import org.apache.isis.core.metamodel.facets.object.parseable.annotcfg.ParseableFacetAnnotationElseConfigurationFactory;
import org.apache.isis.core.metamodel.facets.object.plural.annotation.PluralAnnotationFacetFactory;
import org.apache.isis.core.metamodel.facets.object.plural.staticmethod.PluralFacetStaticMethodFactory;
import org.apache.isis.core.metamodel.facets.object.recreatable.DisabledFacetOnCollectionDerivedFromViewModelFacetFactory;
import org.apache.isis.core.metamodel.facets.object.recreatable.DisabledFacetOnPropertyDerivedFromRecreatableObjectFacetFactory;
import org.apache.isis.core.metamodel.facets.object.recreatable.RecreatableObjectFacetFactory;
import org.apache.isis.core.metamodel.facets.object.regex.annotation.RegExFacetOnTypeAnnotationFactory;
import org.apache.isis.core.metamodel.facets.object.title.annotation.TitleAnnotationFacetFactory;
import org.apache.isis.core.metamodel.facets.object.title.methods.TitleFacetViaMethodsFactory;
import org.apache.isis.core.metamodel.facets.object.typicallen.annotation.TypicalLengthFacetOnTypeAnnotationFactory;
import org.apache.isis.core.metamodel.facets.object.validating.mustsatisfyspec.MustSatisfySpecificationFromMustSatisfyAnnotationOnTypeFacetFactory;
import org.apache.isis.core.metamodel.facets.object.validating.validateobject.method.ValidateObjectFacetMethodFactory;
import org.apache.isis.core.metamodel.facets.object.value.annotcfg.ValueFacetAnnotationOrConfigurationFactory;
import org.apache.isis.core.metamodel.facets.param.autocomplete.method.ActionParameterAutoCompleteFacetViaMethodFactory;
import org.apache.isis.core.metamodel.facets.param.bigdecimal.javaxvaldigits.BigDecimalFacetOnParameterFromJavaxValidationAnnotationFactory;
import org.apache.isis.core.metamodel.facets.param.choices.enums.ActionParameterChoicesFacetDerivedFromChoicesFacetFactory;
import org.apache.isis.core.metamodel.facets.param.choices.method.ActionChoicesFacetViaMethodFactory;
import org.apache.isis.core.metamodel.facets.param.choices.methodnum.ActionParameterChoicesFacetViaMethodFactory;
import org.apache.isis.core.metamodel.facets.param.defaults.fromtype.ActionParameterDefaultFacetDerivedFromTypeFactory;
import org.apache.isis.core.metamodel.facets.param.defaults.methodnum.ActionParameterDefaultsFacetViaMethodFactory;
import org.apache.isis.core.metamodel.facets.param.describedas.annotderived.DescribedAsFacetOnParameterAnnotationElseDerivedFromTypeFactory;
import org.apache.isis.core.metamodel.facets.param.layout.ParameterLayoutFacetFactory;
import org.apache.isis.core.metamodel.facets.param.mandatory.dflt.MandatoryFacetOnParametersDefaultFactory;
import org.apache.isis.core.metamodel.facets.param.multiline.annotation.MultiLineFacetOnParameterAnnotationFactory;
import org.apache.isis.core.metamodel.facets.param.named.annotation.NamedFacetOnParameterAnnotationFactory;
import org.apache.isis.core.metamodel.facets.param.parameter.ParameterAnnotationFacetFactory;
import org.apache.isis.core.metamodel.facets.param.renderedasdaybefore.annotation.RenderedAsDayBeforeFacetOnParameterAnnotationFactory;
import org.apache.isis.core.metamodel.facets.param.typicallen.annotation.TypicalLengthFacetOnParameterAnnotationFactory;
import org.apache.isis.core.metamodel.facets.param.typicallen.fromtype.TypicalLengthFacetOnParameterDerivedFromTypeFacetFactory;
import org.apache.isis.core.metamodel.facets.param.validating.maskannot.MaskFacetOnParameterAnnotationFactory;
import org.apache.isis.core.metamodel.facets.properties.accessor.PropertyAccessorFacetViaAccessorFactory;
import org.apache.isis.core.metamodel.facets.properties.autocomplete.method.PropertyAutoCompleteFacetMethodFactory;
import org.apache.isis.core.metamodel.facets.properties.bigdecimal.javaxvaldigits.BigDecimalFacetOnPropertyFromJavaxValidationDigitsAnnotationFactory;
import org.apache.isis.core.metamodel.facets.properties.choices.enums.PropertyChoicesFacetDerivedFromChoicesFacetFactory;
import org.apache.isis.core.metamodel.facets.properties.choices.method.PropertyChoicesFacetViaMethodFactory;
import org.apache.isis.core.metamodel.facets.properties.defaults.fromtype.PropertyDefaultFacetDerivedFromTypeFactory;
import org.apache.isis.core.metamodel.facets.properties.defaults.method.PropertyDefaultFacetViaMethodFactory;
import org.apache.isis.core.metamodel.facets.properties.disabled.fromimmutable.DisabledFacetOnPropertyDerivedFromImmutableFactory;
import org.apache.isis.core.metamodel.facets.properties.disabled.inferred.DisabledFacetOnPropertyInferredFactory;
import org.apache.isis.core.metamodel.facets.properties.mandatory.dflt.MandatoryFacetOnProperyDefaultFactory;
import org.apache.isis.core.metamodel.facets.properties.mandatory.staticmethod.MandatoryFacetOnPropertyStaticMethodFactory;
import org.apache.isis.core.metamodel.facets.properties.multiline.annotation.MultiLineFacetOnPropertyFactory;
import org.apache.isis.core.metamodel.facets.properties.property.PropertyAnnotationFacetFactory;
import org.apache.isis.core.metamodel.facets.properties.propertylayout.PropertyLayoutFacetFactory;
import org.apache.isis.core.metamodel.facets.properties.renderedasdaybefore.annotation.RenderedAsDayBeforeAnnotationOnPropertyFacetFactory;
import org.apache.isis.core.metamodel.facets.properties.typicallen.annotation.TypicalLengthOnPropertyFacetFactory;
import org.apache.isis.core.metamodel.facets.properties.typicallen.fromtype.TypicalLengthFacetOnPropertyDerivedFromTypeFacetFactory;
import org.apache.isis.core.metamodel.facets.properties.update.PropertyModifyFacetFactory;
import org.apache.isis.core.metamodel.facets.properties.update.PropertySetAndClearFacetFactory;
import org.apache.isis.core.metamodel.facets.properties.validating.dflt.PropertyValidateFacetDefaultFactory;
import org.apache.isis.core.metamodel.facets.properties.validating.maskannot.MaskFacetOnPropertyAnnotationFactory;
import org.apache.isis.core.metamodel.facets.properties.validating.method.PropertyValidateFacetViaMethodFactory;
import org.apache.isis.core.metamodel.facets.value.bigdecimal.BigDecimalValueFacetUsingSemanticsProviderFactory;
import org.apache.isis.core.metamodel.facets.value.biginteger.BigIntegerValueFacetUsingSemanticsProviderFactory;
import org.apache.isis.core.metamodel.facets.value.blobs.BlobValueFacetUsingSemanticsProviderFactory;
import org.apache.isis.core.metamodel.facets.value.booleans.BooleanPrimitiveValueFacetUsingSemanticsProviderFactory;
import org.apache.isis.core.metamodel.facets.value.booleans.BooleanWrapperValueFacetUsingSemanticsProviderFactory;
import org.apache.isis.core.metamodel.facets.value.bytes.BytePrimitiveValueFacetUsingSemanticsProviderFactory;
import org.apache.isis.core.metamodel.facets.value.bytes.ByteWrapperValueFacetUsingSemanticsProviderFactory;
import org.apache.isis.core.metamodel.facets.value.chars.CharPrimitiveValueFacetUsingSemanticsProviderFactory;
import org.apache.isis.core.metamodel.facets.value.chars.CharWrapperValueFacetUsingSemanticsProviderFactory;
import org.apache.isis.core.metamodel.facets.value.clobs.ClobValueFacetUsingSemanticsProviderFactory;
import org.apache.isis.core.metamodel.facets.value.color.ColorValueFacetUsingSemanticsProviderFactory;
import org.apache.isis.core.metamodel.facets.value.date.DateValueFacetUsingSemanticsProviderFactory;
import org.apache.isis.core.metamodel.facets.value.datejodalocal.JodaLocalDateValueFacetUsingSemanticsProviderFactory;
import org.apache.isis.core.metamodel.facets.value.datesql.JavaSqlDateValueFacetUsingSemanticsProviderFactory;
import org.apache.isis.core.metamodel.facets.value.datetime.DateTimeValueFacetUsingSemanticsProviderFactory;
import org.apache.isis.core.metamodel.facets.value.datetimejoda.JodaDateTimeValueFacetUsingSemanticsProviderFactory;
import org.apache.isis.core.metamodel.facets.value.datetimejodalocal.JodaLocalDateTimeValueFacetUsingSemanticsProviderFactory;
import org.apache.isis.core.metamodel.facets.value.dateutil.JavaUtilDateValueFacetUsingSemanticsProviderFactory;
import org.apache.isis.core.metamodel.facets.value.doubles.DoublePrimitiveValueFacetUsingSemanticsProviderFactory;
import org.apache.isis.core.metamodel.facets.value.doubles.DoubleWrapperValueFacetUsingSemanticsProviderFactory;
import org.apache.isis.core.metamodel.facets.value.floats.FloatPrimitiveValueFacetUsingSemanticsProviderFactory;
import org.apache.isis.core.metamodel.facets.value.floats.FloatWrapperValueFacetUsingSemanticsProviderFactory;
import org.apache.isis.core.metamodel.facets.value.image.ImageValueFacetUsingSemanticsProviderFactory;
import org.apache.isis.core.metamodel.facets.value.imageawt.JavaAwtImageValueFacetUsingSemanticsProviderFactory;
import org.apache.isis.core.metamodel.facets.value.integer.IntPrimitiveValueFacetUsingSemanticsProviderFactory;
import org.apache.isis.core.metamodel.facets.value.integer.IntWrapperValueFacetUsingSemanticsProviderFactory;
import org.apache.isis.core.metamodel.facets.value.longs.LongPrimitiveValueFacetUsingSemanticsProviderFactory;
import org.apache.isis.core.metamodel.facets.value.longs.LongWrapperValueFacetUsingSemanticsProviderFactory;
import org.apache.isis.core.metamodel.facets.value.money.MoneyValueFacetUsingSemanticsProviderFactory;
import org.apache.isis.core.metamodel.facets.value.password.PasswordValueFacetUsingSemanticsProviderFactory;
import org.apache.isis.core.metamodel.facets.value.percentage.PercentageValueFacetUsingSemanticsProviderFactory;
import org.apache.isis.core.metamodel.facets.value.shortint.ShortPrimitiveValueFacetUsingSemanticsProviderFactory;
import org.apache.isis.core.metamodel.facets.value.shortint.ShortWrapperValueFacetUsingSemanticsProviderFactory;
import org.apache.isis.core.metamodel.facets.value.string.StringValueFacetUsingSemanticsProviderFactory;
import org.apache.isis.core.metamodel.facets.value.time.TimeValueFacetUsingSemanticsProviderFactory;
import org.apache.isis.core.metamodel.facets.value.timesql.JavaSqlTimeValueFacetUsingSemanticsProviderFactory;
import org.apache.isis.core.metamodel.facets.value.timestamp.TimeStampValueFacetUsingSemanticsProviderFactory;
import org.apache.isis.core.metamodel.facets.value.timestampsql.JavaSqlTimeStampValueFacetUsingSemanticsProviderFactory;
import org.apache.isis.core.metamodel.facets.value.url.URLValueFacetUsingSemanticsProviderFactory;
import org.apache.isis.core.metamodel.facets.value.uuid.UUIDValueFacetUsingSemanticsProviderFactory;
import org.apache.isis.core.metamodel.progmodel.ProgrammingModelAbstract;

public final class ProgrammingModelFacetsJava5 extends ProgrammingModelAbstract {

    public ProgrammingModelFacetsJava5(final IsisConfiguration configuration) {
        this(DeprecatedPolicy.parse(configuration));
    }

    public ProgrammingModelFacetsJava5(final DeprecatedPolicy deprecatedPolicy) {
        super(deprecatedPolicy);

        // must be first, so any Facets created can be replaced by other
        // FacetFactorys later.
        addFactory(new FallbackFacetFactory());

        addFactory(new ObjectSpecIdFacetDerivedFromClassNameFactory());
        addFactory(new DomainServiceFacetAnnotationFactory());

        addFactory(new IteratorFilteringFacetFactory());

        addFactory(new RemoveMethodsFacetFactory());

        addFactory(new RemoveStaticGettersAndSettersFacetFactory());

        addFactory(new RemoveAnnotatedMethodsFacetFactory());

        // come what may, we have to ignore the PersistenceCapable supertype.
        addFactory(new RemoveJdoEnhancementTypesFacetFactory());
        // so we may as well also just ignore any 'jdo' prefixed methods here also.
        addFactory(new RemoveJdoPrefixedMethodsFacetFactory());
        // DN 4.x
        addFactory(new RemoveDatanucleusPersistableTypesFacetFactory());
        addFactory(new RemoveDnPrefixedMethodsFacetFactory());

        // must be before any other FacetFactories that install
        // MandatoryFacet.class facets
        addFactory(new MandatoryFacetOnProperyDefaultFactory());
        addFactory(new MandatoryFacetOnParametersDefaultFactory());

        addFactory(new PropertyValidateFacetDefaultFactory());

        // enum support
        addFactory(new EnumFacetUsingValueFacetUsingSemanticsProviderFactory());
        addFactory(new ActionParameterChoicesFacetDerivedFromChoicesFacetFactory());
        addFactory(new PropertyChoicesFacetDerivedFromChoicesFacetFactory());

        // properties
        addFactory(new PropertyAccessorFacetViaAccessorFactory());
        addFactory(new PropertySetAndClearFacetFactory());
        // must come after PropertySetAndClearFacetFactory (replaces setter facet with modify if need be)
        addFactory(new PropertyModifyFacetFactory());

        addFactory(new PropertyValidateFacetViaMethodFactory());
        addFactory(new PropertyChoicesFacetViaMethodFactory());
        addFactory(new PropertyAutoCompleteFacetMethodFactory());
        addFactory(new PropertyDefaultFacetViaMethodFactory());

        addFactory(new MandatoryFacetOnPropertyStaticMethodFactory());

        // collections
        addFactory(new CollectionAccessorFacetViaAccessorFactory());
        addFactory(new CollectionClearFacetFactory());
        addFactory(new CollectionAddToRemoveFromAndValidateFacetFactory());

        addFactory(new SortedByFacetAnnotationFactory());

        // actions

        addFactory(new ActionValidationFacetViaMethodFactory());
        addFactory(new ActionChoicesFacetViaMethodFactory());
        addFactory(new ActionParameterChoicesFacetViaMethodFactory());
        addFactory(new ActionParameterAutoCompleteFacetViaMethodFactory());
        addFactory(new ActionDefaultsFacetViaMethodFactory());
        addFactory(new ActionParameterDefaultsFacetViaMethodFactory());

        // members in general

        addFactory(new NamedFacetStaticMethodFactory());

        addFactory(new DescribedAsFacetStaticMethodFactory());
        addFactory(new DisableForSessionFacetViaMethodFactory());
        addFactory(new DisableForContextFacetViaMethodFactory());

        addFactory(new DisabledFacetStaticMethodFacetFactory());
        addFactory(new HideForSessionFacetViaMethodFactory());

        addFactory(new HiddenFacetStaticMethodFactory());
        addFactory(new HideForContextFacetViaMethodFactory());
        addFactory(new RenderFacetOrResolveFactory());

        addFactory(new CreatedCallbackFacetFactory());
        addFactory(new LoadCallbackFacetFactory());
        addFactory(new PersistCallbackViaSaveMethodFacetFactory());
        addFactory(new PersistCallbackFacetFactory());
        addFactory(new UpdateCallbackFacetFactory());
        addFactory(new RemoveCallbackFacetFactory());

        addFactory(new ValidateObjectFacetMethodFactory());
        addFactory(new ObjectValidPropertiesFacetImplFactory());

        addFactory(new PluralFacetStaticMethodFactory());

        addFactory(new org.apache.isis.core.metamodel.facets.object.named.staticmethod.NamedFacetStaticMethodFactory());

        addFactory(new MemberOrderFacetFactory());

        addFactory(new ActionOrderFacetAnnotationFactory());

        addFactory(new FieldOrderFacetAnnotationFactory());
        addFactory(new MemberGroupLayoutFacetFactory());

        addFactory(new AggregatedAnnotationFactory());

        addFactory(new BookmarkPolicyFacetViaBookmarkableAnnotationElseFallbackFactory());
        addFactory(new HomePageFacetAnnotationFactory());
        addFactory(new ChoicesFacetFromBoundedMarkerInterfaceFactory());

        addFactory(new DefaultedFacetAnnotationElseConfigurationFactory());
        addFactory(new PropertyDefaultFacetDerivedFromTypeFactory());
        addFactory(new ActionParameterDefaultFacetDerivedFromTypeFactory());

        addFactory(new DescribedAsFacetOnTypeAnnotationFactory());
        addFactory(new DescribedAsFacetOnMemberFactory());
        addFactory(new DescribedAsFacetOnParameterAnnotationElseDerivedFromTypeFactory());

        addFactory(new BigDecimalFacetOnParameterFromJavaxValidationAnnotationFactory());
        addFactory(new BigDecimalFacetOnPropertyFromJavaxValidationDigitsAnnotationFactory());

        addFactory(new DisabledFacetOnMemberFromPropertiesFactory());
        addFactory(new EncodableFacetAnnotationElseConfigurationFactory());

        addFactory(new PrototypeFacetForExplorationAnnotationFactory());

        addFactory(new NotContributedFacetAnnotationFactory());

        addFactory(new NotInServiceMenuFacetAnnotationFactory());

        addFactory(new NotInServiceMenuFacetViaMethodFactory());

        addFactory(new NotContributedFacetDerivedFromDomainServiceFacetFactory());
        addFactory(new NotInServiceMenuFacetDerivedFromDomainServiceFacetFactory());

        addFactory(new HiddenFacetOnTypeAnnotationFactory());
        // must come after the TitleAnnotationFacetFactory, because can act as an override

        addFactory(new HiddenFacetOnMemberFromPropertiesFactory());

            addFactory(new CssClassFacetOnTypeAnnotationFactory());
        addFactory(new CssClassFacetOnMemberFactory());
        // must come after CssClassFacetOnMemberFactory
        addFactory(new CssClassFacetOnActionFromConfiguredRegexFactory());

        // addFactory(new CssClassFaFacetOnTypeAnnotationFactory());
        addFactory(new CssClassFaFacetOnMemberFactory());

        addFactory(new HiddenObjectFacetViaMethodFactory());
        addFactory(new DisabledObjectFacetViaMethodFactory());

        addFactory(new CopyImmutableFacetOntoMembersFactory());
        addFactory(new ImmutableFacetMarkerInterfaceFactory());

        addFactory(new RecreatableObjectFacetFactory());
        addFactory(new MixinFacetForMixinAnnotationFactory());

        addFactory(new MaxLengthFacetOnTypeAnnotationFactory());

        addFactory(new MaxLengthFacetOnActionAnnotationFactory());

        addFactory(new MustSatisfySpecificationFromMustSatisfyAnnotationOnTypeFacetFactory());

        addFactory(new MultiLineFacetOnTypeAnnotationFactory());
        addFactory(new MultiLineFacetOnPropertyFactory());
        addFactory(new MultiLineFacetOnParameterAnnotationFactory());

        // must come after RecreatableObjectFacetFactory
        addFactory(new DomainObjectAnnotationFacetFactory());

        // must come after the property/collection accessor+mutator facet factories
        addFactory(new ActionAnnotationFacetFactory());
        // after the ActionAnnotationFacetFactory so that takes precedent for contributed associations
        addFactory(new PropertyAnnotationFacetFactory());
        // after the ActionAnnotationFacetFactory so that takes precedent for contributed associations
        addFactory(new CollectionAnnotationFacetFactory());

        addFactory(new ParameterAnnotationFacetFactory());

        // must come after DomainObjectAnnotationFacetFactory
        addFactory(new DisabledFacetOnPropertyDerivedFromRecreatableObjectFacetFactory());
        addFactory(new DisabledFacetOnCollectionDerivedFromViewModelFacetFactory());
        // must come after DomainObjectAnnotationFacetFactory & MixinFacetFactory
        addFactory(new NotContributedFacetDerivedFromMixinFacetFactory());

        addFactory(new GridFacetFactory());

        addFactory(new DomainServiceLayoutFacetFactory());
        addFactory(new DomainObjectLayoutFacetFactory());
        // must come after MultiLine
        addFactory(new PropertyLayoutFacetFactory());
        addFactory(new ParameterLayoutFacetFactory());
        addFactory(new ActionLayoutFacetFactory());
        addFactory(new CollectionLayoutFacetFactory());

        // must come after DomainObjectLayoutFacetFactory
        addFactory(new TitleAnnotationFacetFactory());
        addFactory(new TitleFacetViaMethodsFactory());
        addFactory(new IconFacetMethodFactory());
        addFactory(new CssClassFacetMethodFactory());

        addFactory(new NamedFacetOnTypeAnnotationFactory());
        addFactory(new NamedFacetOnMemberFactory());

        addFactory(new NamedFacetOnParameterAnnotationFactory());

        addFactory(new NotPersistableFacetAnnotationFactory());
        addFactory(new NotPersistableFacetMarkerInterfaceFactory());

        addFactory(new ParseableFacetAnnotationElseConfigurationFactory());

        addFactory(new PluralAnnotationFacetFactory());

        addFactory(new PagedFacetOnTypeAnnotationFactory());

        addFactory(new PagedFacetOnCollectionFactory());

        addFactory(new PagedFacetOnActionFactory());

        // must come after any facets that install titles

        addFactory(new MaskFacetOnTypeAnnotationFactory());
        addFactory(new MaskFacetOnPropertyAnnotationFactory());

        addFactory(new MaskFacetOnParameterAnnotationFactory());

        // must come after any facets that install titles, and after mask
        // if takes precedence over mask.

        addFactory(new RegExFacetOnTypeAnnotationFactory());

        addFactory(new TypicalLengthFacetOnPropertyDerivedFromTypeFacetFactory());
        addFactory(new TypicalLengthFacetOnParameterDerivedFromTypeFacetFactory());

        addFactory(new TypicalLengthFacetOnTypeAnnotationFactory());
        addFactory(new TypicalLengthOnPropertyFacetFactory());

        addFactory(new TypicalLengthFacetOnParameterAnnotationFactory());

        addFactory(new RenderedAsDayBeforeAnnotationOnPropertyFacetFactory());

        addFactory(new RenderedAsDayBeforeFacetOnParameterAnnotationFactory());

        // built-in value types for Java language
        addFactory(new BooleanPrimitiveValueFacetUsingSemanticsProviderFactory());
        addFactory(new BooleanWrapperValueFacetUsingSemanticsProviderFactory());
        addFactory(new BytePrimitiveValueFacetUsingSemanticsProviderFactory());
        addFactory(new ByteWrapperValueFacetUsingSemanticsProviderFactory());
        addFactory(new ShortPrimitiveValueFacetUsingSemanticsProviderFactory());
        addFactory(new ShortWrapperValueFacetUsingSemanticsProviderFactory());
        addFactory(new IntPrimitiveValueFacetUsingSemanticsProviderFactory());
        addFactory(new IntWrapperValueFacetUsingSemanticsProviderFactory());
        addFactory(new LongPrimitiveValueFacetUsingSemanticsProviderFactory());
        addFactory(new LongWrapperValueFacetUsingSemanticsProviderFactory());
        addFactory(new FloatPrimitiveValueFacetUsingSemanticsProviderFactory());
        addFactory(new FloatWrapperValueFacetUsingSemanticsProviderFactory());
        addFactory(new DoublePrimitiveValueFacetUsingSemanticsProviderFactory());
        addFactory(new DoubleWrapperValueFacetUsingSemanticsProviderFactory());
        addFactory(new CharPrimitiveValueFacetUsingSemanticsProviderFactory());
        addFactory(new CharWrapperValueFacetUsingSemanticsProviderFactory());
        addFactory(new BigIntegerValueFacetUsingSemanticsProviderFactory());
        addFactory(new BigDecimalValueFacetUsingSemanticsProviderFactory());
        addFactory(new JavaSqlDateValueFacetUsingSemanticsProviderFactory());
        addFactory(new JavaSqlTimeValueFacetUsingSemanticsProviderFactory());
        addFactory(new JavaUtilDateValueFacetUsingSemanticsProviderFactory());
        addFactory(new JavaSqlTimeStampValueFacetUsingSemanticsProviderFactory());
        addFactory(new StringValueFacetUsingSemanticsProviderFactory());
        addFactory(new URLValueFacetUsingSemanticsProviderFactory());
        addFactory(new UUIDValueFacetUsingSemanticsProviderFactory());

        addFactory(new JavaAwtImageValueFacetUsingSemanticsProviderFactory());

        // applib values
        addFactory(new BlobValueFacetUsingSemanticsProviderFactory());
        addFactory(new ClobValueFacetUsingSemanticsProviderFactory());
        addFactory(new DateValueFacetUsingSemanticsProviderFactory());
        addFactory(new DateTimeValueFacetUsingSemanticsProviderFactory());
        addFactory(new ColorValueFacetUsingSemanticsProviderFactory());
        addFactory(new MoneyValueFacetUsingSemanticsProviderFactory());
        addFactory(new PasswordValueFacetUsingSemanticsProviderFactory());
        addFactory(new PercentageValueFacetUsingSemanticsProviderFactory());
        addFactory(new TimeStampValueFacetUsingSemanticsProviderFactory());
        addFactory(new TimeValueFacetUsingSemanticsProviderFactory());
        addFactory(new ImageValueFacetUsingSemanticsProviderFactory());

        // jodatime values
        addFactory(new JodaLocalDateValueFacetUsingSemanticsProviderFactory());
        addFactory(new JodaLocalDateTimeValueFacetUsingSemanticsProviderFactory());
        addFactory(new JodaDateTimeValueFacetUsingSemanticsProviderFactory());

        // written to not trample over TypeOf if already installed
        addFactory(new CollectionFacetFactory());
        // must come after CollectionFacetFactory
        addFactory(new ParentedFacetSinceCollectionFactory());

        // so we can dogfood the applib "value" types
        addFactory(new ValueFacetAnnotationOrConfigurationFactory());

        addFactory(new DisabledFacetOnPropertyDerivedFromImmutableFactory());
        addFactory(new DisabledFacetOnCollectionDerivedFromImmutableFactory());

        // should come near the end, after any facets that install PropertySetterFacet have run.
        addFactory(new DisabledFacetOnPropertyInferredFactory());

        addFactory(new AuditableFacetMarkerInterfaceFactory());

        addFactory(new FacetsFacetAnnotationFactory());

        // must be after all named facets and description facets have been installed
        addFactory(new TranslationFacetFactory());

        addFactory(new ViewModelSemanticCheckingFacetFactory());
    }
}


text:
package com.carrotgarden.nexus.aws.s3.publish.task;

import static com.carrotgarden.nexus.aws.s3.publish.util.PathHelp.*;

import java.io.File;
import java.util.List;
import java.util.regex.Pattern;

import javax.inject.Inject;
import javax.inject.Named;

import org.sonatype.nexus.plugins.capabilities.CapabilityIdentity;
import org.sonatype.nexus.plugins.capabilities.CapabilityReference;
import org.sonatype.nexus.plugins.capabilities.CapabilityRegistry;
import org.sonatype.nexus.proxy.ResourceStoreRequest;
import org.sonatype.nexus.proxy.access.AccessManager;
import org.sonatype.nexus.proxy.attributes.Attributes;
import org.sonatype.nexus.proxy.item.StorageFileItem;
import org.sonatype.nexus.proxy.item.StorageItem;
import org.sonatype.nexus.proxy.registry.RepositoryRegistry;
import org.sonatype.nexus.proxy.repository.Repository;
import org.sonatype.nexus.scheduling.NexusScheduler;
import org.sonatype.scheduling.ScheduledTask;
import org.sonatype.scheduling.TaskInterruptedException;
import org.sonatype.scheduling.TaskState;

import com.carrotgarden.nexus.aws.s3.publish.amazon.AmazonService;
import com.carrotgarden.nexus.aws.s3.publish.attribute.CarrotAttribute;
import com.carrotgarden.nexus.aws.s3.publish.config.ConfigCapability;
import com.carrotgarden.nexus.aws.s3.publish.config.ConfigEntry;
import com.carrotgarden.nexus.aws.s3.publish.mailer.CarrotMailer;
import com.carrotgarden.nexus.aws.s3.publish.mailer.Report;
import com.carrotgarden.nexus.aws.s3.publish.metrics.Reporter;
import com.carrotgarden.nexus.aws.s3.publish.metrics.TaskReporter;
import com.carrotgarden.nexus.aws.s3.publish.scanner.CarrotListener;
import com.carrotgarden.nexus.aws.s3.publish.scanner.CarrotListenerSupport;
import com.carrotgarden.nexus.aws.s3.publish.scanner.CarrotScanner;
import com.carrotgarden.nexus.aws.s3.publish.util.AmazonHelp;
import com.carrotgarden.nexus.aws.s3.publish.util.ConfigHelp;
import com.carrotgarden.nexus.aws.s3.publish.util.RepoHelp;
import com.carrotgarden.nexus.aws.s3.publish.util.TaskHelp;
import com.google.common.base.Throwables;
import com.yammer.metrics.core.Gauge;

/**
 * scan repository and publish newly found files to amazon
 */
@Named(ScannerTask.NAME)
public class ScannerTask extends BaseTask {

	public enum ConfigType {

		/** a task must run on a configuration change */
		ON_DEMAND, //

		/** a task must run on provided schedule */
		SCHEDULED, //

	}

	/** persistent task binding to owner capability */
	private static final String KEY_CONFIG_ID = "scanner.task.config-id";
	private static final String KEY_CONFIG_TYPE = "scanner.task.config-type";

	public static final String NAME = "ScannerTask";

	public static String taskNameRule(final String configId,
			final ConfigType configType) {
		return NAME + " [" + configId + "] " + configType + " ("
				+ ConfigHelp.pluginName() + ")";
	}

	private final CapabilityRegistry capaRegistry;
	private final RepositoryRegistry repoRegistry;
	private final CarrotScanner scanner;
	private final TaskReporter reporter;
	private final NexusScheduler scheduler;
	private final CarrotMailer mailer;

	@Inject
	public ScannerTask( //
			final CarrotMailer mailer, //
			final TaskReporter reporter, //
			final NexusScheduler scheduler, //
			@Named("serial") final CarrotScanner scanner, //
			final CapabilityRegistry capaRegistry, //
			final RepositoryRegistry repoRegistry //
	) {
		this.mailer = mailer;
		this.scheduler = scheduler;
		this.reporter = reporter;
		this.scanner = scanner;
		this.capaRegistry = capaRegistry;
		this.repoRegistry = repoRegistry;

		reporter.newGauge("task name", new Gauge<String>() {
			@Override
			public String value() {
				return getName();
			}
		});
		reporter.newGauge("task state", new Gauge<String>() {
			@Override
			public String value() {
				return state();
			}
		});
		reporter.newGauge("task failure", new Gauge<String>() {
			@Override
			public String value() {
				return "" + failure;
			}
		});

	}

	private String state() {
		try {
			final ScheduledTask<?> reference = //
			TaskHelp.reference(scheduler, this);
			final TaskState state = reference.getTaskState();
			return state.name();
		} catch (final Exception e) {
			return "UNKNOWN";
		}
	}

	public String configId() {
		return getParameters().get(KEY_CONFIG_ID);
	}

	public void configId(final String configId) {
		getParameters().put(KEY_CONFIG_ID, configId);
	}

	public ConfigType configType() {
		return ConfigType.valueOf(getParameters().get(KEY_CONFIG_TYPE));
	}

	public void configType(final ConfigType type) {
		getParameters().put(KEY_CONFIG_TYPE, type.name());
	}

	private Throwable failure;

	public Throwable failure() {
		return failure;
	}

	@Override
	protected Object doRun() {

		reporter.taskRunCount.inc();

		boolean isSuccess = false;

		try {
			failure = null;
			doWork();
			isSuccess = true;
			log.info("task success");
		} catch (final InterruptedException e) {
			failure = e;
			log.debug("task cancel 1");
		} catch (final TaskInterruptedException e) {
			failure = e;
			log.debug("task cancel 2");
		} catch (final Exception e) {
			failure = e;
			log.error("task failure", e);
		}

		log.info("\n{}", reporter.report());

		if (isSuccess) {
			mailer.sendScannerReport(Report.SCANNER_TASK_SUCCESS,
					configEntry(), this);
			mailer.sendScannerReport(Report.SCANNER_TASK_SUCCESS_REPORT,
					configEntry(), this);
		} else {
			mailer.sendScannerReport(Report.SCANNER_TASK_FAILURE,
					configEntry(), this);
			mailer.sendScannerReport(Report.SCANNER_TASK_FAILURE_REPORT,
					configEntry(), this);
		}

		return null;

	}

	private void doSleep(final long millis) {
		try {
			Thread.sleep(millis);
		} catch (final InterruptedException e) {
			throw new TaskInterruptedException("sleep interrupted", e);
		} finally {
		}
	}

	private ConfigEntry configEntry() {

		final CapabilityIdentity capaId = new CapabilityIdentity(configId());

		final CapabilityReference reference = capaRegistry.get(capaId);

		final ConfigEntry entry = reference
				.capabilityAs(ConfigCapability.class);

		return entry;

	}

	private void doWork() throws Exception {

		reporter.reset();

		if (shouldYield()) {
			log.info("yielding to priority tasks");
			return;
		}

		final ConfigEntry entry = configEntry();

		final String comboId = entry.comboId();

		final AmazonService service = entry.amazonService();

		final List<String> repoList = RepoHelp.repoList(repoRegistry, comboId);

		final Pattern defaultExclude = ConfigHelp.defaultExclude();

		for (final String repoId : repoList) {

			checkInterruption();

			doSleep(scannerRepositorySleepTime());

			final Repository repo = repoRegistry.getRepository(repoId);

			final File root = RepoHelp.repoRoot(repo);

			final CarrotListener listener = new CarrotListenerSupport() {

				@Override
				public void onBegin() {

					log.info("##########################################");
					log.info("repo scan init : {} {}", configId(), repoId);

				}

				@Override
				public void onEnd() {

					log.info("repo stats : processed={} published={}",
							reporter.scanCount.count(),
							reporter.amazonPublishedFileCount.count());
					log.info("repo scan done : {} {}", configId(), repoId);
					log.info("##########################################");
				}

				@Override
				public boolean skipDirectory(final File directory) {

					final String path = //
					rootFullPath(relativePath(root, directory));

					final boolean isDefaultExclude = //
					defaultExclude.matcher(path).matches();

					if (isDefaultExclude) {
						log.info("ignore direcotry : {}", directory);
						reporter.skipFileWatch.add(directory
								+ "[default exclude]");
					}

					return isDefaultExclude;

				}

				@Override
				public boolean skipFile(final File file) {

					return false;

				}

				@Override
				public void onFile(final File file) {
					try {

						checkInterruption();

						reporter.scanCount.inc();
						reporter.scanRate.mark();
						reporter.repoFileWatch.add(file);

						final String path = //
						rootFullPath(relativePath(root, file));

						if (entry.isExcluded(path)) {
							reporter.amazonIgnoredFileCount.inc();
							reporter.skipFileWatch.add(file
									+ "[entry is excluded]");
							return;
						}

						final ResourceStoreRequest request = //
						new ResourceStoreRequest(path);

						request.getRequestContext().put(//
								AccessManager.REQUEST_AUTHORIZED, "true");

						final StorageItem any = repo.retrieveItem(request);

						final boolean isFileItem = any instanceof StorageFileItem;

						if (!isFileItem) {
							reporter.amazonIgnoredFileCount.inc();
							reporter.skipFileWatch.add(file
									+ "[not a file item]");
							return;
						}

						reporter.repoFileCount.inc();
						reporter.repoFileSize.inc(file.length());

						final StorageFileItem item = (StorageFileItem) any;

						final Attributes attributes = item
								.getRepositoryItemAttributes();

						final String value = attributes
								.get(CarrotAttribute.ATTR_IS_SAVED);

						if ("true".equals(value)) {
							reporter.amazonExistingFileCount.inc();
							reporter.skipFileWatch.add(file
									+ "[already stored]");
							return;
						}

						int countSleep = 0;

						/** block till bucket available */

						while (true) {

							checkInterruption();

							final boolean isAmazonSaved = AmazonHelp.storeItem(
									service, repo, item, file, log);

							if (isAmazonSaved) {
								reporter.saveFileWatch.add(file);
								reporter.amazonPublishedFileCount.inc();
								reporter.amazonPublishedFileSize.inc( //
										file.length());
								break;
							} else {
								reporter.amazonRetriedFileCount.inc();
								reporter.skipFileWatch.add(file
										+ "[amazon failure]");
							}

							if (countSleep == 0) {
								log.warn(
										"amazon failure - will wait and try again : {}",
										file);
							}

							doSleep(scannerFailureSleepTime());

							countSleep++;

						}

					} catch (final Exception e) {
						Throwables.propagate(e);
					}
				}

			};

			scanner.scan(root, listener);

		}

	}

	/** scheduled tasks should yield to on-demand tasks, if any */
	private boolean shouldYield() {

		/** self is on-demand */
		if (configType() == ConfigType.ON_DEMAND) {
			return false;
		}

		/** no scanner tasks */
		final List<ScheduledTask<?>> referenceList = //
		scheduler.getAllTasks().get(NAME);

		if (referenceList == null) {
			return false;
		}

		/** any other on-demand scanner task running ? */
		for (final ScheduledTask<?> reference : referenceList) {

			final ScannerTask task = (ScannerTask) reference.getTask();

			if (task.configType() == ConfigType.ON_DEMAND) {
				return true;
			}

		}

		return false;

	}

	public boolean equals(final String configId, final ConfigType type) {
		return configId().equals(configId) && configType().equals(type);
	}

	@Override
	protected String getAction() {
		return "scan";
	}

	@Override
	protected String getMessage() {
		return getName();
	}

	public static long scannerFailureSleepTime() {
		return ConfigHelp.reference().getMilliseconds(
				"scanner-task.failure-sleep-time");
	}

	public static long scannerRepositorySleepTime() {
		return ConfigHelp.reference().getMilliseconds(
				"scanner-task.repository-sleep-time");
	}

	public Reporter reporter() {
		return reporter;
	}

}


text:
Headzoo\Bitcoin\Wallet\Api\Exceptions\InternalServerErrorException
===============

Thrown when the rpc when the api responds with an internal server error status code.

* Class name: InternalServerErrorException
* Namespace: Headzoo\Bitcoin\Wallet\Api\Exceptions
* Parent class: [Headzoo\Bitcoin\Wallet\Api\Exceptions\RPCException](Headzoo-Bitcoin-Wallet-Api-Exceptions-RPCException.md)