private AnimatorListener createSweepAnimatorListener() {
        return new AnimatorListener() {

            @Override
            public void onAnimationStart(final Animator animation) {

            }

            @Override
            public void onAnimationEnd(final Animator animation) {

            }

            @Override
            public void onAnimationCancel(final Animator animation) {

            }

            @Override
            public void onAnimationRepeat(final Animator animation) {
                appearing = !appearing;

                if (appearing) {
                    currentGlobalAngleOffset =
                            (currentGlobalAngleOffset + MIN_SWEEP_ANGLE * 2) % MAX_DEGREES;
                }
            }

        };
    }

private AnimatorListener createSweepAnimatorListener ( ) { return new AnimatorListener ( ) { @ Override public void onAnimationStart ( final Animator animation ) { } @ Override public void onAnimationEnd ( final Animator animation ) { } @ Override public void onAnimationCancel ( final Animator animation ) { } @ Override public void onAnimationRepeat ( final Animator animation ) { appearing = ! appearing ; if ( appearing ) { currentGlobalAngleOffset = ( currentGlobalAngleOffset + MIN_SWEEP_ANGLE * 2 ) % MAX_DEGREES ; } } } ; }

Creates and returns a listener, which allows to restart the progress drawable's animation,
when it has been finished.

@return The listener, which has been created, as an instance of the type {@link
AnimatorListener}

Creates and returns a listener which allows to restart the progress drawable s animation when it has been finished .


private void initializeFloatingActionButtons() {
        smallFloatingActionButton = findViewById(R.id.floating_action_button_small);
        smallFloatingActionButton.setOnClickListener(createFloatingActionButtonListener());
        normalFloatingActionButton = findViewById(R.id.floating_action_button_normal);
        normalFloatingActionButton.setOnClickListener(createFloatingActionButtonListener());
        largeFloatingActionButton = findViewById(R.id.floating_action_button_large);
        largeFloatingActionButton.setOnClickListener(createFloatingActionButtonListener());
    }

private void initializeFloatingActionButtons ( ) { smallFloatingActionButton = findViewById ( R . id . floating_action_button_small ) ; smallFloatingActionButton . setOnClickListener ( createFloatingActionButtonListener ( ) ) ; normalFloatingActionButton = findViewById ( R . id . floating_action_button_normal ) ; normalFloatingActionButton . setOnClickListener ( createFloatingActionButtonListener ( ) ) ; largeFloatingActionButton = findViewById ( R . id . floating_action_button_large ) ; largeFloatingActionButton . setOnClickListener ( createFloatingActionButtonListener ( ) ) ; }

Initializes the floating action buttons.

Initializes the floating action buttons .


private OnClickListener createFloatingActionButtonListener() {
        return new OnClickListener() {

            @Override
            public void onClick(final View v) {
                Toast toast =
                        Toast.makeText(MainActivity.this, R.string.floating_action_button_toast,
                                Toast.LENGTH_SHORT);
                toast.show();
            }

        };
    }

private OnClickListener createFloatingActionButtonListener ( ) { return new OnClickListener ( ) { @ Override public void onClick ( final View v ) { Toast toast = Toast . makeText ( MainActivity . this , R . string . floating_action_button_toast , Toast . LENGTH_SHORT ) ; toast . show ( ) ; } } ; }

Creates and returns a listener, which allows to show a toast when a floating action button
has been clicked.

@return The listener, which has been created, as an instance of the type {@link
OnClickListener}

Creates and returns a listener which allows to show a toast when a floating action button has been clicked .


private void initializeHideFloatingActionButtonsButton() {
        Button button = findViewById(R.id.hide_floating_action_buttons);
        button.setOnClickListener(createHideFloatingActionButtonsListener());
    }

Initializes the button, which allows to show or hide the floating action buttons.

Initializes the button which allows to show or hide the floating action buttons .


private OnClickListener createHideFloatingActionButtonsListener() {
        return new OnClickListener() {

            @Override
            public void onClick(final View v) {
                int visibility = floatingActionButtonsVisible ? View.INVISIBLE : View.VISIBLE;
                smallFloatingActionButton.setVisibility(visibility, true);
                normalFloatingActionButton.setVisibility(visibility, true);
                largeFloatingActionButton.setVisibility(visibility, true);
                floatingActionButtonsVisible = !floatingActionButtonsVisible;
            }

        };
    }

private OnClickListener createHideFloatingActionButtonsListener ( ) { return new OnClickListener ( ) { @ Override public void onClick ( final View v ) { int visibility = floatingActionButtonsVisible ? View . INVISIBLE : View . VISIBLE ; smallFloatingActionButton . setVisibility ( visibility , true ) ; normalFloatingActionButton . setVisibility ( visibility , true ) ; largeFloatingActionButton . setVisibility ( visibility , true ) ; floatingActionButtonsVisible = ! floatingActionButtonsVisible ; } } ; }

Creates and returns a listener, which allows to show or hide the floating action buttons.

@return The listener, which has been created, as an instance of the type {@link
OnClickListener}

Creates and returns a listener which allows to show or hide the floating action buttons .


private void initializeChips() {
        Chip closableChipLight = findViewById(R.id.chip_closable_light);
        closableChipLight.addCloseListener(createChipCloseListener());
        Chip closableChipDark = findViewById(R.id.chip_closable_dark);
        closableChipDark.addCloseListener(createChipCloseListener());
        Chip closableIconChipLight = findViewById(R.id.chip_icon_closable_light);
        closableIconChipLight.addCloseListener(createChipCloseListener());
        Chip closableIconChipDark = findViewById(R.id.chip_icon_closable_dark);
        closableIconChipDark.addCloseListener(createChipCloseListener());
    }

private void initializeChips ( ) { Chip closableChipLight = findViewById ( R . id . chip_closable_light ) ; closableChipLight . addCloseListener ( createChipCloseListener ( ) ) ; Chip closableChipDark = findViewById ( R . id . chip_closable_dark ) ; closableChipDark . addCloseListener ( createChipCloseListener ( ) ) ; Chip closableIconChipLight = findViewById ( R . id . chip_icon_closable_light ) ; closableIconChipLight . addCloseListener ( createChipCloseListener ( ) ) ; Chip closableIconChipDark = findViewById ( R . id . chip_icon_closable_dark ) ; closableIconChipDark . addCloseListener ( createChipCloseListener ( ) ) ; }


private Chip.CloseListener createChipCloseListener() {
        return new Chip.CloseListener() {

            @Override
            public void onChipClosed(@NonNull final Chip chip) {
                chip.setVisibility(View.GONE);
                Toast.makeText(MainActivity.this, R.string.chip_closed_toast, Toast.LENGTH_SHORT)
                        .show();
            }

        };
    }

private Chip . CloseListener createChipCloseListener ( ) { return new Chip . CloseListener ( ) { @ Override public void onChipClosed ( @ NonNull final Chip chip ) { chip . setVisibility ( View . GONE ) ; Toast . makeText ( MainActivity . this , R . string . chip_closed_toast , Toast . LENGTH_SHORT ) . show ( ) ; } } ; }

Creates and returns a listener, which allows to show a toast, when a chip has been closed.

@return The listener, which has been created, as an instance of the type {@link
Chip.CloseListener}

Creates and returns a listener which allows to show a toast when a chip has been closed .


private void handleSavedInstanceState(@Nullable final Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            floatingActionButtonsVisible =
                    savedInstanceState.getBoolean(FLOATING_ACTION_BUTTONS_VISIBLE_EXTRA);
            int visibility = floatingActionButtonsVisible ? View.VISIBLE : View.INVISIBLE;
            smallFloatingActionButton.setVisibility(visibility);
            normalFloatingActionButton.setVisibility(visibility);
            largeFloatingActionButton.setVisibility(visibility);
        }
    }

private void handleSavedInstanceState ( @ Nullable final Bundle savedInstanceState ) { if ( savedInstanceState != null ) { floatingActionButtonsVisible = savedInstanceState . getBoolean ( FLOATING_ACTION_BUTTONS_VISIBLE_EXTRA ) ; int visibility = floatingActionButtonsVisible ? View . VISIBLE : View . INVISIBLE ; smallFloatingActionButton . setVisibility ( visibility ) ; normalFloatingActionButton . setVisibility ( visibility ) ; largeFloatingActionButton . setVisibility ( visibility ) ; } }

Adapts the activity's views depending on the saved instance state, which has been passed to
the activity.

@param savedInstanceState
The saved instance state as an instance of the class {@link Bundle} or null, if no
saved instance state is available

Adapts the activity s views depending on the saved instance state which has been passed to the activity .


private void obtainText(@NonNull final TypedArray typedArray) {
        setText(typedArray.getText(R.styleable.Chip_android_text));
    }

private void obtainText ( @ NonNull final TypedArray typedArray ) { setText ( typedArray . getText ( R . styleable . Chip_android_text ) ) ; }

Obtains the chip's text from a specific typed array.

@param typedArray
The typed array, the text should be obtained from, as an instance of the class {@link
TypedArray}. The typed array may not be null

Obtains the chip s text from a specific typed array .


private void obtainTextColor(@NonNull final TypedArray typedArray) {
        int defaultColor = ContextCompat.getColor(getContext(), R.color.chip_text_color_light);
        setTextColor(typedArray.getColor(R.styleable.Chip_android_textColor, defaultColor));
    }

private void obtainTextColor ( @ NonNull final TypedArray typedArray ) { int defaultColor = ContextCompat . getColor ( getContext ( ) , R . color . chip_text_color_light ) ; setTextColor ( typedArray . getColor ( R . styleable . Chip_android_textColor , defaultColor ) ) ; }

Obtains the chip's text color from a specific typed array.

@param typedArray
The typed array, the text color should be obtained from, as an instance of the class
{@link TypedArray}. The typed array may not be null

Obtains the chip s text color from a specific typed array .


private void obtainColor(@NonNull final TypedArray typedArray) {
        int defaultColor = ContextCompat.getColor(getContext(), R.color.chip_color_light);
        setColor(typedArray.getColor(R.styleable.Chip_android_color, defaultColor));
    }

private void obtainColor ( @ NonNull final TypedArray typedArray ) { int defaultColor = ContextCompat . getColor ( getContext ( ) , R . color . chip_color_light ) ; setColor ( typedArray . getColor ( R . styleable . Chip_android_color , defaultColor ) ) ; }

Obtains the chip's color from a specific typed array.

@param typedArray
The typed array, the color should be obtained from, as an instance of the class
{@link TypedArray}. The typed array may not be null

Obtains the chip s color from a specific typed array .


private void obtainIcon(@NonNull final TypedArray typedArray) {
        setIcon(typedArray.getDrawable(R.styleable.Chip_android_icon));
    }

private void obtainIcon ( @ NonNull final TypedArray typedArray ) { setIcon ( typedArray . getDrawable ( R . styleable . Chip_android_icon ) ) ; }

Obtains the chip's icon from a specific typed array.

@param typedArray
The typed array, the icon should be obtained from, as an instance of the class {@link
TypedArray}. The typed array may not be null

Obtains the chip s icon from a specific typed array .


private void obtainClosable(@NonNull final TypedArray typedArray) {
        setClosable(typedArray.getBoolean(R.styleable.Chip_closable, false));
    }

private void obtainClosable ( @ NonNull final TypedArray typedArray ) { setClosable ( typedArray . getBoolean ( R . styleable . Chip_closable , false ) ) ; }

Obtains, whether the chip should be closable, or not, from a specific typed array.

@param typedArray
The typed array, which should be used to obtain, whether the chip should be closable,
or not, as an instance of the class {@link TypedArray}. The typed array may not be
null

Obtains whether the chip should be closable or not from a specific typed array .


private void obtainCloseIcon(@NonNull final TypedArray typedArray) {
        Drawable icon = typedArray.getDrawable(R.styleable.Chip_closeButtonIcon);

        if (icon != null) {
            setCloseButtonIcon(icon);
        }
    }

private void obtainCloseIcon ( @ NonNull final TypedArray typedArray ) { Drawable icon = typedArray . getDrawable ( R . styleable . Chip_closeButtonIcon ) ; if ( icon != null ) { setCloseButtonIcon ( icon ) ; } }

Obtains the icon of the button, which allows to close the chip, from a specific typed array.

@param typedArray
The typed array, which should be used to obtain the icon of the button, which allows
to close the chip, as an instance of the class {@link TypedArray}. The typed array
may not be null

Obtains the icon of the button which allows to close the chip from a specific typed array .


public final void addCloseListener(@NonNull final CloseListener listener) {
        Condition.INSTANCE.ensureNotNull(listener, "The listener may not be null");
        listeners.add(listener);
    }

public
final
void
addCloseListener
(
@
NonNull
final
CloseListener
listener
)
{
Condition
.
INSTANCE
.
ensureNotNull
(
listener
,
"The listener may not be null"
)
;
listeners
.
add
(
listener
)
;
}

Adds a new listener, which should be notified, when the chip has been closed.

@param listener
The listener, which should be added, as an instance of the type {@link
CloseListener}. The listener may not be null

Adds a new listener which should be notified when the chip has been closed .


public final void removeCloseListener(@NonNull final CloseListener listener) {
        Condition.INSTANCE.ensureNotNull(listener, "The listener may not be null");
        listeners.remove(listener);
    }

public
final
void
removeCloseListener
(
@
NonNull
final
CloseListener
listener
)
{
Condition
.
INSTANCE
.
ensureNotNull
(
listener
,
"The listener may not be null"
)
;
listeners
.
remove
(
listener
)
;
}

Removes a specific listener, which should not be notified, when the chip has been closed,
anymore.

@param listener
The listener, which should be removed, as an instance of the type {@link
CloseListener}. The listener may not be null

Removes a specific listener which should not be notified when the chip has been closed anymore .


public final void setColor(@ColorInt final int color) {
        this.color = color;
        getBackground().setColorFilter(color, PorterDuff.Mode.SRC_IN);
    }

public final void setColor ( @ ColorInt final int color ) { this . color = color ; getBackground ( ) . setColorFilter ( color , PorterDuff . Mode . SRC_IN ) ; }

Sets the chip's color.

@param color
The color, which should be set, as an {@link Integer} value


public final void setClosable(final boolean closable) {
        this.closable = closable;

        if (closable) {
            closeButton.setVisibility(View.VISIBLE);
            textView.setPadding(textView.getPaddingLeft(), textView.getPaddingTop(), 0,
                    textView.getPaddingBottom());
        } else {
            closeButton.setVisibility(View.GONE);
            textView.setPadding(textView.getPaddingLeft(), textView.getPaddingTop(),
                    getResources().getDimensionPixelSize(R.dimen.chip_horizontal_padding),
                    textView.getPaddingBottom());
        }
    }

public final void setClosable ( final boolean closable ) { this . closable = closable ; if ( closable ) { closeButton . setVisibility ( View . VISIBLE ) ; textView . setPadding ( textView . getPaddingLeft ( ) , textView . getPaddingTop ( ) , 0 , textView . getPaddingBottom ( ) ) ; } else { closeButton . setVisibility ( View . GONE ) ; textView . setPadding ( textView . getPaddingLeft ( ) , textView . getPaddingTop ( ) , getResources ( ) . getDimensionPixelSize ( R . dimen . chip_horizontal_padding ) , textView . getPaddingBottom ( ) ) ; } }

Sets, whether the chip is closable, or not.

@param closable
True, if the chip should be closable, false otherwise

Sets whether the chip is closable or not .


@SuppressWarnings("unchecked")
	public Map<String, String> getPartials() {
		final View view = this.getView();
		if (view != null && view instanceof MustacheView) {
			MustacheView mustacheView = (MustacheView) view;
			return mustacheView.getAliases();
		} else {
			final Object object = getModelMap().get(MustacheSettings.PARTIALS_KEY);

			if (object != null && !(object instanceof Map)) {
				throw new MustachePartialsMappingException();
			}

			final Map<String, String> map;

			if (object == null) {
				map = new HashMap<String, String>();
			} else {
				map = (Map<String, String>) object;
			}

			return map;
		}
	}

@ SuppressWarnings ( "unchecked" ) public Map < String , String > getPartials ( ) { final View view = this . getView ( ) ; if ( view != null && view instanceof MustacheView ) { MustacheView mustacheView = ( MustacheView ) view ; return mustacheView . getAliases ( ) ; } else { final Object object = getModelMap ( ) . get ( MustacheSettings . PARTIALS_KEY ) ; if ( object != null && ! ( object instanceof Map ) ) { throw new MustachePartialsMappingException ( ) ; } final Map < String , String > map ; if ( object == null ) { map = new HashMap < String , String > ( ) ; } else { map = ( Map < String , String > ) object ; } return map ; } }

Get current partials stored in view.

@return Current partials.


public static ScriptEngine getEngine(Collection<InputStream> scripts) {
		ScriptEngine engine = getEngine();

		for (InputStream script : scripts) {
			evaluate(engine, script);
		}

		return engine;
	}

public static ScriptEngine getEngine ( Collection < InputStream > scripts ) { ScriptEngine engine = getEngine ( ) ; for ( InputStream script : scripts ) { evaluate ( engine , script ) ; } return engine ; }

Get new nashorn engine.

@param scripts List of scripts to evaluate.
@return Nashorn Engine.


public Map<String, String> getLayoutMappings() {
		String mappingsValues = environment.getProperty("mustache.layoutMappings", MustacheSettings.LAYOUT_MAPPINGS).trim();

		if (mappingsValues.isEmpty()) {
			return emptyMap();
		}

		Map<String, String> mappings = new HashMap<String, String>();
		String[] values = mappingsValues.split(";");
		if (values.length > 0) {
			for (String value : values) {
				String val = value == null ? "" : value.trim();
				if (val.isEmpty()) {
					continue;
				}

				String[] mapping = val.split(":");
				if (mapping.length != 2) {
					throw new IllegalArgumentException("Mapping must use [viewName]:[layout] format!");
				}

				mappings.put(mapping[0].trim(), mapping[1].trim());
			}
		}

		return unmodifiableMap(mappings);
	}

Get mappings to use with resolvers.

@return Layouts mappings


public static boolean isPresent(String klass) {
		hasText(klass, "Class name must not be empty");
		try {
			Class.forName(klass);
			return true;
		}
		catch (Exception ex) {
			return false;
		}
	}

public
static
boolean
isPresent
(
String
klass
)
{
hasText
(
klass
,
"Class name must not be empty"
)
;
try
{
Class
.
forName
(
klass
)
;
return
true
;
}
catch
(
Exception
ex
)
{
return
false
;
}
}

Check that a given class is available on
classpath.

@param klass Class name.
@return True if class is available, false otherwise.

Check that a given class is available on classpath .


@SuppressWarnings("unchecked")
	public static <T> T getAnnotationValue(AnnotationMetadata importingClassMetadata, Class annotationClass, String name, T defaultValue) {
		Map<String, Object> attributes = importingClassMetadata.getAnnotationAttributes(annotationClass.getName());
		return attributes != null && attributes.containsKey(name) ? (T) attributes.get(name) : defaultValue;
	}

@ SuppressWarnings ( "unchecked" ) public static < T > T getAnnotationValue ( AnnotationMetadata importingClassMetadata , Class annotationClass , String name , T defaultValue ) { Map < String , Object > attributes = importingClassMetadata . getAnnotationAttributes ( annotationClass . getName ( ) ) ; return attributes != null && attributes . containsKey ( name ) ? ( T ) attributes . get ( name ) : defaultValue ; }

Get annotation method value.

@param importingClassMetadata Metadata.
@param annotationClass        Annotation class to look for.
@param name                   Name of method.
@param defaultValue           Default value if original value is null.
@param <T>                    Type of returned value.
@return Annotation value, or default value if original value is null.


public static InputStream getStream(String name) {
		ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(IOUtils.class.getClassLoader());
		InputStream stream = getInputStreamWithResolver(resolver, name);

		// Not Found
		if (stream == null) {
			throw new MustacheIOException("Unable to locate {}" + name);
		}

		return stream;
	}

public
static
InputStream
getStream
(
String
name
)
{
ResourcePatternResolver
resolver
=
new
PathMatchingResourcePatternResolver
(
IOUtils
.
class
.
getClassLoader
(
)
)
;
InputStream
stream
=
getInputStreamWithResolver
(
resolver
,
name
)
;
// Not Found
if
(
stream
==
)
{
throw
new
MustacheIOException
(
"Unable to locate {}"
+
name
)
;
}
return
stream
;
}

Return an input stream from given name.
Name is searched into the classpath.
Name can contains ant style pattern.

@param name Name.
@return Input Stream.

Return an input stream from given name . Name is searched into the classpath . Name can contains ant style pattern .


public static InputStream getFirstAvailableStream(Collection<String> names) {
		ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(IOUtils.class.getClassLoader());
		for (String name : names) {
			try {
				InputStream stream = getInputStreamWithResolver(resolver, name);
				if (stream != null) {
					return stream;
				}
			}
			catch (MustacheIOException ex) {
				// Go to the next test
			}
		}

		throw new MustacheIOException("Unable to locate one of: " + names);
	}

public
static
InputStream
getFirstAvailableStream
(
Collection
<
String
>
names
)
{
ResourcePatternResolver
resolver
=
new
PathMatchingResourcePatternResolver
(
IOUtils
.
class
.
getClassLoader
(
)
)
;
for
(
String
name
:
names
)
{
try
{
InputStream
stream
=
getInputStreamWithResolver
(
resolver
,
name
)
;
if
(
stream
!=
)
{
return
stream
;
}
}
catch
(
MustacheIOException
ex
)
{
// Go to the next test
}
}
throw
new
MustacheIOException
(
"Unable to locate one of: "
+
names
)
;
}

Return an input stream from given names.
First result returning a valid stream is returned.
Names are searched into the classpath.
Names can contains ant style pattern.

@param names Names collection.
@return Input Stream.
@throws MustacheIOException If everything fail.

Return an input stream from given names . First result returning a valid stream is returned . Names are searched into the classpath . Names can contains ant style pattern .


public String render(String template, Map<String, Object> model) {
		try {
			Invocable invocable = (Invocable) engine;
			return (String) invocable.invokeFunction("render", template, model, partials);
		}
		catch (ScriptException ex) {
			throw new NashornException(ex);
		}
		catch (NoSuchMethodException ex) {
			throw new NashornException(ex);
		}
	}

public String render ( String template , Map < String , Object > model ) { try { Invocable invocable = ( Invocable ) engine ; return ( String ) invocable . invokeFunction ( "render" , template , model , partials ) ; } catch ( ScriptException ex ) { throw new NashornException ( ex ) ; } catch ( NoSuchMethodException ex ) { throw new NashornException ( ex ) ; } }

Render template with given model object.

@param template Template.
@param model Model object.
@return Rendered template.

Render template with given model object .


public void addAliases(Map<String, String> aliases) {
		notNull(aliases, "Aliases must not be null");
		for (Map.Entry<String, String> entry : aliases.entrySet()) {
			addAlias(entry.getKey(), entry.getValue());
		}
	}

public
void
addAliases
(
Map
<
String
,
String
>
aliases
)
{
notNull
(
aliases
,
"Aliases must not be null"
)
;
for
(
Map
.
Entry
<
String
,
String
>
entry
:
aliases
.
entrySet
(
)
)
{
addAlias
(
entry
.
getKey
(
)
,
entry
.
getValue
(
)
)
;
}
}

Add partials mapping.

@param aliases New aliases.


public void addAlias(String key, String value) {
		this.aliases.put(
				notNull(key, "Key must not be null"),
				notNull(value, "Value must not be null")
		);
	}

public
void
addAlias
(
String
key
,
String
value
)
{
this
.
aliases
.
put
(
notNull
(
key
,
"Key must not be null"
)
,
notNull
(
value
,
"Value must not be null"
)
)
;
}

Add alias mapping.

@param key Partial key.
@param value Partial name.


@NonNull
    public final synchronized ChronosListener getListener(final int id) {
        ChronosListener chronosListener = mListeners.get(id);
        if (chronosListener == null) {
            chronosListener = new ChronosListener(id);
            mListeners.put(id, chronosListener);
        }
        return chronosListener;
    }

@ NonNull public final synchronized ChronosListener getListener ( final int id ) { ChronosListener chronosListener = mListeners . get ( id ) ; if ( chronosListener == null ) { chronosListener = new ChronosListener ( id ) ; mListeners . put ( id , chronosListener ) ; } return chronosListener ; }

Gets previously created ServiceConnector by its id.

@param id an id of the saved ServiceConnector
@return a restored ServiceConnector, or a new one, if there is no saved instance with a given
id
@see {@link ChronosListener#getId()}
@see #createListener()

Gets previously created ServiceConnector by its id .


@NonNull
    public static <Output> ChronosOperationResult<Output> run(
            @NonNull final ChronosOperation<Output> operation) {
        return ChronosService.getInstance().runSync(operation, false);
    }

@ NonNull public static < Output > ChronosOperationResult < Output > run ( @ NonNull final ChronosOperation < Output > operation ) { return ChronosService . getInstance ( ) . runSync ( operation , false ) ; }

Runs operation synchronously.

@param operation Operation to be executed.
@param <Output>  class of the result, returned by the Operations' {@code run} method
@return OperationResult which contains the result of the Operation, or the error, occurred
during the execution


@Contract(pure = true)
    private static boolean isCallback(@NonNull final Method method,
            @NonNull final Class<?> resultClass,
            @NonNull final String methodName) {
        if (method.getName().equals(methodName)) {
            if (method.getReturnType() == Void.TYPE) {
                final Class<?>[] parameters = method.getParameterTypes();
                if (parameters.length == 1 && parameters[0].isAssignableFrom(resultClass)) {
                    return true;
                }
            }
        }

        return false;
    }

@ Contract ( pure = true ) private static boolean isCallback ( @ NonNull final Method method , @ NonNull final Class < ? > resultClass , @ NonNull final String methodName ) { if ( method . getName ( ) . equals ( methodName ) ) { if ( method . getReturnType ( ) == Void . TYPE ) { final Class < ? > [ ] parameters = method . getParameterTypes ( ) ; if ( parameters . length == 1 && parameters [ 0 ] . isAssignableFrom ( resultClass ) ) { return true ; } } } return false ; }

Checks if a method can be used as a callback to handle operation result.

@param method      a method to be checked
@param resultClass an operation result class
@param methodName  a required method name
@return {@code true} if method can be used as a callback; {@code false} otherwise

Checks if a method can be used as a callback to handle operation result .


public final void onResume(@NonNull final Object serviceListener) {
        logd("onResume");
        mServiceListener = serviceListener;
        mState = State.RESUMED;

        if (!mStoredResults.isEmpty()) {
            logd("has undelivered results");
            final List<SoftReference<OperationDelivery<?>>> oldResults = new ArrayList<>(
                    mStoredResults);
            mStoredResults.clear();
            for (SoftReference<OperationDelivery<?>> result : oldResults) {
                final OperationDelivery<?> delivery = result.get();
                if (delivery != null) {
                    deliverResult(delivery);
                }
            }
            logd("no more undelivered results");
        } else {
            logd("has no undelivered results");
        }
    }

public
final
void
onResume
(
@
NonNull
final
Object
serviceListener
)
{
logd
(
"onResume"
)
;
mServiceListener
=
serviceListener
;
mState
=
State
.
RESUMED
;
if
(
!
mStoredResults
.
isEmpty
(
)
)
{
logd
(
"has undelivered results"
)
;
final
List
<
SoftReference
<
OperationDelivery
<
>
>
>
oldResults
=
new
ArrayList
<>
(
mStoredResults
)
;
mStoredResults
.
clear
(
)
;
for
(
SoftReference
<
OperationDelivery
<
>
>
result
:
oldResults
)
{
final
OperationDelivery
<
>
delivery
=
result
.
get
(
)
;
if
(
delivery
!=
)
{
deliverResult
(
delivery
)
;
}
}
logd
(
"no more undelivered results"
)
;
}
else
{
logd
(
"has no undelivered results"
)
;
}
}

This method must be called by a bound GUI element when it passes its own onResume state.

@param serviceListener a GUI element that wants to connect to Chronos via the
ServiceConnector. In fact, it could be any object, no matter it is an
Activity, Fragment, or something else, but Chronos is designed to work
with GUI elements.
@see #onPause()

This method must be called by a bound GUI element when it passes its own onResume state .


@SuppressWarnings("unused")
    public final void onEventMainThread(@Nullable final ChronosOperationResult<?> operationResult) {
        if (operationResult == null) {
            //somehow the bus delivered us a null object, it should be ignored
            return;
        }
        final int operationId = operationResult.getId();

        DeliveryMode deliveryMode = null;

        if (!RunningOperationStorage.getInstance().isOperationCancelled(operationId)) {
            if (mTaggedRequests.containsValue(operationId)) {
                deliveryMode = DeliveryMode.NORMAL;
            } else if (mUntaggedRequests.contains(operationResult.getId())) {
                mUntaggedRequests.remove(Integer.valueOf(operationId));
                deliveryMode = DeliveryMode.NORMAL;
            } else if (operationResult.isBroadcast()) {
                deliveryMode = DeliveryMode.BROADCAST;
            }
        }

        if (deliveryMode != null) {
            final OperationDelivery<?> operationDelivery = new OperationDelivery<>(operationResult,
                    deliveryMode);
            logd("operation delivery: " + operationDelivery);
            onOperationFinished(operationDelivery);
        }
    }

This method is used to listening to results stream and operate with them. User should never
call this method manually.

@param operationResult the result to process

This method is used to listening to results stream and operate with them . User should never call this method manually .


public final int invoke(@NonNull final ChronosOperation<?> operation,
            final boolean broadcastResult) {
        logd("invoking untagged operation");
        final int id = ChronosService.getInstance().runAsync(operation, broadcastResult);
        mUntaggedRequests.add(id);
        return id;
    }

public
final
int
invoke
(
@
NonNull
final
ChronosOperation
<
>
operation
,
final
boolean
broadcastResult
)
{
logd
(
"invoking untagged operation"
)
;
final
int
id
=
ChronosService
.
getInstance
(
)
.
runAsync
(
operation
,
broadcastResult
)
;
mUntaggedRequests
.
add
(
id
)
;
return
id
;
}

Launches an operation in background thread.

@param operation       an operation to be launched
@param broadcastResult {@code true} if the result should be broadcasted, {@code false}
otherwise
@return a unique launch id
@see #invoke(ChronosOperation, String, boolean)
@see #cancel(int, boolean)

Launches an operation in background thread .


public final int invoke(@NonNull final ChronosOperation<?> operation, @NonNull final String tag,
            final boolean broadcastResult) {
        logd("invoking tagged operation, tag=" + tag);
        final Integer savedId = mTaggedRequests.get(tag);
        if (savedId != null && isRunning(savedId)) {
            logd("operation with tag=" + tag + " is running, do nothing");
            return savedId;
        }

        logd("operation with tag=" + tag + " is not running, start it");
        final int id = ChronosService.getInstance().runAsync(operation, broadcastResult);
        mTaggedRequests.put(tag, id);
        return id;
    }

public
final
int
invoke
(
@
NonNull
final
ChronosOperation
<
>
operation
,
@
NonNull
final
String
tag
,
final
boolean
broadcastResult
)
{
logd
(
"invoking tagged operation, tag="
+
tag
)
;
final
Integer
savedId
=
mTaggedRequests
.
get
(
tag
)
;
if
(
savedId
!=
&&
isRunning
(
savedId
)
)
{
logd
(
"operation with tag="
+
tag
+
" is running, do nothing"
)
;
return
savedId
;
}
logd
(
"operation with tag="
+
tag
+
" is not running, start it"
)
;
final
int
id
=
ChronosService
.
getInstance
(
)
.
runAsync
(
operation
,
broadcastResult
)
;
mTaggedRequests
.
put
(
tag
,
id
)
;
return
id
;
}

Launches an operation in background thread. If operation, launched with the same tag from the
same ServiceConnector is running, new operation launch will not be triggered.

@param operation       an operation to be launched
@param tag             a pre-cache key of the launch
@param broadcastResult {@code true} if the result should be broadcasted, {@code false}
otherwise
@return a launch id, may be the same with the previous call of the method, if the operation
with the same tag is still running
@see #invoke(ChronosOperation, boolean)
@see #cancel(int, boolean)
@see #cancel(String, boolean)

Launches an operation in background thread . If operation launched with the same tag from the same ServiceConnector is running new operation launch will not be triggered .


public final boolean cancel(final int id, final boolean mayInterrupt) {
        //noinspection SimplifiableIfStatement
        if (mUntaggedRequests.contains(id) || mTaggedRequests.containsValue(id)) {
            return RunningOperationStorage.getInstance().cancel(id, mayInterrupt);
        } else {
            return false;
        }
    }

public
final
boolean
cancel
(
final
int
id
,
final
boolean
mayInterrupt
)
{
//noinspection SimplifiableIfStatement
if
(
mUntaggedRequests
.
contains
(
id
)
||
mTaggedRequests
.
containsValue
(
id
)
)
{
return
RunningOperationStorage
.
getInstance
(
)
.
cancel
(
id
,
mayInterrupt
)
;
}
else
{
return
false
;
}
}

Cancels operation launch by its id. May not physically kill the background thread, but it is
guaranteed that the result of the operation will not be delivered to any ServiceConnector.

@param id           an id of the operation launch that should be cancelled
@param mayInterrupt {@code true} if threads executing operations task should be interrupted;
otherwise, in-progress tasks are allowed to complete
@return {@code false} if the task could not be cancelled, typically because it has already
completed normally; {@code true} otherwise
@see #invoke(ChronosOperation, boolean)
@see #invoke(ChronosOperation, String, boolean)
@see #cancel(String, boolean)
@see Chronos#cancelAll(boolean)

Cancels operation launch by its id . May not physically kill the background thread but it is guaranteed that the result of the operation will not be delivered to any ServiceConnector .


public final boolean cancel(@NonNull final String tag, final boolean mayInterrupt) {
        final Integer id = mTaggedRequests.get(tag);
        //noinspection SimplifiableIfStatement
        if (id != null) {
            return cancel(id, mayInterrupt);
        } else {
            return false;
        }
    }

public
final
boolean
cancel
(
@
NonNull
final
String
tag
,
final
boolean
mayInterrupt
)
{
final
Integer
id
=
mTaggedRequests
.
get
(
tag
)
;
//noinspection SimplifiableIfStatement
if
(
id
!=
)
{
return
cancel
(
id
,
mayInterrupt
)
;
}
else
{
return
false
;
}
}

Cancels operation launch by its tag. May not physically kill the background thread, but it is
guaranteed that the result of the operation will not be delivered to any ServiceConnector.

@param tag          a pre-cache key of the operation launch that should be cancelled
@param mayInterrupt {@code true} if threads executing operations task should be interrupted;
otherwise, in-progress tasks are allowed to complete
@return {@code false} if the task could not be cancelled, typically because it has already
completed normally or there is no running operation with a given tag; {@code true} otherwise
@see #invoke(ChronosOperation, boolean)
@see #invoke(ChronosOperation, String, boolean)
@see #cancel(int, boolean)
@see Chronos#cancelAll(boolean)

Cancels operation launch by its tag . May not physically kill the background thread but it is guaranteed that the result of the operation will not be delivered to any ServiceConnector .


@Contract(pure = true)
    public final boolean isRunning(@NonNull final String tag) {
        final Integer id = mTaggedRequests.get(tag);
        //noinspection SimplifiableIfStatement
        if (id != null) {
            return isRunning(id);
        } else {
            return false;
        }
    }

@
Contract
(
pure
=
true
)
public
final
boolean
isRunning
(
@
NonNull
final
String
tag
)
{
final
Integer
id
=
mTaggedRequests
.
get
(
tag
)
;
//noinspection SimplifiableIfStatement
if
(
id
!=
)
{
return
isRunning
(
id
)
;
}
else
{
return
false
;
}
}

Checks if an operation with given launch tag is running.

@param tag a pre-cache key of the operation launch
@return {@code true} if the operation is running, {@code false} if it is not running, or
there was no operation launch with the tag at all

Checks if an operation with given launch tag is running .


private void onOperationFinished(@NonNull final OperationDelivery<?> operationResult) {
        logd("onOperationFinished " + operationResult);
        switch (mState) {
            case PAUSED:
                storeResult(operationResult);
                break;
            case RESUMED:
                deliverResult(operationResult);
                break;
            default:
                throw new IllegalStateException("Unknown state: " + mState);
        }
    }

private
void
onOperationFinished
(
@
NonNull
final
OperationDelivery
<
>
operationResult
)
{
logd
(
"onOperationFinished "
+
operationResult
)
;
switch
(
mState
)
{
case
PAUSED
:
storeResult
(
operationResult
)
;
break
;
case
RESUMED
:
deliverResult
(
operationResult
)
;
break
;
default
:
throw
new
IllegalStateException
(
"Unknown state: "
+
mState
)
;
}
}

A dispatcher method which decides what to do with an operation result.

@param operationResult an operation result which needs to be dispatched

A dispatcher method which decides what to do with an operation result .


private void storeResult(@NonNull final OperationDelivery<?> operationDelivery) {
        logd("store delivery " + operationDelivery);
        mStoredResults.add(new SoftReference<OperationDelivery<?>>(operationDelivery));
    }

private
void
storeResult
(
@
NonNull
final
OperationDelivery
<
>
operationDelivery
)
{
logd
(
"store delivery "
+
operationDelivery
)
;
mStoredResults
.
add
(
new
SoftReference
<
OperationDelivery
<
>
>
(
operationDelivery
)
)
;
}

Storing an operation result to use it later.

@param operationDelivery an operation result to be stored
@see #deliverResult(OperationDelivery)

Storing an operation result to use it later .


private void deliverResult(@NonNull final OperationDelivery<?> operationDelivery) {
        logd("deliver delivery " + operationDelivery);
        switch (operationDelivery.getDeliveryMode()) {
            case NORMAL:
                deliverResult(operationDelivery.getResult(), Chronos.OWN_CALLBACK_METHOD_NAME,
                        true);
                break;
            case BROADCAST:
                deliverResult(operationDelivery.getResult(), Chronos.BROADCAST_CALLBACK_METHOD_NAME,
                        false);
                break;
            default:
                break;
        }
    }

private
void
deliverResult
(
@
NonNull
final
OperationDelivery
<
>
operationDelivery
)
{
logd
(
"deliver delivery "
+
operationDelivery
)
;
switch
(
operationDelivery
.
getDeliveryMode
(
)
)
{
case
NORMAL
:
deliverResult
(
operationDelivery
.
getResult
(
)
,
Chronos
.
OWN_CALLBACK_METHOD_NAME
,
true
)
;
break
;
case
BROADCAST
:
deliverResult
(
operationDelivery
.
getResult
(
)
,
Chronos
.
BROADCAST_CALLBACK_METHOD_NAME
,
false
)
;
break
;
default
:
break
;
}
}

Delivers an operation result to the bound client.

@param operationDelivery an operation result to be delivered
@see #onResume(Object)
@see #storeResult(OperationDelivery)

Delivers an operation result to the bound client .


@SuppressWarnings("TryWithIdenticalCatches")
    private void deliverResult(@NonNull final ChronosOperationResult<?> operationResult,
            @NonNull final String methodName, final boolean warnIfNoCallback) {
        final Class listenerClass = mServiceListener.getClass();
        final Method[] listenerMethods = listenerClass.getMethods();

        Method callbackMethod = null;

        final Class resultClass = operationResult.getClass();
        for (Method method : listenerMethods) {
            if (isCallback(method, resultClass, methodName)) {
                callbackMethod = method;
                try {
                    callbackMethod.invoke(mServiceListener, operationResult);
                } catch (IllegalAccessException e) {
                    Log.w(LOG_TAG, Log.getStackTraceString(e));
                } catch (InvocationTargetException e) {
                    Log.w(LOG_TAG, Log.getStackTraceString(e));
                }
            }
        }

        if (warnIfNoCallback && callbackMethod == null) {
            Log.w(LOG_TAG,
                    "Operation result (id=" + operationResult.getId() + "; class=" + operationResult
                            .getClass().getName() + ") was obtained, but there is no method in "
                            + mServiceListener + " to get it"
            );
            Log.w(LOG_TAG, "Method should look like");
            Log.w(LOG_TAG,
                    "public void " + methodName + "(" + resultClass.getName()
                            + " result) {}"
            );
        }
    }

Call bound client methods to pass an operation result.

@param operationResult  an operation result to be delivered
@param methodName       a name of a method that will be called
@param warnIfNoCallback {@code true} if a warning message should be posted to LogCat if there
is no suitable method in the bound client; {@code false} otherwise

Call bound client methods to pass an operation result .


private void logd(@NonNull final String message) {
        if (LOG_ENABLED) {
            Log.d(LOG_TAG, this.toString() + " " + message);
        }
    }

private
void
logd
(
@
NonNull
final
String
message
)
{
if
(
LOG_ENABLED
)
{
Log
.
d
(
LOG_TAG
,
this
.
toString
(
)
+
" "
+
message
)
;
}
}

Logs debug message.

@param message сообщение для вывода в лог.
@see #LOG_ENABLED


private synchronized boolean cancel(final int id, final boolean mayInterrupt,
            final boolean removeOperation) {
        final RunningOperation runningOperation = mRunningOperations.get(id);
        if (runningOperation != null) {
            if (removeOperation) {
                mRunningOperations.remove(id);
            }
            mCancelledOperations.add(id);
            return runningOperation.cancel(mayInterrupt);
        } else {
            return false;
        }
    }

private synchronized boolean cancel ( final int id , final boolean mayInterrupt , final boolean removeOperation ) { final RunningOperation runningOperation = mRunningOperations . get ( id ) ; if ( runningOperation != null ) { if ( removeOperation ) { mRunningOperations . remove ( id ) ; } mCancelledOperations . add ( id ) ; return runningOperation . cancel ( mayInterrupt ) ; } else { return false ; } }

Cancels running operation.

@param id              the unique id of operations' launch
@param mayInterrupt    {@code true} if thread executing operation task should be interrupted;
otherwise, in-progress tasks are allowed to complete
@param removeOperation {@code true} if the operation should be marked as removed
@return {@code false} if the task could not be cancelled, typically because it has already
completed normally; {@code true} otherwise


synchronized final void operationStarted(final int id, @NonNull final ChronosOperation<?> operation,
            @NonNull final Future<?> future
    ) {
        mRunningOperations.put(id, new RunningOperation(operation, future));
    }

synchronized final void operationStarted ( final int id , @ NonNull final ChronosOperation < ? > operation , @ NonNull final Future < ? > future ) { mRunningOperations . put ( id , new RunningOperation ( operation , future ) ) ; }

Stores the future as a running operation with a given runs' id.

@param id     the unique id of an operation launch
@param future the object that represents a running operation

Stores the future as a running operation with a given runs id .


synchronized final void cancelAll(final boolean mayInterrupt) {
        for (final Integer key : mRunningOperations.keySet()) {
            cancel(key, mayInterrupt, false);
        }

        mRunningOperations.clear();
    }

synchronized final void cancelAll ( final boolean mayInterrupt ) { for ( final Integer key : mRunningOperations . keySet ( ) ) { cancel ( key , mayInterrupt , false ) ; } mRunningOperations . clear ( ) ; }

Cancels all running operations.

@param mayInterrupt {@code true} if threads executing operations task should be interrupted;
otherwise, in-progress tasks are allowed to complete


@Contract(pure = true)
    synchronized final boolean isOperationCancelled(final int id) {
        return mCancelledOperations.contains(Integer.valueOf(id));
    }

@ Contract ( pure = true ) synchronized final boolean isOperationCancelled ( final int id ) { return mCancelledOperations . contains ( Integer . valueOf ( id ) ) ; }

Checks if operation launch with given id was cancelled.

@param id the unique id of operations' launch
@return {@code true} if the operation was cancelled, {@code false} otherwise

Checks if operation launch with given id was cancelled .


private static <Output> void silentRun(@NonNull final ChronosOperation<Output> operation,
            @NonNull final ChronosOperationResult<Output> operationResult) {
        try {
            final Output output = operation.run();
            operationResult.setOutput(output);
        } catch (Exception e) {
            operationResult.setException(e);
        }
    }

private static < Output > void silentRun ( @ NonNull final ChronosOperation < Output > operation , @ NonNull final ChronosOperationResult < Output > operationResult ) { try { final Output output = operation . run ( ) ; operationResult . setOutput ( output ) ; } catch ( Exception e ) { operationResult . setException ( e ) ; } }

Runs operation, handling all the exceptions that may ne thrown while running.

@param operation       an operation to be executed
@param operationResult an empty result object to be filled with business-logic content
@param <Output>        class of the result, returned by the Operations' {@code run} method

Runs operation handling all the exceptions that may ne thrown while running .


@NonNull
    @Contract(pure = true)
    private <Output> ChronosOperationResult<Output> createEmptyResult(
            @NonNull final ChronosOperation<Output> operation, final boolean broadcastResult) {
        final ChronosOperationResult<Output> operationResult;
        final Class<? extends ChronosOperationResult<Output>> resultClass = operation
                .getResultClass();
        try {
            operationResult = resultClass.newInstance();
        } catch (InstantiationException e) {
            throw new RuntimeException("Can't create a new instance of " + resultClass.getName());
        } catch (IllegalAccessException e) {
            throw new RuntimeException(resultClass.getName() + " constructor is not accessible");
        }
        operationResult.setId(mLastOperationId.incrementAndGet());
        operationResult.setOperation(operation);
        operationResult.setBroadcast(broadcastResult);

        return operationResult;
    }

@
NonNull
@
Contract
(
pure
=
true
)
private
<
Output
>
ChronosOperationResult
<
Output
>
createEmptyResult
(
@
NonNull
final
ChronosOperation
<
Output
>
operation
,
final
boolean
broadcastResult
)
{
final
ChronosOperationResult
<
Output
>
operationResult
;
final
Class
<
extends
ChronosOperationResult
<
Output
>
>
resultClass
=
operation
.
getResultClass
(
)
;
try
{
operationResult
=
resultClass
.
newInstance
(
)
;
}
catch
(
InstantiationException
e
)
{
throw
new
RuntimeException
(
"Can't create a new instance of "
+
resultClass
.
getName
(
)
)
;
}
catch
(
IllegalAccessException
e
)
{
throw
new
RuntimeException
(
resultClass
.
getName
(
)
+
" constructor is not accessible"
)
;
}
operationResult
.
setId
(
mLastOperationId
.
incrementAndGet
(
)
)
;
operationResult
.
setOperation
(
operation
)
;
operationResult
.
setBroadcast
(
broadcastResult
)
;
return
operationResult
;
}

Creates a template object for storing operations' run result.

@param operation       an operation to create a result for
@param broadcastResult {@code true} if the result should be broadcasted, {@code false}
otherwise
@param <Output>        class of the result, returned by the Operations' {@code run} method
@return an empty OperationResult without business-logic content

Creates a template object for storing operations run result .


final <Output> int runAsync(@NonNull final ChronosOperation<Output> operation,
            final boolean broadcastResult) {
        final ChronosOperationResult<Output> result = createEmptyResult(operation, broadcastResult);
        final int id = result.getId();

        synchronized (ChronosService.this) {
            RunningOperationStorage.getInstance().operationStarted(id, operation,
                    mExecutorService.submit(new Runnable() {
                        @Override
                        public void run() {
                            silentRun(operation, result);
                            mEventBus.post(result);
                            synchronized (ChronosService.this) {
                                RunningOperationStorage.getInstance().operationFinished(id);
                            }
                        }
                    }));
        }
        return id;
    }

final < Output > int runAsync ( @ NonNull final ChronosOperation < Output > operation , final boolean broadcastResult ) { final ChronosOperationResult < Output > result = createEmptyResult ( operation , broadcastResult ) ; final int id = result . getId ( ) ; synchronized ( ChronosService . this ) { RunningOperationStorage . getInstance ( ) . operationStarted ( id , operation , mExecutorService . submit ( new Runnable ( ) { @ Override public void run ( ) { silentRun ( operation , result ) ; mEventBus . post ( result ) ; synchronized ( ChronosService . this ) { RunningOperationStorage . getInstance ( ) . operationFinished ( id ) ; } } } ) ) ; } return id ; }

Runs operation in background.

@param operation       an operation to be executed
@param <Output>        class of the result, returned by the Operations' {@code run} method
@param broadcastResult {@code true} if the result should be broadcasted, {@code false}
otherwise
@return the unique id of the launch


@NonNull
    final <Output> ChronosOperationResult<Output> runSync(
            @NonNull final ChronosOperation<Output> operation, final boolean broadcastResult) {
        final ChronosOperationResult<Output> result = createEmptyResult(operation, broadcastResult);

        silentRun(operation, result);
        mEventBus.post(result);

        return result;
    }

@ NonNull final < Output > ChronosOperationResult < Output > runSync ( @ NonNull final ChronosOperation < Output > operation , final boolean broadcastResult ) { final ChronosOperationResult < Output > result = createEmptyResult ( operation , broadcastResult ) ; silentRun ( operation , result ) ; mEventBus . post ( result ) ; return result ; }

Runs operation in the same thread.

@param operation       an operation to be executed
@param <Output>        class of the result, returned by the Operations' {@code run} method
@param broadcastResult {@code true} if the result should be broadcasted, {@code false}
otherwise
@return operations' result


public void onOperationFinished(final SimpleOperation.Result result) {
        if (result.isSuccessful()) {
            mData = result.getOutput();
            showData();
        } else {
            mTextOutput.setText(result.getErrorMessage());
        }
    }

public void onOperationFinished ( final SimpleOperation . Result result ) { if ( result . isSuccessful ( ) ) { mData = result . getOutput ( ) ; showData ( ) ; } else { mTextOutput . setText ( result . getErrorMessage ( ) ) ; } }


protected static void main(Main main, String... args) {
    main.getInjector().getInstance(main.getMainClass()).doMain(args);
  }

protected static void main ( Main main , String ... args ) { main . getInjector ( ) . getInstance ( main . getMainClass ( ) ) . doMain ( args ) ; }

Subclass specific entry point.

@param main The actual main class implementation to use.
@param args The command line arguments.


protected Module[] getModules() {
    Module[] modules = { new WireModule(new EventHandlerModule(),
        new SpaceModule(new URLClassSpace(Main.class.getClassLoader()))) };
    return modules;
  }

protected Module [ ] getModules ( ) { Module [ ] modules = { new WireModule ( new EventHandlerModule ( ) , new SpaceModule ( new URLClassSpace ( Main . class . getClassLoader ( ) ) ) ) } ; return modules ; }

Get the Guice modules to be used in injecting dependencies.

@return The modules.

Get the Guice modules to be used in injecting dependencies .


protected void doMain(String... args) {
    properties = new MergeableProperties();
    properties.putAll(System.getProperties());
    for (String arg : args) {
      properties.merge(arg);
    }
    // Read event handling configuration
    Map<String, List<EventHandler>> eventHandlers = new LinkedHashMap<>();
    MergeableProperties allProperties = properties.getPrefixed("willow-event-handler.handlers");
    int i = 0;
    while (true) {
      MergeableProperties handlerProperties = allProperties.getPrefixed("[" + i++ + "]");
      if (handlerProperties.isEmpty()) {
        break;
      }
      String handlerClassName = handlerProperties.getProperty("handler");
      String eventClassName = handlerProperties.getProperty("event");
      try {
        EventHandler eventHandler = (EventHandler) injector.getInstance(Class.forName(handlerClassName));
        MergeableProperties beanProperties = handlerProperties.getPrefixed("properties");
        for (String propertyName : beanProperties.stringPropertyNames()) {
          String propertyValue = beanProperties.getProperty(propertyName);
          BeanUtils.setProperty(eventHandler, propertyName, propertyValue);
        }
        List<EventHandler> eventHandlersForType = eventHandlers.get(eventClassName);
        if (eventHandlersForType == null) {
          eventHandlersForType = new ArrayList<>();
          eventHandlers.put(eventClassName, eventHandlersForType);
        }
        eventHandlersForType.add(eventHandler);
      } catch (ClassNotFoundException | IllegalAccessException | InvocationTargetException e) {
        logger.log(Level.SEVERE, "Error instantiating handler", e);
        System.exit(1);
      }
    }

    if (eventHandlers .isEmpty()) {
      logger.info("No event handlers configured. Exiting.");
      System.exit(0);
    }

    Runtime.getRuntime().addShutdownHook(new Thread() {
      @Override
      public void run() {
        Main.this.stop();
      }
    });

    // Start polling events
    String uri = properties.getProperty("willow-event-handler.eventsUri");
    try {
      logger.info("Initializing event poller");
      eventPoller.initialize(eventHandlers, new URI(uri));
    } catch (URISyntaxException e) {
      logger.log(Level.SEVERE, "Invalid URI: " + uri, e);
      System.exit(1);
    }
  }

Actual main implementation.

@param args The command line arguments. These should be URLs that point to the configuration file(s).


private void checkLine() {
    String endStr = new String(buf, count - LINE_SEPERATOR.length(), LINE_SEPERATOR.length(), charset);
    if (LINE_SEPERATOR.equals(endStr)) {
      flush();
    }
  }

private void checkLine ( ) { String endStr = new String ( buf , count - LINE_SEPERATOR . length ( ) , LINE_SEPERATOR . length ( ) , charset ) ; if ( LINE_SEPERATOR . equals ( endStr ) ) { flush ( ) ; } }

Checks if the end of the buffer contains a newline and if so, flushes the stream

Checks if the end of the buffer contains a newline and if so flushes the stream


public void initialize(Map<String, List<EventHandler>> eventHandlers, URI uri) {
    this.eventHandlers = eventHandlers;
    EventListener listener = new EventListener(uri);
    executorService.submit(listener);
    logger.fine("Started event listener");
  }

public
void
initialize
(
Map
<
String
,
List
<
EventHandler
>
>
eventHandlers
,
URI
uri
)
{
this
.
eventHandlers
=
eventHandlers
;
EventListener
listener
=
new
EventListener
(
uri
)
;
executorService
.
submit
(
listener
)
;
logger
.
fine
(
"Started event listener"
)
;
}

Initialize the event poller.

@param eventHandlers The handlers for different event types.
@param uri The web socket connection URI.


protected MBeanServerConnection getMBeanServerConnection(String childName) {
    MBeanConnectionInfo connInfo = connections.get(childName);
    if (connInfo == null) {
      connInfo = new MBeanConnectionInfo();
      connections.put(childName, connInfo);
    }
    long childPid = main.getFirstJavaChildPid(childName);
    if (childPid > 0 && childPid != connInfo.childPid && connInfo.connector != null) {
      try {
        connInfo.connector.close();
      } catch (IOException e) {
        logger.log(Level.FINE, "Failed to close JMXConnector", e);
      }
      connInfo.connector = null;
      connInfo.server = null;
    }
    if (childPid > 0) {
      try {
        if (connInfo.connector == null) {
          connInfo.connector = DeployerControl.getJMXConnector(childPid);
        }
        if (connInfo.connector != null && connInfo.server == null) {
          connInfo.server = connInfo.connector.getMBeanServerConnection();
          connInfo.childPid = childPid;
        }
      } catch (IOException e) {
        logger.log(Level.FINE, "Failed to get JMX connection", e);
        try {
          connInfo.connector.close();
        } catch (Exception e2) {
          logger.log(Level.FINE, "Failed to close JMXConnector", e2);
        }
        connInfo.connector = null;
        connInfo.server = null;
      }
    }
    return connInfo.server;
  }

protected
MBeanServerConnection
getMBeanServerConnection
(
String
childName
)
{
MBeanConnectionInfo
connInfo
=
connections
.
get
(
childName
)
;
if
(
connInfo
==
)
{
connInfo
=
new
MBeanConnectionInfo
(
)
;
connections
.
put
(
childName
,
connInfo
)
;
}
long
childPid
=
main
.
getFirstJavaChildPid
(
childName
)
;
if
(
childPid
>
0
&&
childPid
!=
connInfo
.
childPid
&&
connInfo
.
connector
!=
)
{
try
{
connInfo
.
connector
.
close
(
)
;
}
catch
(
IOException
e
)
{
logger
.
log
(
Level
.
FINE
,
"Failed to close JMXConnector"
,
e
)
;
}
connInfo
.
connector
=
;
connInfo
.
server
=
;
}
if
(
childPid
>
0
)
{
try
{
if
(
connInfo
.
connector
==
)
{
connInfo
.
connector
=
DeployerControl
.
getJMXConnector
(
childPid
)
;
}
if
(
connInfo
.
connector
!=
&&
connInfo
.
server
==
)
{
connInfo
.
server
=
connInfo
.
connector
.
getMBeanServerConnection
(
)
;
connInfo
.
childPid
=
childPid
;
}
}
catch
(
IOException
e
)
{
logger
.
log
(
Level
.
FINE
,
"Failed to get JMX connection"
,
e
)
;
try
{
connInfo
.
connector
.
close
(
)
;
}
catch
(
Exception
e2
)
{
logger
.
log
(
Level
.
FINE
,
"Failed to close JMXConnector"
,
e2
)
;
}
connInfo
.
connector
=
;
connInfo
.
server
=
;
}
}
return
connInfo
.
server
;
}

Return the MBean server connection to the child process.

@return MBean server connection.

Return the MBean server connection to the child process .


protected void closeMBeanServerConnection(String childName) {
    MBeanConnectionInfo connInfo = connections.get(childName);
    if (connInfo != null && connInfo.connector != null) {
      try {
        connInfo.connector.close();
      } catch (IOException e) {
        logger.log(Level.FINE, "Failed to close JMXConnector", e);
      }
      connInfo.connector = null;
    }
  }

protected
void
closeMBeanServerConnection
(
String
childName
)
{
MBeanConnectionInfo
connInfo
=
connections
.
get
(
childName
)
;
if
(
connInfo
!=
&&
connInfo
.
connector
!=
)
{
try
{
connInfo
.
connector
.
close
(
)
;
}
catch
(
IOException
e
)
{
logger
.
log
(
Level
.
FINE
,
"Failed to close JMXConnector"
,
e
)
;
}
connInfo
.
connector
=
;
}
}


protected void init(Context context) {
    LayoutInflater.from(context).inflate(R.layout.fake_search_view, this, true);
    wrappedEditText = (EditText) findViewById(R.id.wrapped_search);
    wrappedEditText.addTextChangedListener(this);
    wrappedEditText.setOnEditorActionListener(this);
  }

protected void init ( Context context ) { LayoutInflater . from ( context ) . inflate ( R . layout . fake_search_view , this , true ) ; wrappedEditText = ( EditText ) findViewById ( R . id . wrapped_search ) ; wrappedEditText . addTextChangedListener ( this ) ; wrappedEditText . setOnEditorActionListener ( this ) ; }

Inflate the layout to this FrameLayout wrapper
@param context for inflate views


public static void main(String[] args) throws Throwable {
        try {
            Class<?> initialClass;
            // make it independent - get class name & method from props/manifest
            initialClass = Thread.currentThread().getContextClassLoader().loadClass("kg.apc.cmdtools.PluginsCMD");
            Object instance = initialClass.newInstance();
            Method startup = initialClass.getMethod("processParams", (new String[0]).getClass());
            Object res = startup.invoke(instance, new Object[]{args});
            int rc = (Integer) res;
            if (rc != 0) {
                System.exit(rc);
            }
        } catch (Throwable e) {
            if (e.getCause() != null) {
                System.err.println("ERROR: " + e.getCause().toString());
                System.err.println("*** Problem's technical details go below ***");
                System.err.println("Home directory was detected as: " + jarDirectory);
                throw e.getCause();
            } else {
                System.err.println("Home directory was detected as: " + jarDirectory);
                throw e;
            }
        }
    }

The main program which actually runs JMeter.

@param args the command line arguments

The main program which actually runs JMeter .


private com.github.fge.jsonschema.main.JsonSchema getValidator() throws ProcessingException {
        if (validator == null) {
            synchronized (this) {
                if (validator == null) {
                    ValidationConfigurationBuilder cfgBuilder = ValidationConfiguration.newBuilder();
                    cfgBuilder.addLibrary("http://brutusin.org/json/json-schema-spec", DraftV3Library.get());
                    validator = JsonSchemaFactory.newBuilder().setValidationConfiguration(cfgBuilder.freeze()).freeze().getJsonSchema(getNode());
                }
            }
        }
        return validator;
    }

Lazy intialization of validator instance

@return
@throws ProcessingException


public List<Column> getFindColumnList() {
		List<Column> findColumnList = new ArrayList<Column>();
		List<Column> tempColumnList = new ArrayList<Column>();

		for (int i = 1; i <= this.cardinality; i++) {
			if (this.columns.get(i).referenceTable != null) {
				tempColumnList = this.columns.get(i).referenceTable.getFindColumnList();
				for (int j = 0; j < tempColumnList.size(); j++) {
					Column column = new Column();
					column.name = columns.get(i).name.replace("_ID", "_").replace("_id", "_") + tempColumnList.get(j).name;
					column.dataType = tempColumnList.get(j).dataType;
					column.nullable = this.columns.get(i).nullable;
					findColumnList.add(column);
				}
			} else {
				Column column = new Column();
				column.name = columns.get(i).name;
				column.dataType = columns.get(i).dataType;
				column.nullable = this.columns.get(i).nullable;
				findColumnList.add(column);
			}
		}

		return findColumnList;

	}

public List < Column > getFindColumnList ( ) { List < Column > findColumnList = new ArrayList < Column > ( ) ; List < Column > tempColumnList = new ArrayList < Column > ( ) ; for ( int i = 1 ; i <= this . cardinality ; i ++ ) { if ( this . columns . get ( i ) . referenceTable != null ) { tempColumnList = this . columns . get ( i ) . referenceTable . getFindColumnList ( ) ; for ( int j = 0 ; j < tempColumnList . size ( ) ; j ++ ) { Column column = new Column ( ) ; column . name = columns . get ( i ) . name . replace ( "_ID" , "_" ) . replace ( "_id" , "_" ) + tempColumnList . get ( j ) . name ; column . dataType = tempColumnList . get ( j ) . dataType ; column . nullable = this . columns . get ( i ) . nullable ; findColumnList . add ( column ) ; } } else { Column column = new Column ( ) ; column . name = columns . get ( i ) . name ; column . dataType = columns . get ( i ) . dataType ; column . nullable = this . columns . get ( i ) . nullable ; findColumnList . add ( column ) ; } } return findColumnList ; }

get the list of arguments used in find stored procedure

@return


public List<Column> getInsertColumnList() {
		List<Column> result = new ArrayList<>();
		List<Column> tempColumnList = new ArrayList<>();

		for (Column currentColumn:this.columns) {
			if (currentColumn.referenceTable != null) {
				tempColumnList = currentColumn.referenceTable.getFindColumnList();
				for (Column tempColumn : tempColumnList) {
					Column column = new Column();
					column.name = currentColumn.name.replace("_ID", "_").replace("_id", "_") + tempColumn.name;
					column.dataType = tempColumn.dataType;
					column.nullable = currentColumn.nullable;
					result.add(column);
				}
			} else {
				Column column = new Column();
				column.name = currentColumn.name;
				column.dataType = currentColumn.dataType;
				column.nullable = currentColumn.nullable;
				result.add(column);
			}
		}

		return result;

	}

public List < Column > getInsertColumnList ( ) { List < Column > result = new ArrayList <> ( ) ; List < Column > tempColumnList = new ArrayList <> ( ) ; for ( Column currentColumn : this . columns ) { if ( currentColumn . referenceTable != null ) { tempColumnList = currentColumn . referenceTable . getFindColumnList ( ) ; for ( Column tempColumn : tempColumnList ) { Column column = new Column ( ) ; column . name = currentColumn . name . replace ( "_ID" , "_" ) . replace ( "_id" , "_" ) + tempColumn . name ; column . dataType = tempColumn . dataType ; column . nullable = currentColumn . nullable ; result . add ( column ) ; } } else { Column column = new Column ( ) ; column . name = currentColumn . name ; column . dataType = currentColumn . dataType ; column . nullable = currentColumn . nullable ; result . add ( column ) ; } } return result ; }

get the list of arguments used in insert by code stored procedure

@return


@XmlTransient
	public List<PackageMetaData> getAllPackages() {
		List<PackageMetaData> result = new ArrayList<>();

		if (packages != null) {
			for (PackageMetaData pack : packages) {
				result.addAll(getPackages(pack));
			}
		}
		return result;
	}

@ XmlTransient public List < PackageMetaData > getAllPackages ( ) { List < PackageMetaData > result = new ArrayList <> ( ) ; if ( packages != null ) { for ( PackageMetaData pack : packages ) { result . addAll ( getPackages ( pack ) ) ; } } return result ; }

recursive method to get all packages including children packages


private final String getNotOverridableContent() throws IOException {

		if (Files.exists(filePath)) {
			List<String> lines = Files.readAllLines(filePath,
					fileType.getEncoding());
			boolean isNotOverridable = false;
			StringWriter notOverridableContentWriter = new StringWriter();
			for (String line : lines) {
				if (line.contains(fileType.getSpecificCodeStartMark())) {
					isNotOverridable = true;
				} else if (line.contains(fileType.getSpecificCodeEndMark())) {
					isNotOverridable = false;
				} else {
					if (isNotOverridable) {
						notOverridableContentWriter.append(line + SKIP_LINE);
					}
				}
			}
			return notOverridableContentWriter.toString();
		}
		return "";
	}

private final String getNotOverridableContent ( ) throws IOException { if ( Files . exists ( filePath ) ) { List < String > lines = Files . readAllLines ( filePath , fileType . getEncoding ( ) ) ; boolean isNotOverridable = false ; StringWriter notOverridableContentWriter = new StringWriter ( ) ; for ( String line : lines ) { if ( line . contains ( fileType . getSpecificCodeStartMark ( ) ) ) { isNotOverridable = true ; } else if ( line . contains ( fileType . getSpecificCodeEndMark ( ) ) ) { isNotOverridable = false ; } else { if ( isNotOverridable ) { notOverridableContentWriter . append ( line + SKIP_LINE ) ; } } } return notOverridableContentWriter . toString ( ) ; } return "" ; }

extract non generated content from a file to keep it after next generation
@return
@throws IOException


protected final void writeNotOverridableContent() throws IOException {

		String content = getNotOverridableContent();

		writeLine(fileType.getSpecificCodeStartMark());
		write(content);
		writeLine(fileType.getSpecificCodeEndMark());
	}

protected final void writeNotOverridableContent ( ) throws IOException { String content = getNotOverridableContent ( ) ; writeLine ( fileType . getSpecificCodeStartMark ( ) ) ; write ( content ) ; writeLine ( fileType . getSpecificCodeEndMark ( ) ) ; }

appends non generated content to be kept at next generation
@throws IOException


public Table findTable(String tableName) {

		if (tableName == null) {
			return null;
		}
		if (tableName.isEmpty()) {
			return null;
		}
		for (Package myPackage : this.packages) {
			for (Table table : myPackage.tables) {
				if (table.originalName.equals(tableName)) {
					return table;
				}
			}
		}
		throw new TableNotFoundException("Invalid table reference : "
				+ tableName);
	}

public
Table
findTable
(
String
tableName
)
{
if
(
tableName
==
)
{
return
;
}
if
(
tableName
.
isEmpty
(
)
)
{
return
;
}
for
(
Package
myPackage
:
this
.
packages
)
{
for
(
Table
table
:
myPackage
.
tables
)
{
if
(
table
.
originalName
.
equals
(
tableName
)
)
{
return
table
;
}
}
}
throw
new
TableNotFoundException
(
"Invalid table reference : "
+
tableName
)
;
}

run through all the tables until it is found
@param tableName
@return
@throws TableNotFoundException if no table with the corresponding name is found


public Bean findBean(String tableOriginalName) {
		for (Package myPackage : this.packages) {
			for (Bean bean : myPackage.beans) {
				if (bean.table.originalName.equals(tableOriginalName)) {
					return bean;
				}
			}
		}
		throw new BeanNotFoundException("invalid table reference : " + tableOriginalName);
	}

public
Bean
findBean
(
String
tableOriginalName
)
{
for
(
Package
myPackage
:
this
.
packages
)
{
for
(
Bean
bean
:
myPackage
.
beans
)
{
if
(
bean
.
table
.
originalName
.
equals
(
tableOriginalName
)
)
{
return
bean
;
}
}
}
throw
new
BeanNotFoundException
(
"invalid table reference : "
+
tableOriginalName
)
;
}

run through all the beans until it is found
@param tableOriginalName the original table name
@return
@throws BeanNotFoundException if no bean which associated table has the corresponding name


public List<ViewProperty> getReferenceProperties(Bean bean) {
		List<ViewProperty> result = new ArrayList<>();

		for (int i = 0; i < bean.cardinality; i++) {
			Property property = bean.properties.get(i);
			result.addAll(property.viewProperties);
		}

		return result;

	}

public List < ViewProperty > getReferenceProperties ( Bean bean ) { List < ViewProperty > result = new ArrayList <> ( ) ; for ( int i = 0 ; i < bean . cardinality ; i ++ ) { Property property = bean . properties . get ( i ) ; result . addAll ( property . viewProperties ) ; } return result ; }

get the list of properties that will be used in bean views to show
references to other beans

@return


private List<ViewProperty> getVisibleProperties(OneToMany oneToMany) {

		return getViewPropertiesExcludingField(oneToMany.referenceBean, oneToMany.referenceProperty.name);
	}

private List < ViewProperty > getVisibleProperties ( OneToMany oneToMany ) { return getViewPropertiesExcludingField ( oneToMany . referenceBean , oneToMany . referenceProperty . name ) ; }

get the list of properties that will be available in a basic view bean

@return


public void update(Versionable target, Versionable source) {
        target.setDirty(source.getDirty());
        target.setMajorVersion(source.getMajorVersion());
        target.setMidVersion(source.getMidVersion());
        target.setMinorVersion(source.getMinorVersion());
        target.setModifierId(source.getModifierId());
        target.setReason(source.getReason());
        target.setModificationTime(source.getModificationTime());
        target.setHistoryList(source.getHistoryList());
        try {
            target.updateHistory();
        }
        catch (Exception ex) {
            LOG.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
        }
    }

public void update ( Versionable target , Versionable source ) { target . setDirty ( source . getDirty ( ) ) ; target . setMajorVersion ( source . getMajorVersion ( ) ) ; target . setMidVersion ( source . getMidVersion ( ) ) ; target . setMinorVersion ( source . getMinorVersion ( ) ) ; target . setModifierId ( source . getModifierId ( ) ) ; target . setReason ( source . getReason ( ) ) ; target . setModificationTime ( source . getModificationTime ( ) ) ; target . setHistoryList ( source . getHistoryList ( ) ) ; try { target . updateHistory ( ) ; } catch ( Exception ex ) { LOG . log ( Level . SEVERE , ex . getLocalizedMessage ( ) , ex ) ; } }

Increase minor is done by default when updating a record.

@param target Target of the update.
@param source Source of the update

Increase minor is done by default when updating a record .


public void addHistory(History history) {
        if (getHistoryList() == null) {
            setHistoryList(new ArrayList<>());
        }
        getHistoryList().add(history);
    }

public void addHistory ( History history ) { if ( getHistoryList ( ) == null ) { setHistoryList ( new ArrayList <> ( ) ) ; } getHistoryList ( ) . add ( history ) ; }

Add history to this entity.

@param history History to add.


@Override
    public void customize(Session session) throws Exception {
        JNDIConnector connector;
        // Initialize session customizer
        DataSource dataSource;
        try {
            Context context = new InitialContext();
            if (null == context) {
                throw new VMException("Context is null");
            }
            connector = (JNDIConnector) session.getLogin().getConnector(); // possible CCE
            // Lookup this new dataSource
            dataSource = (DataSource) context.lookup(JNDI_DATASOURCE_NAME);
            connector.setDataSource(dataSource);
            // Change from COMPOSITE_NAME_LOOKUP to STRING_LOOKUP
            // Note: if both jta and non-jta elements exist this will only change the first one - and may still result in the COMPOSITE_NAME_LOOKUP being set
            // Make sure only jta-data-source is in persistence.xml with no non-jta-data-source property set
            connector.setLookupType(JNDIConnector.STRING_LOOKUP);

            // if you are specifying both JTA and non-JTA in your persistence.xml then set both connectors to be safe
            JNDIConnector writeConnector
                    = (JNDIConnector) session.getLogin().getConnector();
            writeConnector.setLookupType(JNDIConnector.STRING_LOOKUP);
            JNDIConnector readConnector
                    = (JNDIConnector) ((DatabaseLogin) ((ServerSession) session)
                            .getReadConnectionPool().getLogin()).getConnector();
            readConnector.setLookupType(JNDIConnector.STRING_LOOKUP);

            // Set the new connection on the session
            session.getLogin().setConnector(connector);
        }
        catch (Exception e) {
            LOG.log(Level.SEVERE, JNDI_DATASOURCE_NAME, e);
        }
    }

Get a dataSource connection and set it on the session with
lookupType=STRING_LOOKUP

@param session Session
@throws java.lang.Exception If an error occurs.

Get a dataSource connection and set it on the session with lookupType = STRING_LOOKUP


public RequirementSpecNodeServer addSpecNode(String name,
            String description, String scope) throws Exception {
        RequirementSpecNodeServer sns = new RequirementSpecNodeServer(
                new RequirementSpecJpaController(
                        getEntityManagerFactory())
                        .findRequirementSpec(getRequirementSpecPK()),
                name, description, scope);
        sns.write2DB();
        getRequirementSpecNodeList().add(
                new RequirementSpecNodeJpaController(
                        getEntityManagerFactory())
                        .findRequirementSpecNode(sns.getRequirementSpecNodePK()));
        write2DB();
        return sns;
    }

public RequirementSpecNodeServer addSpecNode ( String name , String description , String scope ) throws Exception { RequirementSpecNodeServer sns = new RequirementSpecNodeServer ( new RequirementSpecJpaController ( getEntityManagerFactory ( ) ) . findRequirementSpec ( getRequirementSpecPK ( ) ) , name , description , scope ) ; sns . write2DB ( ) ; getRequirementSpecNodeList ( ) . add ( new RequirementSpecNodeJpaController ( getEntityManagerFactory ( ) ) . findRequirementSpecNode ( sns . getRequirementSpecNodePK ( ) ) ) ; write2DB ( ) ; return sns ; }

Add a node to this spec.

This is equivalent to a section in a document.

Although database might allow a requirement being on different nodes,
this constraint is imposed via software.

@param name name of new node
@param description description of node
@param scope scope of node
@return Created node.
@throws Exception if errors creating the node occur


@Override
    public int write2DB() throws VMException {
        try {
            VmIdJpaController controller = new VmIdJpaController(
                    getEntityManagerFactory());
            VmId vmId;
            if (getId() == null) {
                vmId = new VmId();
                update(vmId, this);
                controller.create(vmId);
                setId(vmId.getId());
            } else {
                vmId = getEntity();
                update(vmId, this);
                controller.edit(vmId);
            }
            update();
            return getId();
        }
        catch (Exception ex) {
            LOG.log(Level.SEVERE, null, ex);
            throw new VMException(ex);
        }
    }

@ Override public int write2DB ( ) throws VMException { try { VmIdJpaController controller = new VmIdJpaController ( getEntityManagerFactory ( ) ) ; VmId vmId ; if ( getId ( ) == null ) { vmId = new VmId ( ) ; update ( vmId , this ) ; controller . create ( vmId ) ; setId ( vmId . getId ( ) ) ; } else { vmId = getEntity ( ) ; update ( vmId , this ) ; controller . edit ( vmId ) ; } update ( ) ; return getId ( ) ; } catch ( Exception ex ) { LOG . log ( Level . SEVERE , null , ex ) ; throw new VMException ( ex ) ; } }


public static IssueType getType(String typename) {
        IssueType result = null;
        for (IssueType type : new IssueTypeJpaController(DataBaseManager
                .getEntityManagerFactory()).findIssueTypeEntities()) {
            if (type.getTypeName().equals(typename)) {
                result = type;
                break;
            }
        }
        return result;
    }

public static IssueType getType ( String typename ) { IssueType result = null ; for ( IssueType type : new IssueTypeJpaController ( DataBaseManager . getEntityManagerFactory ( ) ) . findIssueTypeEntities ( ) ) { if ( type . getTypeName ( ) . equals ( typename ) ) { result = type ; break ; } } return result ; }

Get an Issue Type by name.

@param typename name to search for
@return Issue Type for the specified name or null if not found.


@SuppressWarnings("unchecked")
    public static VmSetting getSetting(String s) {
        PARAMETERS.clear();
        PARAMETERS.put("setting", s);
        result = namedQuery("VmSetting.findBySetting",
                PARAMETERS);
        if (result.isEmpty()) {
            return null;
        } else {
            return (VmSetting) result.get(0);
        }
    }

@ SuppressWarnings ( "unchecked" ) public static VmSetting getSetting ( String s ) { PARAMETERS . clear ( ) ; PARAMETERS . put ( "setting" , s ) ; result = namedQuery ( "VmSetting.findBySetting" , PARAMETERS ) ; if ( result . isEmpty ( ) ) { return null ; } else { return ( VmSetting ) result . get ( 0 ) ; } }

Get setting from database

@param s Setting name to retrieve
@return Setting with the specified name.


public static DataEntry getStringField(String name, String expected,
            boolean matchCase) {
        DataEntry de = new DataEntry();
        DataEntryType det = DataEntryTypeServer.getType("type.string.name");
        de.setEntryName(name);
        de.setDataEntryPropertyList(getDefaultProperties(det));
        de.setDataEntryType(det);
        if (expected != null) {
            getProperty(de, "property.expected.result")
                    .setPropertyValue(expected);
            getProperty(de, "property.match.case")
                    .setPropertyValue(matchCase ? "true" : "false");
        }
        return de;
    }

public static DataEntry getStringField ( String name , String expected , boolean matchCase ) { DataEntry de = new DataEntry ( ) ; DataEntryType det = DataEntryTypeServer . getType ( "type.string.name" ) ; de . setEntryName ( name ) ; de . setDataEntryPropertyList ( getDefaultProperties ( det ) ) ; de . setDataEntryType ( det ) ; if ( expected != null ) { getProperty ( de , "property.expected.result" ) . setPropertyValue ( expected ) ; getProperty ( de , "property.match.case" ) . setPropertyValue ( matchCase ? "true" : "false" ) ; } return de ; }

Create a default string field

@param name Field name
@param expected Expected result.
@param matchCase True if answer must match the case of the expected
result. False otherwise.
@return DataEntry. The entry is not persisted into the database yet.


public static DataEntry getBooleanField(String name) {
        DataEntry de = new DataEntry();
        de.setEntryName(name);
        DataEntryType det = DataEntryTypeServer.getType("type.boolean.name");
        de.setDataEntryPropertyList(getDefaultProperties(det));
        de.setDataEntryType(det);
        return de;
    }

public static DataEntry getBooleanField ( String name ) { DataEntry de = new DataEntry ( ) ; de . setEntryName ( name ) ; DataEntryType det = DataEntryTypeServer . getType ( "type.boolean.name" ) ; de . setDataEntryPropertyList ( getDefaultProperties ( det ) ) ; de . setDataEntryType ( det ) ; return de ; }

Create a boolean field

@param name Field name
@return DataEntry. The entry is not persisted into the database yet.


public static DataEntry getNumericField(String name, Float min, Float max) {
        DataEntry de = new DataEntry();
        de.setEntryName(name);
        DataEntryType det = DataEntryTypeServer.getType("type.numeric.name");
        de.setDataEntryPropertyList(getDefaultProperties(det));
        de.setDataEntryType(det);
        for (DataEntryProperty dep : de.getDataEntryPropertyList()) {
            if (dep.getPropertyName().equals("property.min") && min != null) {
                //Set minimum
                dep.setPropertyValue(min.toString());
            }
            if (dep.getPropertyName().equals("property.max") && max != null) {
                //Set minimum
                dep.setPropertyValue(max.toString());
            }
        }
        return de;
    }

public
static
DataEntry
getNumericField
(
String
name
,
Float
min
,
Float
max
)
{
DataEntry
de
=
new
DataEntry
(
)
;
de
.
setEntryName
(
name
)
;
DataEntryType
det
=
DataEntryTypeServer
.
getType
(
"type.numeric.name"
)
;
de
.
setDataEntryPropertyList
(
getDefaultProperties
(
det
)
)
;
de
.
setDataEntryType
(
det
)
;
for
(
DataEntryProperty
dep
:
de
.
getDataEntryPropertyList
(
)
)
{
if
(
dep
.
getPropertyName
(
)
.
equals
(
"property.min"
)
&&
min
!=
)
{
//Set minimum
dep
.
setPropertyValue
(
min
.
toString
(
)
)
;
}
if
(
dep
.
getPropertyName
(
)
.
equals
(
"property.max"
)
&&
max
!=
)
{
//Set minimum
dep
.
setPropertyValue
(
max
.
toString
(
)
)
;
}
}
return
de
;
}

Create a numeric field.

@param name Field name
@param min Minimum value. Set as null for no limit.
@param max Maximum value. Set as null for no limit.
@return DataEntry. The entry is not persisted into the database yet.


private void displayWorkflow(Workflow w) {
        Graph graph = new Graph(w.getWorkflowName(), Graph.DIGRAPH);
        nodes.clear();
        //Create the nodes
        w.getWorkflowStepList().forEach(step -> {
            addStep(step, graph);
            //Now add the links
            step.getSourceTransitions().forEach(t -> {
                addStep(t.getWorkflowStepSource(), graph);
                addStep(t.getWorkflowStepTarget(), graph);
                Subgraph.Edge edge
                        = graph.addEdge(nodes.get(t.getWorkflowStepSource()
                                .getWorkflowStepPK().getId()),
                                nodes.get(t.getWorkflowStepTarget()
                                        .getWorkflowStepPK().getId()));
                edge.setParam("label", TRANSLATOR.translate(t.getTransitionName()));
                //Workaround https://github.com/pontusbostrom/VaadinGraphvizComponent/issues/9
                edge.setDest(nodes.get(t.getWorkflowStepTarget()
                        .getWorkflowStepPK().getId()));
                edges.put(TRANSLATOR.translate(t.getTransitionName()),
                        new AbstractMap.SimpleEntry<>(
                                nodes.get(t.getWorkflowStepSource()
                                        .getWorkflowStepPK().getId()), edge));
            });
        });
        diagram.drawGraph(graph);
    }

Create workflow from database

@param w workflow to create from


private void refreshWorkflow() {
        Graph graph = new Graph(((Workflow) workflows.getValue())
                .getWorkflowName(), Graph.DIGRAPH);
        nodes.values().forEach(node -> {
            graph.addNode(node);
        });
        edges.values().forEach(edge -> {
            graph.addEdge(edge.getKey(), edge.getValue().getDest());
        });
        diagram.drawGraph(graph);
        selected = null;
        updateControls();
    }

private void refreshWorkflow ( ) { Graph graph = new Graph ( ( ( Workflow ) workflows . getValue ( ) ) . getWorkflowName ( ) , Graph . DIGRAPH ) ; nodes . values ( ) . forEach ( node -> { graph . addNode ( node ) ; } ) ; edges . values ( ) . forEach ( edge -> { graph . addEdge ( edge . getKey ( ) , edge . getValue ( ) . getDest ( ) ) ; } ) ; diagram . drawGraph ( graph ) ; selected = null ; updateControls ( ) ; }


private static void walkComponentTree(Component c, Consumer<Component> visitor) {
        visitor.accept(c);
        if (c instanceof HasComponents) {
            for (Component child : ((HasComponents) c)) {
                walkComponentTree(child, visitor);
            }
        }
    }

private static void walkComponentTree ( Component c , Consumer < Component > visitor ) { visitor . accept ( c ) ; if ( c instanceof HasComponents ) { for ( Component child : ( ( HasComponents ) c ) ) { walkComponentTree ( child , visitor ) ; } } }


@Override
    public OutputStream receiveUpload(String filename,
            String MIMEType) {
        FileOutputStream fos; // Output stream to write to
        try {
            file = File.createTempFile("upload",
                    filename.substring(filename.lastIndexOf('.')));
            // Open the file for writing.
            fos = new FileOutputStream(getFile());
        } catch (FileNotFoundException ex) {
            // Error while opening the file. Not reported here.
            LOG.log(Level.SEVERE, null, ex);
            return null;
        } catch (IOException ex) {
            // Error while opening the file. Not reported here.
            LOG.log(Level.SEVERE, null, ex);
            return null;
        }
        return fos; // Return the output stream to write to
    }

Callback method to begin receiving the upload.

Callback method to begin receiving the upload .


@Nullable
  public ResultStrength getAddressRisk() {
    if (addressRisk == null) {
      return null;
    }
    return ResultStrength.toEnum(addressRisk.toLowerCase());
  }

@ Nullable public ResultStrength getAddressRisk ( ) { if ( addressRisk == null ) { return null ; } return ResultStrength . toEnum ( addressRisk . toLowerCase ( ) ) ; }

Gets the risk of this particular address.

@return the risk factor

Gets the risk of this particular address .


@Deprecated
    protected <D extends FileDescriptor> D toFileDescriptor(Descriptor descriptor, Class<D> type, String path, ScannerContext context) {
        if (descriptor == null) {
            D result = context.getStore().create(type);
            result.setFileName(path);
            return result;
        }
        return migrateOrCast(descriptor, type, context);
    }

@ Deprecated protected < D extends FileDescriptor > D toFileDescriptor ( Descriptor descriptor , Class < D > type , String path , ScannerContext context ) { if ( descriptor == null ) { D result = context . getStore ( ) . create ( type ) ; result . setFileName ( path ) ; return result ; } return migrateOrCast ( descriptor , type , context ) ; }

Takes an optional descriptor and transforms it to file descriptor.

@param descriptor
The descriptor, if null a new descriptor is created.
@param type
The required type.
@param path
The path (to set as file name).
@param context
The scanner context.
@param <D>
The required type.
@return The file descriptor.
@deprecated migrate to
{@link #getOrCreateAs(String, Class, Function, ScannerContext)}.

Takes an optional descriptor and transforms it to file descriptor .


@Nullable
  public static BlockscoreError getBlockscoreError(@NotNull final RetrofitError cause) {
    Object rawError = cause.getBodyAs(BlockscoreError.class);
    if (rawError instanceof BlockscoreError) {
      return (BlockscoreError) rawError;
    } else {
      return null;
    }
  }

@ Nullable public static BlockscoreError getBlockscoreError ( @ NotNull final RetrofitError cause ) { Object rawError = cause . getBodyAs ( BlockscoreError . class ) ; if ( rawError instanceof BlockscoreError ) { return ( BlockscoreError ) rawError ; } else { return null ; } }

Converts a Retrofit Error into a Blockscore Error.

@param cause  the Retrofit error to convert
@return the Blockscore Error

Converts a Retrofit Error into a Blockscore Error .


@NotNull
  public void score(@NotNull final AnswerSet answers) {
    QuestionSet scoredSet = restAdapter.scoreQuestionSet(getId(), answers);
    expired = scoredSet.isExpired();
    score = scoredSet.getScore();
  }

@ NotNull public void score ( @ NotNull final AnswerSet answers ) { QuestionSet scoredSet = restAdapter . scoreQuestionSet ( getId ( ) , answers ) ; expired = scoredSet . isExpired ( ) ; score = scoredSet . getScore ( ) ; }

Scores a question set.

@param answers  the answers to the QuestionSet


public <D extends MD5Descriptor> D digest(InputStream stream, DigestOperation<D> digestOperation) throws IOException {
        DigestInputStream digestInputStream = new DigestInputStream(stream, md5Digest);
        D md5Descriptor = digestOperation.execute(digestInputStream);
        String md5 = DatatypeConverter.printHexBinary(md5Digest.digest());
        md5Descriptor.setMd5(md5);
        return md5Descriptor;
    }

public < D extends MD5Descriptor > D digest ( InputStream stream , DigestOperation < D > digestOperation ) throws IOException { DigestInputStream digestInputStream = new DigestInputStream ( stream , md5Digest ) ; D md5Descriptor = digestOperation . execute ( digestInputStream ) ; String md5 = DatatypeConverter . printHexBinary ( md5Digest . digest ( ) ) ; md5Descriptor . setMd5 ( md5 ) ; return md5Descriptor ; }

Calculate the MD5 hash sum for the given input stream using the given
operation.

@param stream
The stream.
@param digestOperation
The operation.
@param <D>
The MD5 descriptor type.
@return The MD5 descriptor.
@throws IOException
If reading the stream fails.

Calculate the MD5 hash sum for the given input stream using the given operation .


public boolean accepts(String path) {
        boolean result;
        if (includeFilePatterns != null) {
            result = matches(path, includeFilePatterns);
        } else {
            result = true;
        }
        if (excludeFilePatterns != null) {
            result = result && !matches(path, excludeFilePatterns);
        }
        return result;
    }

public boolean accepts ( String path ) { boolean result ; if ( includeFilePatterns != null ) { result = matches ( path , includeFilePatterns ) ; } else { result = true ; } if ( excludeFilePatterns != null ) { result = result && ! matches ( path , excludeFilePatterns ) ; } return result ; }

Determines if the given path matches the configured include and exclude
patterns.

NOTE: The include pattern is evaluated before the exclude pattern.

@param path
The path.
@return true if the path matches.

Determines if the given path matches the configured include and exclude patterns .


public void addAnswer(int questionId, int answerId) {
    QuestionAnswerPair answerPair = new QuestionAnswerPair(questionId, answerId);
    answers.add(answerPair);
  }

public void addAnswer ( int questionId , int answerId ) { QuestionAnswerPair answerPair = new QuestionAnswerPair ( questionId , answerId ) ; answers . add ( answerPair ) ; }

Adds an answer to a question to the AnswerSet.

@param questionId  the id of the question to be answered
@param answerId  the id of the answer selected

Adds an answer to a question to the AnswerSet .


@NotNull
  public String[] getMatchingInfo() {
    if (matchingInfo == null) {
      return new String[0];
    }

    return Arrays.copyOf(matchingInfo, matchingInfo.length);
  }

@ NotNull public String [ ] getMatchingInfo ( ) { if ( matchingInfo == null ) { return new String [ 0 ] ; } return Arrays . copyOf ( matchingInfo , matchingInfo . length ) ; }

Gets a list of elements in your request that match this watchlist hit.

@return an array of strings containing the matching info

Gets a list of elements in your request that match this watchlist hit .


@Nullable
  public Address getAddress() {
    return new Address(addressStreet1,
                       addressStreet2,
                       addressCity,
                       addressState,
                       addressPostalCode,
                       addressCountryCode);
  }

@ Nullable public Address getAddress ( ) { return new Address ( addressStreet1 , addressStreet2 , addressCity , addressState , addressPostalCode , addressCountryCode ) ; }

Gets the address of the candidate.

@return the address


public QuestionSet createQuestionSet(long timeLimit) {
    Map<String, String> queryOptions = new HashMap<String, String>();
    queryOptions.put("person_id", getId());
    queryOptions.put("time_limit", String.valueOf(timeLimit));

    QuestionSet questionSet = restAdapter.createQuestionSet(queryOptions);
    questionSet.setAdapter(restAdapter);
    return questionSet;
  }

public QuestionSet createQuestionSet ( long timeLimit ) { Map < String , String > queryOptions = new HashMap < String , String > ( ) ; queryOptions . put ( "person_id" , getId ( ) ) ; queryOptions . put ( "time_limit" , String . valueOf ( timeLimit ) ) ; QuestionSet questionSet = restAdapter . createQuestionSet ( queryOptions ) ; questionSet . setAdapter ( restAdapter ) ; return questionSet ; }

Creates a question set with a set time limit in seconds.

@param timeLimit  the time limit
@return the new question set

Creates a question set with a set time limit in seconds .


public QuestionSet retrieveQuestionSet(@NotNull final String questionSetId) {
    QuestionSet questionSet = restAdapter.retrieveQuestionSet(questionSetId);
    questionSet.setAdapter(restAdapter);
    return questionSet;
  }

public QuestionSet retrieveQuestionSet ( @ NotNull final String questionSetId ) { QuestionSet questionSet = restAdapter . retrieveQuestionSet ( questionSetId ) ; questionSet . setAdapter ( restAdapter ) ; return questionSet ; }

Retrieve a question set you have created.

@param questionSetId  Question set ID
@return the retrieved question set

Retrieve a question set you have created .


@NotNull
  public Date getDateOfBirth() {
    GregorianCalendar calendar = new GregorianCalendar(birthYear, birthMonth, birthDay);
    return calendar.getTime();
  }

@ NotNull public Date getDateOfBirth ( ) { GregorianCalendar calendar = new GregorianCalendar ( birthYear , birthMonth , birthDay ) ; return calendar . getTime ( ) ; }

Gets the date of birth for this individual.

@return the date of birth

Gets the date of birth for this individual .


@NotNull
  public Address getAddress() {
    Address addressObject = new Address(addressStreet1,
                      addressStreet2,
                      addressCity,
                      addressSubdivision,
                      addressPostalCode,
                      addressCountryCode);
    return addressObject;
  }

@ NotNull public Address getAddress ( ) { Address addressObject = new Address ( addressStreet1 , addressStreet2 , addressCity , addressSubdivision , addressPostalCode , addressCountryCode ) ; return addressObject ; }

Gets the address for this individual.

@return the address