@PostConstruct
	public void init() throws Exception {
    log.info("=======================");
    log.info("Adding camunda BPM Component to Camel");
    log.info("=======================");

	  CamundaBpmComponent component = new CamundaBpmComponent(processEngine);
    component.setCamelContext(cdiCamelContext);
    cdiCamelContext.addComponent("camunda-bpm", component); // TODO: could be done by META-INF/service as well- maybe switch?

    // For simplicity JMS was removed from the example - but you can easily re-add it:
		// inject the JMS connection factory into camel's JMS component
//		JmsComponent jmsComponent = cdiCamelContext.getComponent("jms", JmsComponent.class);
//		jmsComponent.setConnectionFactory(queueConnectionFactory);

    // Instead we exchanged the JMS component by replacing it with Camel seda component for in memory queues
    cdiCamelContext.addComponent("jms", cdiCamelContext.getComponent("seda", SedaComponent.class));

		// add routes to camel context
		log.info("=======================");
		log.info("adding OpenAccountRoute to camel context");
		log.info("=======================");
		cdiCamelContext.addRoutes(openAccountRoute);
		log.info("=======================");
		log.info("Camel Components: " + cdiCamelContext.getComponentNames());
		log.info("=======================");
		log.info("=======================");
		log.info("starting camel context");
		log.info("=======================");
		// cdiCamelContext.setTracing(true);
		cdiCamelContext.start();
		log.info("=======================");
		log.info("successfully created camel context and started open account route!");
		log.info("=======================");
	}

private QueueConnectionFactory queueConnectionFactory ;


public static void checkIsSet(final DelegateExecution execution, final String variableName) {
    checkArgument(variableName != null, VARIABLE_NAME_MUST_BE_NOT_NULL);

    final Object variableLocal = execution.getVariableLocal(variableName);
    final Object variable = execution.getVariable(variableName);

    checkState(variableLocal != null || variable != null,
        format(CONDITION_VIOLATED + "Variable '%s' is not set.", execution.getCurrentActivityId(), variableName));
  }

public
static
void
checkIsSet
(
final
DelegateExecution
execution
,
final
String
variableName
)
{
checkArgument
(
variableName
!=
,
VARIABLE_NAME_MUST_BE_NOT_NULL
)
;
final
Object
variableLocal
=
execution
.
getVariableLocal
(
variableName
)
;
final
Object
variable
=
execution
.
getVariable
(
variableName
)
;
checkState
(
variableLocal
!=
||
variable
!=
,
format
(
CONDITION_VIOLATED
+
"Variable '%s' is not set."
,
execution
.
getCurrentActivityId
(
)
,
variableName
)
)
;
}

Checks if a variable is set.

@param execution
current process execution
@param variableName
name of the variable.


public static void checkIsSetGlobal(final DelegateExecution execution, final String variableName) {
    checkArgument(variableName != null, VARIABLE_NAME_MUST_BE_NOT_NULL);

    final Object variable = execution.getVariable(variableName);
    checkState(variable != null, format(CONDITION_VIOLATED + "Global variable '%s' is not set.", execution.getCurrentActivityId(), variableName));
  }

public
static
void
checkIsSetGlobal
(
final
DelegateExecution
execution
,
final
String
variableName
)
{
checkArgument
(
variableName
!=
,
VARIABLE_NAME_MUST_BE_NOT_NULL
)
;
final
Object
variable
=
execution
.
getVariable
(
variableName
)
;
checkState
(
variable
!=
,
format
(
CONDITION_VIOLATED
+
"Global variable '%s' is not set."
,
execution
.
getCurrentActivityId
(
)
,
variableName
)
)
;
}

Checks if a global variable is set.

@param execution
current process execution
@param variableName
name of the variable.


public void open(boolean animated) {

        // Get the center of the action view from the following function for efficiency
        // populate destination x,y coordinates of Items
        Point center = calculateItemPositions();

        WindowManager.LayoutParams overlayParams = null;

        if(systemOverlay) {
            // If this is a system overlay menu, use the overlay container and place it behind
            // the main action button so that all the views will be added into it.
            attachOverlayContainer();

            overlayParams = (WindowManager.LayoutParams) overlayContainer.getLayoutParams();
        }

        if(animated && animationHandler != null) {
            // If animations are enabled and we have a MenuAnimationHandler, let it do the heavy work
            if(animationHandler.isAnimating()) {
                // Do not proceed if there is an animation currently going on.
                return;
            }

            for (int i = 0; i < subActionItems.size(); i++) {
                // It is required that these Item views are not currently added to any parent
                // Because they are supposed to be added to the Activity content view,
                // just before the animation starts
                if (subActionItems.get(i).view.getParent() != null) {
                    throw new RuntimeException("All of the sub action items have to be independent from a parent.");
                }

                // Initially, place all items right at the center of the main action view
                // Because they are supposed to start animating from that point.
                final FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(subActionItems.get(i).width, subActionItems.get(i).height, Gravity.TOP | Gravity.LEFT);

                if(systemOverlay) {
                    params.setMargins(center.x - overlayParams.x - subActionItems.get(i).width / 2, center.y - overlayParams.y - subActionItems.get(i).height / 2, 0, 0);
                }
                else {
                    params.setMargins(center.x - subActionItems.get(i).width / 2, center.y - subActionItems.get(i).height / 2, 0, 0);
                }
                addViewToCurrentContainer(subActionItems.get(i).view, params);
            }
            // Tell the current MenuAnimationHandler to animate from the center
            animationHandler.animateMenuOpening(center);
        }
        else {
            // If animations are disabled, just place each of the items to their calculated destination positions.
            for (int i = 0; i < subActionItems.size(); i++) {
                // This is currently done by giving them large margins

                final FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(subActionItems.get(i).width, subActionItems.get(i).height, Gravity.TOP | Gravity.LEFT);
                if(systemOverlay) {
                    params.setMargins(subActionItems.get(i).x - overlayParams.x, subActionItems.get(i).y - overlayParams.y, 0, 0);
                    subActionItems.get(i).view.setLayoutParams(params);
                }
                else {
                    params.setMargins(subActionItems.get(i).x, subActionItems.get(i).y, 0, 0);
                    subActionItems.get(i).view.setLayoutParams(params);
                    // Because they are placed into the main content view of the Activity,
                    // which is itself a FrameLayout
                }
                addViewToCurrentContainer(subActionItems.get(i).view, params);
            }
        }
        // do not forget to specify that the menu is open.
        open = true;

        if(stateChangeListener != null) {
            stateChangeListener.onMenuOpened(this);
        }

    }

Simply opens the menu by doing necessary calculations.
@param animated if true, this action is executed by the current {@link MenuAnimationHandler}

Simply opens the menu by doing necessary calculations .


public void close(boolean animated) {
        // If animations are enabled and we have a MenuAnimationHandler, let it do the heavy work
        if(animated && animationHandler != null) {
            if(animationHandler.isAnimating()) {
                // Do not proceed if there is an animation currently going on.
                return;
            }
            animationHandler.animateMenuClosing(getActionViewCenter());
        }
        else {
            // If animations are disabled, just detach each of the Item views from the Activity content view.
            for (int i = 0; i < subActionItems.size(); i++) {
                removeViewFromCurrentContainer(subActionItems.get(i).view);
            }
            detachOverlayContainer();
        }
        // do not forget to specify that the menu is now closed.
        open = false;

        if(stateChangeListener != null) {
            stateChangeListener.onMenuClosed(this);
        }
    }

Closes the menu.
@param animated if true, this action is executed by the current {@link MenuAnimationHandler}


public void updateItemPositions() {
        // Only update if the menu is currently open
        if(!isOpen()) {
            return;
        }
        // recalculate x,y coordinates of Items
        calculateItemPositions();

        // Simply update layout params for each item
        for (int i = 0; i < subActionItems.size(); i++) {
            // This is currently done by giving them large margins
            final FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(subActionItems.get(i).width, subActionItems.get(i).height, Gravity.TOP | Gravity.LEFT);
            params.setMargins(subActionItems.get(i).x, subActionItems.get(i).y, 0, 0);
            subActionItems.get(i).view.setLayoutParams(params);
        }
    }

Recalculates the positions of each sub action item on demand.

Recalculates the positions of each sub action item on demand .


private Point getActionViewCoordinates() {
        int[] coords = new int[2];
        // This method returns a x and y values that can be larger than the dimensions of the device screen.
        mainActionView.getLocationOnScreen(coords);

        // So, we need to deduce the offsets.
        if(systemOverlay) {
            coords[1] -= getStatusBarHeight();
        }
        else {
            Rect activityFrame = new Rect();
            getActivityContentView().getWindowVisibleDisplayFrame(activityFrame);
            coords[0] -= (getScreenSize().x - getActivityContentView().getMeasuredWidth());
            coords[1] -= (activityFrame.height() + activityFrame.top - getActivityContentView().getMeasuredHeight());
        }
        return new Point(coords[0], coords[1]);
    }

Gets the coordinates of the main action view
This method should only be called after the main layout of the Activity is drawn,
such as when a user clicks the action button.
@return a Point containing x and y coordinates of the top left corner of action view

Gets the coordinates of the main action view This method should only be called after the main layout of the Activity is drawn such as when a user clicks the action button .


public Point getActionViewCenter() {
        Point point = getActionViewCoordinates();
        point.x += mainActionView.getMeasuredWidth() / 2;
        point.y += mainActionView.getMeasuredHeight() / 2;
        return point;
    }

public Point getActionViewCenter ( ) { Point point = getActionViewCoordinates ( ) ; point . x += mainActionView . getMeasuredWidth ( ) / 2 ; point . y += mainActionView . getMeasuredHeight ( ) / 2 ; return point ; }

Returns the center point of the main action view
@return the action view center point


private Point calculateItemPositions() {
        // Create an arc that starts from startAngle and ends at endAngle
        // in an area that is as large as 4*radius^2
        final Point center = getActionViewCenter();
        RectF area = new RectF(center.x - radius, center.y - radius, center.x + radius, center.y + radius);

        Path orbit = new Path();
        orbit.addArc(area, startAngle, endAngle - startAngle);

        PathMeasure measure = new PathMeasure(orbit, false);

        // Prevent overlapping when it is a full circle
        int divisor;
        if(Math.abs(endAngle - startAngle) >= 360 || subActionItems.size() <= 1) {
            divisor = subActionItems.size();
        }
        else {
            divisor = subActionItems.size() -1;
        }

        // Measure this path, in order to find points that have the same distance between each other
        for(int i=0; i<subActionItems.size(); i++) {
            float[] coords = new float[] {0f, 0f};
            measure.getPosTan((i) * measure.getLength() / divisor, coords, null);
            // get the x and y values of these points and set them to each of sub action items.
            subActionItems.get(i).x = (int) coords[0] - subActionItems.get(i).width / 2;
            subActionItems.get(i).y = (int) coords[1] - subActionItems.get(i).height / 2;
        }
        return center;
    }

Calculates the desired positions of all items.
@return getActionViewCenter()

Calculates the desired positions of all items .


public View getActivityContentView() {
        try {
            return ((Activity) mainActionView.getContext()).getWindow().getDecorView().findViewById(android.R.id.content);
        }
        catch(ClassCastException e) {
            throw new ClassCastException("Please provide an Activity context for this FloatingActionMenu.");
        }
    }

Finds and returns the main content view from the Activity context.
@return the main content view

Finds and returns the main content view from the Activity context .


private Point getScreenSize() {
        Point size = new Point();
        getWindowManager().getDefaultDisplay().getSize(size);
        return size;
    }

private Point getScreenSize ( ) { Point size = new Point ( ) ; getWindowManager ( ) . getDefaultDisplay ( ) . getSize ( size ) ; return size ; }

Retrieves the screen size from the Activity context
@return the screen size as a Point object


protected void restoreSubActionViewAfterAnimation(FloatingActionMenu.Item subActionItem, ActionType actionType) {
        ViewGroup.LayoutParams params = subActionItem.view.getLayoutParams();
        subActionItem.view.setTranslationX(0);
        subActionItem.view.setTranslationY(0);
        subActionItem.view.setRotation(0);
        subActionItem.view.setScaleX(1);
        subActionItem.view.setScaleY(1);
        subActionItem.view.setAlpha(1);
        if(actionType == ActionType.OPENING) {
            FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) params;
            if(menu.isSystemOverlay()) {
                WindowManager.LayoutParams overlayParams = (WindowManager.LayoutParams) menu.getOverlayContainer().getLayoutParams();
                lp.setMargins(subActionItem.x - overlayParams.x, subActionItem.y - overlayParams.y, 0, 0);
            }
            else {
                lp.setMargins(subActionItem.x, subActionItem.y, 0, 0);
            }
            subActionItem.view.setLayoutParams(lp);
        }
        else if(actionType == ActionType.CLOSING) {
            Point center = menu.getActionViewCenter();
            FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) params;
            if(menu.isSystemOverlay()) {
                WindowManager.LayoutParams overlayParams = (WindowManager.LayoutParams) menu.getOverlayContainer().getLayoutParams();
                lp.setMargins(center.x - overlayParams.x - subActionItem.width / 2, center.y - overlayParams.y - subActionItem.height / 2, 0, 0);
            }
            else {
                lp.setMargins(center.x - subActionItem.width / 2, center.y - subActionItem.height / 2, 0, 0);
            }
            subActionItem.view.setLayoutParams(lp);
            menu.removeViewFromCurrentContainer(subActionItem.view);

            if(menu.isSystemOverlay()) {
                // When all the views are removed from the overlay container,
                // we also need to detach it
                if (menu.getOverlayContainer().getChildCount() == 0) {
                    menu.detachOverlayContainer();
                }
            }
        }
    }

Restores the specified sub action view to its final state, according to the current actionType
Should be called after an animation finishes.
@param subActionItem
@param actionType

Restores the specified sub action view to its final state according to the current actionType Should be called after an animation finishes .


public void setContentView(View contentView, FrameLayout.LayoutParams params) {
        if(params == null) {
            params = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.CENTER);
            final int margin = getResources().getDimensionPixelSize(R.dimen.sub_action_button_content_margin);
            params.setMargins(margin, margin, margin, margin);
        }

        contentView.setClickable(false);
        this.addView(contentView, params);
    }

public void setContentView ( View contentView , FrameLayout . LayoutParams params ) { if ( params == null ) { params = new FrameLayout . LayoutParams ( LayoutParams . WRAP_CONTENT , LayoutParams . WRAP_CONTENT , Gravity . CENTER ) ; final int margin = getResources ( ) . getDimensionPixelSize ( R . dimen . sub_action_button_content_margin ) ; params . setMargins ( margin , margin , margin , margin ) ; } contentView . setClickable ( false ) ; this . addView ( contentView , params ) ; }

Sets a content view with custom LayoutParams that will be displayed inside this SubActionButton.
@param contentView
@param params

Sets a content view with custom LayoutParams that will be displayed inside this SubActionButton .


public void setPosition(int position, ViewGroup.LayoutParams layoutParams) {

        boolean setDefaultMargin = false;

        int gravity;
        switch (position) {
            case POSITION_TOP_CENTER:
                gravity = Gravity.TOP | Gravity.CENTER_HORIZONTAL;
                break;
            case POSITION_TOP_RIGHT:
                gravity = Gravity.TOP | Gravity.RIGHT;
                break;
            case POSITION_RIGHT_CENTER:
                gravity = Gravity.RIGHT | Gravity.CENTER_VERTICAL;
                break;
            case POSITION_BOTTOM_CENTER:
                gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
                break;
            case POSITION_BOTTOM_LEFT:
                gravity = Gravity.BOTTOM | Gravity.LEFT;
                break;
            case POSITION_LEFT_CENTER:
                gravity = Gravity.LEFT | Gravity.CENTER_VERTICAL;
                break;
            case POSITION_TOP_LEFT:
                gravity = Gravity.TOP | Gravity.LEFT;
                break;
            case POSITION_BOTTOM_RIGHT:
            default:
                setDefaultMargin = true;
                gravity = Gravity.BOTTOM | Gravity.RIGHT;
                break;
        }
        if(!systemOverlay) {
            try {
                FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) layoutParams;
                lp.gravity = gravity;
                setLayoutParams(lp);
            } catch (ClassCastException e) {
                throw new ClassCastException("layoutParams must be an instance of " +
                        "FrameLayout.LayoutParams, since this FAB is not a systemOverlay");
            }
        }
        else {
            try {
                WindowManager.LayoutParams lp = (WindowManager.LayoutParams) layoutParams;
                lp.gravity = gravity;
                if(setDefaultMargin) {
                    int margin =  getContext().getResources().getDimensionPixelSize(R.dimen.action_button_margin);
                    lp.x = margin;
                    lp.y = margin;
                }
                setLayoutParams(lp);
            } catch(ClassCastException e) {
                throw new ClassCastException("layoutParams must be an instance of " +
                        "WindowManager.LayoutParams, since this FAB is a systemOverlay");
            }
        }
    }

Sets the position of the button by calculating its Gravity from the position parameter
@param position one of 8 specified positions.
@param layoutParams should be either FrameLayout.LayoutParams or WindowManager.LayoutParams


public void attach(ViewGroup.LayoutParams layoutParams) {
        if(systemOverlay) {
            try {
                getWindowManager().addView(this, layoutParams);
            }
            catch(SecurityException e) {
                throw new SecurityException("Your application must have SYSTEM_ALERT_WINDOW " +
                        "permission to create a system window.");
            }
        }
        else {
            ((ViewGroup) getActivityContentView()).addView(this, layoutParams);
        }
    }

Attaches it to the content view with specified LayoutParams.
@param layoutParams

Attaches it to the content view with specified LayoutParams .


public StateConfiguration<S, T> permit(T trigger, S destinationState) {
        enforceNotIdentityTransition(destinationState);
        return publicPermit(trigger, destinationState);
    }

public StateConfiguration < S , T > permit ( T trigger , S destinationState ) { enforceNotIdentityTransition ( destinationState ) ; return publicPermit ( trigger , destinationState ) ; }

Accept the specified trigger and transition to the destination state

@param trigger          The accepted trigger
@param destinationState The state that the trigger will cause a transition to
@return The receiver


public StateConfiguration<S, T> permitIf(T trigger, S destinationState, FuncBoolean guard) {
        enforceNotIdentityTransition(destinationState);
        return publicPermitIf(trigger, destinationState, guard);
    }

public StateConfiguration < S , T > permitIf ( T trigger , S destinationState , FuncBoolean guard ) { enforceNotIdentityTransition ( destinationState ) ; return publicPermitIf ( trigger , destinationState , guard ) ; }

Accept the specified trigger and transition to the destination state if guard is true

@param trigger          The accepted trigger
@param destinationState The state that the trigger will cause a transition to
@param guard            Function that must return true in order for the trigger to be accepted
@return The receiver


public StateConfiguration<S, T> permitIfOtherwiseIgnore(T trigger, S destinationState, final FuncBoolean guard) {
        enforceNotIdentityTransition(destinationState);
        ignoreIf(trigger, new FuncBoolean() {
            @Override
            public boolean call() {
                return !guard.call();
            }
        });
        return publicPermitIf(trigger, destinationState, guard);
    }

public StateConfiguration < S , T > permitIfOtherwiseIgnore ( T trigger , S destinationState , final FuncBoolean guard ) { enforceNotIdentityTransition ( destinationState ) ; ignoreIf ( trigger , new FuncBoolean ( ) { @ Override public boolean call ( ) { return ! guard . call ( ) ; } } ) ; return publicPermitIf ( trigger , destinationState , guard ) ; }

Accept the specified trigger and transition to the destination state if guard true, otherwise ignore

@param trigger          The accepted trigger
@param destinationState The state that the trigger will cause a transition to
@param guard            Function that must return true in order for the trigger to be accepted
@return The receiver

Accept the specified trigger and transition to the destination state if guard true otherwise ignore


public StateConfiguration<S, T> ignoreIf(T trigger, FuncBoolean guard) {
        assert guard != null : GUARD_IS_NULL;
        representation.addTriggerBehaviour(new InternalTriggerBehaviour<S, T>(trigger, guard, NO_ACTION));
        return this;
    }

public StateConfiguration < S , T > ignoreIf ( T trigger , FuncBoolean guard ) { assert guard != null : GUARD_IS_NULL ; representation . addTriggerBehaviour ( new InternalTriggerBehaviour < S , T > ( trigger , guard , NO_ACTION ) ) ; return this ; }

ignore the specified trigger when in the configured state, if the guard returns true

@param trigger The trigger to ignore
@param guard   Function that must return true in order for the trigger to be ignored
@return The receiver

ignore the specified trigger when in the configured state if the guard returns true


private StateRepresentation<TState, TTrigger> getOrCreateRepresentation(TState state) {
        StateRepresentation<TState, TTrigger> result = stateConfiguration.get(state);
        if (result == null) {
            result = new StateRepresentation<>(state);
            stateConfiguration.put(state, result);
        }

        return result;
    }

private StateRepresentation < TState , TTrigger > getOrCreateRepresentation ( TState state ) { StateRepresentation < TState , TTrigger > result = stateConfiguration . get ( state ) ; if ( result == null ) { result = new StateRepresentation <> ( state ) ; stateConfiguration . put ( state , result ) ; } return result ; }

Return StateRepresentation for the specified state. Creates representation if it does not exist.

@param state The state
@return StateRepresentation for the specified state.

Return StateRepresentation for the specified state . Creates representation if it does not exist .


public void addInstance(Object instance)
            throws Exception
    {
        State currentState = state.get();
        if ((currentState == State.STOPPING) || (currentState == State.STOPPED)) {
            throw new IllegalStateException();
        }
        else {
            startInstance(instance);
            if (methodsMap.get(instance.getClass()).hasFor(PreDestroy.class)) {
                managedInstances.add(instance);
            }
        }
    }

public void addInstance ( Object instance ) throws Exception { State currentState = state . get ( ) ; if ( ( currentState == State . STOPPING ) || ( currentState == State . STOPPED ) ) { throw new IllegalStateException ( ) ; } else { startInstance ( instance ) ; if ( methodsMap . get ( instance . getClass ( ) ) . hasFor ( PreDestroy . class ) ) { managedInstances . add ( instance ) ; } } }

Add an additional managed instance

@param instance instance to add
@throws Exception errors


private boolean setOverflow(int bucket, int overflow)
    {
        for (int i = 0; i < overflows; i++) {
            if (overflowBuckets[i] == bucket) {
                overflowValues[i] = (byte) overflow;
                return true;
            }
        }
        return false;
    }

private boolean setOverflow ( int bucket , int overflow ) { for ( int i = 0 ; i < overflows ; i ++ ) { if ( overflowBuckets [ i ] == bucket ) { overflowValues [ i ] = ( byte ) overflow ; return true ; } } return false ; }

Returns false if not overflow bucket matching the given bucket id was found


public DenseHll mergeWith(DenseHll other)
    {
        if (indexBitLength != other.indexBitLength) {
            throw new IllegalArgumentException(String.format(
                    "Cannot merge HLLs with different number of buckets: %s vs %s",
                    numberOfBuckets(indexBitLength),
                    numberOfBuckets(other.indexBitLength)));
        }

        int baseline = Math.max(this.baseline, other.baseline);
        int baselineCount = 0;

        int overflows = 0;
        int[] overflowBuckets = new int[OVERFLOW_GROW_INCREMENT];
        byte[] overflowValues = new byte[OVERFLOW_GROW_INCREMENT];

        int numberOfBuckets = numberOfBuckets(indexBitLength);
        for (int i = 0; i < numberOfBuckets; i++) {
            int value = Math.max(getValue(i), other.getValue(i));

            int delta = value - baseline;
            if (delta == 0) {
                baselineCount++;
            }
            else if (delta > MAX_DELTA) {
                // grow overflows arrays if necessary
                overflowBuckets = Ints.ensureCapacity(overflowBuckets, overflows + 1, OVERFLOW_GROW_INCREMENT);
                overflowValues = Bytes.ensureCapacity(overflowValues, overflows + 1, OVERFLOW_GROW_INCREMENT);

                overflowBuckets[overflows] = i;
                overflowValues[overflows] = (byte) (delta - MAX_DELTA);

                overflows++;

                delta = MAX_DELTA;
            }

            setDelta(i, delta);
        }

        this.baseline = (byte) baseline;
        this.baselineCount = baselineCount;
        this.overflows = overflows;
        this.overflowBuckets = overflowBuckets;
        this.overflowValues = overflowValues;

        // all baseline values in one of the HLLs lost to the values
        // in the other HLL, so we need to adjust the final baseline
        adjustBaselineIfNeeded();

        return this;
    }


public static byte[] encodeSequence(byte[]... encodedValues)
    {
        int length = 0;
        for (byte[] encodedValue : encodedValues) {
            length += encodedValue.length;
        }
        byte[] lengthEncoded = encodeLength(length);

        ByteArrayDataOutput out = ByteStreams.newDataOutput(1 + lengthEncoded.length + length);
        out.write(SEQUENCE_TAG);
        out.write(lengthEncoded);
        for (byte[] entry : encodedValues) {
            out.write(entry);
        }
        return out.toByteArray();
    }

public static byte [ ] encodeSequence ( byte [ ] ... encodedValues ) { int length = 0 ; for ( byte [ ] encodedValue : encodedValues ) { length += encodedValue . length ; } byte [ ] lengthEncoded = encodeLength ( length ) ; ByteArrayDataOutput out = ByteStreams . newDataOutput ( 1 + lengthEncoded . length + length ) ; out . write ( SEQUENCE_TAG ) ; out . write ( lengthEncoded ) ; for ( byte [ ] entry : encodedValues ) { out . write ( entry ) ; } return out . toByteArray ( ) ; }


public static List<byte[]> decodeSequence(byte[] sequence)
    {
        int index = 0;

        // check tag
        checkArgument(sequence[0] == SEQUENCE_TAG, "Expected sequence tag");
        index++;

        // read length
        int sequenceDataLength = decodeLength(sequence, index);
        index += encodedLengthSize(sequenceDataLength);
        checkArgument(sequenceDataLength + index == sequence.length, "Invalid sequence");

        // read elements
        ImmutableList.Builder<byte[]> elements = ImmutableList.builder();
        while (index < sequence.length) {
            int elementStart = index;

            // skip the tag
            index++;

            // read length
            int length = decodeLength(sequence, index);
            index += encodedLengthSize(length);

            byte[] data = Arrays.copyOfRange(sequence, elementStart, index + length);
            elements.add(data);
            index += length;
        }
        return elements.build();
    }

public
static
List
<
byte
[
]
>
decodeSequence
(
byte
[
]
sequence
)
{
int
index
=
0
;
// check tag
checkArgument
(
sequence
[
0
]
==
SEQUENCE_TAG
,
"Expected sequence tag"
)
;
index
++
;
// read length
int
sequenceDataLength
=
decodeLength
(
sequence
,
index
)
;
index
+=
encodedLengthSize
(
sequenceDataLength
)
;
checkArgument
(
sequenceDataLength
+
index
==
sequence
.
length
,
"Invalid sequence"
)
;
// read elements
ImmutableList
.
Builder
<
byte
[
]
>
elements
=
ImmutableList
.
builder
(
)
;
while
(
index
<
sequence
.
length
)
{
int
elementStart
=
index
;
// skip the tag
index
++
;
// read length
int
length
=
decodeLength
(
sequence
,
index
)
;
index
+=
encodedLengthSize
(
length
)
;
byte
[
]
data
=
Arrays
.
copyOfRange
(
sequence
,
elementStart
,
index
+
length
)
;
elements
.
add
(
data
)
;
index
+=
length
;
}
return
elements
.
build
(
)
;
}


public static byte[] decodeSequenceOptionalElement(byte[] element)
    {
        int index = 0;

        // check tag
        checkArgument((element[0] & 0xE0) == 0xA0, "Expected optional sequence element tag");
        index++;

        // read length
        int length = decodeLength(element, index);
        index += encodedLengthSize(length);
        checkArgument(length + index == element.length, "Invalid optional sequence element");

        return Arrays.copyOfRange(element, index, index + length);
    }

Decodes a optional element of a sequence.

Decodes a optional element of a sequence .


public static byte[] encodeBitString(int padBits, byte[] value)
    {
        checkArgument(padBits >= 0 && padBits < 8, "Invalid pad bits");

        byte[] lengthEncoded = encodeLength(value.length + 1);
        ByteArrayDataOutput out = ByteStreams.newDataOutput(2 + lengthEncoded.length + value.length);
        out.write(BIT_STRING_TAG);
        out.write(lengthEncoded);
        out.write(padBits);
        out.write(value);
        return out.toByteArray();
    }

public
static
byte
[
]
encodeBitString
(
int
padBits
,
byte
[
]
value
)
{
checkArgument
(
padBits
>=
0
&&
padBits
<
8
,
"Invalid pad bits"
)
;
byte
[
]
lengthEncoded
=
encodeLength
(
value
.
length
+
1
)
;
ByteArrayDataOutput
out
=
ByteStreams
.
newDataOutput
(
2
+
lengthEncoded
.
length
+
value
.
length
)
;
out
.
write
(
BIT_STRING_TAG
)
;
out
.
write
(
lengthEncoded
)
;
out
.
write
(
padBits
)
;
out
.
write
(
value
)
;
return
out
.
toByteArray
(
)
;
}

Encodes a bit string padded with the specified number of bits.
The encoding is a byte containing the padBits followed by the value bytes.

Encodes a bit string padded with the specified number of bits . The encoding is a byte containing the padBits followed by the value bytes .


public static byte[] encodeOctetString(byte[] value)
    {
        byte[] lengthEncoded = encodeLength(value.length);
        ByteArrayDataOutput out = ByteStreams.newDataOutput(2 + lengthEncoded.length + value.length);
        out.write(OCTET_STRING_TAG);
        out.write(lengthEncoded);
        out.write(value);
        return out.toByteArray();
    }

public static byte [ ] encodeOctetString ( byte [ ] value ) { byte [ ] lengthEncoded = encodeLength ( value . length ) ; ByteArrayDataOutput out = ByteStreams . newDataOutput ( 2 + lengthEncoded . length + value . length ) ; out . write ( OCTET_STRING_TAG ) ; out . write ( lengthEncoded ) ; out . write ( value ) ; return out . toByteArray ( ) ; }


public static byte[] encodeLength(int length)
    {
        if (length < 128) {
            return new byte[] {(byte) length};
        }
        int numberOfBits = 32 - Integer.numberOfLeadingZeros(length);
        int numberOfBytes = (numberOfBits + 7) / 8;
        byte[] encoded = new byte[1 + numberOfBytes];
        encoded[0] = (byte) (numberOfBytes | 0x80);
        for (int i = 0; i < numberOfBytes; i++) {
            int byteToEncode = (numberOfBytes - i);
            int shiftSize = (byteToEncode - 1) * 8;
            encoded[i + 1] = (byte) (length >>> shiftSize);
        }
        return encoded;
    }

public static byte [ ] encodeLength ( int length ) { if ( length < 128 ) { return new byte [ ] { ( byte ) length } ; } int numberOfBits = 32 - Integer . numberOfLeadingZeros ( length ) ; int numberOfBytes = ( numberOfBits + 7 ) / 8 ; byte [ ] encoded = new byte [ 1 + numberOfBytes ] ; encoded [ 0 ] = ( byte ) ( numberOfBytes | 0x80 ) ; for ( int i = 0 ; i < numberOfBytes ; i ++ ) { int byteToEncode = ( numberOfBytes - i ) ; int shiftSize = ( byteToEncode - 1 ) * 8 ; encoded [ i + 1 ] = ( byte ) ( length >>> shiftSize ) ; } return encoded ; }

Encodes the length of a DER value.  The encoding of a 7bit value is simply the value.  Values needing more than 7bits
are encoded as a lead byte with the high bit set and containing the number of value bytes.  Then the following bytes
encode the length using the least number of bytes possible.

Encodes the length of a DER value . The encoding of a 7bit value is simply the value . Values needing more than 7bits are encoded as a lead byte with the high bit set and containing the number of value bytes . Then the following bytes encode the length using the least number of bytes possible .


public static Logger get(String name)
    {
        java.util.logging.Logger logger = java.util.logging.Logger.getLogger(name);
        return new Logger(logger);
    }

public static Logger get ( String name ) { java . util . logging . Logger logger = java . util . logging . Logger . getLogger ( name ) ; return new Logger ( logger ) ; }

Gets a named logger

@param name the name of the logger
@return the named logger


public void debug(Throwable exception, String message)
    {
        logger.log(FINE, message, exception);
    }

public void debug ( Throwable exception , String message ) { logger . log ( FINE , message , exception ) ; }

Logs a message at DEBUG level.

@param exception an exception associated with the debug message being logged
@param message a literal message to log


public void warn(Throwable exception, String message)
    {
        logger.log(WARNING, message, exception);
    }

public void warn ( Throwable exception , String message ) { logger . log ( WARNING , message , exception ) ; }

Logs a message at WARN level.

@param exception an exception associated with the warning being logged
@param message a literal message to log


public void error(Throwable exception, String message)
    {
        logger.log(SEVERE, message, exception);
    }

public void error ( Throwable exception , String message ) { logger . log ( SEVERE , message , exception ) ; }

Logs a message at ERROR level.

@param exception an exception associated with the error being logged
@param message a literal message to log


public HttpUriBuilder replacePath(String path)
    {
        requireNonNull(path, "path is null");

        if (!path.isEmpty() && !path.startsWith("/")) {
            path = "/" + path;
        }

        this.path = path;
        return this;
    }

public
HttpUriBuilder
replacePath
(
String
path
)
{
requireNonNull
(
path
,
"path is null"
)
;
if
(
!
path
.
isEmpty
(
)
&&
!
path
.
startsWith
(
"/"
)
)
{
path
=
"/"
+
path
;
}
this
.
path
=
path
;
return
this
;
}

Replace the current path with the given unencoded path


private static String percentDecode(String encoded)
    {
        Preconditions.checkArgument(ascii().matchesAllOf(encoded), "string must be ASCII");

        ByteArrayOutputStream out = new ByteArrayOutputStream(encoded.length());
        for (int i = 0; i < encoded.length(); i++) {
            char c = encoded.charAt(i);

            if (c == '%') {
                Preconditions.checkArgument(i + 2 < encoded.length(), "percent encoded value is truncated");

                int high = Character.digit(encoded.charAt(i + 1), 16);
                int low = Character.digit(encoded.charAt(i + 2), 16);

                Preconditions.checkArgument(high != -1 && low != -1, "percent encoded value is not a valid hex string: ", encoded.substring(i, i + 2));

                int value = (high << 4) | (low);
                out.write(value);
                i += 2;
            }
            else {
                out.write((int) c);
            }
        }

        try {
            return UTF_8.newDecoder()
                    .onMalformedInput(CodingErrorAction.REPORT)
                    .decode(ByteBuffer.wrap(out.toByteArray()))
                    .toString();
        }
        catch (CharacterCodingException e) {
            throw new IllegalArgumentException("input does not represent a proper UTF8-encoded string");
        }
    }

input must be an ASCII string representing a percent-encoded UTF-8 byte sequence

input must be an ASCII string representing a percent - encoded UTF - 8 byte sequence


@Nullable
    private static DoubleSummaryStats processContentTimestamps(List<Long> contentTimestamps)
    {
        requireNonNull(contentTimestamps, "contentTimestamps is null");

        // no content (HTTP 204) or there was a single response chunk (so no interarrival time)
        if (contentTimestamps.size() == 0 || contentTimestamps.size() == 1) {
            return null;
        }

        DoubleSummaryStatistics statistics = new DoubleSummaryStatistics();
        long previousTimestamp = contentTimestamps.get(0);
        for (int i = 1; i < contentTimestamps.size(); i++) {
            long timestamp = contentTimestamps.get(i);
            statistics.accept(NANOSECONDS.toMillis(timestamp - previousTimestamp));
            previousTimestamp = timestamp;
        }
        return new DoubleSummaryStats(statistics);
    }

Calculate the summary statistics for the interarrival time of the onResponseContent callbacks.

Calculate the summary statistics for the interarrival time of the onResponseContent callbacks .


<T> T build(ConfigurationProvider<T> configurationProvider)
    {
        requireNonNull(configurationProvider, "configurationProvider");
        registerConfigurationProvider(configurationProvider, Optional.empty());

        // check for a prebuilt instance
        T instance = getCachedInstance(configurationProvider);
        if (instance != null) {
            return instance;
        }

        ConfigurationBinding<T> configurationBinding = configurationProvider.getConfigurationBinding();
        ConfigurationHolder<T> holder = build(configurationBinding.getConfigClass(), configurationBinding.getPrefix(), getConfigDefaults(configurationBinding.getKey()));
        instance = holder.getInstance();

        // inform caller about warnings
        if (warningsMonitor != null) {
            for (Message message : holder.getProblems().getWarnings()) {
                warningsMonitor.onWarning(message.toString());
            }
        }

        // add to instance cache
        T existingValue = putCachedInstance(configurationProvider, instance);
        // if key was already associated with a value, there was a
        // creation race and we lost. Just use the winners' instance;
        if (existingValue != null) {
            return existingValue;
        }
        return instance;
    }

This is used by the configuration provider


public void update(long value, long timestamp)
    {
        lockForRegularUsage();
        try {
            final double priority = weight(timestamp - startTime) / random();
            final long newCount = count.incrementAndGet();
            if (newCount <= reservoirSize) {
                values.put(priority, value);
            }
            else {
                Double first = values.firstKey();
                if (first < priority) {
                    if (values.putIfAbsent(priority, value) == null) {
                        // ensure we always remove an item
                        while (values.remove(first) == null) {
                            first = values.firstKey();
                        }
                    }
                }
            }
        }
        finally {
            unlockForRegularUsage();
        }

        final long now = System.nanoTime();
        final long next = nextScaleTime.get();
        if (now >= next) {
            rescale(now, next);
        }
    }

public
void
update
(
long
value
,
long
timestamp
)
{
lockForRegularUsage
(
)
;
try
{
final
double
priority
=
weight
(
timestamp
startTime
)
/
random
(
)
;
final
long
newCount
=
count
.
incrementAndGet
(
)
;
if
(
newCount
<=
reservoirSize
)
{
values
.
put
(
priority
,
value
)
;
}
else
{
Double
first
=
values
.
firstKey
(
)
;
if
(
first
<
priority
)
{
if
(
values
.
putIfAbsent
(
priority
,
value
)
==
)
{
// ensure we always remove an item
while
(
values
.
remove
(
first
)
==
)
{
first
=
values
.
firstKey
(
)
;
}
}
}
}
}
finally
{
unlockForRegularUsage
(
)
;
}
final
long
now
=
System
.
nanoTime
(
)
;
final
long
next
=
nextScaleTime
.
get
(
)
;
if
(
now
>=
next
)
{
rescale
(
now
,
next
)
;
}
}

Adds an old value with a fixed timestamp to the sample.

@param value the value to be added
@param timestamp the epoch timestamp of {@code value} in seconds

Adds an old value with a fixed timestamp to the sample .


public static String base64Encode(byte[] bytes)
    {
        // always sequence of 4 characters for each 3 bytes; padded with '='s as necessary:
        StringBuilder buf = new StringBuilder(((bytes.length + 2) / 3) * 4);

        // first, handle complete chunks (fast loop)
        int i = 0;
        for (int end = bytes.length - 2; i < end; ) {
            int chunk = ((bytes[i++] & 0xFF) << 16)
                    | ((bytes[i++] & 0xFF) << 8)
                    | (bytes[i++] & 0xFF);
            buf.append(lookup[chunk >> 18]);
            buf.append(lookup[(chunk >> 12) & 0x3F]);
            buf.append(lookup[(chunk >> 6) & 0x3F]);
            buf.append(lookup[chunk & 0x3F]);
        }

        // then leftovers, if any
        int len = bytes.length;
        if (i < len) { // 1 or 2 extra bytes?
            int chunk = ((bytes[i++] & 0xFF) << 16);
            buf.append(lookup[chunk >> 18]);
            if (i < len) { // 2 bytes
                chunk |= ((bytes[i] & 0xFF) << 8);
                buf.append(lookup[(chunk >> 12) & 0x3F]);
                buf.append(lookup[(chunk >> 6) & 0x3F]);
            }
            else { // 1 byte
                buf.append(lookup[(chunk >> 12) & 0x3F]);
                buf.append('=');
            }
            buf.append('=');
        }
        return buf.toString();
    }

Encodes the specified data into a base64 string.

@param bytes The unencoded raw data.

Encodes the specified data into a base64 string .


public static byte[] base64Decode(String encoded)
    {
        int padding = 0;

        for (int i = encoded.length() - 1; encoded.charAt(i) == '='; i--) {
            padding++;
        }

        int length = encoded.length() * 6 / 8 - padding;
        byte[] bytes = new byte[length];

        for (int i = 0, index = 0, n = encoded.length(); i < n; i += 4) {
            int word = reverseLookup[encoded.charAt(i)] << 18;
            word += reverseLookup[encoded.charAt(i + 1)] << 12;
            word += reverseLookup[encoded.charAt(i + 2)] << 6;
            word += reverseLookup[encoded.charAt(i + 3)];

            for (int j = 0; j < 3 && index + j < length; j++) {
                bytes[index + j] = (byte) (word >> (8 * (2 - j)));
            }

            index += 3;
        }

        return bytes;
    }

public static byte [ ] base64Decode ( String encoded ) { int padding = 0 ; for ( int i = encoded . length ( ) - 1 ; encoded . charAt ( i ) == ' ' ; i -- ) { padding ++ ; } int length = encoded . length ( ) * 6 / 8 - padding ; byte [ ] bytes = new byte [ length ] ; for ( int i = 0 , index = 0 , n = encoded . length ( ) ; i < n ; i += 4 ) { int word = reverseLookup [ encoded . charAt ( i ) ] << 18 ; word += reverseLookup [ encoded . charAt ( i + 1 ) ] << 12 ; word += reverseLookup [ encoded . charAt ( i + 2 ) ] << 6 ; word += reverseLookup [ encoded . charAt ( i + 3 ) ] ; for ( int j = 0 ; j < 3 && index + j < length ; j ++ ) { bytes [ index + j ] = ( byte ) ( word >> ( 8 * ( 2 - j ) ) ) ; } index += 3 ; } return bytes ; }

Decodes the specified base64 string back into its raw data.

@param encoded The base64 encoded string.

Decodes the specified base64 string back into its raw data .


@Override
    public synchronized void flush()
            throws IOException
    {
        super.flush();
        String record = this.toString();
        reset();

        if (record.isEmpty() || record.equals(lineSeparator)) {
            // avoid empty records
            return;
        }

        logger.info(record);
    }

@
Override
public
synchronized
void
flush
(
)
throws
IOException
{
super
.
flush
(
)
;
String
record
=
this
.
toString
(
)
;
reset
(
)
;
if
(
record
.
isEmpty
(
)
||
record
.
equals
(
lineSeparator
)
)
{
// avoid empty records
return
;
}
logger
.
info
(
record
)
;
}

write the current buffer contents to the underlying logger.

write the current buffer contents to the underlying logger .


@SuppressWarnings("UnusedDeclaration")
    public String dumpDestination(URI uri)
    {
        Destination destination = httpClient.getDestination(uri.getScheme(), uri.getHost(), uri.getPort());
        if (destination == null) {
            return null;
        }

        return dumpDestination(destination);
    }

@ SuppressWarnings ( "UnusedDeclaration" ) public String dumpDestination ( URI uri ) { Destination destination = httpClient . getDestination ( uri . getScheme ( ) , uri . getHost ( ) , uri . getPort ( ) ) ; if ( destination == null ) { return null ; } return dumpDestination ( destination ) ; }

todo this should be @Managed but operations with parameters are broken in jmx utils https://github.com/martint/jmxutils/issues/27


public static double computeAlpha(double targetWeight, long targetAgeInSeconds)
    {
        checkArgument(targetAgeInSeconds > 0, "targetAgeInSeconds must be > 0");
        checkArgument(targetWeight > 0 && targetWeight < 1, "targetWeight must be in range (0, 1)");

        return -Math.log(targetWeight) / targetAgeInSeconds;
    }

public
static
double
computeAlpha
(
double
targetWeight
,
long
targetAgeInSeconds
)
{
checkArgument
(
targetAgeInSeconds
>
0
,
"targetAgeInSeconds must be > 0"
)
;
checkArgument
(
targetWeight
>
0
&&
targetWeight
<
1
,
"targetWeight must be in range (0, 1)"
)
;
return
Math
.
log
(
targetWeight
)
/
targetAgeInSeconds
;
}

Compute the alpha decay factor such that the weight of an entry with age 'targetAgeInSeconds' is targetWeight'

Compute the alpha decay factor such that the weight of an entry with age targetAgeInSeconds is targetWeight


public static <X, Y> void propagateCancellation(ListenableFuture<? extends X> source, Future<? extends Y> destination, boolean mayInterruptIfRunning)
    {
        source.addListener(() -> {
            if (source.isCancelled()) {
                destination.cancel(mayInterruptIfRunning);
            }
        }, directExecutor());
    }

public static < X , Y > void propagateCancellation ( ListenableFuture < ? extends X > source , Future < ? extends Y > destination , boolean mayInterruptIfRunning ) { source . addListener ( ( ) -> { if ( source . isCancelled ( ) ) { destination . cancel ( mayInterruptIfRunning ) ; } } , directExecutor ( ) ) ; }

Cancels the destination Future if the source Future is cancelled.

Cancels the destination Future if the source Future is cancelled .


@Deprecated
    public static <V> CompletableFuture<V> unmodifiableFuture(CompletableFuture<V> future)
    {
        return unmodifiableFuture(future, false);
    }

@ Deprecated public static < V > CompletableFuture < V > unmodifiableFuture ( CompletableFuture < V > future ) { return unmodifiableFuture ( future , false ) ; }

Returns a future that can not be completed or canceled.

Returns a future that can not be completed or canceled .


@Deprecated
    public static <V> CompletableFuture<V> unmodifiableFuture(CompletableFuture<V> future, boolean propagateCancel)
    {
        requireNonNull(future, "future is null");

        Function<Boolean, Boolean> onCancelFunction;
        if (propagateCancel) {
            onCancelFunction = future::cancel;
        }
        else {
            onCancelFunction = mayInterrupt -> false;
        }

        UnmodifiableCompletableFuture<V> unmodifiableFuture = new UnmodifiableCompletableFuture<>(onCancelFunction);
        future.whenComplete((value, exception) -> {
            if (exception != null) {
                unmodifiableFuture.internalCompleteExceptionally(exception);
            }
            else {
                unmodifiableFuture.internalComplete(value);
            }
        });
        return unmodifiableFuture;
    }

@
Deprecated
public
static
<
V
>
CompletableFuture
<
V
>
unmodifiableFuture
(
CompletableFuture
<
V
>
future
,
boolean
propagateCancel
)
{
requireNonNull
(
future
,
"future is null"
)
;
Function
<
Boolean
,
Boolean
>
onCancelFunction
;
if
(
propagateCancel
)
{
onCancelFunction
=
future
::
cancel
;
}
else
{
onCancelFunction
=
mayInterrupt
->
false
;
}
UnmodifiableCompletableFuture
<
V
>
unmodifiableFuture
=
new
UnmodifiableCompletableFuture
<>
(
onCancelFunction
)
;
future
.
whenComplete
(
(
value
,
exception
)
->
{
if
(
exception
!=
)
{
unmodifiableFuture
.
internalCompleteExceptionally
(
exception
)
;
}
else
{
unmodifiableFuture
.
internalComplete
(
value
)
;
}
}
)
;
return
unmodifiableFuture
;
}

Returns a future that can not be completed or optionally canceled.

Returns a future that can not be completed or optionally canceled .


@Deprecated
    public static <V> CompletableFuture<V> failedFuture(Throwable throwable)
    {
        requireNonNull(throwable, "throwable is null");
        CompletableFuture<V> future = new CompletableFuture<>();
        future.completeExceptionally(throwable);
        return future;
    }

@
Deprecated
public
static
<
V
>
CompletableFuture
<
V
>
failedFuture
(
Throwable
throwable
)
{
requireNonNull
(
throwable
,
"throwable is null"
)
;
CompletableFuture
<
V
>
future
=
new
CompletableFuture
<>
(
)
;
future
.
completeExceptionally
(
throwable
)
;
return
future
;
}

Returns a failed future containing the specified throwable.

Returns a failed future containing the specified throwable .


public static <V, E extends Exception> V getFutureValue(Future<V> future, Class<E> exceptionType)
            throws E
    {
        requireNonNull(future, "future is null");
        requireNonNull(exceptionType, "exceptionType is null");

        try {
            return future.get();
        }
        catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new RuntimeException("interrupted", e);
        }
        catch (ExecutionException e) {
            Throwable cause = e.getCause() == null ? e : e.getCause();
            propagateIfPossible(cause, exceptionType);
            throw new RuntimeException(cause);
        }
    }

public
static
<
V
,
E
extends
Exception
>
V
getFutureValue
(
Future
<
V
>
future
,
Class
<
E
>
exceptionType
)
throws
E
{
requireNonNull
(
future
,
"future is null"
)
;
requireNonNull
(
exceptionType
,
"exceptionType is null"
)
;
try
{
return
future
.
get
(
)
;
}
catch
(
InterruptedException
e
)
{
Thread
.
currentThread
(
)
.
interrupt
(
)
;
throw
new
RuntimeException
(
"interrupted"
,
e
)
;
}
catch
(
ExecutionException
e
)
{
Throwable
cause
=
e
.
getCause
(
)
==
e
:
e
.
getCause
(
)
;
propagateIfPossible
(
cause
,
exceptionType
)
;
throw
new
RuntimeException
(
cause
)
;
}
}

Waits for the value from the future. If the future is failed, the exception
is thrown directly if it is an instance of the specified exception type or
unchecked, or it is wrapped in a RuntimeException. If the thread is
interrupted, the thread interruption flag is set and the original
InterruptedException is wrapped in a RuntimeException and thrown.

Waits for the value from the future . If the future is failed the exception is thrown directly if it is an instance of the specified exception type or unchecked or it is wrapped in a RuntimeException . If the thread is interrupted the thread interruption flag is set and the original InterruptedException is wrapped in a RuntimeException and thrown .


public static <T> Optional<T> tryGetFutureValue(Future<T> future)
    {
        requireNonNull(future, "future is null");
        if (!future.isDone()) {
            return Optional.empty();
        }

        return tryGetFutureValue(future, 0, MILLISECONDS);
    }

public
static
<
T
>
Optional
<
T
>
tryGetFutureValue
(
Future
<
T
>
future
)
{
requireNonNull
(
future
,
"future is null"
)
;
if
(
!
future
.
isDone
(
)
)
{
return
Optional
.
empty
(
)
;
}
return
tryGetFutureValue
(
future
,
0
,
MILLISECONDS
)
;
}

Gets the current value of the future without waiting. If the future
value is null, an empty Optional is still returned, and in this case the caller
must check the future directly for the null value.

Gets the current value of the future without waiting . If the future value is null an empty Optional is still returned and in this case the caller must check the future directly for the null value .


public static <V> Optional<V> tryGetFutureValue(Future<V> future, int timeout, TimeUnit timeUnit)
    {
        return tryGetFutureValue(future, timeout, timeUnit, RuntimeException.class);
    }

public static < V > Optional < V > tryGetFutureValue ( Future < V > future , int timeout , TimeUnit timeUnit ) { return tryGetFutureValue ( future , timeout , timeUnit , RuntimeException . class ) ; }

Waits for the the value from the future for the specified time.  If the future
value is null, an empty Optional is still returned, and in this case the caller
must check the future directly for the null value.  If the future is failed,
the exception is thrown directly if unchecked or wrapped in a RuntimeException.
If the thread is interrupted, the thread interruption flag is set and the original
InterruptedException is wrapped in a RuntimeException and thrown.

Waits for the the value from the future for the specified time . If the future value is null an empty Optional is still returned and in this case the caller must check the future directly for the null value . If the future is failed the exception is thrown directly if unchecked or wrapped in a RuntimeException . If the thread is interrupted the thread interruption flag is set and the original InterruptedException is wrapped in a RuntimeException and thrown .


public static <V, E extends Exception> Optional<V> tryGetFutureValue(Future<V> future, int timeout, TimeUnit timeUnit, Class<E> exceptionType)
            throws E
    {
        requireNonNull(future, "future is null");
        checkArgument(timeout >= 0, "timeout is negative");
        requireNonNull(timeUnit, "timeUnit is null");
        requireNonNull(exceptionType, "exceptionType is null");

        try {
            return Optional.ofNullable(future.get(timeout, timeUnit));
        }
        catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new RuntimeException("interrupted", e);
        }
        catch (ExecutionException e) {
            Throwable cause = e.getCause() == null ? e : e.getCause();
            propagateIfPossible(cause, exceptionType);
            throw new RuntimeException(cause);
        }
        catch (TimeoutException expected) {
            // expected
        }
        return Optional.empty();
    }

public
static
<
V
,
E
extends
Exception
>
Optional
<
V
>
tryGetFutureValue
(
Future
<
V
>
future
,
int
timeout
,
TimeUnit
timeUnit
,
Class
<
E
>
exceptionType
)
throws
E
{
requireNonNull
(
future
,
"future is null"
)
;
checkArgument
(
timeout
>=
0
,
"timeout is negative"
)
;
requireNonNull
(
timeUnit
,
"timeUnit is null"
)
;
requireNonNull
(
exceptionType
,
"exceptionType is null"
)
;
try
{
return
Optional
.
ofNullable
(
future
.
get
(
timeout
,
timeUnit
)
)
;
}
catch
(
InterruptedException
e
)
{
Thread
.
currentThread
(
)
.
interrupt
(
)
;
throw
new
RuntimeException
(
"interrupted"
,
e
)
;
}
catch
(
ExecutionException
e
)
{
Throwable
cause
=
e
.
getCause
(
)
==
e
:
e
.
getCause
(
)
;
propagateIfPossible
(
cause
,
exceptionType
)
;
throw
new
RuntimeException
(
cause
)
;
}
catch
(
TimeoutException
expected
)
{
// expected
}
return
Optional
.
empty
(
)
;
}

Waits for the the value from the future for the specified time.  If the future
value is null, an empty Optional is still returned, and in this case the caller
must check the future directly for the null value.  If the future is failed,
the exception is thrown directly if it is an instance of the specified exception
type or unchecked, or it is wrapped in a RuntimeException. If the thread is
interrupted, the thread interruption flag is set and the original
InterruptedException is wrapped in a RuntimeException and thrown.

Waits for the the value from the future for the specified time . If the future value is null an empty Optional is still returned and in this case the caller must check the future directly for the null value . If the future is failed the exception is thrown directly if it is an instance of the specified exception type or unchecked or it is wrapped in a RuntimeException . If the thread is interrupted the thread interruption flag is set and the original InterruptedException is wrapped in a RuntimeException and thrown .


public static void checkSuccess(Future<?> future, String errorMessage)
    {
        requireNonNull(future, "future is null");
        requireNonNull(errorMessage, "errorMessage is null");
        checkArgument(future.isDone(), "future not done yet");
        try {
            getFutureValue(future);
        }
        catch (RuntimeException e) {
            throw new IllegalArgumentException(errorMessage, e);
        }
    }

public
static
void
checkSuccess
(
Future
<
>
future
,
String
errorMessage
)
{
requireNonNull
(
future
,
"future is null"
)
;
requireNonNull
(
errorMessage
,
"errorMessage is null"
)
;
checkArgument
(
future
.
isDone
(
)
,
"future not done yet"
)
;
try
{
getFutureValue
(
future
)
;
}
catch
(
RuntimeException
e
)
{
throw
new
IllegalArgumentException
(
errorMessage
,
e
)
;
}
}

Checks that the completed future completed successfully.

Checks that the completed future completed successfully .


public static <V> ListenableFuture<V> whenAnyComplete(Iterable<? extends ListenableFuture<? extends V>> futures)
    {
        requireNonNull(futures, "futures is null");
        checkArgument(!isEmpty(futures), "futures is empty");

        ExtendedSettableFuture<V> firstCompletedFuture = ExtendedSettableFuture.create();
        for (ListenableFuture<? extends V> future : futures) {
            firstCompletedFuture.setAsync(future);
        }
        return firstCompletedFuture;
    }

public
static
<
V
>
ListenableFuture
<
V
>
whenAnyComplete
(
Iterable
<
extends
ListenableFuture
<
extends
V
>
>
futures
)
{
requireNonNull
(
futures
,
"futures is null"
)
;
checkArgument
(
!
isEmpty
(
futures
)
,
"futures is empty"
)
;
ExtendedSettableFuture
<
V
>
firstCompletedFuture
=
ExtendedSettableFuture
.
create
(
)
;
for
(
ListenableFuture
<
extends
V
>
future
:
futures
)
{
firstCompletedFuture
.
setAsync
(
future
)
;
}
return
firstCompletedFuture
;
}

Creates a future that completes when the first future completes either normally
or exceptionally. Cancellation of the future propagates to the supplied futures.

Creates a future that completes when the first future completes either normally or exceptionally . Cancellation of the future propagates to the supplied futures .


@Deprecated
    public static <V> CompletableFuture<V> firstCompletedFuture(Iterable<? extends CompletionStage<? extends V>> futures)
    {
        return firstCompletedFuture(futures, false);
    }

@ Deprecated public static < V > CompletableFuture < V > firstCompletedFuture ( Iterable < ? extends CompletionStage < ? extends V > > futures ) { return firstCompletedFuture ( futures , false ) ; }

Creates a future that completes when the first future completes either normally
or exceptionally. Cancellation of the future does not propagate to the supplied
futures.

Creates a future that completes when the first future completes either normally or exceptionally . Cancellation of the future does not propagate to the supplied futures .


@Deprecated
    public static <V> CompletableFuture<V> firstCompletedFuture(Iterable<? extends CompletionStage<? extends V>> futures, boolean propagateCancel)
    {
        requireNonNull(futures, "futures is null");
        checkArgument(!isEmpty(futures), "futures is empty");

        CompletableFuture<V> future = new CompletableFuture<>();
        for (CompletionStage<? extends V> stage : futures) {
            stage.whenComplete((value, exception) -> {
                if (exception != null) {
                    future.completeExceptionally(exception);
                }
                else {
                    future.complete(value);
                }
            });
        }
        if (propagateCancel) {
            future.exceptionally(throwable -> {
                if (throwable instanceof CancellationException) {
                    for (CompletionStage<? extends V> sourceFuture : futures) {
                        if (sourceFuture instanceof Future) {
                            ((Future<?>) sourceFuture).cancel(true);
                        }
                    }
                }
                return null;
            });
        }
        return future;
    }

@
Deprecated
public
static
<
V
>
CompletableFuture
<
V
>
firstCompletedFuture
(
Iterable
<
extends
CompletionStage
<
extends
V
>
>
futures
,
boolean
propagateCancel
)
{
requireNonNull
(
futures
,
"futures is null"
)
;
checkArgument
(
!
isEmpty
(
futures
)
,
"futures is empty"
)
;
CompletableFuture
<
V
>
future
=
new
CompletableFuture
<>
(
)
;
for
(
CompletionStage
<
extends
V
>
stage
:
futures
)
{
stage
.
whenComplete
(
(
value
,
exception
)
->
{
if
(
exception
!=
)
{
future
.
completeExceptionally
(
exception
)
;
}
else
{
future
.
complete
(
value
)
;
}
}
)
;
}
if
(
propagateCancel
)
{
future
.
exceptionally
(
throwable
->
{
if
(
throwable
instanceof
CancellationException
)
{
for
(
CompletionStage
<
extends
V
>
sourceFuture
:
futures
)
{
if
(
sourceFuture
instanceof
Future
)
{
(
(
Future
<
>
)
sourceFuture
)
.
cancel
(
true
)
;
}
}
}
return
;
}
)
;
}
return
future
;
}

Creates a future that completes when the first future completes either normally
or exceptionally. Cancellation of the future will optionally propagate to the
supplied futures.

Creates a future that completes when the first future completes either normally or exceptionally . Cancellation of the future will optionally propagate to the supplied futures .


@Deprecated
    public static <V> CompletableFuture<List<V>> allAsList(List<CompletableFuture<? extends V>> futures)
    {
        CompletableFuture<Void> allDoneFuture = CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()]));

        // Eagerly propagate exceptions, rather than waiting for all the futures to complete first (default behavior)
        for (CompletableFuture<? extends V> future : futures) {
            future.whenComplete((v, throwable) -> {
                if (throwable != null) {
                    allDoneFuture.completeExceptionally(throwable);
                }
            });
        }

        return unmodifiableFuture(allDoneFuture.thenApply(v ->
                futures.stream()
                        .map(CompletableFuture::join)
                        .collect(Collectors.<V>toList())));
    }

Returns an unmodifiable future that is completed when all of the given
futures complete. If any of the given futures complete exceptionally, then the
returned future also does so immediately, with a CompletionException holding this exception
as its cause. Otherwise, the results of the given futures are reflected in the
returned future as a list of results matching the input order. If no futures are
provided, returns a future completed with an empty list.

Returns an unmodifiable future that is completed when all of the given futures complete . If any of the given futures complete exceptionally then the returned future also does so immediately with a CompletionException holding this exception as its cause . Otherwise the results of the given futures are reflected in the returned future as a list of results matching the input order . If no futures are provided returns a future completed with an empty list .


public static <V> CompletableFuture<V> toCompletableFuture(ListenableFuture<V> listenableFuture)
    {
        requireNonNull(listenableFuture, "listenableFuture is null");

        CompletableFuture<V> future = new CompletableFuture<>();
        future.exceptionally(throwable -> {
            if (throwable instanceof CancellationException) {
                listenableFuture.cancel(true);
            }
            return null;
        });

        FutureCallback<V> callback = new FutureCallback<V>()
        {
            @Override
            public void onSuccess(V result)
            {
                future.complete(result);
            }

            @Override
            public void onFailure(Throwable t)
            {
                future.completeExceptionally(t);
            }
        };
        Futures.addCallback(listenableFuture, callback, directExecutor());
        return future;
    }

public
static
<
V
>
CompletableFuture
<
V
>
toCompletableFuture
(
ListenableFuture
<
V
>
listenableFuture
)
{
requireNonNull
(
listenableFuture
,
"listenableFuture is null"
)
;
CompletableFuture
<
V
>
future
=
new
CompletableFuture
<>
(
)
;
future
.
exceptionally
(
throwable
->
{
if
(
throwable
instanceof
CancellationException
)
{
listenableFuture
.
cancel
(
true
)
;
}
return
;
}
)
;
FutureCallback
<
V
>
callback
=
new
FutureCallback
<
V
>
(
)
{
@
Override
public
void
onSuccess
(
V
result
)
{
future
.
complete
(
result
)
;
}
@
Override
public
void
onFailure
(
Throwable
t
)
{
future
.
completeExceptionally
(
t
)
;
}
}
;
Futures
.
addCallback
(
listenableFuture
,
callback
,
directExecutor
(
)
)
;
return
future
;
}

Converts a ListenableFuture to a CompletableFuture. Cancellation of the
CompletableFuture will be propagated to the ListenableFuture.

Converts a ListenableFuture to a CompletableFuture . Cancellation of the CompletableFuture will be propagated to the ListenableFuture .


public static <V> ListenableFuture<V> toListenableFuture(CompletableFuture<V> completableFuture)
    {
        requireNonNull(completableFuture, "completableFuture is null");
        SettableFuture<V> future = SettableFuture.create();
        propagateCancellation(future, completableFuture, true);

        completableFuture.whenComplete((value, exception) -> {
            if (exception != null) {
                future.setException(exception);
            }
            else {
                future.set(value);
            }
        });
        return future;
    }

public
static
<
V
>
ListenableFuture
<
V
>
toListenableFuture
(
CompletableFuture
<
V
>
completableFuture
)
{
requireNonNull
(
completableFuture
,
"completableFuture is null"
)
;
SettableFuture
<
V
>
future
=
SettableFuture
.
create
(
)
;
propagateCancellation
(
future
,
completableFuture
,
true
)
;
completableFuture
.
whenComplete
(
(
value
,
exception
)
->
{
if
(
exception
!=
)
{
future
.
setException
(
exception
)
;
}
else
{
future
.
set
(
value
)
;
}
}
)
;
return
future
;
}

Converts a CompletableFuture to a ListenableFuture. Cancellation of the
ListenableFuture will be propagated to the CompletableFuture.

Converts a CompletableFuture to a ListenableFuture . Cancellation of the ListenableFuture will be propagated to the CompletableFuture .


public static <T> void addExceptionCallback(ListenableFuture<T> future, Runnable exceptionCallback, Executor executor)
    {
        requireNonNull(exceptionCallback, "exceptionCallback is null");

        addExceptionCallback(future, t -> exceptionCallback.run(), executor);
    }

public
static
<
T
>
void
addExceptionCallback
(
ListenableFuture
<
T
>
future
,
Runnable
exceptionCallback
,
Executor
executor
)
{
requireNonNull
(
exceptionCallback
,
"exceptionCallback is null"
)
;
addExceptionCallback
(
future
,
t
->
exceptionCallback
.
run
(
)
,
executor
)
;
}

Invokes the callback, using the specified executor, if the future fails.

Invokes the callback using the specified executor if the future fails .


public List<Bucket> getHistogram(List<Long> bucketUpperBounds, MiddleFunction middleFunction)
    {
        checkArgument(Ordering.natural().isOrdered(bucketUpperBounds), "buckets must be sorted in increasing order");

        ImmutableList.Builder<Bucket> builder = ImmutableList.builder();
        PeekingIterator<Long> iterator = Iterators.peekingIterator(bucketUpperBounds.iterator());

        HistogramBuilderStateHolder holder = new HistogramBuilderStateHolder();

        double normalizationFactor = weight(TimeUnit.NANOSECONDS.toSeconds(ticker.read()));

        postOrderTraversal(root, node -> {
            while (iterator.hasNext() && iterator.peek() <= upperBound(node)) {
                double bucketCount = holder.sum - holder.lastSum;

                Bucket bucket = new Bucket(bucketCount / normalizationFactor, holder.bucketWeightedSum / bucketCount);

                builder.add(bucket);
                holder.lastSum = holder.sum;
                holder.bucketWeightedSum = 0;
                iterator.next();
            }

            holder.bucketWeightedSum += middleFunction.middle(lowerBound(node), upperBound(node)) * counts[node];
            holder.sum += counts[node];
            return iterator.hasNext();
        });

        while (iterator.hasNext()) {
            double bucketCount = holder.sum - holder.lastSum;
            Bucket bucket = new Bucket(bucketCount / normalizationFactor, holder.bucketWeightedSum / bucketCount);

            builder.add(bucket);

            iterator.next();
        }

        return builder.build();
    }


private int tryRemove(int node)
    {
        checkArgument(node != -1, "node is -1");

        int left = lefts[node];
        int right = rights[node];

        if (left == -1 && right == -1) {
            // leaf, just remove it
            remove(node);
            return -1;
        }

        if (left != -1 && right != -1) {
            // node has both children so we can't physically remove it
            counts[node] = 0;
            return node;
        }

        // node has a single child, so remove it and return the child
        remove(node);
        if (left != -1) {
            return left;
        }
        else {
            return right;
        }
    }

Remove the node if possible or set its count to 0 if it has children and
it needs to be kept around


private double computeMaxPathWeight(int node)
    {
        if (node == -1 || levels[node] == 0) {
            return 0;
        }

        double leftMaxWeight = computeMaxPathWeight(lefts[node]);
        double rightMaxWeight = computeMaxPathWeight(rights[node]);

        return Math.max(leftMaxWeight, rightMaxWeight) + counts[node];
    }

private double computeMaxPathWeight ( int node ) { if ( node == - 1 || levels [ node ] == 0 ) { return 0 ; } double leftMaxWeight = computeMaxPathWeight ( lefts [ node ] ) ; double rightMaxWeight = computeMaxPathWeight ( rights [ node ] ) ; return Math . max ( leftMaxWeight , rightMaxWeight ) + counts [ node ] ; }

Computes the max "weight" of any path starting at node and ending at a leaf in the
hypothetical complete tree. The weight is the sum of counts in the ancestors of a given node

Computes the max weight of any path starting at node and ending at a leaf in the hypothetical complete tree . The weight is the sum of counts in the ancestors of a given node


public void addHash(long hash)
    {
        instance.insertHash(hash);

        if (instance instanceof SparseHll) {
            instance = makeDenseIfNecessary((SparseHll) instance);
        }
    }

public void addHash ( long hash ) { instance . insertHash ( hash ) ; if ( instance instanceof SparseHll ) { instance = makeDenseIfNecessary ( ( SparseHll ) instance ) ; } }

Adds a value that has already been hashed to the set of values tracked by this HyperLogLog instance.

@param hash The hash should be the 64 least significant bits of the murmur3_128 hash of the value.
For example: io.airlift.slice.Murmur3.hash64(value).

Adds a value that has already been hashed to the set of values tracked by this HyperLogLog instance .


public static Map<String, String> loadPropertiesFrom(String path)
            throws IOException
    {
        Properties properties = new Properties();
        try (InputStream inputStream = new FileInputStream(path)) {
            properties.load(inputStream);
        }

        return fromProperties(properties);
    }

public static Map < String , String > loadPropertiesFrom ( String path ) throws IOException { Properties properties = new Properties ( ) ; try ( InputStream inputStream = new FileInputStream ( path ) ) { properties . load ( inputStream ) ; } return fromProperties ( properties ) ; }

Loads properties from the given file

@param path file path
@return properties
@throws IOException errors


public <T> void bindConfigGlobalDefaults(Class<T> configClass, ConfigDefaults<T> configDefaults)
    {
        Key<T> key = Key.get(configClass, GlobalDefaults.class);
        binder.bindConfigDefaults(new ConfigDefaultsHolder<>(key, configDefaults));
    }

public < T > void bindConfigGlobalDefaults ( Class < T > configClass , ConfigDefaults < T > configDefaults ) { Key < T > key = Key . get ( configClass , GlobalDefaults . class ) ; binder . bindConfigDefaults ( new ConfigDefaultsHolder <> ( key , configDefaults ) ) ; }

Binds default values for all the instances of given config class for the current binder


public Duration next(int pollCount, Duration previousDuration) {
        return new Duration(fibonacci(offset + pollCount), timeUnit);
    }

public Duration next ( int pollCount , Duration previousDuration ) { return new Duration ( fibonacci ( offset + pollCount ) , timeUnit ) ; }

Generate the next duration

@param pollCount        The number of times the condition has been polled (evaluated)
@param previousDuration The duration of the previously returned poll interval
@return The next duration in the fibonacci sequence.


private int fib(int value, int current, int previous) {
        if (value == 0) {
            return previous;
        } else if (value == 1) {
            return current;
        }
        return fib(value - 1, current + previous, current);
    }

private int fib ( int value , int current , int previous ) { if ( value == 0 ) { return previous ; } else if ( value == 1 ) { return current ; } return fib ( value - 1 , current + previous , current ) ; }

Tail recursive implementation of fibonacci


public Duration multiply(long amount) {
        return new Multiply().apply(this, unit == null ? FOREVER : new Duration(amount, unit));
    }

public Duration multiply ( long amount ) { return new Multiply ( ) . apply ( this , unit == null ? FOREVER : new Duration ( amount , unit ) ) ; }

Multiply this amount with the given amount

@param amount The amount
@return A new amount


public Duration divide(long amount) {
        return new Divide().apply(this, unit == null ? FOREVER : new Duration(amount, unit));
    }

public Duration divide ( long amount ) { return new Divide ( ) . apply ( this , unit == null ? FOREVER : new Duration ( amount , unit ) ) ; }

Divide this duration amount with the given amount

@param amount The amount
@return A new amount


private static Field findSingleFieldUsingStrategy(FieldMatcherStrategy strategy, Object object,
                                                      boolean checkHierarchy, Class<?> startClass) {
        assertObjectInGetInternalStateIsNotNull(object);
        Field foundField = null;
        final Class<?> originalStartClass = startClass;
        while (startClass != null) {
            final Field[] declaredFields = startClass.getDeclaredFields();
            for (Field field : declaredFields) {
                if (strategy.matches(field) && hasFieldProperModifier(object, field)) {
                    if (foundField != null) {
                        throw new TooManyFieldsFoundException("Two or more fields matching " + strategy + ".");
                    }
                    foundField = field;
                }
            }
            if (foundField != null) {
                break;
            } else if (!checkHierarchy) {
                break;
            }
            startClass = startClass.getSuperclass();
        }
        if (foundField == null) {
            strategy.notFound(originalStartClass, !isClass(object));
            return null;
        }
        foundField.setAccessible(true);
        return foundField;
    }

private
static
Field
findSingleFieldUsingStrategy
(
FieldMatcherStrategy
strategy
,
Object
object
,
boolean
checkHierarchy
,
Class
<
>
startClass
)
{
assertObjectInGetInternalStateIsNotNull
(
object
)
;
Field
foundField
=
;
final
Class
<
>
originalStartClass
=
startClass
;
while
(
startClass
!=
)
{
final
Field
[
]
declaredFields
=
startClass
.
getDeclaredFields
(
)
;
for
(
Field
field
:
declaredFields
)
{
if
(
strategy
.
matches
(
field
)
&&
hasFieldProperModifier
(
object
,
field
)
)
{
if
(
foundField
!=
)
{
throw
new
TooManyFieldsFoundException
(
"Two or more fields matching "
+
strategy
+
"."
)
;
}
foundField
=
field
;
}
}
if
(
foundField
!=
)
{
break
;
}
else
if
(
!
checkHierarchy
)
{
break
;
}
startClass
=
startClass
.
getSuperclass
(
)
;
}
if
(
foundField
==
)
{
strategy
.
notFound
(
originalStartClass
,
!
isClass
(
object
)
)
;
return
;
}
foundField
.
setAccessible
(
true
)
;
return
foundField
;
}

Find single field using strategy.

@param strategy       the strategy
@param object         the object
@param checkHierarchy the check hierarchy
@param startClass     the start class
@return the field


private static boolean hasFieldProperModifier(Object object, Field field) {
        return ((object instanceof Class<?> && Modifier.isStatic(field.getModifiers())) || !(object instanceof Class<?> || Modifier
                .isStatic(field.getModifiers())));
    }

private static boolean hasFieldProperModifier ( Object object , Field field ) { return ( ( object instanceof Class < ? > && Modifier . isStatic ( field . getModifiers ( ) ) ) || ! ( object instanceof Class < ? > || Modifier . isStatic ( field . getModifiers ( ) ) ) ) ; }

Checks for field proper modifier.

@param object the object
@param field  the field
@return true, if successful


public static void throwExceptionIfFieldWasNotFound(Class<?> type, String fieldName, Field field) {
        if (field == null) {
            throw new FieldNotFoundException("No field was found with name '" + fieldName + "' in class "
                    + type.getName() + ".");
        }
    }

public
static
void
throwExceptionIfFieldWasNotFound
(
Class
<
>
type
,
String
fieldName
,
Field
field
)
{
if
(
field
==
)
{
throw
new
FieldNotFoundException
(
"No field was found with name '"
+
fieldName
+
"' in class "
+
type
.
getName
(
)
+
"."
)
;
}
}

Throw exception if field was not found.

@param type      the type
@param fieldName the field name
@param field     the field

Throw exception if field was not found .


public static Field getFieldAnnotatedWith(Object object, Class<? extends Annotation> annotationType) {
        return findSingleFieldUsingStrategy(new FieldAnnotationMatcherStrategy(annotationType), object, true,
                getType(object));
    }

public static Field getFieldAnnotatedWith ( Object object , Class < ? extends Annotation > annotationType ) { return findSingleFieldUsingStrategy ( new FieldAnnotationMatcherStrategy ( annotationType ) , object , true , getType ( object ) ) ; }

Get field annotated with a particular annotation. This method traverses
the class hierarchy when checking for the annotation.

@param object         The object to look for annotations. Note that if're you're
passing an object only instance fields are checked, passing a
class will only check static fields.
@param annotationType The annotation types to look for
@return A set of all fields containing the particular annotation(s).
@since 1.3

Get field annotated with a particular annotation . This method traverses the class hierarchy when checking for the annotation .


public ConditionFactory conditionEvaluationListener(ConditionEvaluationListener conditionEvaluationListener) {
        return new ConditionFactory(alias, timeoutConstraint, pollInterval, pollDelay, catchUncaughtExceptions,
                exceptionsIgnorer, conditionEvaluationListener, executorLifecycle);
    }

public ConditionFactory conditionEvaluationListener ( ConditionEvaluationListener conditionEvaluationListener ) { return new ConditionFactory ( alias , timeoutConstraint , pollInterval , pollDelay , catchUncaughtExceptions , exceptionsIgnorer , conditionEvaluationListener , executorLifecycle ) ; }

Handle condition evaluation results each time evaluation of a condition occurs. Works only with a Hamcrest matcher-based condition.

@param conditionEvaluationListener the condition evaluation listener
@return the condition factory

Handle condition evaluation results each time evaluation of a condition occurs . Works only with a Hamcrest matcher - based condition .


public ConditionFactory pollExecutorService(ExecutorService executorService) {
        if (executorService != null && executorService instanceof ScheduledExecutorService) {
            throw new IllegalArgumentException("Poll executor service cannot be an instance of " + ScheduledExecutorService.class.getName());
        }
        return new ConditionFactory(alias, timeoutConstraint, pollInterval, pollDelay, false,
                exceptionsIgnorer, conditionEvaluationListener, ExecutorLifecycle.withoutCleanup(executorService));
    }

Specify the executor service whose threads will be used to evaluate the poll condition in Awaitility.
Note that the executor service must be shutdown manually!

This is an advanced feature and it should only be used sparingly.

@param executorService The executor service that Awaitility will use when polling condition evaluations
@return the condition factory

Specify the executor service whose threads will be used to evaluate the poll condition in Awaitility . Note that the executor service must be shutdown manually!


public void untilTrue(final AtomicBoolean atomic) {
        untilAtomic(atomic, anyOf(is(Boolean.TRUE), is(true)));
    }

public void untilTrue ( final AtomicBoolean atomic ) { untilAtomic ( atomic , anyOf ( is ( Boolean . TRUE ) , is ( true ) ) ) ; }

Await until a Atomic boolean becomes true.

@param atomic the atomic variable
@throws org.awaitility.core.ConditionTimeoutException If condition was not fulfilled within the given time period.

Await until a Atomic boolean becomes true .


public void untilFalse(final AtomicBoolean atomic) {
        untilAtomic(atomic, anyOf(is(Boolean.FALSE), is(false)));
    }

public void untilFalse ( final AtomicBoolean atomic ) { untilAtomic ( atomic , anyOf ( is ( Boolean . FALSE ) , is ( false ) ) ) ; }

Await until a Atomic boolean becomes false.

@param atomic the atomic variable
@throws org.awaitility.core.ConditionTimeoutException If condition was not fulfilled within the given time period.

Await until a Atomic boolean becomes false .


public static ConditionFactory catchUncaughtExceptions() {
        return new ConditionFactory(null, defaultWaitConstraint, defaultPollInterval, defaultPollDelay,
                defaultCatchUncaughtExceptions, defaultExceptionIgnorer, defaultConditionEvaluationListener,
                defaultExecutorLifecycle);
    }

public static ConditionFactory catchUncaughtExceptions ( ) { return new ConditionFactory ( null , defaultWaitConstraint , defaultPollInterval , defaultPollDelay , defaultCatchUncaughtExceptions , defaultExceptionIgnorer , defaultConditionEvaluationListener , defaultExecutorLifecycle ) ; }

Catching uncaught exceptions in other threads. This will make the await
statement fail even if exceptions occur in other threads. This is the
default behavior.

@return the condition factory

Catching uncaught exceptions in other threads . This will make the await statement fail even if exceptions occur in other threads . This is the default behavior .


public static void setDefaultTimeout(long timeout, TimeUnit unit) {
        defaultWaitConstraint = defaultWaitConstraint.withMaxWaitTime(new Duration(timeout, unit));
    }

public static void setDefaultTimeout ( long timeout , TimeUnit unit ) { defaultWaitConstraint = defaultWaitConstraint . withMaxWaitTime ( new Duration ( timeout , unit ) ) ; }

Sets the default timeout all await statements will use.

@param timeout the timeout
@param unit    the unit

Sets the default timeout all await statements will use .


public static void setDefaultTimeout(Duration defaultTimeout) {
        if (defaultTimeout == null) {
            throw new IllegalArgumentException("You must specify a default timeout (was null).");
        }
        defaultWaitConstraint = defaultWaitConstraint.withMaxWaitTime(defaultTimeout);
    }

Sets the default timeout that all await statements will use.

@param defaultTimeout the new default timeout

Sets the default timeout that all await statements will use .


public static List<String> tokenize(String arguments, boolean stringify) {

    LinkedList<String> argList = new LinkedList<>();
    StringBuilder currArg = new StringBuilder();
    boolean escaped = false;
    int state = NO_TOKEN_STATE;  // start in the NO_TOKEN_STATE
    int len = arguments.length();

    // Loop over each character in the string
    for (int i = 0; i < len; i++) {
      char c = arguments.charAt(i);
      if (escaped) {
        // Escaped state: just append the next character to the current arg.
        escaped = false;
        currArg.append(c);
      }
      else {
        switch(state) {
          case SINGLE_QUOTE_STATE:
            if (c == '\'') {
            // Seen the close quote; continue this arg until whitespace is seen
            state = NORMAL_TOKEN_STATE;
          }
            else {
              currArg.append(c);
            }
            break;
          case DOUBLE_QUOTE_STATE:
            if (c == '"') {
            // Seen the close quote; continue this arg until whitespace is seen
            state = NORMAL_TOKEN_STATE;
          }
            else if (c == '\\') {
              // Look ahead, and only escape quotes or backslashes
              i++;
              char next = arguments.charAt(i);
              if (next == '"' || next == '\\') {
                currArg.append(next);
              }
              else {
                currArg.append(c);
                currArg.append(next);
              }
            }
            else {
              currArg.append(c);
            }
            break;
//          case NORMAL_TOKEN_STATE:
//            if (Character.isWhitespace(c)) {
//              // Whitespace ends the token; start a new one
//              argList.add(currArg.toString());
//              currArg = new StringBuffer();
//              state = NO_TOKEN_STATE;
//            }
//            else if (c == '\\') {
//              // Backslash in a normal token: escape the next character
//              escaped = true;
//            }
//            else if (c == '\'') {
//              state = SINGLE_QUOTE_STATE;
//            }
//            else if (c == '"') {
//              state = DOUBLE_QUOTE_STATE;
//            }
//            else {
//              currArg.append(c);
//            }
//            break;
          case NO_TOKEN_STATE:
          case NORMAL_TOKEN_STATE:
            switch(c) {
            case '\\':
              escaped = true;
              state = NORMAL_TOKEN_STATE;
              break;
            case '\'':
              state = SINGLE_QUOTE_STATE;
              break;
            case '"':
              state = DOUBLE_QUOTE_STATE;
              break;
            default:
              if (!Character.isWhitespace(c)) {
              currArg.append(c);
              state = NORMAL_TOKEN_STATE;
            }
              else if (state == NORMAL_TOKEN_STATE) {
                // Whitespace ends the token; start a new one
                argList.add(currArg.toString());
                currArg = new StringBuilder();
                state = NO_TOKEN_STATE;
              }
          }
            break;
          default:
            throw new IllegalStateException("ArgumentTokenizer state " + state + " is invalid!");
        }
      }
    }

    // If we're still escaped, put in the backslash
    if (escaped) {
      currArg.append('\\');
      argList.add(currArg.toString());
    }
    // Close the last argument if we haven't yet
    else if (state != NO_TOKEN_STATE) {
      argList.add(currArg.toString());
    }
    // Format each argument if we've been told to stringify them
    if (stringify) {
      for (int i = 0; i < argList.size(); i++) {
        argList.set(i, "\"" + _escapeQuotesAndBackslashes(argList.get(i)) + "\"");
      }
    }
    return argList;
  }

//            if (Character.isWhitespace(c)) {

//              argList.add(currArg.toString());

//              currArg = new StringBuffer();

//              state = SINGLE_QUOTE_STATE;

//              state = DOUBLE_QUOTE_STATE;

Tokenizes the given String into String tokens.
@param arguments A String containing one or more command-line style arguments to be tokenized.
@param stringify whether or not to include escape special characters
@return A list of parsed and properly escaped arguments.

Tokenizes the given String into String tokens .


protected static String _escapeQuotesAndBackslashes(String s) {
    final StringBuilder buf = new StringBuilder(s);

    // Walk backwards, looking for quotes or backslashes.
    //  If we see any, insert an extra backslash into the buffer at
    //  the same index.  (By walking backwards, the index into the buffer
    //  will remain correct as we change the buffer.)
    for (int i = s.length()-1; i >= 0; i--) {
      char c = s.charAt(i);
      if ((c == '\\') || (c == '"')) {
        buf.insert(i, '\\');
      }
      // Replace any special characters with escaped versions
      else if (c == '\n') {
        buf.deleteCharAt(i);
        buf.insert(i, "\\n");
      }
      else if (c == '\t') {
        buf.deleteCharAt(i);
        buf.insert(i, "\\t");
      }
      else if (c == '\r') {
        buf.deleteCharAt(i);
        buf.insert(i, "\\r");
      }
      else if (c == '\b') {
        buf.deleteCharAt(i);
        buf.insert(i, "\\b");
      }
      else if (c == '\f') {
        buf.deleteCharAt(i);
        buf.insert(i, "\\f");
      }
    }
    return buf.toString();
  }

Inserts backslashes before any occurrences of a backslash or
quote in the given string.  Also converts any special characters
appropriately.

Inserts backslashes before any occurrences of a backslash or quote in the given string . Also converts any special characters appropriately .


public Result serveStatic() {
        Object renderable = new Renderable() {
            @Override
            public void render(Context context, Result result) {
                String fileName = getFileNameFromPathOrReturnRequestPath(context);
                URL url = getStaticFileFromAssetsDir(fileName);
                streamOutUrlEntity(url, context, result);
            }
        };
        return Results.ok().render(renderable);
    }

public Result serveStatic ( ) { Object renderable = new Renderable ( ) { @ Override public void render ( Context context , Result result ) { String fileName = getFileNameFromPathOrReturnRequestPath ( context ) ; URL url = getStaticFileFromAssetsDir ( fileName ) ; streamOutUrlEntity ( url , context , result ) ; } } ; return Results . ok ( ) . render ( renderable ) ; }

Serves resources from the assets directory of your application.

For instance:
route: /robots.txt
A request to /robots.txt will be served from /assets/robots.txt.

You can also use a path like the following to serve files:
route: /assets/{fileName: .*}

matches
/assets/app/app.css
and will return
/assets/app/app.css (from your jar).

Serves resources from the assets directory of your application .


private PropertiesConfiguration loadLanguageConfiguration(String fileOrUrl) {
        PropertiesConfiguration configuration = SwissKnife
                .loadConfigurationInUtf8(fileOrUrl);

        if (configuration != null && ninjaProperties.isDev()) {
            // enable runtime reloading of translations in dev mode
            FileChangedReloadingStrategy strategy = new FileChangedReloadingStrategy();
            configuration.setReloadingStrategy(strategy);
        }

        return configuration;
    }

Attempts to load a message file and sets the file changed reloading
strategy on the configuration if the runtime mode is Dev.

Attempts to load a message file and sets the file changed reloading strategy on the configuration if the runtime mode is Dev .


private  Map<String, Configuration> loadAllMessageFilesForRegisteredLanguages() {

        Map<String, Configuration> langToKeyAndValuesMappingMutable = Maps.newHashMap();

        // Load default messages:
        Configuration defaultLanguage = loadLanguageConfiguration("conf/messages.properties");

        // Make sure we got the file.
        // Everything else does not make much sense.
        if (defaultLanguage == null) {
            throw new RuntimeException(
                    "Did not find conf/messages.properties. Please add a default language file.");
        } else {
            langToKeyAndValuesMappingMutable.put("", defaultLanguage);
        }

        // Get the languages from the application configuration.
        String[] applicationLangs = ninjaProperties
                .getStringArray(NinjaConstant.applicationLanguages);

        // If we don't have any languages declared we just return.
        // We'll use the default messages.properties file.
        if (applicationLangs == null) {
            return ImmutableMap.copyOf(langToKeyAndValuesMappingMutable);
        }

        // Load each language into the HashMap containing the languages:
        for (String lang : applicationLangs) {

            // First step: Load complete language eg. en-US
            Configuration configuration = loadLanguageConfiguration(String
                    .format("conf/messages_%s.properties", lang));

            Configuration configurationLangOnly = null;

            // If the language has a country code load the default values for
            // the language, too. For instance missing variables in en-US will
            // be
            // Overwritten by the default languages.
            if (lang.contains("-")) {
                // get the lang
                String langOnly = lang.split("-")[0];

                // And load the configuraion
                configurationLangOnly = loadLanguageConfiguration(String
                        .format("conf/messages_%s.properties", langOnly));

            }

            // This is strange. If you defined the language in application.conf
            // it should be there propably.
            if (configuration == null) {
                logger.info(
                        "Did not find conf/messages_{}.properties but it was specified in application.conf. Using default language instead.",
                        lang);

            } else {

                // add new language, but combine with default language if stuff
                // is missing...
                CompositeConfiguration compositeConfiguration = new CompositeConfiguration();
                // Add eg. "en-US"
                compositeConfiguration.addConfiguration(configuration);

                // Add eg. "en"
                if (configurationLangOnly != null) {
                    compositeConfiguration
                            .addConfiguration(configurationLangOnly);
                }
                // Add messages.conf (default pack)
                compositeConfiguration.addConfiguration(defaultLanguage);

                // and add the composed configuration to the hashmap with the
                // mapping.
                langToKeyAndValuesMappingMutable.put(lang,
                        (Configuration) compositeConfiguration);
            }

        }

        return ImmutableMap.copyOf(langToKeyAndValuesMappingMutable);

    }

Does all the loading of message files.

Only registered messages in application.conf are loaded.