text
stringlengths 7
1.01M
|
|---|
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.aliyuncs.alb.transform.v20200616;
import java.util.ArrayList;
import java.util.List;
import com.aliyuncs.alb.model.v20200616.GetListenerHealthStatusResponse;
import com.aliyuncs.alb.model.v20200616.GetListenerHealthStatusResponse.ListenerHealthStatusModel;
import com.aliyuncs.alb.model.v20200616.GetListenerHealthStatusResponse.ListenerHealthStatusModel.ServerGroupHealthStatusModel;
import com.aliyuncs.alb.model.v20200616.GetListenerHealthStatusResponse.ListenerHealthStatusModel.ServerGroupHealthStatusModel.BackendServerHealthStatusModel;
import com.aliyuncs.alb.model.v20200616.GetListenerHealthStatusResponse.ListenerHealthStatusModel.ServerGroupHealthStatusModel.BackendServerHealthStatusModel.Reason;
import com.aliyuncs.alb.model.v20200616.GetListenerHealthStatusResponse.RuleHealthStatusModel;
import com.aliyuncs.alb.model.v20200616.GetListenerHealthStatusResponse.RuleHealthStatusModel.ServerGroupHealthStatusModel2;
import com.aliyuncs.alb.model.v20200616.GetListenerHealthStatusResponse.RuleHealthStatusModel.ServerGroupHealthStatusModel2.NonNormalServer;
import com.aliyuncs.alb.model.v20200616.GetListenerHealthStatusResponse.RuleHealthStatusModel.ServerGroupHealthStatusModel2.NonNormalServer.Reason4;
import com.aliyuncs.transform.UnmarshallerContext;
public class GetListenerHealthStatusResponseUnmarshaller {
public static GetListenerHealthStatusResponse unmarshall(GetListenerHealthStatusResponse getListenerHealthStatusResponse, UnmarshallerContext _ctx) {
getListenerHealthStatusResponse.setRequestId(_ctx.stringValue("GetListenerHealthStatusResponse.RequestId"));
getListenerHealthStatusResponse.setNextToken(_ctx.stringValue("GetListenerHealthStatusResponse.NextToken"));
List<ListenerHealthStatusModel> listenerHealthStatus = new ArrayList<ListenerHealthStatusModel>();
for (int i = 0; i < _ctx.lengthValue("GetListenerHealthStatusResponse.ListenerHealthStatus.Length"); i++) {
ListenerHealthStatusModel listenerHealthStatusModel = new ListenerHealthStatusModel();
listenerHealthStatusModel.setListenerId(_ctx.stringValue("GetListenerHealthStatusResponse.ListenerHealthStatus["+ i +"].ListenerId"));
listenerHealthStatusModel.setListenerPort(_ctx.integerValue("GetListenerHealthStatusResponse.ListenerHealthStatus["+ i +"].ListenerPort"));
listenerHealthStatusModel.setListenerProtocol(_ctx.stringValue("GetListenerHealthStatusResponse.ListenerHealthStatus["+ i +"].ListenerProtocol"));
List<ServerGroupHealthStatusModel> serverGroupInfos = new ArrayList<ServerGroupHealthStatusModel>();
for (int j = 0; j < _ctx.lengthValue("GetListenerHealthStatusResponse.ListenerHealthStatus["+ i +"].ServerGroupInfos.Length"); j++) {
ServerGroupHealthStatusModel serverGroupHealthStatusModel = new ServerGroupHealthStatusModel();
serverGroupHealthStatusModel.setHealthCheckEnabled(_ctx.stringValue("GetListenerHealthStatusResponse.ListenerHealthStatus["+ i +"].ServerGroupInfos["+ j +"].HealthCheckEnabled"));
serverGroupHealthStatusModel.setServerGroupId(_ctx.stringValue("GetListenerHealthStatusResponse.ListenerHealthStatus["+ i +"].ServerGroupInfos["+ j +"].ServerGroupId"));
serverGroupHealthStatusModel.setActionType(_ctx.stringValue("GetListenerHealthStatusResponse.ListenerHealthStatus["+ i +"].ServerGroupInfos["+ j +"].ActionType"));
List<BackendServerHealthStatusModel> nonNormalServers = new ArrayList<BackendServerHealthStatusModel>();
for (int k = 0; k < _ctx.lengthValue("GetListenerHealthStatusResponse.ListenerHealthStatus["+ i +"].ServerGroupInfos["+ j +"].NonNormalServers.Length"); k++) {
BackendServerHealthStatusModel backendServerHealthStatusModel = new BackendServerHealthStatusModel();
backendServerHealthStatusModel.setPort(_ctx.integerValue("GetListenerHealthStatusResponse.ListenerHealthStatus["+ i +"].ServerGroupInfos["+ j +"].NonNormalServers["+ k +"].Port"));
backendServerHealthStatusModel.setServerId(_ctx.stringValue("GetListenerHealthStatusResponse.ListenerHealthStatus["+ i +"].ServerGroupInfos["+ j +"].NonNormalServers["+ k +"].ServerId"));
backendServerHealthStatusModel.setServerIp(_ctx.stringValue("GetListenerHealthStatusResponse.ListenerHealthStatus["+ i +"].ServerGroupInfos["+ j +"].NonNormalServers["+ k +"].ServerIp"));
backendServerHealthStatusModel.setStatus(_ctx.stringValue("GetListenerHealthStatusResponse.ListenerHealthStatus["+ i +"].ServerGroupInfos["+ j +"].NonNormalServers["+ k +"].Status"));
Reason reason = new Reason();
reason.setActualResponse(_ctx.stringValue("GetListenerHealthStatusResponse.ListenerHealthStatus["+ i +"].ServerGroupInfos["+ j +"].NonNormalServers["+ k +"].Reason.ActualResponse"));
reason.setExpectedResponse(_ctx.stringValue("GetListenerHealthStatusResponse.ListenerHealthStatus["+ i +"].ServerGroupInfos["+ j +"].NonNormalServers["+ k +"].Reason.ExpectedResponse"));
reason.setReasonCode(_ctx.stringValue("GetListenerHealthStatusResponse.ListenerHealthStatus["+ i +"].ServerGroupInfos["+ j +"].NonNormalServers["+ k +"].Reason.ReasonCode"));
backendServerHealthStatusModel.setReason(reason);
nonNormalServers.add(backendServerHealthStatusModel);
}
serverGroupHealthStatusModel.setNonNormalServers(nonNormalServers);
serverGroupInfos.add(serverGroupHealthStatusModel);
}
listenerHealthStatusModel.setServerGroupInfos(serverGroupInfos);
listenerHealthStatus.add(listenerHealthStatusModel);
}
getListenerHealthStatusResponse.setListenerHealthStatus(listenerHealthStatus);
List<RuleHealthStatusModel> ruleHealthStatus = new ArrayList<RuleHealthStatusModel>();
for (int i = 0; i < _ctx.lengthValue("GetListenerHealthStatusResponse.RuleHealthStatus.Length"); i++) {
RuleHealthStatusModel ruleHealthStatusModel = new RuleHealthStatusModel();
ruleHealthStatusModel.setRuleId(_ctx.stringValue("GetListenerHealthStatusResponse.RuleHealthStatus["+ i +"].RuleId"));
List<ServerGroupHealthStatusModel2> serverGroupInfos1 = new ArrayList<ServerGroupHealthStatusModel2>();
for (int j = 0; j < _ctx.lengthValue("GetListenerHealthStatusResponse.RuleHealthStatus["+ i +"].ServerGroupInfos.Length"); j++) {
ServerGroupHealthStatusModel2 serverGroupHealthStatusModel2 = new ServerGroupHealthStatusModel2();
serverGroupHealthStatusModel2.setHealthCheckEnabled(_ctx.stringValue("GetListenerHealthStatusResponse.RuleHealthStatus["+ i +"].ServerGroupInfos["+ j +"].HealthCheckEnabled"));
serverGroupHealthStatusModel2.setServerGroupId(_ctx.stringValue("GetListenerHealthStatusResponse.RuleHealthStatus["+ i +"].ServerGroupInfos["+ j +"].ServerGroupId"));
serverGroupHealthStatusModel2.setActionType(_ctx.stringValue("GetListenerHealthStatusResponse.RuleHealthStatus["+ i +"].ServerGroupInfos["+ j +"].ActionType"));
List<NonNormalServer> nonNormalServers3 = new ArrayList<NonNormalServer>();
for (int k = 0; k < _ctx.lengthValue("GetListenerHealthStatusResponse.RuleHealthStatus["+ i +"].ServerGroupInfos["+ j +"].NonNormalServers.Length"); k++) {
NonNormalServer nonNormalServer = new NonNormalServer();
nonNormalServer.setPort(_ctx.integerValue("GetListenerHealthStatusResponse.RuleHealthStatus["+ i +"].ServerGroupInfos["+ j +"].NonNormalServers["+ k +"].Port"));
nonNormalServer.setServerId(_ctx.stringValue("GetListenerHealthStatusResponse.RuleHealthStatus["+ i +"].ServerGroupInfos["+ j +"].NonNormalServers["+ k +"].ServerId"));
nonNormalServer.setServerIp(_ctx.stringValue("GetListenerHealthStatusResponse.RuleHealthStatus["+ i +"].ServerGroupInfos["+ j +"].NonNormalServers["+ k +"].ServerIp"));
nonNormalServer.setStatus(_ctx.stringValue("GetListenerHealthStatusResponse.RuleHealthStatus["+ i +"].ServerGroupInfos["+ j +"].NonNormalServers["+ k +"].Status"));
Reason4 reason4 = new Reason4();
reason4.setActualResponse(_ctx.stringValue("GetListenerHealthStatusResponse.RuleHealthStatus["+ i +"].ServerGroupInfos["+ j +"].NonNormalServers["+ k +"].Reason.ActualResponse"));
reason4.setExpectedResponse(_ctx.stringValue("GetListenerHealthStatusResponse.RuleHealthStatus["+ i +"].ServerGroupInfos["+ j +"].NonNormalServers["+ k +"].Reason.ExpectedResponse"));
reason4.setReasonCode(_ctx.stringValue("GetListenerHealthStatusResponse.RuleHealthStatus["+ i +"].ServerGroupInfos["+ j +"].NonNormalServers["+ k +"].Reason.ReasonCode"));
nonNormalServer.setReason4(reason4);
nonNormalServers3.add(nonNormalServer);
}
serverGroupHealthStatusModel2.setNonNormalServers3(nonNormalServers3);
serverGroupInfos1.add(serverGroupHealthStatusModel2);
}
ruleHealthStatusModel.setServerGroupInfos1(serverGroupInfos1);
ruleHealthStatus.add(ruleHealthStatusModel);
}
getListenerHealthStatusResponse.setRuleHealthStatus(ruleHealthStatus);
return getListenerHealthStatusResponse;
}
}
|
package com.github.rotty3000.sample.messaging.listener;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.metatype.annotations.Designate;
import org.osgi.service.metatype.annotations.ObjectClassDefinition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.liferay.portal.kernel.messaging.Message;
import com.liferay.portal.kernel.messaging.MessageListenerException;
@ObjectClassDefinition
@interface Config {
String destination_name() default "default";
}
@Component(property = "destination.name=default")
@Designate(ocd = Config.class)
public class MessageListener
implements com.liferay.portal.kernel.messaging.MessageListener {
@Override
public void receive(Message message) throws MessageListenerException {
_log.info("Recieved Message: {}", message.toString());
}
void activate(Config config) {
if (_log.isDebugEnabled()) {
_log.debug(
"Activating Message Listener with {destination.name = {}}", config.destination_name());
}
}
void deactivate() {
if (_log.isDebugEnabled()) {
_log.debug("Deactivating Message Listener");
}
}
private static final Logger _log = LoggerFactory.getLogger(MessageListener.class);
}
|
package com.tuya.smart.sweeper.demo.base.widget.circleprogress;
import android.animation.TimeInterpolator;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.PointF;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.SweepGradient;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Message;
import android.support.annotation.ColorInt;
import android.support.annotation.FloatRange;
import android.support.annotation.IntRange;
import android.support.annotation.NonNull;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import com.tuya.smart.sweeper.demo.R;
import java.text.DecimalFormat;
/**
* An circle view, similar to Android's ProgressBar.
* Can be used in 'value mode' or 'spinning mode'.
* <p/>
* In spinning mode it can be used like a intermediate progress bar.
* <p/>
* In value mode it can be used as a progress bar or to visualize any other value.
* Setting a value is fully animated. There are also nice transitions from animating to value mode.
* <p/>
* Typical use case would be to load a new value. During the loading time set the CircleView to spinning.
* As soon as you get your value, just set it with {@link #setValueAnimated(float, long)}.
*
* @author Jakob Grabner, based on the Progress wheel of Todd Davies
* https://github.com/Todd-Davies/CircleView
* <p/>
* Licensed under the Creative Commons Attribution 3.0 license see:
* http://creativecommons.org/licenses/by/3.0/
*/
@SuppressWarnings("unused")
public class CircleProgressView extends View {
/**
* The log tag.
*/
private final static String TAG = "CircleView";
private static final boolean DEBUG = false;
//----------------------------------
//region members
//value animation
float mCurrentValue = 42;
float mValueTo = 0;
float mValueFrom = 0;
float mMaxValue = 100;
// spinner animation
float mSpinningBarLengthCurrent = 0;
float mSpinningBarLengthOrig = 42;
float mCurrentSpinnerDegreeValue = 0;
//Animation
//The amount of degree to move the bar by on each draw
float mSpinSpeed = 2.8f;
/**
* The animation duration in ms
*/
double mAnimationDuration = 900;
//The number of milliseconds to wait in between each draw
int mFrameDelayMillis = 10;
// helper for AnimationState.END_SPINNING_START_ANIMATING
boolean mDrawBarWhileSpinning;
//The animation handler containing the animation state machine.
AnimationHandler mAnimationHandler = new AnimationHandler(this);
//The current state of the animation state machine.
AnimationState mAnimationState = AnimationState.IDLE;
AnimationStateChangedListener mAnimationStateChangedListener;
protected int mLayoutHeight = 0;
protected int mLayoutWidth = 0;
private int mBarWidth = 40;
private int mRimWidth = 40;
private int mStartAngle = 270;
private float mContourSize = 1;
//Default text sizes
private int mUnitTextSize = 10;
private int mTextSize = 10;
//Text scale
private float mTextScale = 1;
private float mUnitScale = 1;
//Colors (with defaults)
private final int mBarColorStandard = 0xff009688; //stylish blue
private int mContourColor = 0xAA000000;
private int mSpinnerColor = mBarColorStandard; //stylish blue
private int mBackgroundCircleColor = 0x00000000; //transparent
private int mRimColor = 0xAA83d0c9;
private int mTextColor = 0xFF000000;
private int mUnitColor = 0xFF000000;
private boolean mIsAutoColorEnabled = false;
private int[] mBarColors = new int[]{
mBarColorStandard //stylish blue
};
//Caps
private Paint.Cap mBarStrokeCap = Paint.Cap.BUTT;
private Paint.Cap mSpinnerStrokeCap = Paint.Cap.BUTT;
//Paints
private Paint mBarPaint = new Paint();
private Paint mBarSpinnerPaint = new Paint();
private Paint mBackgroundCirclePaint = new Paint();
private Paint mRimPaint = new Paint();
private Paint mTextPaint = new Paint();
private Paint mUnitTextPaint = new Paint();
private Paint mContourPaint = new Paint();
//Rectangles
protected RectF mCircleBounds = new RectF();
protected RectF mInnerCircleBound = new RectF();
protected PointF mCenter;
/**
* Maximum size of the text.
*/
protected RectF mOuterTextBounds = new RectF();
/**
* Actual size of the text.
*/
protected RectF mActualTextBounds = new RectF();
protected RectF mUnitBounds = new RectF();
protected RectF mCircleOuterContour = new RectF();
protected RectF mCircleInnerContour = new RectF();
//Other
// The text to show
private String mText = "";
private int mTextLength;
private String mUnit = "";
private UnitPosition mUnitPosition = UnitPosition.RIGHT_TOP;
/**
* Indicates if the given text, the current percentage, or the current value should be shown.
*/
private TextMode mTextMode = TextMode.PERCENT;
private boolean mIsAutoTextSize;
private boolean mShowUnit = false;
//clipping
private Bitmap mClippingBitmap;
private Paint mMaskPaint;
/**
* Relative size of the unite string to the value string.
*/
private float mRelativeUniteSize = 1f;
private boolean mSeekModeEnabled = false;
private boolean mShowTextWhileSpinning = false;
private boolean mShowBlock = false;
private int mBlockCount = 18;
private float mBlockScale = 0.9f;
private float mBlockDegree = 360 / mBlockCount;
private float mBlockScaleDegree = mBlockDegree * mBlockScale;
private int mTouchEventCount;
private OnProgressChangedListener onProgressChangedListener;
private float previousProgressChangedValue;
private DecimalFormat decimalFormat = new DecimalFormat("0");
// Text typeface
private Typeface textTypeface;
private Typeface unitTextTypeface;
//endregion members
//----------------------------------
//----------------------------------
//region getter/setter
public int[] getBarColors() {
return mBarColors;
}
public Paint.Cap getBarStrokeCap() {
return mBarStrokeCap;
}
/**
* @param _barStrokeCap The stroke cap of the progress bar.
*/
public void setBarStrokeCap(Paint.Cap _barStrokeCap) {
mBarStrokeCap = _barStrokeCap;
mBarPaint.setStrokeCap(_barStrokeCap);
}
public int getBarWidth() {
return mBarWidth;
}
/**
* @param barWidth The width of the progress bar in pixel.
*/
public void setBarWidth(@FloatRange(from = 0.0) int barWidth) {
this.mBarWidth = barWidth;
mBarPaint.setStrokeWidth(barWidth);
mBarSpinnerPaint.setStrokeWidth(barWidth);
}
public int getBlockCount() {
return mBlockCount;
}
public void setBlockCount(int blockCount) {
if (blockCount > 1) {
mShowBlock = true;
mBlockCount = blockCount;
mBlockDegree = 360.0f / blockCount;
mBlockScaleDegree = mBlockDegree * mBlockScale;
} else {
mShowBlock = false;
}
}
public float getBlockScale() {
return mBlockScale;
}
public void setBlockScale(@FloatRange(from = 0.0, to = 1) float blockScale) {
if (blockScale >= 0.0f && blockScale <= 1.0f) {
mBlockScale = blockScale;
mBlockScaleDegree = mBlockDegree * blockScale;
}
}
public int getContourColor() {
return mContourColor;
}
/**
* @param _contourColor The color of the background contour of the circle.
*/
public void setContourColor(@ColorInt int _contourColor) {
mContourColor = _contourColor;
mContourPaint.setColor(_contourColor);
}
public float getContourSize() {
return mContourSize;
}
/**
* @param _contourSize The size of the background contour of the circle.
*/
public void setContourSize(@FloatRange(from = 0.0) float _contourSize) {
mContourSize = _contourSize;
mContourPaint.setStrokeWidth(_contourSize);
}
/**
* @return The number of ms to wait between each draw call.
*/
public int getDelayMillis() {
return mFrameDelayMillis;
}
/**
* @param delayMillis The number of ms to wait between each draw call.
*/
public void setDelayMillis(int delayMillis) {
this.mFrameDelayMillis = delayMillis;
}
public int getFillColor() {
return mBackgroundCirclePaint.getColor();
}
public float getMaxValue() {
return mMaxValue;
}
/**
* The max value of the progress bar. Used to calculate the percentage of the current value.
* The bar fills according to the percentage. The default value is 100.
*
* @param _maxValue The max value.
*/
public void setMaxValue(@FloatRange(from = 0) float _maxValue) {
mMaxValue = _maxValue;
}
/**
* @return The relative size (scale factor) of the unit text size to the text size
*/
public float getRelativeUniteSize() {
return mRelativeUniteSize;
}
public int getRimColor() {
return mRimColor;
}
/**
* @param rimColor The color of the rim around the Circle.
*/
public void setRimColor(@ColorInt int rimColor) {
mRimColor = rimColor;
mRimPaint.setColor(rimColor);
}
public Shader getRimShader() {
return mRimPaint.getShader();
}
public void setRimShader(Shader shader) {
this.mRimPaint.setShader(shader);
}
public int getRimWidth() {
return mRimWidth;
}
/**
* @param rimWidth The width in pixel of the rim around the circle
*/
public void setRimWidth(@IntRange(from = 0) int rimWidth) {
mRimWidth = rimWidth;
mRimPaint.setStrokeWidth(rimWidth);
}
public float getSpinSpeed() {
return mSpinSpeed;
}
/**
* The amount of degree to move the bar on every draw call.
*
* @param spinSpeed the speed of the spinner
*/
public void setSpinSpeed(float spinSpeed) {
mSpinSpeed = spinSpeed;
}
public Paint.Cap getSpinnerStrokeCap() {
return mSpinnerStrokeCap;
}
/**
* @param _spinnerStrokeCap The stroke cap of the progress bar in spinning mode.
*/
public void setSpinnerStrokeCap(Paint.Cap _spinnerStrokeCap) {
mSpinnerStrokeCap = _spinnerStrokeCap;
mBarSpinnerPaint.setStrokeCap(_spinnerStrokeCap);
}
public int getStartAngle() {
return mStartAngle;
}
public void setStartAngle(int _startAngle) {
// get a angle between 0 and 360
mStartAngle = (int) normalizeAngle(_startAngle);
}
public int calcTextColor() {
return mTextColor;
}
/**
* Sets the text color.
* You also need to set {@link #setTextColorAuto(boolean)} to false to see your color.
*
* @param textColor the color
*/
public void setTextColor(@ColorInt int textColor) {
mTextColor = textColor;
mTextPaint.setColor(textColor);
}
/**
* @return The scale value
*/
public float getTextScale() {
return mTextScale;
}
/**
* Scale factor for main text in the center of the circle view.
* Only used if auto text size is enabled.
*
* @param _textScale The scale value.
*/
public void setTextScale(@FloatRange(from = 0.0) float _textScale) {
mTextScale = _textScale;
}
public int getTextSize() {
return mTextSize;
}
/**
* Text size of the text string. Disables auto text size
* If auto text size is on, use {@link #setTextScale(float)} to scale textSize.
*
* @param textSize The text size of the unit.
*/
public void setTextSize(@IntRange(from = 0) int textSize) {
this.mTextPaint.setTextSize(textSize);
mTextSize = textSize;
mIsAutoTextSize = false;
}
public String getUnit() {
return mUnit;
}
/**
* @param _unit The unit to show next to the current value.
* You also need to set {@link #setUnitVisible(boolean)} to true.
*/
public void setUnit(String _unit) {
if (_unit == null) {
mUnit = "";
} else {
mUnit = _unit;
}
invalidate();
}
/**
* @return The scale value
*/
public float getUnitScale() {
return mUnitScale;
}
/**
* Scale factor for unit text next to the main text.
* Only used if auto text size is enabled.
*
* @param _unitScale The scale value.
*/
public void setUnitScale(@FloatRange(from = 0.0) float _unitScale) {
mUnitScale = _unitScale;
}
public int getUnitSize() {
return mUnitTextSize;
}
/**
* Text size of the unit string. Only used if text size is also set. (So automatic text size
* calculation is off. see {@link #setTextSize(int)}).
* If auto text size is on, use {@link #setUnitScale(float)} to scale unit size.
*
* @param unitSize The text size of the unit.
*/
public void setUnitSize(@IntRange(from = 0) int unitSize) {
mUnitTextSize = unitSize;
mUnitTextPaint.setTextSize(unitSize);
}
/**
* @return true if auto text size is enabled, false otherwise.
*/
public boolean isAutoTextSize() {
return mIsAutoTextSize;
}
/**
* @param _autoTextSize true to enable auto text size calculation.
*/
public void setAutoTextSize(boolean _autoTextSize) {
mIsAutoTextSize = _autoTextSize;
}
public boolean isSeekModeEnabled() {
return mSeekModeEnabled;
}
public void setSeekModeEnabled(boolean _seekModeEnabled) {
mSeekModeEnabled = _seekModeEnabled;
}
public boolean isShowBlock() {
return mShowBlock;
}
public void setShowBlock(boolean showBlock) {
mShowBlock = showBlock;
}
public boolean isShowTextWhileSpinning() {
return mShowTextWhileSpinning;
}
/**
* @param shouldDrawTextWhileSpinning True to show text in spinning mode, false to hide it.
*/
public void setShowTextWhileSpinning(boolean shouldDrawTextWhileSpinning) {
mShowTextWhileSpinning = shouldDrawTextWhileSpinning;
}
public boolean isUnitVisible() {
return mShowUnit;
}
/**
* @param _showUnit True to show unit, false to hide it.
*/
public void setUnitVisible(boolean _showUnit) {
if (_showUnit != mShowUnit) {
mShowUnit = _showUnit;
triggerReCalcTextSizesAndPositions(); // triggers recalculating text sizes
}
}
/**
* Sets the color of progress bar.
*
* @param barColors One or more colors. If more than one color is specified, a gradient of the colors is used.
*/
public void setBarColor(@ColorInt int... barColors) {
this.mBarColors = barColors;
if (barColors.length > 1) {
mBarPaint.setShader(new SweepGradient(mCircleBounds.centerX(), mCircleBounds.centerY(), barColors, null));
Matrix matrix = new Matrix();
mBarPaint.getShader().getLocalMatrix(matrix);
matrix.postTranslate(-mCircleBounds.centerX(), -mCircleBounds.centerY());
matrix.postRotate(mStartAngle);
matrix.postTranslate(mCircleBounds.centerX(), mCircleBounds.centerY());
mBarPaint.getShader().setLocalMatrix(matrix);
mBarPaint.setColor(barColors[0]);
} else if (barColors.length == 1) {
mBarPaint.setColor(barColors[0]);
mBarPaint.setShader(null);
} else {
mBarPaint.setColor(mBarColorStandard);
mBarPaint.setShader(null);
}
}
/**
* @param _clippingBitmap The bitmap used for clipping. Set to null to disable clipping.
* Default: No clipping.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void setClippingBitmap(Bitmap _clippingBitmap) {
if (getWidth() > 0 && getHeight() > 0) {
mClippingBitmap = Bitmap.createScaledBitmap(_clippingBitmap, getWidth(), getHeight(), false);
} else {
mClippingBitmap = _clippingBitmap;
}
if (mClippingBitmap == null) {
// enable HW acceleration
setLayerType(View.LAYER_TYPE_HARDWARE, null);
} else {
// disable HW acceleration
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
}
/**
* Sets the background color of the entire Progress Circle.
* Set the color to 0x00000000 (Color.TRANSPARENT) to hide it.
*
* @param circleColor the color.
*/
public void setFillCircleColor(@ColorInt int circleColor) {
mBackgroundCircleColor = circleColor;
mBackgroundCirclePaint.setColor(circleColor);
}
public void setOnAnimationStateChangedListener(AnimationStateChangedListener _animationStateChangedListener) {
mAnimationStateChangedListener = _animationStateChangedListener;
}
public void setOnProgressChangedListener(OnProgressChangedListener listener) {
onProgressChangedListener = listener;
}
/**
* @param _color The color of progress the bar in spinning mode.
*/
public void setSpinBarColor(@ColorInt int _color) {
mSpinnerColor = _color;
mBarSpinnerPaint.setColor(mSpinnerColor);
}
/**
* Length of spinning bar in degree.
*
* @param barLength length in degree
*/
public void setSpinningBarLength(@FloatRange(from = 0.0) float barLength) {
this.mSpinningBarLengthCurrent = mSpinningBarLengthOrig = barLength;
}
/**
* Set the text in the middle of the circle view.
* You need also set the {@link TextMode} to TextMode.TEXT to see the text.
*
* @param text The text to show
*/
public void setText(String text) {
mText = text != null ? text : "";
invalidate();
}
/**
* If auto text color is enabled, the text color and the unit color is always the same as the rim color.
* This is useful if the rim has multiple colors (color gradient), than the text will always have
* the color of the tip of the rim.
*
* @param isEnabled true to enable, false to disable
*/
public void setTextColorAuto(boolean isEnabled) {
mIsAutoColorEnabled = isEnabled;
}
/**
* Sets the auto text mode.
*
* @param _textValue The mode
*/
public void setTextMode(TextMode _textValue) {
mTextMode = _textValue;
}
/**
* @param typeface The typeface to use for the text
*/
public void setTextTypeface(Typeface typeface) {
mTextPaint.setTypeface(typeface);
}
/**
* Sets the unit text color.
* Also sets {@link #setTextColorAuto(boolean)} to false
*
* @param unitColor The color.
*/
public void setUnitColor(@ColorInt int unitColor) {
mUnitColor = unitColor;
mUnitTextPaint.setColor(unitColor);
mIsAutoColorEnabled = false;
}
public void setUnitPosition(UnitPosition _unitPosition) {
mUnitPosition = _unitPosition;
triggerReCalcTextSizesAndPositions(); // triggers recalculating text sizes
}
/**
* @param typeface The typeface to use for the unit text
*/
public void setUnitTextTypeface(Typeface typeface) {
mUnitTextPaint.setTypeface(typeface);
}
/**
* @param _relativeUniteSize The relative scale factor of the unit text size to the text size.
* Only useful for autotextsize=true; Effects both, the unit text size and the text size.
*/
public void setUnitToTextScale(@FloatRange(from = 0.0) float _relativeUniteSize) {
mRelativeUniteSize = _relativeUniteSize;
triggerReCalcTextSizesAndPositions();
}
/**
* Set the value of the circle view without an animation.
* Stops any currently active animations.
*
* @param _value The value.
*/
public void setValue(float _value) {
Message msg = new Message();
msg.what = AnimationMsg.SET_VALUE.ordinal();
msg.obj = new float[]{_value, _value};
mAnimationHandler.sendMessage(msg);
triggerOnProgressChanged(_value);
}
/**
* Sets the value of the circle view with an animation.
* The current value is used as the start value of the animation
*
* @param _valueTo value after animation
*/
public void setValueAnimated(float _valueTo) {
setValueAnimated(_valueTo, 1200);
}
/**
* Sets the value of the circle view with an animation.
* The current value is used as the start value of the animation
*
* @param _valueTo value after animation
* @param _animationDuration the duration of the animation in milliseconds.
*/
public void setValueAnimated(float _valueTo, long _animationDuration) {
setValueAnimated(mCurrentValue, _valueTo, _animationDuration);
}
/**
* Sets the value of the circle view with an animation.
*
* @param _valueFrom start value of the animation
* @param _valueTo value after animation
* @param _animationDuration the duration of the animation in milliseconds
*/
public void setValueAnimated(float _valueFrom, float _valueTo, long _animationDuration) {
mAnimationDuration = _animationDuration;
Message msg = new Message();
msg.what = AnimationMsg.SET_VALUE_ANIMATED.ordinal();
msg.obj = new float[]{_valueFrom, _valueTo};
mAnimationHandler.sendMessage(msg);
triggerOnProgressChanged(_valueTo);
}
public DecimalFormat getDecimalFormat() {
return decimalFormat;
}
public void setDecimalFormat(DecimalFormat decimalFormat) {
if (decimalFormat == null) {
throw new IllegalArgumentException("decimalFormat must not be null!");
}
this.decimalFormat = decimalFormat;
}
/**
* Sets interpolator for value animations.
*
* @param interpolator the interpolator
*/
public void setValueInterpolator(TimeInterpolator interpolator) {
mAnimationHandler.setValueInterpolator(interpolator);
}
/**
* Sets the interpolator for length changes of the bar.
*
* @param interpolator the interpolator
*/
public void setLengthChangeInterpolator(TimeInterpolator interpolator) {
mAnimationHandler.setLengthChangeInterpolator(interpolator);
}
//endregion getter/setter
//----------------------------------
/**
* The constructor for the CircleView
*
* @param context The context.
* @param attrs The attributes.
*/
public CircleProgressView(Context context, AttributeSet attrs) {
super(context, attrs);
parseAttributes(context.obtainStyledAttributes(attrs,
R.styleable.CircleProgressView));
if (!isInEditMode()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
setLayerType(View.LAYER_TYPE_HARDWARE, null);
}
}
mMaskPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mMaskPaint.setFilterBitmap(false);
mMaskPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
setupPaints();
}
/**
* Parse the attributes passed to the view from the XML
*
* @param a the attributes to parse
*/
private void parseAttributes(TypedArray a) {
setBarWidth((int) a.getDimension(R.styleable.CircleProgressView_cpv_barWidth,
mBarWidth));
setRimWidth((int) a.getDimension(R.styleable.CircleProgressView_cpv_rimWidth,
mRimWidth));
setSpinSpeed((int) a.getFloat(R.styleable.CircleProgressView_cpv_spinSpeed,
mSpinSpeed));
float value = a.getFloat(R.styleable.CircleProgressView_cpv_value, mCurrentValue);
setValue(value);
mCurrentValue = value;
if (a.hasValue(R.styleable.CircleProgressView_cpv_barColor) && a.hasValue(R.styleable.CircleProgressView_cpv_barColor1) && a.hasValue(R.styleable.CircleProgressView_cpv_barColor2) && a.hasValue(R.styleable.CircleProgressView_cpv_barColor3)) {
mBarColors = new int[]{a.getColor(R.styleable.CircleProgressView_cpv_barColor, mBarColorStandard), a.getColor(R.styleable.CircleProgressView_cpv_barColor1, mBarColorStandard), a.getColor(R.styleable.CircleProgressView_cpv_barColor2, mBarColorStandard), a.getColor(R.styleable.CircleProgressView_cpv_barColor3, mBarColorStandard)};
} else if (a.hasValue(R.styleable.CircleProgressView_cpv_barColor) && a.hasValue(R.styleable.CircleProgressView_cpv_barColor1) && a.hasValue(R.styleable.CircleProgressView_cpv_barColor2)) {
mBarColors = new int[]{a.getColor(R.styleable.CircleProgressView_cpv_barColor, mBarColorStandard), a.getColor(R.styleable.CircleProgressView_cpv_barColor1, mBarColorStandard), a.getColor(R.styleable.CircleProgressView_cpv_barColor2, mBarColorStandard)};
} else if (a.hasValue(R.styleable.CircleProgressView_cpv_barColor) && a.hasValue(R.styleable.CircleProgressView_cpv_barColor1)) {
mBarColors = new int[]{a.getColor(R.styleable.CircleProgressView_cpv_barColor, mBarColorStandard), a.getColor(R.styleable.CircleProgressView_cpv_barColor1, mBarColorStandard)};
} else {
mBarColors = new int[]{a.getColor(R.styleable.CircleProgressView_cpv_barColor, mBarColorStandard), a.getColor(R.styleable.CircleProgressView_cpv_barColor, mBarColorStandard)};
}
setSpinBarColor(a.getColor(R.styleable.CircleProgressView_cpv_spinColor, mSpinnerColor));
setSpinningBarLength(a.getFloat(R.styleable.CircleProgressView_cpv_spinBarLength,
mSpinningBarLengthOrig));
if (a.hasValue(R.styleable.CircleProgressView_cpv_textSize)) {
setTextSize((int) a.getDimension(R.styleable.CircleProgressView_cpv_textSize, mTextSize));
}
if (a.hasValue(R.styleable.CircleProgressView_cpv_unitSize)) {
setUnitSize((int) a.getDimension(R.styleable.CircleProgressView_cpv_unitSize, mUnitTextSize));
}
if (a.hasValue(R.styleable.CircleProgressView_cpv_textColor)) {
setTextColor(a.getColor(R.styleable.CircleProgressView_cpv_textColor, mTextColor));
}
if (a.hasValue(R.styleable.CircleProgressView_cpv_unitColor)) {
setUnitColor(a.getColor(R.styleable.CircleProgressView_cpv_unitColor, mUnitColor));
}
if (a.hasValue(R.styleable.CircleProgressView_cpv_autoTextColor)) {
setTextColorAuto(a.getBoolean(R.styleable.CircleProgressView_cpv_autoTextColor, mIsAutoColorEnabled));
}
if (a.hasValue(R.styleable.CircleProgressView_cpv_autoTextSize)) {
setAutoTextSize(a.getBoolean(R.styleable.CircleProgressView_cpv_autoTextSize, mIsAutoTextSize));
}
if (a.hasValue(R.styleable.CircleProgressView_cpv_textMode)) {
setTextMode(TextMode.values()[a.getInt(R.styleable.CircleProgressView_cpv_textMode, 0)]);
}
if (a.hasValue(R.styleable.CircleProgressView_cpv_unitPosition)) {
setUnitPosition(UnitPosition.values()[a.getInt(R.styleable.CircleProgressView_cpv_unitPosition, 3)]);
}
//if the mText is empty, show current percentage value
if (a.hasValue(R.styleable.CircleProgressView_cpv_text)) {
setText(a.getString(R.styleable.CircleProgressView_cpv_text));
}
setUnitToTextScale(a.getFloat(R.styleable.CircleProgressView_cpv_unitToTextScale, 1f));
setRimColor(a.getColor(R.styleable.CircleProgressView_cpv_rimColor,
mRimColor));
setFillCircleColor(a.getColor(R.styleable.CircleProgressView_cpv_fillColor,
mBackgroundCircleColor));
setContourColor(a.getColor(R.styleable.CircleProgressView_cpv_contourColor, mContourColor));
setContourSize(a.getDimension(R.styleable.CircleProgressView_cpv_contourSize, mContourSize));
setMaxValue(a.getFloat(R.styleable.CircleProgressView_cpv_maxValue, mMaxValue));
setUnit(a.getString(R.styleable.CircleProgressView_cpv_unit));
setUnitVisible(a.getBoolean(R.styleable.CircleProgressView_cpv_showUnit, mShowUnit));
setTextScale(a.getFloat(R.styleable.CircleProgressView_cpv_textScale, mTextScale));
setUnitScale(a.getFloat(R.styleable.CircleProgressView_cpv_unitScale, mUnitScale));
setSeekModeEnabled(a.getBoolean(R.styleable.CircleProgressView_cpv_seekMode, mSeekModeEnabled));
setStartAngle(a.getInt(R.styleable.CircleProgressView_cpv_startAngle, mStartAngle));
setShowTextWhileSpinning(a.getBoolean(R.styleable.CircleProgressView_cpv_showTextInSpinningMode, mShowTextWhileSpinning));
if (a.hasValue(R.styleable.CircleProgressView_cpv_blockCount)) {
setBlockCount(a.getInt(R.styleable.CircleProgressView_cpv_blockCount, 1));
setBlockScale(a.getFloat(R.styleable.CircleProgressView_cpv_blockScale, 0.9f));
}
if (a.hasValue(R.styleable.CircleProgressView_cpv_textTypeface)) {
try {
textTypeface = Typeface.createFromAsset(getContext().getAssets(), a.getString(R.styleable.CircleProgressView_cpv_textTypeface));
} catch (Exception exception) {
// error while trying to inflate typeface (is the path set correctly?)
}
}
if (a.hasValue(R.styleable.CircleProgressView_cpv_unitTypeface)) {
try {
unitTextTypeface = Typeface.createFromAsset(getContext().getAssets(), a.getString(R.styleable.CircleProgressView_cpv_unitTypeface));
} catch (Exception exception) {
// error while trying to inflate typeface (is the path set correctly?)
}
}
if (a.hasValue(R.styleable.CircleProgressView_cpv_decimalFormat)) {
try {
String pattern = a.getString(R.styleable.CircleProgressView_cpv_decimalFormat);
if (pattern != null) {
decimalFormat = new DecimalFormat(pattern);
}
} catch (Exception exception) {
Log.w(TAG, exception.getMessage());
}
}
// Recycle
a.recycle();
}
/*
* When this is called, make the view square.
* From: http://www.jayway.com/2012/12/12/creating-custom-android-views-part-4-measuring-and-how-to-force-a-view-to-be-square/
*
*/
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// The first thing that happen is that we call the superclass
// implementation of onMeasure. The reason for that is that measuring
// can be quite a complex process and calling the super method is a
// convenient way to get most of this complexity handled.
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// We can’t use getWidth() or getHeight() here. During the measuring
// pass the view has not gotten its final size yet (this happens first
// at the start of the layout pass) so we have to use getMeasuredWidth()
// and getMeasuredHeight().
int size;
int width = getMeasuredWidth();
int height = getMeasuredHeight();
int widthWithoutPadding = width - getPaddingLeft() - getPaddingRight();
int heightWithoutPadding = height - getPaddingTop() - getPaddingBottom();
// Finally we have some simple logic that calculates the size of the view
// and calls setMeasuredDimension() to set that size.
// Before we compare the width and height of the view, we remove the padding,
// and when we set the dimension we add it back again. Now the actual content
// of the view will be square, but, depending on the padding, the total dimensions
// of the view might not be.
if (widthWithoutPadding > heightWithoutPadding) {
size = heightWithoutPadding;
} else {
size = widthWithoutPadding;
}
// If you override onMeasure() you have to call setMeasuredDimension().
// This is how you report back the measured size. If you don’t call
// setMeasuredDimension() the parent will throw an exception and your
// application will crash.
// We are calling the onMeasure() method of the superclass so we don’t
// actually need to call setMeasuredDimension() since that takes care
// of that. However, the purpose with overriding onMeasure() was to
// change the default behaviour and to do that we need to call
// setMeasuredDimension() with our own values.
setMeasuredDimension(size + getPaddingLeft() + getPaddingRight(), size + getPaddingTop() + getPaddingBottom());
}
/**
* Use onSizeChanged instead of onAttachedToWindow to get the dimensions of the view,
* because this method is called after measuring the dimensions of MATCH_PARENT and WRAP_CONTENT.
* Use this dimensions to setup the bounds and paints.
*/
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
// Share the dimensions
mLayoutWidth = w;
mLayoutHeight = h;
setupBounds();
setupBarPaint();
if (mClippingBitmap != null) {
mClippingBitmap = Bitmap.createScaledBitmap(mClippingBitmap, getWidth(), getHeight(), false);
}
invalidate();
}
//----------------------------------
// region helper
private float calcTextSizeForCircle(String _text, Paint _textPaint, RectF _circleBounds) {
//get mActualTextBounds bounds
RectF innerCircleBounds = getInnerCircleRect(_circleBounds);
return calcTextSizeForRect(_text, _textPaint, innerCircleBounds);
}
private RectF getInnerCircleRect(RectF _circleBounds) {
double circleWidth = +_circleBounds.width() - (Math.max(mBarWidth, mRimWidth)) - (mContourSize * 2);
double width = ((circleWidth / 2d) * Math.sqrt(2d));
float widthDelta = (_circleBounds.width() - (float) width) / 2f;
float scaleX = 1;
float scaleY = 1;
if (isUnitVisible()) {
switch (mUnitPosition) {
case TOP:
case BOTTOM:
scaleX = 1.1f; // scaleX square to rectangle, so the longer text with unit fits better
scaleY = 0.88f;
break;
case LEFT_TOP:
case RIGHT_TOP:
case LEFT_BOTTOM:
case RIGHT_BOTTOM:
scaleX = 0.77f; // scaleX square to rectangle, so the longer text with unit fits better
scaleY = 1.33f;
break;
}
}
return new RectF(_circleBounds.left + (widthDelta * scaleX), _circleBounds.top + (widthDelta * scaleY), _circleBounds.right - (widthDelta * scaleX), _circleBounds.bottom - (widthDelta * scaleY));
}
private static float calcTextSizeForRect(String _text, Paint _textPaint, RectF _rectBounds) {
Matrix matrix = new Matrix();
Rect textBoundsTmp = new Rect();
//replace ones because for some fonts the 1 takes less space which causes issues
String text = _text.replace('1', '0');
//get current mText bounds
_textPaint.getTextBounds(text, 0, text.length(), textBoundsTmp);
RectF textBoundsTmpF = new RectF(textBoundsTmp);
matrix.setRectToRect(textBoundsTmpF, _rectBounds, Matrix.ScaleToFit.CENTER);
float values[] = new float[9];
matrix.getValues(values);
return _textPaint.getTextSize() * values[Matrix.MSCALE_X];
}
private void triggerOnProgressChanged(float value) {
if (onProgressChangedListener != null && value != previousProgressChangedValue) {
onProgressChangedListener.onProgressChanged(value);
previousProgressChangedValue = value;
}
}
private void triggerReCalcTextSizesAndPositions() {
mTextLength = -1;
mOuterTextBounds = getInnerCircleRect(mCircleBounds);
invalidate();
}
/**
* @param _angle The angle in degree to normalize
* @return the angle between 0 (EAST) and 360
*/
private static float normalizeAngle(float _angle) {
return (((_angle % 360) + 360) % 360);
}
/**
* Calculates the angle from centerPt to targetPt in degrees.
* The return should range from [0,360), rotating CLOCKWISE,
* 0 and 360 degrees represents EAST,
* 90 degrees represents SOUTH, etc...
* <p/>
* Assumes all points are in the same coordinate space. If they are not,
* you will need to call SwingUtilities.convertPointToScreen or equivalent
* on all arguments before passing them to this function.
*
* @param centerPt Point we are rotating around.
* @param targetPt Point we want to calculate the angle to.
* @return angle in degrees. This is the angle from centerPt to targetPt.
*/
public static double calcRotationAngleInDegrees(PointF centerPt, PointF targetPt) {
// calculate the angle theta from the deltaY and deltaX values
// (atan2 returns radians values from [-PI,PI])
// 0 currently points EAST.
// NOTE: By preserving Y and X param order to atan2, we are expecting
// a CLOCKWISE angle direction.
double theta = Math.atan2(targetPt.y - centerPt.y, targetPt.x - centerPt.x);
// rotate the theta angle clockwise by 90 degrees
// (this makes 0 point NORTH)
// NOTE: adding to an angle rotates it clockwise.
// subtracting would rotate it counter-clockwise
// theta += Math.PI/2.0;
// convert from radians to degrees
// this will give you an angle from [0->270],[-180,0]
double angle = Math.toDegrees(theta);
// convert to positive range [0-360)
// since we want to prevent negative angles, adjust them now.
// we can assume that atan2 will not return a negative value
// greater than one partial rotation
if (angle < 0) {
angle += 360;
}
return angle;
}
private int calcTextColor(double value) {
if (mBarColors.length > 1) {
double percent = 1f / getMaxValue() * value;
int low = (int) Math.floor((mBarColors.length - 1) * percent);
int high = low + 1;
if (low < 0) {
low = 0;
high = 1;
} else if (high >= mBarColors.length) {
low = mBarColors.length - 2;
high = mBarColors.length - 1;
}
return ColorUtils.getRGBGradient(mBarColors[low], mBarColors[high], (float) (1 - (((mBarColors.length - 1) * percent) % 1d)));
} else if (mBarColors.length == 1) {
return mBarColors[0];
} else {
return Color.BLACK;
}
}
private void setTextSizeAndTextBoundsWithAutoTextSize(float unitGapWidthHalf, float unitWidth, float unitGapHeightHalf, float unitHeight, String text) {
RectF textRect = mOuterTextBounds;
if (mShowUnit) {
//shrink text Rect so that there is space for the unit
switch (mUnitPosition) {
case TOP:
textRect = new RectF(mOuterTextBounds.left, mOuterTextBounds.top + unitHeight + unitGapHeightHalf, mOuterTextBounds.right, mOuterTextBounds.bottom);
break;
case BOTTOM:
textRect = new RectF(mOuterTextBounds.left, mOuterTextBounds.top, mOuterTextBounds.right, mOuterTextBounds.bottom - unitHeight - unitGapHeightHalf);
break;
case LEFT_TOP:
case LEFT_BOTTOM:
textRect = new RectF(mOuterTextBounds.left + unitWidth + unitGapWidthHalf, mOuterTextBounds.top, mOuterTextBounds.right, mOuterTextBounds.bottom);
break;
case RIGHT_TOP:
case RIGHT_BOTTOM:
default:
textRect = new RectF(mOuterTextBounds.left, mOuterTextBounds.top, mOuterTextBounds.right - unitWidth - unitGapWidthHalf, mOuterTextBounds.bottom);
break;
}
}
mTextPaint.setTextSize(calcTextSizeForRect(text, mTextPaint, textRect) * mTextScale);
mActualTextBounds = calcTextBounds(text, mTextPaint, textRect); // center text in text rect
}
private void setTextSizeAndTextBoundsWithFixedTextSize(String text) {
mTextPaint.setTextSize(mTextSize);
mActualTextBounds = calcTextBounds(text, mTextPaint, mCircleBounds); //center text in circle
}
private void setUnitTextBoundsAndSizeWithAutoTextSize(float unitGapWidthHalf, float unitWidth, float unitGapHeightHalf, float unitHeight) {
//calc the rectangle containing the unit text
switch (mUnitPosition) {
case TOP: {
mUnitBounds = new RectF(mOuterTextBounds.left, mOuterTextBounds.top, mOuterTextBounds.right, mOuterTextBounds.top + unitHeight - unitGapHeightHalf);
break;
}
case BOTTOM:
mUnitBounds = new RectF(mOuterTextBounds.left, mOuterTextBounds.bottom - unitHeight + unitGapHeightHalf, mOuterTextBounds.right, mOuterTextBounds.bottom);
break;
case LEFT_TOP:
case LEFT_BOTTOM: {
mUnitBounds = new RectF(mOuterTextBounds.left, mOuterTextBounds.top, mOuterTextBounds.left + unitWidth - unitGapWidthHalf, mOuterTextBounds.top + unitHeight);
break;
}
case RIGHT_TOP:
case RIGHT_BOTTOM:
default: {
mUnitBounds = new RectF(mOuterTextBounds.right - unitWidth + unitGapWidthHalf, mOuterTextBounds.top, mOuterTextBounds.right, mOuterTextBounds.top + unitHeight);
}
break;
}
mUnitTextPaint.setTextSize(calcTextSizeForRect(mUnit, mUnitTextPaint, mUnitBounds) * mUnitScale);
mUnitBounds = calcTextBounds(mUnit, mUnitTextPaint, mUnitBounds); // center text in rectangle and reuse it
switch (mUnitPosition) {
case LEFT_TOP:
case RIGHT_TOP: {
//move unite to top of text
float dy = mActualTextBounds.top - mUnitBounds.top;
mUnitBounds.offset(0, dy);
break;
}
case LEFT_BOTTOM:
case RIGHT_BOTTOM: {
//move unite to bottom of text
float dy = mActualTextBounds.bottom - mUnitBounds.bottom;
mUnitBounds.offset(0, dy);
break;
}
}
}
private void setUnitTextBoundsAndSizeWithFixedTextSize(float unitGapWidth, float unitGapHeight) {
mUnitTextPaint.setTextSize(mUnitTextSize);
mUnitBounds = calcTextBounds(mUnit, mUnitTextPaint, mOuterTextBounds); // center text in rectangle and reuse it
switch (mUnitPosition) {
case TOP:
mUnitBounds.offsetTo(mUnitBounds.left, mActualTextBounds.top - unitGapHeight - mUnitBounds.height());
break;
case BOTTOM:
mUnitBounds.offsetTo(mUnitBounds.left, mActualTextBounds.bottom + unitGapHeight);
break;
case LEFT_TOP:
case LEFT_BOTTOM:
mUnitBounds.offsetTo(mActualTextBounds.left - unitGapWidth - mUnitBounds.width(), mUnitBounds.top);
break;
case RIGHT_TOP:
case RIGHT_BOTTOM:
default:
mUnitBounds.offsetTo(mActualTextBounds.right + unitGapWidth, mUnitBounds.top);
break;
}
switch (mUnitPosition) {
case LEFT_TOP:
case RIGHT_TOP: {
//move unite to top of text
float dy = mActualTextBounds.top - mUnitBounds.top;
mUnitBounds.offset(0, dy);
break;
}
case LEFT_BOTTOM:
case RIGHT_BOTTOM: {
//move unite to bottom of text
float dy = mActualTextBounds.bottom - mUnitBounds.bottom;
mUnitBounds.offset(0, dy);
break;
}
}
}
/**
* Returns the bounding rectangle of the given _text, with the size and style defined in the _textPaint centered in the middle of the _textBounds
*
* @param _text The text.
* @param _textPaint The paint defining the text size and style.
* @param _textBounds The rect where the text will be centered.
* @return The bounding box of the text centered in the _textBounds.
*/
private RectF calcTextBounds(String _text, Paint _textPaint, RectF _textBounds) {
Rect textBoundsTmp = new Rect();
//get current text bounds
_textPaint.getTextBounds(_text, 0, _text.length(), textBoundsTmp);
float width = textBoundsTmp.left + textBoundsTmp.width();
float height = textBoundsTmp.bottom + textBoundsTmp.height() * 0.93f; // the height of calcTextBounds is a bit to high, therefore * 0.93
//center in circle
RectF textRect = new RectF();
textRect.left = (_textBounds.left + ((_textBounds.width() - width) / 2));
textRect.top = _textBounds.top + ((_textBounds.height() - height) / 2);
textRect.right = textRect.left + width;
textRect.bottom = textRect.top + height;
return textRect;
}
//endregion helper
//----------------------------------
//----------------------------------
//region Setting up stuff
/**
* Set the bounds of the component
*/
private void setupBounds() {
// Width should equal to Height, find the min value to setup the circle
int minValue = Math.min(mLayoutWidth, mLayoutHeight);
// Calc the Offset if needed
int xOffset = mLayoutWidth - minValue;
int yOffset = mLayoutHeight - minValue;
// Add the offset
float paddingTop = this.getPaddingTop() + (yOffset / 2);
float paddingBottom = this.getPaddingBottom() + (yOffset / 2);
float paddingLeft = this.getPaddingLeft() + (xOffset / 2);
float paddingRight = this.getPaddingRight() + (xOffset / 2);
int width = getWidth(); //this.getLayoutParams().width;
int height = getHeight(); //this.getLayoutParams().height;
float circleWidthHalf = mBarWidth / 2f > mRimWidth / 2f + mContourSize ? mBarWidth / 2f : mRimWidth / 2f + mContourSize;
mCircleBounds = new RectF(paddingLeft + circleWidthHalf,
paddingTop + circleWidthHalf,
width - paddingRight - circleWidthHalf,
height - paddingBottom - circleWidthHalf);
mInnerCircleBound = new RectF(paddingLeft + (mBarWidth),
paddingTop + (mBarWidth),
width - paddingRight - (mBarWidth),
height - paddingBottom - (mBarWidth));
mOuterTextBounds = getInnerCircleRect(mCircleBounds);
mCircleInnerContour = new RectF(mCircleBounds.left + (mRimWidth / 2.0f) + (mContourSize / 2.0f), mCircleBounds.top + (mRimWidth / 2.0f) + (mContourSize / 2.0f), mCircleBounds.right - (mRimWidth / 2.0f) - (mContourSize / 2.0f), mCircleBounds.bottom - (mRimWidth / 2.0f) - (mContourSize / 2.0f));
mCircleOuterContour = new RectF(mCircleBounds.left - (mRimWidth / 2.0f) - (mContourSize / 2.0f), mCircleBounds.top - (mRimWidth / 2.0f) - (mContourSize / 2.0f), mCircleBounds.right + (mRimWidth / 2.0f) + (mContourSize / 2.0f), mCircleBounds.bottom + (mRimWidth / 2.0f) + (mContourSize / 2.0f));
mCenter = new PointF(mCircleBounds.centerX(), mCircleBounds.centerY());
}
private void setupBarPaint() {
if (mBarColors.length > 1) {
mBarPaint.setShader(new SweepGradient(mCircleBounds.centerX(), mCircleBounds.centerY(), mBarColors, null));
Matrix matrix = new Matrix();
mBarPaint.getShader().getLocalMatrix(matrix);
matrix.postTranslate(-mCircleBounds.centerX(), -mCircleBounds.centerY());
matrix.postRotate(mStartAngle);
matrix.postTranslate(mCircleBounds.centerX(), mCircleBounds.centerY());
mBarPaint.getShader().setLocalMatrix(matrix);
} else {
mBarPaint.setColor(mBarColors[0]);
mBarPaint.setShader(null);
}
mBarPaint.setAntiAlias(true);
mBarPaint.setStrokeCap(mBarStrokeCap);
mBarPaint.setStyle(Style.STROKE);
mBarPaint.setStrokeWidth(mBarWidth);
}
/**
* Setup all paints.
* Call only if changes to color or size properties are not visible.
*/
public void setupPaints() {
setupBarPaint();
setupBarSpinnerPaint();
setupContourPaint();
setupUnitTextPaint();
setupTextPaint();
setupBackgroundCirclePaint();
setupRimPaint();
}
private void setupContourPaint() {
mContourPaint.setColor(mContourColor);
mContourPaint.setAntiAlias(true);
mContourPaint.setStyle(Style.STROKE);
mContourPaint.setStrokeWidth(mContourSize);
}
private void setupUnitTextPaint() {
mUnitTextPaint.setStyle(Style.FILL);
mUnitTextPaint.setAntiAlias(true);
if (unitTextTypeface != null) {
mUnitTextPaint.setTypeface(unitTextTypeface);
}
}
private void setupTextPaint() {
mTextPaint.setSubpixelText(true);
mTextPaint.setLinearText(true);
mTextPaint.setTypeface(Typeface.MONOSPACE);
mTextPaint.setColor(mTextColor);
mTextPaint.setStyle(Style.FILL);
mTextPaint.setAntiAlias(true);
mTextPaint.setTextSize(mTextSize);
if (textTypeface != null) {
mTextPaint.setTypeface(textTypeface);
} else {
mTextPaint.setTypeface(Typeface.MONOSPACE);
}
}
private void setupBackgroundCirclePaint() {
mBackgroundCirclePaint.setColor(mBackgroundCircleColor);
mBackgroundCirclePaint.setAntiAlias(true);
mBackgroundCirclePaint.setStyle(Style.FILL);
}
private void setupRimPaint() {
mRimPaint.setColor(mRimColor);
mRimPaint.setAntiAlias(true);
mRimPaint.setStyle(Style.STROKE);
mRimPaint.setStrokeWidth(mRimWidth);
}
private void setupBarSpinnerPaint() {
mBarSpinnerPaint.setAntiAlias(true);
mBarSpinnerPaint.setStrokeCap(mSpinnerStrokeCap);
mBarSpinnerPaint.setStyle(Style.STROKE);
mBarSpinnerPaint.setStrokeWidth(mBarWidth);
mBarSpinnerPaint.setColor(mSpinnerColor);
}
//endregion Setting up stuff
//----------------------------------
//----------------------------------
//region draw all the things
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (DEBUG) {
drawDebug(canvas);
}
float degrees = (360f / mMaxValue * mCurrentValue);
// Draw the background circle
if (mBackgroundCircleColor != 0) {
canvas.drawArc(mInnerCircleBound, 360, 360, false, mBackgroundCirclePaint);
}
//Draw the rim
if (mRimWidth > 0) {
if (!mShowBlock) {
canvas.drawArc(mCircleBounds, 360, 360, false, mRimPaint);
} else {
drawBlocks(canvas, mCircleBounds, mStartAngle, 360, false, mRimPaint);
}
}
//Draw contour
if (mContourSize > 0) {
canvas.drawArc(mCircleOuterContour, 360, 360, false, mContourPaint);
canvas.drawArc(mCircleInnerContour, 360, 360, false, mContourPaint);
}
//Draw spinner
if (mAnimationState == AnimationState.SPINNING || mAnimationState == AnimationState.END_SPINNING) {
drawSpinner(canvas);
if (mShowTextWhileSpinning) {
drawTextWithUnit(canvas);
}
} else if (mAnimationState == AnimationState.END_SPINNING_START_ANIMATING) {
//draw spinning arc
drawSpinner(canvas);
if (mDrawBarWhileSpinning) {
drawBar(canvas, degrees);
drawTextWithUnit(canvas);
} else if (mShowTextWhileSpinning) {
drawTextWithUnit(canvas);
}
} else {
drawBar(canvas, degrees);
drawTextWithUnit(canvas);
}
if (mClippingBitmap != null) {
canvas.drawBitmap(mClippingBitmap, 0, 0, mMaskPaint);
}
}
private void drawDebug(Canvas canvas) {
Paint innerRectPaint = new Paint();
innerRectPaint.setColor(Color.YELLOW);
canvas.drawRect(mCircleBounds, innerRectPaint);
}
private void drawBlocks(Canvas _canvas, RectF circleBounds, float startAngle, float _degrees, boolean userCenter, Paint paint) {
float tmpDegree = 0.0f;
while (tmpDegree < _degrees) {
_canvas.drawArc(circleBounds, startAngle + tmpDegree, Math.min(mBlockScaleDegree, _degrees - tmpDegree), userCenter, paint);
tmpDegree += mBlockDegree;
}
}
private void drawSpinner(Canvas canvas) {
if (mSpinningBarLengthCurrent < 0) {
mSpinningBarLengthCurrent = 1;
}
float startAngle = (mStartAngle + mCurrentSpinnerDegreeValue - mSpinningBarLengthCurrent);
canvas.drawArc(mCircleBounds, startAngle, mSpinningBarLengthCurrent, false,
mBarSpinnerPaint);
}
private void drawTextWithUnit(Canvas canvas) {
final float relativeGapHeight;
final float relativeGapWidth;
final float relativeHeight;
final float relativeWidth;
switch (mUnitPosition) {
case TOP:
case BOTTOM:
relativeGapWidth = 0.05f; //gap size between text and unit
relativeGapHeight = 0.025f; //gap size between text and unit
relativeHeight = 0.25f * mRelativeUniteSize;
relativeWidth = 0.4f * mRelativeUniteSize;
break;
default:
case LEFT_TOP:
case RIGHT_TOP:
case LEFT_BOTTOM:
case RIGHT_BOTTOM:
relativeGapWidth = 0.05f; //gap size between text and unit
relativeGapHeight = 0.025f; //gap size between text and unit
relativeHeight = 0.55f * mRelativeUniteSize;
relativeWidth = 0.3f * mRelativeUniteSize;
break;
}
float unitGapWidthHalf = mOuterTextBounds.width() * relativeGapWidth / 2f;
float unitWidth = (mOuterTextBounds.width() * relativeWidth);
float unitGapHeightHalf = mOuterTextBounds.height() * relativeGapHeight / 2f;
float unitHeight = (mOuterTextBounds.height() * relativeHeight);
boolean update = false;
//Draw Text
if (mIsAutoColorEnabled) {
mTextPaint.setColor(calcTextColor(mCurrentValue));
}
//set text
String text;
switch (mTextMode) {
case TEXT:
default:
text = mText != null ? mText : "";
break;
case PERCENT:
text = decimalFormat.format(100f / mMaxValue * mCurrentValue) + "%";
break;
case VALUE:
text = decimalFormat.format(mCurrentValue) + "%";
break;
}
// only re-calc position and size if string length changed
if (mTextLength != text.length()) {
update = true;
mTextLength = text.length();
if (mTextLength == 1) {
mOuterTextBounds = getInnerCircleRect(mCircleBounds);
mOuterTextBounds = new RectF(mOuterTextBounds.left + (mOuterTextBounds.width() * 0.1f), mOuterTextBounds.top, mOuterTextBounds.right - (mOuterTextBounds.width() * 0.1f), mOuterTextBounds.bottom);
} else {
mOuterTextBounds = getInnerCircleRect(mCircleBounds);
}
if (mIsAutoTextSize) {
setTextSizeAndTextBoundsWithAutoTextSize(unitGapWidthHalf, unitWidth, unitGapHeightHalf, unitHeight, text);
} else {
setTextSizeAndTextBoundsWithFixedTextSize(text);
}
}
if (DEBUG) {
Paint rectPaint = new Paint();
rectPaint.setColor(Color.MAGENTA);
canvas.drawRect(mOuterTextBounds, rectPaint);
rectPaint.setColor(Color.GREEN);
canvas.drawRect(mActualTextBounds, rectPaint);
}
canvas.drawText(text, mActualTextBounds.left - (mTextPaint.getTextSize() * 0.02f), mActualTextBounds.bottom, mTextPaint);
if (mShowUnit) {
if (mIsAutoColorEnabled) {
mUnitTextPaint.setColor(calcTextColor(mCurrentValue));
}
if (update) {
//calc unit text position
if (mIsAutoTextSize) {
setUnitTextBoundsAndSizeWithAutoTextSize(unitGapWidthHalf, unitWidth, unitGapHeightHalf, unitHeight);
} else {
setUnitTextBoundsAndSizeWithFixedTextSize(unitGapWidthHalf * 2f, unitGapHeightHalf * 2f);
}
}
if (DEBUG) {
Paint rectPaint = new Paint();
rectPaint.setColor(Color.RED);
canvas.drawRect(mUnitBounds, rectPaint);
}
canvas.drawText(mUnit, mUnitBounds.left - (mUnitTextPaint.getTextSize() * 0.02f), mUnitBounds.bottom, mUnitTextPaint);
}
}
private void drawBar(Canvas _canvas, float _degrees) {
if (!mShowBlock) {
_canvas.drawArc(mCircleBounds, mStartAngle, _degrees, false, mBarPaint);
} else {
drawBlocks(_canvas, mCircleBounds, mStartAngle, _degrees, false, mBarPaint);
}
}
//endregion draw
//----------------------------------
/**
* Turn off spinning mode
*/
public void stopSpinning() {
mAnimationHandler.sendEmptyMessage(AnimationMsg.STOP_SPINNING.ordinal());
}
/**
* Puts the view in spin mode
*/
public void spin() {
mAnimationHandler.sendEmptyMessage(AnimationMsg.START_SPINNING.ordinal());
}
//----------------------------------
//region touch input
@Override
public boolean onTouchEvent(@NonNull MotionEvent event) {
if (mSeekModeEnabled == false) {
return super.onTouchEvent(event);
}
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_UP: {
mTouchEventCount = 0;
PointF point = new PointF(event.getX(), event.getY());
float angle = normalizeAngle(Math.round(calcRotationAngleInDegrees(mCenter, point) - mStartAngle));
setValueAnimated(mMaxValue / 360f * angle, 800);
return true;
}
case MotionEvent.ACTION_MOVE: {
mTouchEventCount++;
if (mTouchEventCount > 5) { //touch/move guard
PointF point = new PointF(event.getX(), event.getY());
float angle = normalizeAngle(Math.round(calcRotationAngleInDegrees(mCenter, point) - mStartAngle));
setValue(mMaxValue / 360f * angle);
return true;
} else {
return false;
}
}
case MotionEvent.ACTION_CANCEL:
mTouchEventCount = 0;
return false;
}
return super.onTouchEvent(event);
}
//endregion touch input
//----------------------------------
//-----------------------------------
//region listener for progress change
public interface OnProgressChangedListener {
void onProgressChanged(float value);
}
//endregion listener for progress change
//--------------------------------------
}
|
package Diaballik.Vue;
import java.awt.Color;
import java.awt.Font;
import java.awt.Image;
import java.awt.event.*;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextArea;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import com.fasterxml.jackson.databind.ObjectMapper;
import Diaballik.Controllers.ControleurMediateur;
import Diaballik.Models.ConfigJeu;
import Diaballik.Models.Jeu;
import Diaballik.Models.ConfigJeu.IALevel;
import Diaballik.Models.ConfigJeu.Mode;
import Diaballik.Models.ConfigJeu.Timer;
public class NewGame extends JPanel {
private static final long serialVersionUID = 1L;
ObjectMapper objectMapper = new ObjectMapper();
JLabel titre = new JLabel("Nouvelle partie");
JLabel duree = new JLabel("Durée d'un tour :");
JLabel priorite = new JLabel("Joue en premier : ");
JButton retour = new JButton("Retour");
JButton jouer = new JButton("Jouer");
JButton humain = new JButton("Humain");
JButton ordinateur = new JButton("Ordinateur");
JButton illimite = new JButton("Illimité");
JButton uneMin = new JButton("10 sec");
JButton deuxMin = new JButton("30 sec");
JButton troisMin = new JButton("1 min");
JButton joueur1 = new JButton("Joueur 1");
JButton joueur2 = new JButton("Joueur 2");
JLabel nomJoueur = new JLabel("Nom du joueur 1 : ");
JLabel nomJoueur2 = new JLabel("Nom du joueur 2 : ");
JLabel jouerContre = new JLabel("Jouer Contre :");
JLabel niveauIA = new JLabel("Niveau de l'IA :");
JTextArea name1 = new JTextArea("Joueur 1");
JTextArea name2 = new JTextArea("Joueur 2");
JTextArea name3 = new JTextArea("IA");
JCheckBox varianteCheckbox = new JCheckBox("Variante");
ButtonGroup b = new ButtonGroup();
JRadioButton br1 = new JRadioButton("Facile");
JRadioButton br2 = new JRadioButton("Moyen");
JRadioButton br3 = new JRadioButton("Difficile");
boolean bHumain = true;
int persoJoueur;
playSound ps = new playSound();
ihm i;
Jeu j;
ConfigJeu configJeu;
Image icon;
JButton choixPersoJoueur1 = new JButton("Personnaliser");
JButton choixPersoJoueur2 = new JButton("Personnaliser");
JButton choisirTerrain = new JButton("Personnaliser le damier");
JLabel choisirTerrainlabel = new JLabel("Choisir terrain : ");
public static choisirPerso cp1,cp2;
// Parametres de la nouvelle partie
/*
* public enum Joueur { humain, ordinateur; }
*
* public enum temps { illimite, 0 un, 1 deux, 2 trois; 3 }
*
* public enum premier { joueurun, true joueurdeux; false }
*/
int tempschrono = 0; // illimite
boolean human = true; // joueur humain
boolean first = true; // joueur 1
public NewGame(ihm ihm) {
i = ihm;
j = new Jeu();
configJeu = new ConfigJeu();
i.setLocationRelativeTo(null);
this.setLayout(null);
i.addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent evt) {
jouerContre.setBounds((i.getWidth() / 2) - 240, (i.getHeight() / 4) - 80, 100, 100);
name1.setBounds((i.getWidth() / 2) - 90, (i.getHeight() / 4) + 50, 200, 20);
name2.setBounds((i.getWidth() / 2) - 90, (i.getHeight() / 4) + 80, 200, 20);
nomJoueur.setBounds((i.getWidth() / 2) - 240, (i.getHeight() / 4) + 50, 110, 20);
nomJoueur2.setBounds((i.getWidth() / 2) - 240, (i.getHeight() / 4) + 80, 110, 20);
choixPersoJoueur1.setBounds((i.getWidth() / 2) + 120, (i.getHeight() / 4) + 50, 130, 20);
choixPersoJoueur2.setBounds((i.getWidth() / 2) + 120, (i.getHeight() / 4) + 80, 130, 20);
choisirTerrainlabel.setBounds((i.getWidth() / 2) - 240, (i.getHeight() / 4) + 120, 120, 30);
choisirTerrain.setBounds((i.getWidth() / 2) - 90, (i.getHeight() / 4) + 120, 200, 30);
titre.setBounds((i.getWidth() / 2) - 100, (i.getHeight() / 4) - 120, 300, 100);
duree.setBounds((i.getWidth() / 2) - 240, (i.getHeight() / 4) + 120, 100, 100);
priorite.setBounds((i.getWidth() / 2) - 240, (i.getHeight() / 4) + 190, 150, 120);
jouer.setBounds((i.getWidth() / 2) + 20, (i.getHeight() / 4) + 350, 120, 40);
retour.setBounds((i.getWidth() / 2) - 130, (i.getHeight() / 4) + 350, 120, 40);
humain.setBounds((i.getWidth() / 2) - 130, (i.getHeight() / 4) - 20, 120, 40);
ordinateur.setBounds((i.getWidth() / 2) + 20, (i.getHeight() / 4) - 20, 120, 40);
illimite.setBounds((i.getWidth() / 2) - 240, (i.getHeight() / 4) + 185, 100, 40);
uneMin.setBounds((i.getWidth() / 2) - 120, (i.getHeight() / 4) + 185, 100, 40);
deuxMin.setBounds((i.getWidth() / 2), (i.getHeight() / 4) + 185, 100, 40);
troisMin.setBounds((i.getWidth() / 2) + 120, (i.getHeight() / 4) + 185, 100, 40);
joueur2.setBounds((i.getWidth() / 2) + 20, (i.getHeight() / 4) + 270, 120, 40);
joueur1.setBounds((i.getWidth() / 2) - 130, (i.getHeight() / 4) + 270, 120, 40);
niveauIA.setBounds((i.getWidth() / 2) - 240, (i.getHeight() / 4) + 40, 110, 20);
br1.setBounds((i.getWidth() / 2) - 100, (i.getHeight() / 4) + 40, 70, 20);
br2.setBounds((i.getWidth() / 2) - 30, (i.getHeight() / 4) + 40, 70, 20);
br3.setBounds((i.getWidth() / 2) + 40, (i.getHeight() / 4) + 40, 70, 20);
i.sound.setBounds(i.getWidth() - 80, 75, 40, 40);
varianteCheckbox.setBounds((i.getWidth() / 2) + 150, (i.getHeight() / 4) + 125, 100, 20);
}
});
Font font = new Font("Arial", Font.BOLD, 30);
titre.setFont(font);
humain.setBackground(Color.pink);
illimite.setBackground(Color.pink);
joueur1.setBackground(Color.pink);
name1.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void changedUpdate(DocumentEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void insertUpdate(DocumentEvent arg0) {
// TODO Auto-generated method stub
joueur1.setText(name1.getText());
configJeu.setName1(name1.getText());
}
@Override
public void removeUpdate(DocumentEvent arg0) {
// TODO Auto-generated method stub
}
});
name2.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void changedUpdate(DocumentEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void insertUpdate(DocumentEvent arg0) {
// TODO Auto-generated method stub
joueur2.setText(name2.getText());
configJeu.setName2(name2.getText());
}
@Override
public void removeUpdate(DocumentEvent arg0) {
// TODO Auto-generated method stub
}
});
retour.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
i.retourMenuPrincipal();
}
});
humain.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
humain.setBackground(Color.pink);
ordinateur.setBackground(null);
// j.IA = false;
configJeu.setMode(Mode.humain);
name2.setText("Joueur 2");
if (bHumain == false) {
i.setSize(i.getWidth(), i.getHeight());
name1.setBounds((i.getWidth() / 2) - 90, (i.getHeight() / 4) + 50, 200, 20);
name2.setBounds((i.getWidth() / 2) - 90, (i.getHeight() / 4) + 80, 200, 20);
nomJoueur.setBounds((i.getWidth() / 2) - 240, (i.getHeight() / 4) + 50, 110, 20);
nomJoueur2.setBounds((i.getWidth() / 2) - 240, (i.getHeight() / 4) + 80, 110, 20);
choixPersoJoueur1.setBounds((i.getWidth() / 2) + 120, (i.getHeight() / 4) + 50, 130, 20);
choixPersoJoueur2.setBounds((i.getWidth() / 2) + 120, (i.getHeight() / 4) + 80, 130, 20);
choisirTerrainlabel.setBounds((i.getWidth() / 2) - 240, (i.getHeight() / 4) + 120, 120, 30);
choisirTerrain.setBounds((i.getWidth() / 2) - 90, (i.getHeight() / 4) + 120, 200, 30);
varianteCheckbox.setBounds((i.getWidth() / 2) + 150, (i.getHeight() / 4) + 125, 100, 20);
bHumain = true;
}
niveauIA.setVisible(false);
br1.setVisible(false);
br2.setVisible(false);
br3.setVisible(false);
}
});
ordinateur.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ordinateur.setBackground(Color.pink);
humain.setBackground(null);
human = false; // joueur IA
// j.IA = true;
configJeu.setMode(Mode.ordinateur);
name2.setText("IA");
if (bHumain == true) {
i.setSize(i.getWidth(), i.getHeight());
name1.setBounds((i.getWidth() / 2) - 90, (i.getHeight() / 4) + 70, 200, 20);
name2.setBounds((i.getWidth() / 2) - 90, (i.getHeight() / 4) + 100, 200, 20);
nomJoueur.setBounds((i.getWidth() / 2) - 240, (i.getHeight() / 4) + 70, 110, 20);
nomJoueur2.setBounds((i.getWidth() / 2) - 240, (i.getHeight() / 4) + 100, 110, 20);
choixPersoJoueur1.setBounds((i.getWidth() / 2) + 120, (i.getHeight() / 4) + 70, 130, 20);
choixPersoJoueur2.setBounds((i.getWidth() / 2) + 120, (i.getHeight() / 4) + 100, 130, 20);
choisirTerrainlabel.setBounds((i.getWidth() / 2) - 240, (i.getHeight() / 4) + 130, 120, 30);
choisirTerrain.setBounds((i.getWidth() / 2) - 90, (i.getHeight() / 4) + 130, 200, 30);
varianteCheckbox.setBounds((i.getWidth() / 2) + 150, (i.getHeight() / 4) + 135, 100, 20);
bHumain = false;
}
niveauIA.setVisible(true);
br1.setVisible(true);
br2.setVisible(true);
br3.setVisible(true);
}
});
illimite.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
illimite.setBackground(Color.pink);
uneMin.setBackground(null);
deuxMin.setBackground(null);
troisMin.setBackground(null);
configJeu.setTimer(Timer.illimite);
}
});
uneMin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
uneMin.setBackground(Color.pink);
illimite.setBackground(null);
deuxMin.setBackground(null);
troisMin.setBackground(null);
tempschrono = 1;
configJeu.setTimer(Timer.un);
}
});
deuxMin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
deuxMin.setBackground(Color.pink);
illimite.setBackground(null);
uneMin.setBackground(null);
troisMin.setBackground(null);
tempschrono = 2;
configJeu.setTimer(Timer.deux);
}
});
troisMin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
troisMin.setBackground(Color.pink);
illimite.setBackground(null);
deuxMin.setBackground(null);
uneMin.setBackground(null);
tempschrono = 3;
configJeu.setTimer(Timer.trois);
}
});
joueur1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
joueur1.setBackground(Color.pink);
joueur2.setBackground(null);
configJeu.setP1First(true);
}
});
joueur2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
joueur2.setBackground(Color.pink);
joueur1.setBackground(null);
first = false; // joueur 2
configJeu.setP1First(false);
}
});
br1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
configJeu.setIALevel(IALevel.facile);
configJeu.setName3("IA facile");
}
});
br2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
configJeu.setIALevel(IALevel.moyen);
configJeu.setName3("IA moyen");
}
});
br3.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
configJeu.setIALevel(IALevel.difficile);
configJeu.setName3("IA difficile");
}
});
varianteCheckbox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
configJeu.setVariante(true);
} else {
configJeu.setVariante(false);
}
;
}
});
jouer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ps.play("/buttonClick.wav", staticConfig.bmute);
j.configurer(configJeu);
j.start();
CollecteurEvenements control = new ControleurMediateur(j);
Plateau.setIHM(i);
Plateau.demarrer(j, control, configJeu);
i.setVisible(false);
}
});
choixPersoJoueur1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
persoJoueur = 1;
cp1 = new choisirPerso(persoJoueur);
}
});
choixPersoJoueur2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
persoJoueur = 2;
cp2 = new choisirPerso(persoJoueur);
}
});
choisirTerrain.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new TerrainCustomize(configJeu);
}
});
String sInfo = "Mode de jeu alternatif avec 2 pions dans le camps adverse au départ";
varianteCheckbox.setToolTipText(sInfo);
b.add(br1);
b.add(br2);
b.add(br3);
this.add(niveauIA);
niveauIA.setVisible(false);
this.add(br1);
br1.setSelected(true);
br1.setVisible(false);
this.add(br2);
br2.setVisible(false);
this.add(br3);
br3.setVisible(false);
this.add(jouerContre);
this.add(nomJoueur);
this.add(nomJoueur2);
this.add(name1);
this.add(name2);
this.add(joueur1);
this.add(joueur2);
this.add(priorite);
this.add(illimite);
this.add(uneMin);
this.add(deuxMin);
this.add(troisMin);
this.add(duree);
this.add(ordinateur);
this.add(humain);
this.add(jouer);
this.add(retour);
this.add(titre);
this.add(varianteCheckbox);
this.add(choixPersoJoueur1);
this.add(choixPersoJoueur2);
this.add(choisirTerrainlabel);
this.add(choisirTerrain);
this.setVisible(true);
}
}
|
/*
* Copyright 2009 Valtech GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.valtech.source.dependometer.ui.console.output;
import java.io.File;
import com.valtech.source.dependometer.app.core.provider.DependencyElementIf;
/**
* @author Dietmar Menges (dietmar.menges@valtech.de)
*/
final class HtmlTypeDocument extends HtmlDependencyElementDocument
{
protected HtmlTypeDocument(File directory, DependencyElementIf element, String metricDescriptionsDocumentName)
{
super(directory, element, metricDescriptionsDocumentName);
}
protected boolean showRelationQualifier()
{
return true;
}
protected String getContainsTypeName()
{
return null;
}
protected boolean showTypeRelations()
{
return false;
}
protected boolean showRelationQualifierForContained()
{
return false;
}
protected boolean showAllowedDependencies()
{
return false;
}
protected boolean showTypeRelationsInInnerDependencies()
{
return false;
}
protected boolean showComponentDependency()
{
return false;
}
protected boolean showRelationQualifierInInnerDependencies()
{
return false;
}
}
|
/*
* Copyright © 2019 Agency for Data Supply and Efficiency
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.kortforsyningen.proj;
import java.util.Map;
import java.util.List;
import java.util.Objects;
import java.lang.annotation.Native;
import javax.measure.Unit;
import javax.measure.UnitConverter;
import javax.measure.IncommensurableException;
import javax.measure.Dimension;
import javax.measure.Quantity;
import javax.measure.quantity.Angle;
import javax.measure.quantity.Length;
import javax.measure.quantity.Time;
import javax.measure.quantity.Dimensionless;
/**
* Mirror of {@code osgeo::proj::common::UnitOfMeasure} constants. This class does not wrap native object.
* It is used only as a fallback when no JSR-363 implementation has been found on the classpath.
*
* @author Martin Desruisseaux (Geomatys)
* @version 1.0
* @since 1.0
*/
final class UnitOfMeasure<Q extends Quantity<Q>> implements Unit<Q> {
/**
* Constants identifying PROJ predefined units. We can provide only constants for quantities enumerated
* in {@link UnitType}. For example PROJ 6.2 does not provide {@code UnitOfMeasure::Type::SPEED} value,
* so we have to skip the {@code METRE_PER_YEAR} unit.
*/
@Native
static final short
SCALE_UNITY = 0,
PARTS_PER_MILLION = 1,
METRE = 2,
RADIAN = 3,
MICRORADIAN = 4,
DEGREE = 5,
ARC_SECOND = 6,
GRAD = 7,
SECOND = 8,
YEAR = 9;
// If YEAR is no longer the last unit, update Units.PREDEFINED array length.
/**
* The type of quantity represented by this unit of measurement.
*/
final Class<Q> type;
/**
* The unit name. This is provided by PROJ.
*/
private final String name;
/**
* The conversion factor to system unit. This is provided by PROJ.
*/
final double toSI;
/**
* Creates a new mirror of {@code osgeo::proj::common::UnitOfMeasure}.
* This constructor is invoked from native code; if the method signature
* is modified, then C/C++ code needs to be modified too.
*
* @param type the unit type as an {@link UnitType} ordinal value.
* @param name unit name (provided by PROJ, matches the name in EPSG database).
* @param toSI the conversion factory to system unit (provided by PROJ).
*/
@SuppressWarnings("unchecked")
private UnitOfMeasure(final int type, final String name, final double toSI) {
this.type = (Class<Q>) UnitType.forOrdinal(type).type;
this.name = name;
this.toSI = toSI;
}
/**
* Creates a new mirror of {@code osgeo::proj::common::UnitOfMeasure}.
*
* @param type the type of quantity represented by the unit of measurement.
* @param toSI the conversion factory to system unit (provided by PROJ).
*/
private UnitOfMeasure(final Class<Q> type, final double toSI) {
this.type = type;
this.name = null;
this.toSI = toSI;
}
/**
* Creates a new mirror of {@code osgeo::proj::common::UnitOfMeasure}.
* The unit name and conversion factor to SI will be provided by PROJ.
*
* @param code one of {@link UnitOfMeasure} constants.
* @return a mirror of PROJ unit of measurement, or {@code null} is the given code is unrecognized.
*/
static native UnitOfMeasure<?> create(short code);
/**
* Returns the symbol of this unit, or {@code null} if this unit has no specific symbol associated with.
*/
@Override
public String getSymbol() {
return null;
}
/**
* Returns the name of this unit. This method is allowed to return {@code null}
* if this unit has no specific name associated with.
*/
@Override
public String getName() {
return name;
}
/**
* Unsupported operation for this simple unit implementation.
*/
@Override
public Dimension getDimension() {
throw new NoUnitImplementationException();
}
/**
* Returns the unscaled system unit from which this unit is derived.
*/
@Override
public Unit<Q> getSystemUnit() {
final short code;
if (Length.class.equals(type)) {
code = METRE;
} else if (Angle.class.equals(type)) {
code = RADIAN;
} else if (Time.class.equals(type)) {
code = SECOND;
} else if (Dimensionless.class.equals(type)) {
code = SCALE_UNITY;
} else {
throw new NoUnitImplementationException();
}
return Units.getUnit(code).asType(type);
}
/**
* Returns the base units and their exponent whose product is this unit,
* or {@code null} if this unit is a base unit.
*/
@Override
public Map<? extends Unit<?>, Integer> getBaseUnits() {
throw new NoUnitImplementationException();
}
/**
* Indicates if this unit is compatible with the unit specified.
*/
@Override
public boolean isCompatible(final Unit<?> other) {
if (other instanceof UnitOfMeasure<?>) {
return type.equals(((UnitOfMeasure<?>) other).type);
}
throw new NoUnitImplementationException(Objects.requireNonNull(other).getClass());
}
/**
* Casts this unit to a parameterized unit of specified nature or
* throw a {@code ClassCastException} if the dimensions do not match.
*/
@Override
@SuppressWarnings("unchecked")
public <T extends Quantity<T>> Unit<T> asType(final Class<T> target) throws ClassCastException {
if (target.isAssignableFrom(type)) {
return (Unit<T>) this;
}
throw new ClassCastException("Unit<" + type.getSimpleName() + "> can not be casted to Unit<"
+ target.getSimpleName() + ">.");
}
/**
* A straightforward converter implementation which only multiplies values by a factor.
* No attempt is made to avoid rounding errors (more sophisticated implementations may
* use ratio for example instead than a IEEE 754 double-prevision value).
*/
private static final class Converter implements UnitConverter {
/** The conversion factor. */ private final double factor;
/**
* Creates a new converter with the given conversion factor.
* @param factor conversion factor from source unit to target unit.
*/
Converter(final double factor) {this.factor = factor;}
@Override public UnitConverter inverse() {return new Converter(1 / factor);}
@Override public boolean isLinear() {return true;}
@Override public boolean isIdentity() {return factor == 1;}
@Override public Number convert(Number value) {return factor * value.doubleValue();}
@Override public double convert(double value) {return factor * value;}
@Override public List<UnitConverter> getConversionSteps() {return List.of(this);}
@Override public UnitConverter concatenate(final UnitConverter other) {
if (other.isLinear()) {
return new Converter(factor * other.convert(1));
} else {
// More sophisticated implementation would be able to create a concatenated converter.
throw new NoUnitImplementationException("Can not concatenate non-linear converter.");
}
}
}
/**
* Returns a converter of numeric values from this unit to another unit of same type.
*/
@Override
public UnitConverter getConverterTo(final Unit<Q> target) {
if (target instanceof UnitOfMeasure<?>) {
return new Converter(toSI / ((UnitOfMeasure<?>) target).toSI);
}
throw new NoUnitImplementationException(Objects.requireNonNull(target).getClass());
}
/**
* Returns a converter from this unit to the specified unit of type unknown.
*/
@Override
public UnitConverter getConverterToAny(final Unit<?> target) throws IncommensurableException {
if (target instanceof UnitOfMeasure<?>) {
final Class<?> t = ((UnitOfMeasure<?>) target).type;
if (type.equals(t)) {
return new Converter(toSI / ((UnitOfMeasure<?>) target).toSI);
}
throw new IncommensurableException("Can not convert " + type.getSimpleName() + " to " + t.getSimpleName());
}
throw new NoUnitImplementationException(Objects.requireNonNull(target).getClass());
}
/**
* Returns a system unit equivalent to this unscaled standard unit but used
* in expressions to distinguish between quantities of a different nature.
*/
@Override
public Unit<Q> alternate(final String label) {
throw new NoUnitImplementationException();
}
/**
* Returns the result of setting the origin of the scale of measurement to the given value.
*/
@Override
public Unit<Q> shift(final double offset) {
throw new NoUnitImplementationException();
}
/**
* Returns the result of multiplying this unit by the specified factor.
*/
@Override
public Unit<Q> multiply(final double multiplier) {
if (multiplier == 1) return this;
return new UnitOfMeasure<>(type, toSI * multiplier);
}
/**
* Returns the product of this unit with the one specified.
*/
@Override
public Unit<?> multiply(final Unit<?> multiplier) {
throw new NoUnitImplementationException();
}
/**
* Returns the reciprocal (multiplicative inverse) of this unit.
*/
@Override
public Unit<?> inverse() {
throw new NoUnitImplementationException();
}
/**
* Returns the result of dividing this unit by a divisor.
*/
@Override
public Unit<Q> divide(final double divisor) {
if (divisor == 1) return this;
return new UnitOfMeasure<>(type, toSI / divisor);
}
/**
* Returns the quotient of this unit with the one specified.
*/
@Override
public Unit<?> divide(final Unit<?> divisor) {
throw new NoUnitImplementationException();
}
/**
* Returns an unit that is the n-th (integer) root of this unit.
*/
@Override
public Unit<?> root(int n) {
throw new NoUnitImplementationException();
}
/**
* Returns an unit raised to the n-th (integer) power of this unit.
*/
@Override
public Unit<?> pow(int n) {
throw new NoUnitImplementationException();
}
/**
* Returns the unit derived from this unit using the specified converter.
*/
@Override
public Unit<Q> transform(final UnitConverter operation) {
throw new NoUnitImplementationException();
}
/**
* Compares this unit with the given object for strict equality.
*/
@Override
public boolean equals(final Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof UnitOfMeasure<?>) {
final UnitOfMeasure<?> other = (UnitOfMeasure<?>) obj;
return type.equals(other.type) && Objects.equals(name, other.name) &&
Double.doubleToLongBits(toSI) == Double.doubleToLongBits(other.toSI);
}
return false;
}
/**
* Returns a hash code value for this unit.
*/
@Override
public int hashCode() {
return Objects.hashCode(name) + type.hashCode() + Double.hashCode(toSI);
}
/**
* Returns a string representation of this unit. Current implementation returns the unit name.
*/
@Override
public String toString() {
return getName();
}
}
|
package redis.clients.jedis.commands;
import java.util.List;
import java.util.Map;
import java.util.Set;
import redis.clients.jedis.*;
import redis.clients.jedis.params.*;
/**
* Common interface for sharded and non-sharded BinaryJedis
*/
public interface BinaryJedisCommands {
String set(byte[] key, byte[] value);
String set(byte[] key, byte[] value, SetParams params);
byte[] get(byte[] key);
byte[] getDel(byte[] key);
byte[] getEx(byte[] key, GetExParams params);
Boolean exists(byte[] key);
Long persist(byte[] key);
String type(byte[] key);
byte[] dump(byte[] key);
/**
* @deprecated Use {@link #restore(byte[], long, byte[])}.
*/
@Deprecated
default String restore(byte[] key, int ttl, byte[] serializedValue) {
return restore(key, (long) ttl, serializedValue);
}
String restore(byte[] key, long ttl, byte[] serializedValue);
/**
* @deprecated Use {@link #restoreReplace(byte[], long, byte[])}.
*/
@Deprecated
default String restoreReplace(byte[] key, int ttl, byte[] serializedValue) {
return restoreReplace(key, (long) ttl, serializedValue);
}
/**
* @deprecated Use {@link #restore(byte[], long, byte[], redis.clients.jedis.params.RestoreParams)}.
*/
@Deprecated
String restoreReplace(byte[] key, long ttl, byte[] serializedValue);
String restore(byte[] key, long ttl, byte[] serializedValue, RestoreParams params);
/**
* @deprecated Use {@link #expire(byte[], long)}.
*/
@Deprecated
default Long expire(byte[] key, int seconds) {
return expire(key, (long) seconds);
}
Long expire(byte[] key, long seconds);
Long pexpire(byte[] key, long milliseconds);
Long expireAt(byte[] key, long unixTime);
Long pexpireAt(byte[] key, long millisecondsTimestamp);
Long ttl(byte[] key);
Long pttl(byte[] key);
Long touch(byte[] key);
Boolean setbit(byte[] key, long offset, boolean value);
/**
* @deprecated Use {@link #setbit(byte[], long, boolean)}.
*/
@Deprecated
Boolean setbit(byte[] key, long offset, byte[] value);
Boolean getbit(byte[] key, long offset);
Long setrange(byte[] key, long offset, byte[] value);
byte[] getrange(byte[] key, long startOffset, long endOffset);
byte[] getSet(byte[] key, byte[] value);
Long setnx(byte[] key, byte[] value);
/**
* @deprecated Use {@link #setex(byte[], long, byte[])}.
*/
@Deprecated
default String setex(byte[] key, int seconds, byte[] value) {
return setex(key, (long) seconds, value);
}
String setex(byte[] key, long seconds, byte[] value);
String psetex(byte[] key, long milliseconds, byte[] value);
Long decrBy(byte[] key, long decrement);
Long decr(byte[] key);
Long incrBy(byte[] key, long increment);
Double incrByFloat(byte[] key, double increment);
Long incr(byte[] key);
Long append(byte[] key, byte[] value);
byte[] substr(byte[] key, int start, int end);
Long hset(byte[] key, byte[] field, byte[] value);
Long hset(byte[] key, Map<byte[], byte[]> hash);
byte[] hget(byte[] key, byte[] field);
Long hsetnx(byte[] key, byte[] field, byte[] value);
String hmset(byte[] key, Map<byte[], byte[]> hash);
List<byte[]> hmget(byte[] key, byte[]... fields);
Long hincrBy(byte[] key, byte[] field, long value);
Double hincrByFloat(byte[] key, byte[] field, double value);
Boolean hexists(byte[] key, byte[] field);
Long hdel(byte[] key, byte[]... field);
Long hlen(byte[] key);
Set<byte[]> hkeys(byte[] key);
List<byte[]> hvals(byte[] key);
Map<byte[], byte[]> hgetAll(byte[] key);
byte[] hrandfield(byte[] key);
List<byte[]> hrandfield(byte[] key, long count);
Map<byte[], byte[]> hrandfieldWithValues(byte[] key, long count);
Long rpush(byte[] key, byte[]... args);
Long lpush(byte[] key, byte[]... args);
Long llen(byte[] key);
List<byte[]> lrange(byte[] key, long start, long stop);
String ltrim(byte[] key, long start, long stop);
byte[] lindex(byte[] key, long index);
String lset(byte[] key, long index, byte[] value);
Long lrem(byte[] key, long count, byte[] value);
byte[] lpop(byte[] key);
List<byte[]> lpop(byte[] key, int count);
Long lpos(byte[] key, byte[] element);
Long lpos(byte[] key, byte[] element, LPosParams params);
List<Long> lpos(byte[] key, byte[] element, LPosParams params, long count);
byte[] rpop(byte[] key);
List<byte[]> rpop(byte[] key, int count);
Long sadd(byte[] key, byte[]... member);
Set<byte[]> smembers(byte[] key);
Long srem(byte[] key, byte[]... member);
byte[] spop(byte[] key);
Set<byte[]> spop(byte[] key, long count);
Long scard(byte[] key);
Boolean sismember(byte[] key, byte[] member);
List<Boolean> smismember(byte[] key, byte[]... members);
byte[] srandmember(byte[] key);
List<byte[]> srandmember(byte[] key, int count);
Long strlen(byte[] key);
Long zadd(byte[] key, double score, byte[] member);
Long zadd(byte[] key, double score, byte[] member, ZAddParams params);
Long zadd(byte[] key, Map<byte[], Double> scoreMembers);
Long zadd(byte[] key, Map<byte[], Double> scoreMembers, ZAddParams params);
Double zaddIncr(byte[] key, double score, byte[] member, ZAddParams params);
Set<byte[]> zrange(byte[] key, long start, long stop);
Long zrem(byte[] key, byte[]... members);
Double zincrby(byte[] key, double increment, byte[] member);
Double zincrby(byte[] key, double increment, byte[] member, ZIncrByParams params);
Long zrank(byte[] key, byte[] member);
Long zrevrank(byte[] key, byte[] member);
Set<byte[]> zrevrange(byte[] key, long start, long stop);
Set<Tuple> zrangeWithScores(byte[] key, long start, long stop);
Set<Tuple> zrevrangeWithScores(byte[] key, long start, long stop);
byte[] zrandmember(byte[] key);
Set<byte[]> zrandmember(byte[] key, long count);
Set<Tuple> zrandmemberWithScores(byte[] key, long count);
Long zcard(byte[] key);
Double zscore(byte[] key, byte[] member);
List<Double> zmscore(byte[] key, byte[]... members);
Tuple zpopmax(byte[] key);
Set<Tuple> zpopmax(byte[] key, int count);
Tuple zpopmin(byte[] key);
Set<Tuple> zpopmin(byte[] key, int count);
List<byte[]> sort(byte[] key);
List<byte[]> sort(byte[] key, SortingParams sortingParameters);
Long zcount(byte[] key, double min, double max);
Long zcount(byte[] key, byte[] min, byte[] max);
Set<byte[]> zrangeByScore(byte[] key, double min, double max);
Set<byte[]> zrangeByScore(byte[] key, byte[] min, byte[] max);
Set<byte[]> zrevrangeByScore(byte[] key, double max, double min);
Set<byte[]> zrangeByScore(byte[] key, double min, double max, int offset, int count);
Set<byte[]> zrevrangeByScore(byte[] key, byte[] max, byte[] min);
Set<byte[]> zrangeByScore(byte[] key, byte[] min, byte[] max, int offset, int count);
Set<byte[]> zrevrangeByScore(byte[] key, double max, double min, int offset, int count);
Set<Tuple> zrangeByScoreWithScores(byte[] key, double min, double max);
Set<Tuple> zrevrangeByScoreWithScores(byte[] key, double max, double min);
Set<Tuple> zrangeByScoreWithScores(byte[] key, double min, double max, int offset, int count);
Set<byte[]> zrevrangeByScore(byte[] key, byte[] max, byte[] min, int offset, int count);
Set<Tuple> zrangeByScoreWithScores(byte[] key, byte[] min, byte[] max);
Set<Tuple> zrevrangeByScoreWithScores(byte[] key, byte[] max, byte[] min);
Set<Tuple> zrangeByScoreWithScores(byte[] key, byte[] min, byte[] max, int offset, int count);
Set<Tuple> zrevrangeByScoreWithScores(byte[] key, double max, double min, int offset, int count);
Set<Tuple> zrevrangeByScoreWithScores(byte[] key, byte[] max, byte[] min, int offset, int count);
Long zremrangeByRank(byte[] key, long start, long stop);
Long zremrangeByScore(byte[] key, double min, double max);
Long zremrangeByScore(byte[] key, byte[] min, byte[] max);
Long zlexcount(byte[] key, byte[] min, byte[] max);
Set<byte[]> zrangeByLex(byte[] key, byte[] min, byte[] max);
Set<byte[]> zrangeByLex(byte[] key, byte[] min, byte[] max, int offset, int count);
Set<byte[]> zrevrangeByLex(byte[] key, byte[] max, byte[] min);
Set<byte[]> zrevrangeByLex(byte[] key, byte[] max, byte[] min, int offset, int count);
Long zremrangeByLex(byte[] key, byte[] min, byte[] max);
Long linsert(byte[] key, ListPosition where, byte[] pivot, byte[] value);
Long lpushx(byte[] key, byte[]... arg);
Long rpushx(byte[] key, byte[]... arg);
Long del(byte[] key);
Long unlink(byte[] key);
byte[] echo(byte[] arg);
Long move(byte[] key, int dbIndex);
Long bitcount(byte[] key);
Long bitcount(byte[] key, long start, long end);
Long pfadd(byte[] key, byte[]... elements);
long pfcount(byte[] key);
// Geo Commands
Long geoadd(byte[] key, double longitude, double latitude, byte[] member);
Long geoadd(byte[] key, Map<byte[], GeoCoordinate> memberCoordinateMap);
Long geoadd(byte[] key, GeoAddParams params, Map<byte[], GeoCoordinate> memberCoordinateMap);
Double geodist(byte[] key, byte[] member1, byte[] member2);
Double geodist(byte[] key, byte[] member1, byte[] member2, GeoUnit unit);
List<byte[]> geohash(byte[] key, byte[]... members);
List<GeoCoordinate> geopos(byte[] key, byte[]... members);
List<GeoRadiusResponse> georadius(byte[] key, double longitude, double latitude, double radius,
GeoUnit unit);
List<GeoRadiusResponse> georadiusReadonly(byte[] key, double longitude, double latitude,
double radius, GeoUnit unit);
List<GeoRadiusResponse> georadius(byte[] key, double longitude, double latitude, double radius,
GeoUnit unit, GeoRadiusParam param);
List<GeoRadiusResponse> georadiusReadonly(byte[] key, double longitude, double latitude,
double radius, GeoUnit unit, GeoRadiusParam param);
List<GeoRadiusResponse> georadiusByMember(byte[] key, byte[] member, double radius, GeoUnit unit);
List<GeoRadiusResponse> georadiusByMemberReadonly(byte[] key, byte[] member, double radius, GeoUnit unit);
List<GeoRadiusResponse> georadiusByMember(byte[] key, byte[] member, double radius, GeoUnit unit,
GeoRadiusParam param);
List<GeoRadiusResponse> georadiusByMemberReadonly(byte[] key, byte[] member, double radius,
GeoUnit unit, GeoRadiusParam param);
ScanResult<Map.Entry<byte[], byte[]>> hscan(byte[] key, byte[] cursor);
ScanResult<Map.Entry<byte[], byte[]>> hscan(byte[] key, byte[] cursor, ScanParams params);
ScanResult<byte[]> sscan(byte[] key, byte[] cursor);
ScanResult<byte[]> sscan(byte[] key, byte[] cursor, ScanParams params);
ScanResult<Tuple> zscan(byte[] key, byte[] cursor);
ScanResult<Tuple> zscan(byte[] key, byte[] cursor, ScanParams params);
/**
* Executes BITFIELD Redis command
* @param key
* @param arguments
* @return
*/
List<Long> bitfield(byte[] key, byte[]... arguments);
List<Long> bitfieldReadonly(byte[] key, byte[]... arguments);
/**
* Used for HSTRLEN Redis command
* @param key
* @param field
* @return lenth of the value for key
*/
Long hstrlen(byte[] key, byte[] field);
byte[] xadd(byte[] key, byte[] id, Map<byte[], byte[]> hash, long maxLen, boolean approximateLength);
byte[] xadd(byte[] key, Map<byte[], byte[]> hash, XAddParams params);
Long xlen(byte[] key);
List<byte[]> xrange(byte[] key, byte[] start, byte[] end);
/**
* @deprecated Use {@link #xrange(byte[], byte[], byte[], int)}.
*/
@Deprecated
default List<byte[]> xrange(byte[] key, byte[] start, byte[] end, long count) {
return xrange(key, start, end, (int) Math.min(count, (long) Integer.MAX_VALUE));
}
List<byte[]> xrange(byte[] key, byte[] start, byte[] end, int count);
List<byte[]> xrevrange(byte[] key, byte[] end, byte[] start);
List<byte[]> xrevrange(byte[] key, byte[] end, byte[] start, int count);
Long xack(byte[] key, byte[] group, byte[]... ids);
String xgroupCreate(byte[] key, byte[] consumer, byte[] id, boolean makeStream);
String xgroupSetID(byte[] key, byte[] consumer, byte[] id);
Long xgroupDestroy(byte[] key, byte[] consumer);
Long xgroupDelConsumer(byte[] key, byte[] consumer, byte[] consumerName);
Long xdel(byte[] key, byte[]... ids);
Long xtrim(byte[] key, long maxLen, boolean approximateLength);
Long xtrim(byte[] key, XTrimParams params);
Object xpending(byte[] key, byte[] groupname);
List<Object> xpending(byte[] key, byte[] groupname, byte[] start, byte[] end, int count, byte[] consumername);
List<Object> xpending(byte[] key, byte[] groupname, XPendingParams params);
List<byte[]> xclaim(byte[] key, byte[] groupname, byte[] consumername, long minIdleTime, long newIdleTime, int retries, boolean force, byte[]... ids);
List<byte[]> xclaim(byte[] key, byte[] group, byte[] consumername, long minIdleTime, XClaimParams params, byte[]... ids);
List<byte[]> xclaimJustId(byte[] key, byte[] group, byte[] consumername, long minIdleTime, XClaimParams params, byte[]... ids);
List<Object> xautoclaim(byte[] key, byte[] groupName, byte[] consumerName,
long minIdleTime, byte[] start, XAutoClaimParams params);
List<Object> xautoclaimJustId(byte[] key, byte[] groupName, byte[] consumerName,
long minIdleTime, byte[] start, XAutoClaimParams params);
/**
* @deprecated Use {@link #xinfoStreamBinary(byte[])}.
*/
@Deprecated
StreamInfo xinfoStream(byte[] key);
Object xinfoStreamBinary(byte[] key);
/**
* @deprecated Use {@link #xinfoGroupBinary(byte[])}.
*/
@Deprecated
List<StreamGroupInfo> xinfoGroup(byte[] key);
List<Object> xinfoGroupBinary(byte[] key);
/**
* @deprecated Use {@link #xinfoConsumersBinary(byte[], byte[])}.
*/
@Deprecated
List<StreamConsumersInfo> xinfoConsumers(byte[] key, byte[] group);
List<Object> xinfoConsumersBinary(byte[] key, byte[] group);
}
|
/*
* Copyright 2017 Flynn van Os
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.oxapps.tradenotifications.apikey;
import com.oxapps.tradenotifications.steamapi.ApiKeyAccess;
import com.oxapps.tradenotifications.model.ApplicationSettings;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
/**
* Presenter for the API key retrieval
*/
public class ApiKeyPresenter implements ApiKeyWebViewClient.PageFinishedCallback {
private final ApiKeyActivityView mView;
private ApplicationSettings settings;
public ApiKeyPresenter(ApiKeyActivityView view, ApplicationSettings settings) {
this.mView = view;
this.settings = settings;
}
/**
* Initialises views with values from their settings
*/
public void initialize() {
mView.initViews();
mView.setWebViewClient(new ApiKeyWebViewClient(this));
mView.showUrl(UrlConsts.LOGIN_URL);
}
/**
* Extracts information from the initial HTTP home URL loaded
* <p>
* Since the application needs the steamLoginSecure cookie, it reloads the page as HTTPS
*
* @param url the URL loaded
*/
@Override
public void onHttpUrlLoaded(String url) {
boolean isProfile = url.matches("http://steamcommunity.com/profiles/(\\w)+/home");
Pattern keyPattern = Pattern.compile("/(\\w+)/home");
Matcher matcher = keyPattern.matcher(url);
if (matcher.find()) {
String username = matcher.group(1);
settings.setUsername(username);
settings.setProfileUrl(isProfile);
}
mView.hideWebShowProgress();
mView.showUrl(url.replace("http://", "https://"));
}
/**
* Extracts information from the HTTPS home URL loaded
*
* @param cookies the cookies from the result
*/
@Override
public void onHttpsUrlLoaded(String cookies) {
String[] cookiesSplit = cookies.split("; ");
for (String cookie : cookiesSplit) {
if (cookie.contains("sessionid")) {
String sessionId = cookie.split("=")[1];
ApiKeyAccess access = new ApiKeyAccess(new ApiKeyCallback());
access.getApiKey(sessionId, cookies);
return;
}
}
mView.cancelAndFinish();
}
/**
* Callback for the result of the API Key request
*/
public class ApiKeyCallback implements Callback {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.code() != 200) {
mView.cancelAndFinish();
}
String bodyString = response.body().string();
Pattern keyPattern = Pattern.compile("<p>Key: ([0-9A-F]+)</p>");
Matcher matcher = keyPattern.matcher(bodyString);
if (matcher.find()) {
String apiKey = matcher.group(1);
mView.successfullyFinish(apiKey);
} else {
mView.cancelAndFinish();
}
}
}
}
|
/*
* Copyright (c) 2008-2019, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.internal.util.collection;
import com.hazelcast.internal.memory.MemoryAccessor;
import com.hazelcast.internal.memory.MemoryManager;
import com.hazelcast.internal.util.hashslot.HashSlotArray8byteKey;
import com.hazelcast.internal.util.hashslot.HashSlotCursor8byteKey;
import com.hazelcast.internal.util.hashslot.SlotAssignmentResult;
import com.hazelcast.internal.util.hashslot.impl.HashSlotArray8byteKeyImpl;
import static com.hazelcast.internal.memory.MemoryAllocator.NULL_ADDRESS;
import static com.hazelcast.internal.nio.Bits.LONG_SIZE_IN_BYTES;
/**
* a {@link Long2LongMap} implemented in terms of a {@link HashSlotArray8byteKey}.
*/
public class Long2LongMapHsa implements Long2LongMap {
private final HashSlotArray8byteKey hsa;
private final long nullValue;
private MemoryAccessor mem;
/**
* @param nullValue the value that represents "null" or missing value
* @param memMgr memory manager to use. It is safe for its {@link MemoryManager#getAccessor} method
* to return an accessor that only supports aligned memory access.
*/
public Long2LongMapHsa(long nullValue, MemoryManager memMgr) {
this.hsa = new HashSlotArray8byteKeyImpl(nullValue, memMgr, LONG_SIZE_IN_BYTES);
hsa.gotoNew();
this.mem = memMgr.getAccessor();
this.nullValue = nullValue;
}
@Override public long get(long key) {
final long valueAddr = hsa.get(key);
return valueAddr != NULL_ADDRESS ? mem.getLong(valueAddr) : nullValue;
}
@Override public long put(long key, long value) {
assert value != nullValue : "put() called with null-sentinel value " + nullValue;
SlotAssignmentResult slot = hsa.ensure(key);
long result;
if (!slot.isNew()) {
result = mem.getLong(slot.address());
} else {
result = nullValue;
}
mem.putLong(slot.address(), value);
return result;
}
@Override public long putIfAbsent(long key, long value) {
assert value != nullValue : "putIfAbsent() called with null-sentinel value " + nullValue;
SlotAssignmentResult slot = hsa.ensure(key);
if (slot.isNew()) {
mem.putLong(slot.address(), value);
return nullValue;
} else {
return mem.getLong(slot.address());
}
}
@Override public void putAll(Long2LongMap from) {
for (LongLongCursor cursor = from.cursor(); cursor.advance();) {
put(cursor.key(), cursor.value());
}
}
@Override public boolean replace(long key, long oldValue, long newValue) {
assert oldValue != nullValue : "replace() called with null-sentinel oldValue " + nullValue;
assert newValue != nullValue : "replace() called with null-sentinel newValue " + nullValue;
final long valueAddr = hsa.get(key);
if (valueAddr == NULL_ADDRESS) {
return false;
}
final long actualValue = mem.getLong(valueAddr);
if (actualValue != oldValue) {
return false;
}
mem.putLong(valueAddr, newValue);
return true;
}
@Override public long replace(long key, long value) {
assert value != nullValue : "replace() called with null-sentinel value " + nullValue;
final long valueAddr = hsa.get(key);
if (valueAddr == NULL_ADDRESS) {
return nullValue;
}
final long oldValue = mem.getLong(valueAddr);
mem.putLong(valueAddr, value);
return oldValue;
}
@Override public long remove(long key) {
final long valueAddr = hsa.get(key);
if (valueAddr == NULL_ADDRESS) {
return nullValue;
}
final long oldValue = mem.getLong(valueAddr);
hsa.remove(key);
return oldValue;
}
@Override public boolean remove(long key, long value) {
assert value != nullValue : "remove() called with null-sentinel value " + nullValue;
final long valueAddr = hsa.get(key);
if (valueAddr == NULL_ADDRESS) {
return false;
}
final long actualValue = mem.getLong(valueAddr);
if (actualValue == value) {
hsa.remove(key);
return true;
}
return false;
}
@Override public boolean containsKey(long key) {
return hsa.get(key) != NULL_ADDRESS;
}
@Override public long size() {
return hsa.size();
}
@Override public boolean isEmpty() {
return hsa.size() == 0;
}
@Override public void clear() {
hsa.clear();
}
@Override public void dispose() {
hsa.dispose();
}
@Override public LongLongCursor cursor() {
return new Cursor(hsa);
}
private final class Cursor implements LongLongCursor {
private final HashSlotCursor8byteKey cursor;
Cursor(HashSlotArray8byteKey hsa) {
this.cursor = hsa.cursor();
}
@Override public boolean advance() {
return cursor.advance();
}
@Override public long key() {
return cursor.key();
}
@Override public long value() {
return mem.getLong(cursor.valueAddress());
}
}
}
|
package android.support.v7.widget;
import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.PorterDuff.Mode;
import android.graphics.drawable.Drawable;
import android.support.v4.view.TintableBackgroundView;
import android.support.v7.appcompat.R;
import android.util.AttributeSet;
import android.widget.EditText;
public class AppCompatEditText extends EditText implements TintableBackgroundView {
private AppCompatBackgroundHelper mBackgroundTintHelper;
private AppCompatTextHelper mTextHelper;
public AppCompatEditText(Context context) {
this(context, null);
}
public AppCompatEditText(Context context, AttributeSet attributeSet) {
this(context, attributeSet, R.attr.editTextStyle);
}
public AppCompatEditText(Context context, AttributeSet attributeSet, int i) {
super(TintContextWrapper.wrap(context), attributeSet, i);
this.mBackgroundTintHelper = new AppCompatBackgroundHelper(this);
this.mBackgroundTintHelper.loadFromAttributes(attributeSet, i);
this.mTextHelper = AppCompatTextHelper.create(this);
this.mTextHelper.loadFromAttributes(attributeSet, i);
this.mTextHelper.applyCompoundDrawablesTints();
}
public void setBackgroundResource(int i) {
super.setBackgroundResource(i);
if (this.mBackgroundTintHelper != null) {
this.mBackgroundTintHelper.onSetBackgroundResource(i);
}
}
public void setBackgroundDrawable(Drawable drawable) {
super.setBackgroundDrawable(drawable);
if (this.mBackgroundTintHelper != null) {
this.mBackgroundTintHelper.onSetBackgroundDrawable(drawable);
}
}
public void setSupportBackgroundTintList(ColorStateList colorStateList) {
if (this.mBackgroundTintHelper != null) {
this.mBackgroundTintHelper.setSupportBackgroundTintList(colorStateList);
}
}
public ColorStateList getSupportBackgroundTintList() {
return this.mBackgroundTintHelper != null ? this.mBackgroundTintHelper.getSupportBackgroundTintList() : null;
}
public void setSupportBackgroundTintMode(Mode mode) {
if (this.mBackgroundTintHelper != null) {
this.mBackgroundTintHelper.setSupportBackgroundTintMode(mode);
}
}
public Mode getSupportBackgroundTintMode() {
return this.mBackgroundTintHelper != null ? this.mBackgroundTintHelper.getSupportBackgroundTintMode() : null;
}
protected void drawableStateChanged() {
super.drawableStateChanged();
if (this.mBackgroundTintHelper != null) {
this.mBackgroundTintHelper.applySupportBackgroundTint();
}
if (this.mTextHelper != null) {
this.mTextHelper.applyCompoundDrawablesTints();
}
}
public void setTextAppearance(Context context, int i) {
super.setTextAppearance(context, i);
if (this.mTextHelper != null) {
this.mTextHelper.onSetTextAppearance(context, i);
}
}
}
|
/*
* Copyright 2011-2021 GatlingCorp (https://gatling.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.gatling.http.client.body;
import io.gatling.http.client.Param;
import io.gatling.http.client.body.form.FormUrlEncodedRequestBody;
import io.gatling.netty.util.ByteBufUtils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import org.junit.jupiter.api.Test;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import static io.netty.handler.codec.http.HttpHeaderValues.TEXT_PLAIN;
import static java.nio.charset.StandardCharsets.US_ASCII;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.jupiter.api.Assertions.assertEquals;
class FormUrlEncodedRequestBodyTest {
private void formUrlEncoding(Charset charset) throws Exception {
String key = "key";
String value = "中文";
List<Param> params = new ArrayList<>();
params.add(new Param(key, value));
ByteBuf bb = (ByteBuf) new FormUrlEncodedRequestBody(params, TEXT_PLAIN.toString(), charset).build(ByteBufAllocator.DEFAULT).getContent();
try {
String ahcString = ByteBufUtils.byteBuf2String(US_ASCII, bb);
String jdkString = key + "=" + URLEncoder.encode(value, charset.name());
assertEquals(ahcString, jdkString);
} finally {
bb.release();
}
}
@Test
public void formUrlEncodingShouldSupportUtf8Charset() throws Exception {
formUrlEncoding(UTF_8);
}
@Test
public void formUrlEncodingShouldSupportNonUtf8Charset() throws Exception {
formUrlEncoding(Charset.forName("GBK"));
}
}
|
package com.github.joomcode.mongoplanchecker.sync;
import com.github.joomcode.mongoplanchecker.core.PlanChecker;
import com.mongodb.ReadConcern;
import com.mongodb.ReadPreference;
import com.mongodb.WriteConcern;
import com.mongodb.client.*;
import com.mongodb.client.model.CreateCollectionOptions;
import com.mongodb.client.model.CreateViewOptions;
import java.util.List;
import org.bson.Document;
import org.bson.codecs.configuration.CodecRegistry;
import org.bson.conversions.Bson;
public class PlanCheckerMongoDatabase implements MongoDatabase {
private final MongoDatabase database;
private final PlanChecker checker;
public PlanCheckerMongoDatabase(MongoDatabase database, PlanChecker checker) {
this.database = database;
this.checker = checker;
}
@Override
public String getName() {
return database.getName();
}
@Override
public CodecRegistry getCodecRegistry() {
return database.getCodecRegistry();
}
@Override
public ReadPreference getReadPreference() {
return database.getReadPreference();
}
@Override
public WriteConcern getWriteConcern() {
return database.getWriteConcern();
}
@Override
public ReadConcern getReadConcern() {
return database.getReadConcern();
}
@Override
public PlanCheckerMongoDatabase withCodecRegistry(CodecRegistry codecRegistry) {
return new PlanCheckerMongoDatabase(database.withCodecRegistry(codecRegistry), checker);
}
@Override
public PlanCheckerMongoDatabase withReadPreference(ReadPreference readPreference) {
return new PlanCheckerMongoDatabase(database.withReadPreference(readPreference), checker);
}
@Override
public PlanCheckerMongoDatabase withWriteConcern(WriteConcern writeConcern) {
return new PlanCheckerMongoDatabase(database.withWriteConcern(writeConcern), checker);
}
@Override
public PlanCheckerMongoDatabase withReadConcern(ReadConcern readConcern) {
return new PlanCheckerMongoDatabase(database.withReadConcern(readConcern), checker);
}
@Override
public PlanCheckerMongoCollection<Document> getCollection(String collectionName) {
return new PlanCheckerMongoCollection<>(database.getCollection(collectionName), checker);
}
@Override
public <TDocument> PlanCheckerMongoCollection<TDocument> getCollection(
String collectionName, Class<TDocument> tDocumentClass) {
return new PlanCheckerMongoCollection<>(
database.getCollection(collectionName, tDocumentClass), checker);
}
@Override
public Document runCommand(Bson command) {
return database.runCommand(command);
}
@Override
public Document runCommand(Bson command, ReadPreference readPreference) {
return database.runCommand(command, readPreference);
}
@Override
public <TResult> TResult runCommand(Bson command, Class<TResult> tResultClass) {
return database.runCommand(command, tResultClass);
}
@Override
public <TResult> TResult runCommand(
Bson command, ReadPreference readPreference, Class<TResult> tResultClass) {
return database.runCommand(command, readPreference, tResultClass);
}
@Override
public Document runCommand(ClientSession clientSession, Bson command) {
return database.runCommand(clientSession, command);
}
@Override
public Document runCommand(
ClientSession clientSession, Bson command, ReadPreference readPreference) {
return database.runCommand(clientSession, command, readPreference);
}
@Override
public <TResult> TResult runCommand(
ClientSession clientSession, Bson command, Class<TResult> tResultClass) {
return database.runCommand(clientSession, command, tResultClass);
}
@Override
public <TResult> TResult runCommand(
ClientSession clientSession,
Bson command,
ReadPreference readPreference,
Class<TResult> tResultClass) {
return database.runCommand(clientSession, command, readPreference, tResultClass);
}
@Override
public void drop() {
database.drop();
}
@Override
public void drop(ClientSession clientSession) {
database.drop(clientSession);
}
@Override
public MongoIterable<String> listCollectionNames() {
return database.listCollectionNames();
}
@Override
public ListCollectionsIterable<Document> listCollections() {
return database.listCollections();
}
@Override
public <TResult> ListCollectionsIterable<TResult> listCollections(Class<TResult> tResultClass) {
return database.listCollections(tResultClass);
}
@Override
public MongoIterable<String> listCollectionNames(ClientSession clientSession) {
return database.listCollectionNames(clientSession);
}
@Override
public ListCollectionsIterable<Document> listCollections(ClientSession clientSession) {
return database.listCollections(clientSession);
}
@Override
public <TResult> ListCollectionsIterable<TResult> listCollections(
ClientSession clientSession, Class<TResult> tResultClass) {
return database.listCollections(clientSession, tResultClass);
}
@Override
public void createCollection(String collectionName) {
database.createCollection(collectionName);
}
@Override
public void createCollection(
String collectionName, CreateCollectionOptions createCollectionOptions) {
database.createCollection(collectionName, createCollectionOptions);
}
@Override
public void createCollection(ClientSession clientSession, String collectionName) {
database.createCollection(clientSession, collectionName);
}
@Override
public void createCollection(
ClientSession clientSession,
String collectionName,
CreateCollectionOptions createCollectionOptions) {
database.createCollection(clientSession, collectionName, createCollectionOptions);
}
@Override
public void createView(String viewName, String viewOn, List<? extends Bson> pipeline) {
database.createView(viewName, viewOn, pipeline);
}
@Override
public void createView(
String viewName,
String viewOn,
List<? extends Bson> pipeline,
CreateViewOptions createViewOptions) {
database.createView(viewName, viewOn, pipeline, createViewOptions);
}
@Override
public void createView(
ClientSession clientSession, String viewName, String viewOn, List<? extends Bson> pipeline) {
database.createView(clientSession, viewName, viewOn, pipeline);
}
@Override
public void createView(
ClientSession clientSession,
String viewName,
String viewOn,
List<? extends Bson> pipeline,
CreateViewOptions createViewOptions) {
database.createView(clientSession, viewName, viewOn, pipeline, createViewOptions);
}
@Override
public ChangeStreamIterable<Document> watch() {
return database.watch();
}
@Override
public <TResult> ChangeStreamIterable<TResult> watch(Class<TResult> tResultClass) {
return database.watch(tResultClass);
}
@Override
public ChangeStreamIterable<Document> watch(List<? extends Bson> pipeline) {
return database.watch(pipeline);
}
@Override
public <TResult> ChangeStreamIterable<TResult> watch(
List<? extends Bson> pipeline, Class<TResult> tResultClass) {
return database.watch(pipeline, tResultClass);
}
@Override
public ChangeStreamIterable<Document> watch(ClientSession clientSession) {
return database.watch(clientSession);
}
@Override
public <TResult> ChangeStreamIterable<TResult> watch(
ClientSession clientSession, Class<TResult> tResultClass) {
return database.watch(clientSession, tResultClass);
}
@Override
public ChangeStreamIterable<Document> watch(
ClientSession clientSession, List<? extends Bson> pipeline) {
return database.watch(clientSession, pipeline);
}
@Override
public <TResult> ChangeStreamIterable<TResult> watch(
ClientSession clientSession, List<? extends Bson> pipeline, Class<TResult> tResultClass) {
return database.watch(clientSession, pipeline, tResultClass);
}
@Override
public AggregateIterable<Document> aggregate(List<? extends Bson> pipeline) {
return database.aggregate(pipeline);
}
@Override
public <TResult> AggregateIterable<TResult> aggregate(
List<? extends Bson> pipeline, Class<TResult> tResultClass) {
return database.aggregate(pipeline, tResultClass);
}
@Override
public AggregateIterable<Document> aggregate(
ClientSession clientSession, List<? extends Bson> pipeline) {
return database.aggregate(clientSession, pipeline);
}
@Override
public <TResult> AggregateIterable<TResult> aggregate(
ClientSession clientSession, List<? extends Bson> pipeline, Class<TResult> tResultClass) {
return database.aggregate(clientSession, pipeline, tResultClass);
}
}
|
package com.deer.wms.device.manage.model;
public class DeviceCheckMasterDto extends DeviceCheckMaster {
private String dutyUserName;
private String recordUserName;
public String getDutyUserName() {
return dutyUserName;
}
public void setDutyUserName(String dutyUserName) {
this.dutyUserName = dutyUserName;
}
public String getRecordUserName() {
return recordUserName;
}
public void setRecordUserName(String recordUserName) {
this.recordUserName = recordUserName;
}
}
|
package com.tome.main.security.validation;
import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;
@Target({ TYPE, FIELD, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = EmailValidator.class)
@Documented
public @interface ValidEmail {
String message() default "Invalid Email";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
|
/*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.restassured.config;
import io.restassured.filter.log.LogDetail;
import io.restassured.filter.log.RequestLoggingFilter;
import io.restassured.filter.log.ResponseLoggingFilter;
import io.restassured.specification.LogSpecification;
import org.apache.commons.lang3.Validate;
import java.io.PrintStream;
/**
* Configure the logging for REST Assured. <p>Note that <i>only</i>
* log things known to REST Assured (i.e. the request- and response specifications) will be logged. If you need to log what's <i>actually</i> sent on the wire
* refer to the <a href="http://hc.apache.org/httpcomponents-client-ga/logging.html">HTTP Client logging docs</a> or use an external tool such as
* <a href="http://www.wireshark.org/">Wireshark</a>.</p>
*/
public class LogConfig implements Config {
private final PrintStream defaultPrintStream;
private final boolean prettyPrintingEnabled;
private final LogDetail logDetailIfValidationFails;
private final boolean urlEncodeRequestUri;
private final boolean isUserDefined;
/**
* Configure the default stream to use the System.out stream (default).
*/
public LogConfig() {
this(System.out, true, null, true, false);
}
/**
* Configure pretty printing and the default stream where logs should be written if <i>not</i> specified explicitly by a filter. I.e. this stream will be used in cases
* where the log specification DSL is used, e.g.
* <pre>
* given().log().all()...
* </pre>
* or
* <pre>
* expect().log.ifError(). ..
* </pre>
* <p/>
* It will not override explicit streams defined by using the {@link RequestLoggingFilter} or the {@link ResponseLoggingFilter}.
*
* @param defaultPrintStream The default print stream to use for the {@link LogSpecification}'s.
* @param prettyPrintingEnabled Enable or disable pretty printing when logging. Pretty printing is only possible when content-type is XML, JSON or HTML.
*/
public LogConfig(PrintStream defaultPrintStream, boolean prettyPrintingEnabled) {
this(defaultPrintStream, prettyPrintingEnabled, null, true, true);
}
/**
* Configure pretty printing and the default stream where logs should be written if <i>not</i> specified explicitly by a filter. I.e. this stream will be used in cases
* where the log specification DSL is used, e.g.
* <pre>
* given().log().all()...
* </pre>
* or
* <pre>
* expect().log.ifError(). ..
* </pre>
* <p/>
* It will not override explicit streams defined by using the {@link RequestLoggingFilter} or the {@link ResponseLoggingFilter}.
*
* @param defaultPrintStream The default print stream to use for the {@link LogSpecification}'s.
* @param prettyPrintingEnabled Enable or disable pretty printing when logging. Pretty printing is only possible when content-type is XML, JSON or HTML.
*/
private LogConfig(PrintStream defaultPrintStream, boolean prettyPrintingEnabled, LogDetail logDetailIfValidationFails,
boolean urlEncodeRequestUri, boolean isUserDefined) {
Validate.notNull(defaultPrintStream, "Stream to write logs to cannot be null");
this.defaultPrintStream = defaultPrintStream;
this.prettyPrintingEnabled = prettyPrintingEnabled;
this.logDetailIfValidationFails = logDetailIfValidationFails;
this.isUserDefined = isUserDefined;
this.urlEncodeRequestUri = urlEncodeRequestUri;
}
/**
* @return The default stream to use
*/
public PrintStream defaultStream() {
return defaultPrintStream;
}
/**
* Specify a new default stream to the print to.
*
* @param printStream The stream
* @return A new LogConfig instance
*/
public LogConfig defaultStream(PrintStream printStream) {
return new LogConfig(printStream, true, logDetailIfValidationFails, urlEncodeRequestUri, true);
}
/**
* @return <code>true</code> if pretty printing is enabled, <code>false</code> otherwise.
*/
public boolean isPrettyPrintingEnabled() {
return prettyPrintingEnabled;
}
/**
* @return <code>true</code> if request and response logging is enabled if test validation fails, <code>false</code> otherwise.
*/
public boolean isLoggingOfRequestAndResponseIfValidationFailsEnabled() {
return logDetailIfValidationFails != null;
}
/**
* @return The log detail to use if request and response logging is enabled if test validation fails.
*/
public LogDetail logDetailOfRequestAndResponseIfValidationFails() {
return logDetailIfValidationFails;
}
/**
* Specify a whether or not to enable pretty printing by default.
*
* @param shouldEnable <code>true</code> if pretty-printing should be enabled, <code>false</code> otherwise.
* @return A new LogConfig instance
*/
public LogConfig enablePrettyPrinting(boolean shouldEnable) {
return new LogConfig(defaultPrintStream, shouldEnable, logDetailIfValidationFails, urlEncodeRequestUri, true);
}
/**
* Enable logging of both the request and the response if REST Assureds test validation fails.
*
* @return A new LogConfig instance
*/
public LogConfig enableLoggingOfRequestAndResponseIfValidationFails() {
return enableLoggingOfRequestAndResponseIfValidationFails(LogDetail.ALL);
}
/**
* Enable logging of both the request and the response if REST Assureds test validation fails with the specified log detail
*
* @param logDetail The log detail to show in the log
* @return A new LogConfig instance
*/
public LogConfig enableLoggingOfRequestAndResponseIfValidationFails(LogDetail logDetail) {
return new LogConfig(defaultPrintStream, prettyPrintingEnabled, logDetail, urlEncodeRequestUri, true);
}
/**
* Instruct REST Assured whether or not to URL encode the request URI when it's presented in the request specification log.
* By default url encoding of the request uri is enabled to show what the URL targeted by REST Assured actually looks like for real.
* But there may be cases where you want to make the URI more readable and this is when you might want to consider setting
* <code>urlEncodeRequestUri</code> to <code>false</code>. Note that this only affects logging.
*
* @param urlEncodeRequestUri Whether or not to url encode the request uri when it's presented in the request log
* @return A new LogConfig instance
*/
public LogConfig urlEncodeRequestUri(boolean urlEncodeRequestUri) {
return new LogConfig(defaultPrintStream, prettyPrintingEnabled, logDetailIfValidationFails, urlEncodeRequestUri, true);
}
/**
* @return <code>true</code> is the request URI should be URL encoded in the request log
*/
public boolean shouldUrlEncodeRequestUri() {
return urlEncodeRequestUri;
}
/**
* @return A static way to create a new LogConfig instance without calling "new" explicitly. Mainly for syntactic sugar.
*/
public static LogConfig logConfig() {
return new LogConfig();
}
/**
* Syntactic sugar.
*
* @return The same log config instance.
*/
public LogConfig and() {
return this;
}
public boolean isUserConfigured() {
return isUserDefined;
}
}
|
package controller;
import java.util.ArrayList;
import java.util.List;
import model.*;
import model.enums.Value;
/**
* A controller to manage the {@link model.Cell} class
*
* @author WrexBG
*/
public class CellController {
/**
* A method to toggle the flagged attribute of a cell
* @param cell the cell object to toggle
*/
public void toggleFlaggedCell(Cell cell) {
cell.setFlagged(!cell.isFlagged());
}
/**
* A method to set a cell to revealed
* @param cell the cell object to be revealed
*/
public void revealCell(Cell cell) {
if(!cell.isRevealed()) {
cell.setRevealed(true);
}
}
/**
* A method to increase the {@link model.enums.Value} of an array cells
* @param cells the array of cells to be modified
*/
public void increaseCellValue(Cell[] cells) {
for(Cell cell : cells) {
Value cellValue = cell.getValue();
if (!cellValue.isMaxValue() && !cellValue.isABomb()) {
cell.setValue(Value.fromInt(cellValue.getValue() + 1));
}
}
}
/** TODO rewrite
* A method to find all neighboring cells based on given x, y, and a grid
* @param cell the origin cell
* @param grid the grid of the game
* @return foundCells
*/
public List<Cell> getAllNearbyCells(Cell cell, GameGrid grid) {
List<Cell> foundCells = new ArrayList<>();
List<Cell> initial = new ArrayList<>(List.of(cell));
int x = cell.getX();
int y = cell.getY();
// Get cell left
if(x != 0) {
foundCells.add(grid.getCellAt(x - 1, y));
}
// Get cell right
if(x != grid.getGridX()-1) {
foundCells.add(grid.getCellAt(x + 1, y));
}
initial.addAll(foundCells);
for(Cell initialCell : initial) {
// Get left above
if(y != 0) {
foundCells.add(grid.getCellAt(initialCell.getX(), initialCell.getY() - 1));
}
// Get left below
if(y != grid.getGridY()-1) {
foundCells.add(grid.getCellAt(initialCell.getX(), initialCell.getY() + 1));
}
}
return foundCells;
}
}
|
package com.prussia.play.spring4spark.service;
import static org.apache.spark.sql.functions.col;
import static org.apache.spark.sql.functions.max;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.SparkSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.prussia.play.spring4spark.entity.Person;
import lombok.extern.log4j.Log4j;
@Component
@Log4j
public class SparkAppService {
@Autowired
private SparkSession sparkSession;
public int getMaxScore() {
log.info("Processing started...");
Dataset<Row> scoresDf = sparkSession.read().table("scores");
int result = scoresDf.agg(max("score")).collectAsList().get(0).getInt(0);
log.info("Result is: " + result);
log.info("Processing completed...");
return result;
}
public void printDataFrames() {
Dataset<Row> df = sparkSession.read().json("./src/main/resources/people.json");
df.show();
df.printSchema();
df.select("name").show();
df.select(col("name"), col("age").plus(1)).show();
df.filter(col("age").gt(21)).show();
df.groupBy("age").count().show();
}
public void printDFbySQL() {
// sparkSession.read().jdbc(url, table, properties)
Dataset<Row> df = sparkSession.read().json("./src/main/resources/people.json");
df.createOrReplaceTempView("people");
Dataset<Row> sqlDF = sparkSession.sql("SELECT * FROM people");
sqlDF.show();
}
public void printDFRDD() {
JavaRDD<Person> peopleRDD = sparkSession.read()
.textFile("./src/main/resources/people.txt")
.javaRDD()
.map(line -> {
String[] parts = line.split(",");
Person person = new Person();
person.setName(parts[0]);
person.setAge(Integer.parseInt(parts[1].trim()));
return person;
});
// Apply a schema to an RDD of JavaBeans to get a DataFrame
Dataset<Row> peopleDF = sparkSession.createDataFrame(peopleRDD, Person.class);
// Register the DataFrame as a temporary view
peopleDF.createOrReplaceTempView("people");
}
}
|
package com.example.lbstest;
import cn.bmob.v3.BmobObject;
/**
* Created by yf on 2017/4/7.
*/
public class Loc extends BmobObject{
public String latitude;
public String longgitude;
public String update;
public String addStreet;
public String locType;
public void setLocType(String locType) {
this.locType = locType;
}
public String getLocType() {
return locType;
}
public void setUpdate(String update) {
this.update = update;
}
public void setAddStreet(String addStreet) {
this.addStreet = addStreet;
}
public String getAddStreet() {
return addStreet;
}
public String getUpdate() {
return update;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public void setLongitude(String longgitude) {
this.longgitude = longgitude;
}
public String getLatitude() {
return latitude;
}
public String getLonggitude() {
return longgitude;
}
}
|
/*
* Copyright (c) 2016-2019 Michael Zhang <yidongnan@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package net.devh.boot.grpc.test.setup;
import static io.grpc.Status.Code.UNIMPLEMENTED;
import static net.devh.boot.grpc.test.util.GrpcAssertions.assertFutureThrowsStatus;
import static net.devh.boot.grpc.test.util.GrpcAssertions.assertThrowsStatus;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import javax.annotation.PostConstruct;
import org.junit.jupiter.api.Test;
import org.springframework.test.annotation.DirtiesContext;
import com.google.protobuf.Empty;
import io.grpc.Channel;
import io.grpc.internal.testing.StreamRecorder;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.client.inject.GrpcClient;
import net.devh.boot.grpc.test.proto.SomeType;
import net.devh.boot.grpc.test.proto.TestServiceGrpc;
import net.devh.boot.grpc.test.proto.TestServiceGrpc.TestServiceBlockingStub;
import net.devh.boot.grpc.test.proto.TestServiceGrpc.TestServiceFutureStub;
import net.devh.boot.grpc.test.proto.TestServiceGrpc.TestServiceStub;
/**
* A test checking that the server and client can start and connect to each other with minimal config.
*
* @author Daniel Theuke (daniel.theuke@heuboe.de)
*/
@Slf4j
public abstract class AbstractSimpleServerClientTest {
@GrpcClient("test")
protected Channel channel;
@GrpcClient("test")
protected TestServiceStub testServiceStub;
@GrpcClient("test")
protected TestServiceBlockingStub testServiceBlockingStub;
@GrpcClient("test")
protected TestServiceFutureStub testServiceFutureStub;
@PostConstruct
public void init() {
// Test injection
assertNotNull(this.channel, "channel");
assertNotNull(this.testServiceBlockingStub, "testServiceBlockingStub");
assertNotNull(this.testServiceFutureStub, "testServiceFutureStub");
assertNotNull(this.testServiceStub, "testServiceStub");
}
/**
* Test successful call.
*
* @throws ExecutionException Should never happen.
* @throws InterruptedException Should never happen.
*/
@Test
@DirtiesContext
public void testSuccessfulCall() throws InterruptedException, ExecutionException {
log.info("--- Starting tests with successful call ---");
assertEquals("1.2.3",
TestServiceGrpc.newBlockingStub(this.channel).normal(Empty.getDefaultInstance()).getVersion());
final StreamRecorder<SomeType> streamRecorder = StreamRecorder.create();
this.testServiceStub.normal(Empty.getDefaultInstance(), streamRecorder);
assertEquals("1.2.3", streamRecorder.firstValue().get().getVersion());
assertEquals("1.2.3", this.testServiceBlockingStub.normal(Empty.getDefaultInstance()).getVersion());
assertEquals("1.2.3", this.testServiceFutureStub.normal(Empty.getDefaultInstance()).get().getVersion());
log.info("--- Test completed ---");
}
/**
* Test failing call.
*/
@Test
@DirtiesContext
public void testFailingCall() {
log.info("--- Starting tests with failing call ---");
assertThrowsStatus(UNIMPLEMENTED,
() -> TestServiceGrpc.newBlockingStub(this.channel).unimplemented(Empty.getDefaultInstance()));
final StreamRecorder<SomeType> streamRecorder = StreamRecorder.create();
this.testServiceStub.unimplemented(Empty.getDefaultInstance(), streamRecorder);
assertFutureThrowsStatus(UNIMPLEMENTED, streamRecorder.firstValue(), 5, TimeUnit.SECONDS);
assertThrowsStatus(UNIMPLEMENTED, () -> this.testServiceBlockingStub.unimplemented(Empty.getDefaultInstance()));
assertFutureThrowsStatus(UNIMPLEMENTED, this.testServiceFutureStub.unimplemented(Empty.getDefaultInstance()),
5, TimeUnit.SECONDS);
log.info("--- Test completed ---");
}
}
|
package org.jzl.io.impl;
import org.jzl.io.IBuffer;
import org.jzl.io.ISegments;
import org.jzl.io.ISink;
import org.jzl.lang.util.ObjectUtils;
import java.io.IOException;
import java.io.OutputStream;
public class OutputStreamSink implements ISink {
private final OutputStream outputStream;
public OutputStreamSink(OutputStream outputStream) {
this.outputStream = outputStream;
}
@Override
public ISink write(IBuffer buffer, int byteCount) throws IOException {
int length = Math.min(byteCount, buffer.size());
ISegments segments = buffer.segments();
while (length > 0) {
Segment segment = segments.commonReadableSegment();
if (ObjectUtils.isNull(segment) || segment.length() == 0) {
break;
}
int readLength = segment.read(outputStream, length);
if (readLength == -1) {
break;
}
length -= readLength;
segments.setSize(buffer.size() - readLength);
segments.require(segment);
}
return this;
}
@Override
public void close() throws IOException {
outputStream.close();
}
@Override
public void flush() throws IOException {
outputStream.flush();
}
}
|
package com.semantalytics.stardog.kibble.string;
import com.complexible.stardog.plan.filter.ExpressionVisitor;
import com.complexible.stardog.plan.filter.expr.ValueOrError;
import com.complexible.stardog.plan.filter.functions.AbstractFunction;
import com.complexible.stardog.plan.filter.functions.string.StringFunction;
import com.stardog.stark.Literal;
import com.stardog.stark.Value;
import static com.stardog.stark.Values.literal;
import static org.apache.commons.lang3.StringUtils.*;
public final class StripEnd extends AbstractFunction implements StringFunction {
protected StripEnd() {
super(2, StringVocabulary.stripEnd.toString());
}
private StripEnd(final StripEnd stripEnd) {
super(stripEnd);
}
@Override
protected ValueOrError internalEvaluate(final Value... values) {
if(!assertStringLiteral(values[0]) || !assertStringLiteral(values[1])) {
return ValueOrError.Error;
}
final String string = ((Literal)values[0]).label();
final String stripChars = ((Literal)values[1]).label();
return ValueOrError.General.of(literal(stripEnd(string, stripChars)));
}
@Override
public StripEnd copy() {
return new StripEnd(this);
}
@Override
public void accept(final ExpressionVisitor expressionVisitor) {
expressionVisitor.visit(this);
}
@Override
public String toString() {
return StringVocabulary.stripEnd.toString();
}
}
|
/***********************************************************************************************************************
* Copyright 2011 Kim Herzig, Sascha Just
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
**********************************************************************************************************************/
package net.ownhero.dev.andama.threads;
import java.lang.reflect.Method;
import java.util.Collection;
import net.ownhero.dev.andama.exceptions.UnrecoverableError;
import net.ownhero.dev.andama.messages.EventBus;
import net.ownhero.dev.kisa.Logger;
/**
* The Class Hook.
*
* @param <K>
* the key type
* @param <V>
* the value type
* @author Sascha Just <sascha.just@st.cs.uni-saarland.de>
*/
public abstract class Hook<K, V> implements IHook<K, V> {
/**
* All completed.
*
* @param <K>
* the key type
* @param <V>
* the value type
* @param hooks
* the hooks
* @return true, if successful
*/
public static <K, V> boolean allCompleted(final Collection<? extends Hook<K, V>> hooks) {
for (final IHook<K, V> hook : hooks) {
if (!hook.completed()) {
return false;
}
}
return true;
}
/** The completed. */
private boolean completed = true;
/** The thread. */
private final Node<K, V> thread;
/**
* Instantiates a new hook.
*
* @param thread
* the thread
*/
public Hook(final Node<K, V> thread) {
if (Logger.logDebug()) {
Logger.debug("Adding '%s' to '%s'.", getHandle(), thread);
}
this.thread = thread;
Class<?> clazz = this.getClass();
while ((clazz.getSuperclass() != null) && (clazz.getSuperclass() != Hook.class)) {
clazz = clazz.getSuperclass();
}
if (clazz.getSuperclass() != Hook.class) {
// TODO ERROR
}
@SuppressWarnings ("unchecked")
final Class<? extends Hook<K, V>> superclass = (Class<? extends Hook<K, V>>) clazz;
try {
final Method method = Node.class.getDeclaredMethod("add" + superclass.getSimpleName(), superclass);
method.invoke(thread, this);
} catch (final Exception e) {
throw new UnrecoverableError(e.getMessage(), e);
}
}
/**
* Completed.
*
* @return if the {@link ProcessHook} is done with the current data
*/
@Override
public final boolean completed() {
return this.completed;
}
/**
* Gets the event bus.
*
* @return the event bus
*/
@Override
public EventBus getEventBus() {
return getThread().getEventBus();
}
/*
* (non-Javadoc)
* @see net.ownhero.dev.andama.threads.Hook#getHandle()
*/
/**
* Gets the handle.
*
* @return the handle
*/
@Override
public final String getHandle() {
return this.getClass().getSimpleName().isEmpty()
? this.getClass().getSuperclass().getSimpleName()
: this.getClass().getSimpleName();
}
/*
* (non-Javadoc)
* @see net.ownhero.dev.andama.threads.Hook#getThread()
*/
/**
* Gets the thread.
*
* @return the thread
*/
@Override
public final Node<K, V> getThread() {
return this.thread;
}
/**
* Sets the completed.
*/
public final void setCompleted() {
this.completed = true;
}
/**
* Unset completed.
*/
public final void unsetCompleted() {
this.completed = false;
}
}
|
package org.jetbrains.kotlin.ui.tests.editors.selection;
import org.junit.Test;
public class KotlinSelectEnclosingTest extends KotlinSelectEnclosingTestCase {
@Test
public void selectEnclosingFunctionNameWithoutSelection() {
doAutoTest();
}
@Test
public void DocComment() {
doAutoTest();
}
@Test
public void ForRange() {
doAutoTest();
}
@Test
public void FunctionWithLineCommentAfter() {
doAutoTest();
}
@Test
public void FunctionWithLineCommentBefore() {
doAutoTest();
}
@Test
public void IfBody() {
doAutoTest();
}
@Test
public void IfCondition() {
doAutoTest();
}
@Test
public void LineComment() {
doAutoTest();
}
@Test
public void ShiftOnWhitespace() {
doAutoTest();
}
@Test
public void SimpleComment() {
doAutoTest();
}
@Test
public void SimpleStringLiteral() {
doAutoTest();
}
@Test
public void SimpleStringLiteral2() {
doAutoTest();
}
@Test
public void Statements() {
doAutoTest();
}
@Test
public void StatementsWithWindowsDelimiter() {
doAutoTest();
}
@Test
public void TemplateStringLiteral1() {
doAutoTest();
}
@Test
public void TemplateStringLiteral2() {
doAutoTest();
}
@Test
public void TemplateStringLiteral3() {
doAutoTest();
}
@Test
public void TypeArguments() {
doAutoTest();
}
@Test
public void TypeParameters() {
doAutoTest();
}
@Test
public void ValueArguments() {
doAutoTest();
}
@Test
public void ValueParameters() {
doAutoTest();
}
@Test
public void WhenEntries() {
doAutoTest();
}
@Test
public void WholeFileSelection() {
doAutoTest();
}
}
|
package com.febs.common.entity;
import com.febs.system.entity.Menu;
import lombok.Data;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* @author MrBird
*/
@Data
public class MenuTree<T> implements Serializable {
private static final long serialVersionUID = 7681873362531265829L;
private String id;
private String icon;
private String href;
private String title;
private Map<String, Object> state;
private boolean checked = false;
private Map<String, Object> attributes;
private List<MenuTree<T>> childs = new ArrayList<>();
private String parentId;
private boolean hasParent = false;
private boolean hasChild = false;
private Menu data;
}
|
package com.g2forge.alexandria.java.adt.tuple.implementations;
import java.util.Objects;
import com.g2forge.alexandria.java.adt.tuple.ITuple2GS;
import com.g2forge.alexandria.java.adt.tuple.ITuple2G_;
public class Tuple2GSO<T0, T1> extends Tuple1GSO<T0> implements ITuple2GS<T0, T1> {
protected T1 value1;
public Tuple2GSO() {
this(null, null);
}
public Tuple2GSO(final T0 value0, final T1 value1) {
super(value0);
this.value1 = value1;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!super.equals(obj)) return false;
if (getClass() != obj.getClass()) return false;
final ITuple2G_<?, ?> that = (ITuple2G_<?, ?>) obj;
return Objects.equals(get0(), that.get0()) && Objects.equals(get1(), that.get1());
}
@Override
public T1 get1() {
return value1;
}
@Override
public int hashCode() {
return Objects.hash(get0(), get1());
}
@Override
public ITuple2GS<T0, T1> set0(final T0 value) {
value0 = value;
return this;
}
@Override
public ITuple2GS<T0, T1> set1(final T1 value) {
this.value1 = value;
return this;
}
}
|
package ru.kpfu.itis.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import ru.kpfu.itis.models.Product;
@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
}
|
package mindustry.type;
import mindustry.ctype.*;
import mindustry.ctype.ContentType;
/** 表示一个错误的空白类型. 替换任何失败的解析. <p/>
* Represents a blank type of content that has an error. Replaces anything that failed to parse. */
public class ErrorContent extends Content{
@Override
public ContentType getContentType(){
return ContentType.error;
}
}
|
/*
* Copyright (c) 2020 jMonkeyEngine
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'jMonkeyEngine' nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jme3.bullet.debug;
import com.jme3.bullet.collision.PhysicsCollisionObject;
import com.jme3.bullet.objects.PhysicsBody;
import com.jme3.material.Material;
import com.jme3.math.Vector3f;
import com.jme3.renderer.queue.RenderQueue;
import com.jme3.scene.Geometry;
import com.jme3.scene.Mesh;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial;
import com.jme3.scene.debug.Arrow;
import java.util.logging.Logger;
/**
* A physics-debug control used to visualize the gravity vector of a dynamic
* body.
*
* @author Stephen Gold sgold@sonic.net
*/
class GravityVectorDebugControl extends AbstractPhysicsDebugControl {
// *************************************************************************
// constants and loggers
/**
* message logger for this class
*/
final static Logger logger
= Logger.getLogger(GravityVectorDebugControl.class.getName());
// *************************************************************************
// fields
/**
* geometry to visualize the gravity vector
*/
final private Geometry geom;
/**
* body to visualize
*/
final private PhysicsBody body;
/**
* physics-space coordinates of the body's center
*/
final private Vector3f center;
/**
* most recent gravity vector
*/
final private Vector3f extent;
// *************************************************************************
// constructors
/**
* Instantiate an enabled control to visualize the gravity vector of the
* specified body.
*
* @param debugAppState which app state (not null, alias created)
* @param pco which body to visualize (not null, alias created)
*/
GravityVectorDebugControl(BulletDebugAppState debugAppState,
PhysicsCollisionObject pco) {
super(debugAppState);
body = (PhysicsBody) pco;
extent = body.getGravity(null);
Arrow mesh = new Arrow(extent);
geom = new Geometry("gravity of " + body, mesh);
center = body.getPhysicsLocation(null);
geom.setLocalTranslation(center);
Material material = debugAppState.getGravityVectorMaterial();
geom.setMaterial(material);
geom.setShadowMode(RenderQueue.ShadowMode.Off);
}
// *************************************************************************
// AbstractPhysicsDebugControl methods
/**
* Update this control. Invoked once per frame during the logical-state
* update, provided the control is enabled and added to a scene. Should be
* invoked only by a subclass or by AbstractControl.
*
* @param tpf the time interval between frames (in seconds, ≥0)
*/
@Override
protected void controlUpdate(float tpf) {
body.getPhysicsLocation(center);
geom.setLocalTranslation(center);
Mesh mesh = geom.getMesh();
Arrow arrow = (Arrow) mesh;
body.getGravity(extent);
arrow.setArrowExtent(extent);
}
/**
* Alter which Spatial is controlled. Invoked when the Control is added to
* or removed from a Spatial. Should be invoked only by a subclass or from
* Spatial. Do not invoke directly from user code.
*
* @param spatial the Spatial to control (or null)
*/
@Override
public void setSpatial(Spatial spatial) {
if (spatial instanceof Node) {
Node node = (Node) spatial;
node.attachChild(geom);
} else if (spatial == null && this.spatial != null) {
Node node = (Node) this.spatial;
node.detachChild(geom);
}
super.setSpatial(spatial);
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.arrow.vector.ipc.message;
import static org.apache.arrow.vector.ipc.message.FBSerializables.writeAllStructsToVector;
import java.util.ArrayList;
import java.util.List;
import org.apache.arrow.flatbuf.Block;
import org.apache.arrow.flatbuf.Footer;
import org.apache.arrow.vector.types.pojo.Schema;
import com.google.flatbuffers.FlatBufferBuilder;
/** Footer metadata for the arrow file format. */
public class ArrowFooter implements FBSerializable {
private final Schema schema;
private final List<ArrowBlock> dictionaries;
private final List<ArrowBlock> recordBatches;
/**
* Constructs a new instance.
*
* @param schema The schema for record batches in the file.
* @param dictionaries The dictionaries relevant to the file.
* @param recordBatches The recordBatches written to the file.
*/
public ArrowFooter(Schema schema, List<ArrowBlock> dictionaries, List<ArrowBlock> recordBatches) {
this.schema = schema;
this.dictionaries = dictionaries;
this.recordBatches = recordBatches;
}
/**
* Constructs from the corresponding Flatbuffer message.
*/
public ArrowFooter(Footer footer) {
this(
Schema.convertSchema(footer.schema()),
dictionaries(footer),
recordBatches(footer)
);
}
private static List<ArrowBlock> recordBatches(Footer footer) {
List<ArrowBlock> recordBatches = new ArrayList<>();
Block tempBlock = new Block();
int recordBatchesLength = footer.recordBatchesLength();
for (int i = 0; i < recordBatchesLength; i++) {
Block block = footer.recordBatches(tempBlock, i);
recordBatches.add(new ArrowBlock(block.offset(), block.metaDataLength(), block.bodyLength()));
}
return recordBatches;
}
private static List<ArrowBlock> dictionaries(Footer footer) {
List<ArrowBlock> dictionaries = new ArrayList<>();
Block tempBlock = new Block();
int dictionariesLength = footer.dictionariesLength();
for (int i = 0; i < dictionariesLength; i++) {
Block block = footer.dictionaries(tempBlock, i);
dictionaries.add(new ArrowBlock(block.offset(), block.metaDataLength(), block.bodyLength()));
}
return dictionaries;
}
public Schema getSchema() {
return schema;
}
public List<ArrowBlock> getDictionaries() {
return dictionaries;
}
public List<ArrowBlock> getRecordBatches() {
return recordBatches;
}
@Override
public int writeTo(FlatBufferBuilder builder) {
int schemaIndex = schema.getSchema(builder);
Footer.startDictionariesVector(builder, dictionaries.size());
int dicsOffset = writeAllStructsToVector(builder, dictionaries);
Footer.startRecordBatchesVector(builder, recordBatches.size());
int rbsOffset = writeAllStructsToVector(builder, recordBatches);
Footer.startFooter(builder);
Footer.addSchema(builder, schemaIndex);
Footer.addDictionaries(builder, dicsOffset);
Footer.addRecordBatches(builder, rbsOffset);
return Footer.endFooter(builder);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((dictionaries == null) ? 0 : dictionaries.hashCode());
result = prime * result + ((recordBatches == null) ? 0 : recordBatches.hashCode());
result = prime * result + ((schema == null) ? 0 : schema.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
ArrowFooter other = (ArrowFooter) obj;
if (dictionaries == null) {
if (other.dictionaries != null) {
return false;
}
} else if (!dictionaries.equals(other.dictionaries)) {
return false;
}
if (recordBatches == null) {
if (other.recordBatches != null) {
return false;
}
} else if (!recordBatches.equals(other.recordBatches)) {
return false;
}
if (schema == null) {
if (other.schema != null) {
return false;
}
} else if (!schema.equals(other.schema)) {
return false;
}
return true;
}
}
|
package br.com.tassioauad.spotifystreamer.view.fragment;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.inject.Inject;
import br.com.tassioauad.spotifystreamer.R;
import br.com.tassioauad.spotifystreamer.SpotifyStreamerApplication;
import br.com.tassioauad.spotifystreamer.model.entity.Artist;
import br.com.tassioauad.spotifystreamer.presenter.ListArtistPresenter;
import br.com.tassioauad.spotifystreamer.utils.dagger.ListArtistModule;
import br.com.tassioauad.spotifystreamer.view.ListArtistView;
import br.com.tassioauad.spotifystreamer.view.listviewadapter.ArtistListViewAdapter;
import butterknife.Bind;
import butterknife.ButterKnife;
public class ListArtistFragment extends Fragment implements ListArtistView {
private static final String ARTIST_LIST_BUNDLE_KEY = "artistlistbundlekey";
private static final String ARTIST_NAME_BUNDLE_KEY = "artistnamebundlekey";
@Inject
ListArtistPresenter presenter;
private List<Artist> artistList = new ArrayList<>();
private ListArtistListener listArtistListener;
@Bind(R.id.linearlayout_notfound) LinearLayout linearLayoutNotFound;
@Bind(R.id.listview_artist) ListView listViewArtist;
@Bind(R.id.linearlayout_lostconnection) LinearLayout linearLayoutLostConnection;
@Bind(R.id.progressbar) ProgressBar progressBar;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if(activity instanceof ListArtistListener) {
listArtistListener = (ListArtistListener) activity;
} else {
throw new RuntimeException("Activity must implement ListArtistFragment");
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_listartistfragment, container, false);
ButterKnife.bind(this, view);
((SpotifyStreamerApplication) getActivity().getApplication()).getObjectGraph().plus(new ListArtistModule(this)).inject(this);
if (savedInstanceState != null) {
artistList = savedInstanceState.getParcelableArrayList(ARTIST_LIST_BUNDLE_KEY);
if (artistList == null || artistList.size() == 0) {
anyArtistFounded();
} else {
showArtists(artistList);
}
} else if(getArguments() != null) {
String artistName = getArguments().getString(ARTIST_NAME_BUNDLE_KEY, null);
presenter.searchByName(artistName);
}
return view;
}
@Override
public void onSaveInstanceState(Bundle outState) {
if (artistList != null && artistList.size() > 0) {
outState.putParcelableArrayList(ARTIST_LIST_BUNDLE_KEY, new ArrayList<Artist>(artistList));
}
super.onSaveInstanceState(outState);
}
public static ListArtistFragment newInstance(Context context, String artistName) {
ListArtistFragment listArtistFragment = new ListArtistFragment();
Bundle bundle = new Bundle();
bundle.putString(ARTIST_NAME_BUNDLE_KEY, artistName);
listArtistFragment.setArguments(bundle);
return listArtistFragment;
}
@Override
public void anyArtistFounded() {
linearLayoutLostConnection.setVisibility(View.GONE);
listViewArtist.setVisibility(View.GONE);
linearLayoutNotFound.setVisibility(View.VISIBLE);
}
@Override
public void showArtists(List<Artist> artistList) {
this.artistList = artistList;
linearLayoutLostConnection.setVisibility(View.GONE);
listViewArtist.setVisibility(View.VISIBLE);
linearLayoutNotFound.setVisibility(View.GONE);
listViewArtist.setAdapter(new ArtistListViewAdapter(getActivity(), artistList));
listViewArtist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
listArtistListener.onArtistSelected((Artist) parent.getAdapter().getItem(position));
}
});
}
@Override
public void showLoadingWarn() {
progressBar.setVisibility(View.VISIBLE);
}
@Override
public void hideLoadingWarn() {
progressBar.setVisibility(View.GONE);
}
@Override
public void lostConnection() {
linearLayoutLostConnection.setVisibility(View.VISIBLE);
listViewArtist.setVisibility(View.GONE);
linearLayoutNotFound.setVisibility(View.GONE);
}
public interface ListArtistListener {
public void onArtistSelected(Artist artist);
}
}
|
package com.spring.insight.api.cases.web.rest.util;
import org.apache.commons.lang.StringUtils;
public class StringUtil {
public static Boolean isBlank(String string) {
return StringUtils.isBlank(string);
}
}
|
package reactiontime.utils;
import java.util.Arrays;
import java.util.List;
public class Statistics {
double[] data;
int size;
public Statistics(double[] data) {
this.data = data;
size = data.length;
}
public Statistics(List<Double> data){
this.size = data.size();
double[] dataArray = new double[data.size()];
for (int i = 0;i <data.size(); i++) {
dataArray[i] = data.get(i);
}
this.data = dataArray;
}
public double getMean() {
double sum = 0.0;
for (double a : data)
sum += a;
return sum / size;
}
public double getVariance() {
double mean = getMean();
double temp = 0;
for (double a : data)
temp += (a - mean) * (a - mean);
return temp / size;
}
public double getStdDev() {
return Math.sqrt(getVariance());
}
public double getMedian() {
Arrays.sort(data);
if (data.length % 2 == 0) {
return (data[(data.length / 2) - 1] + data[data.length / 2]) / 2.0;
} else {
return data[data.length / 2];
}
}
public static float getPercentageComparedWithPreOpValue(float preOpAvgReactionTime, float averageReactionInOpForSingleTest){
return (preOpAvgReactionTime / averageReactionInOpForSingleTest) * 100;
}
}
|
/*
Copyright 2020 NEC Solution Innovators, Ltd.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package jp.co.nec.necst.spf.globalSNS.WebSocketServer.WebSocketApi;
import jp.co.nec.necst.spf.globalSNS.WebSocketServer.GlobalSNSWebSocket;
import jp.co.nec.necst.spf.globalSNS.WebSocketServer.WebSocketApiProcessor;
import jp.co.nec.necst.spf.globalSNS.WebSocketServer.WebSocketApi.Data.SetPresenceResult;
import net.arnx.jsonic.JSONHint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SetPresenceRequestApi extends RequestApi {
@JSONHint(ignore = true)
private static final Logger Log = LoggerFactory
.getLogger(SetPresenceRequestApi.class);
public Content content;
public class Content {
@JSONHint(ignore = true)
public static final int ACTION_TYPE_INVALID = -1;
@JSONHint(ignore = true)
public static final int ACTION_TYPE_MANUAL = 0;
@JSONHint(ignore = true)
public static final int ACTION_TYPE_AUTO = 1;
@JSONHint(ignore = true)
public static final int PRESENCE_TYPE_OFFLINE = 0;
@JSONHint(ignore = true)
public static final int PRESENCE_TYPE_CHAT = 1;
@JSONHint(ignore = true)
public static final int PRESENCE_TYPE_AWAY = 2;
@JSONHint(ignore = true)
public static final int PRESENCE_TYPE_XA = 3;
@JSONHint(ignore = true)
public static final int PRESENCE_TYPE_DND = 4;
public int action = ACTION_TYPE_INVALID;
public int presence = PRESENCE_TYPE_OFFLINE;
}
@Override
public ResponseApi doRequest(GlobalSNSWebSocket globalSNSWebSocket) {
final String logPrefix = "doRequest() : ";
ResponseApi ret = null;
if (globalSNSWebSocket == null) {
Log.error(logPrefix + "globalSNSWebSocket is null.",
new Throwable());
return ret;
}
String jid = globalSNSWebSocket.getJid();
if (jid == null || "".equals(jid)) {
Log.error(logPrefix + "globalSNSWebSocket's jid is invalid",
new Throwable());
return ret;
}
if (content == null || content.action == Content.ACTION_TYPE_INVALID
|| content.presence == Content.PRESENCE_TYPE_OFFLINE) {
Log.error(logPrefix + "content is null.", new Throwable());
ret = new ResponseApi();
ret.id = id;
ret.request = request;
ret.version = version;
ret.errorCode = ResponseApi.ERROR_CODE_ERROR_LOGGED_IN;
ret.content.result = false;
ret.content.reason = ResponseApi.ResponseContent.REASON_CODE_API_FORMAT;
return ret;
}
SetPresenceResult result = WebSocketApiProcessor.getInstance()
.setPresence(jid, content.action, content.presence);
if (result == null) {
Log.error(logPrefix + "result is null.", new Throwable());
return ret;
}
int resultReason = result.getReason();
if (resultReason != ResponseApi.ResponseContent.REASON_CODE_NONE
&& resultReason != SetPresenceResponseApi.Content.REASON_CODE_NOT_CHANGED) {
ret = new ResponseApi();
ret.id = id;
ret.request = request;
ret.version = version;
ret.errorCode = ResponseApi.ERROR_CODE_ERROR_LOGGED_IN;
ret.content.result = false;
ret.content.reason = resultReason;
return ret;
}
SetPresenceResponseApi response = new SetPresenceResponseApi();
response.id = id;
response.request = request;
response.version = version;
((SetPresenceResponseApi.Content) response.content).reason = resultReason;
((SetPresenceResponseApi.Content) response.content).presence = result
.getPresence();
ret = response;
return ret;
}
}
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.fs.viewfs;
import static org.apache.hadoop.fs.viewfs.Constants.PERMISSION_555;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.Collection;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.BlockLocation;
import org.apache.hadoop.fs.BlockStoragePolicySpi;
import org.apache.hadoop.fs.ContentSummary;
import org.apache.hadoop.fs.CreateFlag;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileAlreadyExistsException;
import org.apache.hadoop.fs.FileChecksum;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FsConstants;
import org.apache.hadoop.fs.FsServerDefaults;
import org.apache.hadoop.fs.LocatedFileStatus;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.PathFilter;
import org.apache.hadoop.fs.QuotaUsage;
import org.apache.hadoop.fs.RemoteIterator;
import org.apache.hadoop.fs.UnsupportedFileSystemException;
import org.apache.hadoop.fs.XAttrSetFlag;
import org.apache.hadoop.fs.permission.AclEntry;
import org.apache.hadoop.fs.permission.AclStatus;
import org.apache.hadoop.fs.permission.AclUtil;
import org.apache.hadoop.fs.permission.FsAction;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.fs.viewfs.InodeTree.INode;
import org.apache.hadoop.fs.viewfs.InodeTree.INodeLink;
import org.apache.hadoop.security.AccessControlException;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.util.Progressable;
import org.apache.hadoop.util.Time;
/**
* ViewFileSystem (extends the FileSystem interface) implements a client-side
* mount table. Its spec and implementation is identical to {@link ViewFs}.
*/
@InterfaceAudience.Public
@InterfaceStability.Evolving /*Evolving for a release,to be changed to Stable */
public class ViewFileSystem extends FileSystem {
private static final Path ROOT_PATH = new Path(Path.SEPARATOR);
static AccessControlException readOnlyMountTable(final String operation,
final String p) {
return new AccessControlException(
"InternalDir of ViewFileSystem is readonly; operation=" + operation +
"Path=" + p);
}
static AccessControlException readOnlyMountTable(final String operation,
final Path p) {
return readOnlyMountTable(operation, p.toString());
}
static public class MountPoint {
private Path src; // the src of the mount
private URI[] targets; // target of the mount; Multiple targets imply mergeMount
MountPoint(Path srcPath, URI[] targetURIs) {
src = srcPath;
targets = targetURIs;
}
Path getSrc() {
return src;
}
URI[] getTargets() {
return targets;
}
}
final long creationTime; // of the the mount table
final UserGroupInformation ugi; // the user/group of user who created mtable
URI myUri;
private Path workingDir;
Configuration config;
InodeTree<FileSystem> fsState; // the fs state; ie the mount table
Path homeDir = null;
/**
* Make the path Absolute and get the path-part of a pathname.
* Checks that URI matches this file system
* and that the path-part is a valid name.
*
* @param p path
* @return path-part of the Path p
*/
private String getUriPath(final Path p) {
checkPath(p);
return makeAbsolute(p).toUri().getPath();
}
private Path makeAbsolute(final Path f) {
return f.isAbsolute() ? f : new Path(workingDir, f);
}
/**
* This is the constructor with the signature needed by
* {@link FileSystem#createFileSystem(URI, Configuration)}
*
* After this constructor is called initialize() is called.
* @throws IOException
*/
public ViewFileSystem() throws IOException {
ugi = UserGroupInformation.getCurrentUser();
creationTime = Time.now();
}
/**
* Return the protocol scheme for the FileSystem.
* <p/>
*
* @return <code>viewfs</code>
*/
@Override
public String getScheme() {
return "viewfs";
}
/**
* Called after a new FileSystem instance is constructed.
* @param theUri a uri whose authority section names the host, port, etc. for
* this FileSystem
* @param conf the configuration
*/
@Override
public void initialize(final URI theUri, final Configuration conf)
throws IOException {
super.initialize(theUri, conf);
setConf(conf);
config = conf;
// Now build client side view (i.e. client side mount table) from config.
final String authority = theUri.getAuthority();
try {
myUri = new URI(FsConstants.VIEWFS_SCHEME, authority, "/", null, null);
fsState = new InodeTree<FileSystem>(conf, authority) {
@Override
protected
FileSystem getTargetFileSystem(final URI uri)
throws URISyntaxException, IOException {
return new ChRootedFileSystem(uri, config);
}
@Override
protected
FileSystem getTargetFileSystem(final INodeDir<FileSystem> dir)
throws URISyntaxException {
return new InternalDirOfViewFs(dir, creationTime, ugi, myUri);
}
@Override
protected
FileSystem getTargetFileSystem(URI[] mergeFsURIList)
throws URISyntaxException, UnsupportedFileSystemException {
throw new UnsupportedFileSystemException("mergefs not implemented");
// return MergeFs.createMergeFs(mergeFsURIList, config);
}
};
workingDir = this.getHomeDirectory();
} catch (URISyntaxException e) {
throw new IOException("URISyntax exception: " + theUri);
}
}
/**
* Convenience Constructor for apps to call directly
* @param theUri which must be that of ViewFileSystem
* @param conf
* @throws IOException
*/
ViewFileSystem(final URI theUri, final Configuration conf)
throws IOException {
this();
initialize(theUri, conf);
}
/**
* Convenience Constructor for apps to call directly
* @param conf
* @throws IOException
*/
public ViewFileSystem(final Configuration conf) throws IOException {
this(FsConstants.VIEWFS_URI, conf);
}
public Path getTrashCanLocation(final Path f) throws FileNotFoundException {
final InodeTree.ResolveResult<FileSystem> res =
fsState.resolve(getUriPath(f), true);
return res.isInternalDir() ? null : res.targetFileSystem.getHomeDirectory();
}
@Override
public URI getUri() {
return myUri;
}
@Override
public Path resolvePath(final Path f)
throws IOException {
final InodeTree.ResolveResult<FileSystem> res;
res = fsState.resolve(getUriPath(f), true);
if (res.isInternalDir()) {
return f;
}
return res.targetFileSystem.resolvePath(res.remainingPath);
}
@Override
public Path getHomeDirectory() {
if (homeDir == null) {
String base = fsState.getHomeDirPrefixValue();
if (base == null) {
base = "/user";
}
homeDir = (base.equals("/") ?
this.makeQualified(new Path(base + ugi.getShortUserName())):
this.makeQualified(new Path(base + "/" + ugi.getShortUserName())));
}
return homeDir;
}
@Override
public Path getWorkingDirectory() {
return workingDir;
}
@Override
public void setWorkingDirectory(final Path new_dir) {
getUriPath(new_dir); // this validates the path
workingDir = makeAbsolute(new_dir);
}
@Override
public FSDataOutputStream append(final Path f, final int bufferSize,
final Progressable progress) throws IOException {
InodeTree.ResolveResult<FileSystem> res =
fsState.resolve(getUriPath(f), true);
return res.targetFileSystem.append(res.remainingPath, bufferSize, progress);
}
@Override
public FSDataOutputStream createNonRecursive(Path f, FsPermission permission,
EnumSet<CreateFlag> flags, int bufferSize, short replication, long blockSize,
Progressable progress) throws IOException {
InodeTree.ResolveResult<FileSystem> res;
try {
res = fsState.resolve(getUriPath(f), false);
} catch (FileNotFoundException e) {
throw readOnlyMountTable("create", f);
}
assert(res.remainingPath != null);
return res.targetFileSystem.createNonRecursive(res.remainingPath, permission,
flags, bufferSize, replication, blockSize, progress);
}
@Override
public FSDataOutputStream create(final Path f, final FsPermission permission,
final boolean overwrite, final int bufferSize, final short replication,
final long blockSize, final Progressable progress) throws IOException {
InodeTree.ResolveResult<FileSystem> res;
try {
res = fsState.resolve(getUriPath(f), false);
} catch (FileNotFoundException e) {
throw readOnlyMountTable("create", f);
}
assert(res.remainingPath != null);
return res.targetFileSystem.create(res.remainingPath, permission,
overwrite, bufferSize, replication, blockSize, progress);
}
@Override
public boolean delete(final Path f, final boolean recursive)
throws AccessControlException, FileNotFoundException,
IOException {
InodeTree.ResolveResult<FileSystem> res =
fsState.resolve(getUriPath(f), true);
// If internal dir or target is a mount link (ie remainingPath is Slash)
if (res.isInternalDir() || res.remainingPath == InodeTree.SlashPath) {
throw readOnlyMountTable("delete", f);
}
return res.targetFileSystem.delete(res.remainingPath, recursive);
}
@Override
@SuppressWarnings("deprecation")
public boolean delete(final Path f)
throws AccessControlException, FileNotFoundException,
IOException {
return delete(f, true);
}
@Override
public BlockLocation[] getFileBlockLocations(FileStatus fs,
long start, long len) throws IOException {
final InodeTree.ResolveResult<FileSystem> res =
fsState.resolve(getUriPath(fs.getPath()), true);
return res.targetFileSystem.getFileBlockLocations(
new ViewFsFileStatus(fs, res.remainingPath), start, len);
}
@Override
public FileChecksum getFileChecksum(final Path f)
throws AccessControlException, FileNotFoundException,
IOException {
InodeTree.ResolveResult<FileSystem> res =
fsState.resolve(getUriPath(f), true);
return res.targetFileSystem.getFileChecksum(res.remainingPath);
}
private static FileStatus fixFileStatus(FileStatus orig,
Path qualified) throws IOException {
// FileStatus#getPath is a fully qualified path relative to the root of
// target file system.
// We need to change it to viewfs URI - relative to root of mount table.
// The implementors of RawLocalFileSystem were trying to be very smart.
// They implement FileStatus#getOwner lazily -- the object
// returned is really a RawLocalFileSystem that expect the
// FileStatus#getPath to be unchanged so that it can get owner when needed.
// Hence we need to interpose a new ViewFileSystemFileStatus that
// works around.
if ("file".equals(orig.getPath().toUri().getScheme())) {
orig = wrapLocalFileStatus(orig, qualified);
}
orig.setPath(qualified);
return orig;
}
private static FileStatus wrapLocalFileStatus(FileStatus orig,
Path qualified) {
return orig instanceof LocatedFileStatus
? new ViewFsLocatedFileStatus((LocatedFileStatus)orig, qualified)
: new ViewFsFileStatus(orig, qualified);
}
@Override
public FileStatus getFileStatus(final Path f) throws AccessControlException,
FileNotFoundException, IOException {
InodeTree.ResolveResult<FileSystem> res =
fsState.resolve(getUriPath(f), true);
FileStatus status = res.targetFileSystem.getFileStatus(res.remainingPath);
return fixFileStatus(status, this.makeQualified(f));
}
@Override
public void access(Path path, FsAction mode) throws AccessControlException,
FileNotFoundException, IOException {
InodeTree.ResolveResult<FileSystem> res =
fsState.resolve(getUriPath(path), true);
res.targetFileSystem.access(res.remainingPath, mode);
}
@Override
public FileStatus[] listStatus(final Path f) throws AccessControlException,
FileNotFoundException, IOException {
InodeTree.ResolveResult<FileSystem> res =
fsState.resolve(getUriPath(f), true);
FileStatus[] statusLst = res.targetFileSystem.listStatus(res.remainingPath);
if (!res.isInternalDir()) {
// We need to change the name in the FileStatus as described in
// {@link #getFileStatus }
int i = 0;
for (FileStatus status : statusLst) {
statusLst[i++] = fixFileStatus(status,
getChrootedPath(res, status, f));
}
}
return statusLst;
}
@Override
public RemoteIterator<LocatedFileStatus>listLocatedStatus(final Path f,
final PathFilter filter) throws FileNotFoundException, IOException {
final InodeTree.ResolveResult<FileSystem> res = fsState
.resolve(getUriPath(f), true);
final RemoteIterator<LocatedFileStatus> statusIter = res.targetFileSystem
.listLocatedStatus(res.remainingPath);
if (res.isInternalDir()) {
return statusIter;
}
return new RemoteIterator<LocatedFileStatus>() {
@Override
public boolean hasNext() throws IOException {
return statusIter.hasNext();
}
@Override
public LocatedFileStatus next() throws IOException {
final LocatedFileStatus status = statusIter.next();
return (LocatedFileStatus)fixFileStatus(status,
getChrootedPath(res, status, f));
}
};
}
private Path getChrootedPath(InodeTree.ResolveResult<FileSystem> res,
FileStatus status, Path f) throws IOException {
final String suffix = ((ChRootedFileSystem)res.targetFileSystem)
.stripOutRoot(status.getPath());
return this.makeQualified(
suffix.length() == 0 ? f : new Path(res.resolvedPath, suffix));
}
@Override
public boolean mkdirs(final Path dir, final FsPermission permission)
throws IOException {
InodeTree.ResolveResult<FileSystem> res =
fsState.resolve(getUriPath(dir), false);
return res.targetFileSystem.mkdirs(res.remainingPath, permission);
}
@Override
public FSDataInputStream open(final Path f, final int bufferSize)
throws AccessControlException, FileNotFoundException,
IOException {
InodeTree.ResolveResult<FileSystem> res =
fsState.resolve(getUriPath(f), true);
return res.targetFileSystem.open(res.remainingPath, bufferSize);
}
@Override
public boolean rename(final Path src, final Path dst) throws IOException {
// passing resolveLastComponet as false to catch renaming a mount point to
// itself. We need to catch this as an internal operation and fail.
InodeTree.ResolveResult<FileSystem> resSrc =
fsState.resolve(getUriPath(src), false);
if (resSrc.isInternalDir()) {
throw readOnlyMountTable("rename", src);
}
InodeTree.ResolveResult<FileSystem> resDst =
fsState.resolve(getUriPath(dst), false);
if (resDst.isInternalDir()) {
throw readOnlyMountTable("rename", dst);
}
/**
// Alternate 1: renames within same file system - valid but we disallow
// Alternate 2: (as described in next para - valid but we have disallowed it
//
// Note we compare the URIs. the URIs include the link targets.
// hence we allow renames across mount links as long as the mount links
// point to the same target.
if (!resSrc.targetFileSystem.getUri().equals(
resDst.targetFileSystem.getUri())) {
throw new IOException("Renames across Mount points not supported");
}
*/
//
// Alternate 3 : renames ONLY within the the same mount links.
//
if (resSrc.targetFileSystem !=resDst.targetFileSystem) {
throw new IOException("Renames across Mount points not supported");
}
return resSrc.targetFileSystem.rename(resSrc.remainingPath,
resDst.remainingPath);
}
@Override
public boolean truncate(final Path f, final long newLength)
throws IOException {
InodeTree.ResolveResult<FileSystem> res =
fsState.resolve(getUriPath(f), true);
return res.targetFileSystem.truncate(f, newLength);
}
@Override
public void setOwner(final Path f, final String username,
final String groupname) throws AccessControlException,
FileNotFoundException,
IOException {
InodeTree.ResolveResult<FileSystem> res =
fsState.resolve(getUriPath(f), true);
res.targetFileSystem.setOwner(res.remainingPath, username, groupname);
}
@Override
public void setPermission(final Path f, final FsPermission permission)
throws AccessControlException, FileNotFoundException,
IOException {
InodeTree.ResolveResult<FileSystem> res =
fsState.resolve(getUriPath(f), true);
res.targetFileSystem.setPermission(res.remainingPath, permission);
}
@Override
public boolean setReplication(final Path f, final short replication)
throws AccessControlException, FileNotFoundException,
IOException {
InodeTree.ResolveResult<FileSystem> res =
fsState.resolve(getUriPath(f), true);
return res.targetFileSystem.setReplication(res.remainingPath, replication);
}
@Override
public void setTimes(final Path f, final long mtime, final long atime)
throws AccessControlException, FileNotFoundException,
IOException {
InodeTree.ResolveResult<FileSystem> res =
fsState.resolve(getUriPath(f), true);
res.targetFileSystem.setTimes(res.remainingPath, mtime, atime);
}
@Override
public void modifyAclEntries(Path path, List<AclEntry> aclSpec)
throws IOException {
InodeTree.ResolveResult<FileSystem> res = fsState.resolve(getUriPath(path),
true);
res.targetFileSystem.modifyAclEntries(res.remainingPath, aclSpec);
}
@Override
public void removeAclEntries(Path path, List<AclEntry> aclSpec)
throws IOException {
InodeTree.ResolveResult<FileSystem> res = fsState.resolve(getUriPath(path),
true);
res.targetFileSystem.removeAclEntries(res.remainingPath, aclSpec);
}
@Override
public void removeDefaultAcl(Path path)
throws IOException {
InodeTree.ResolveResult<FileSystem> res =
fsState.resolve(getUriPath(path), true);
res.targetFileSystem.removeDefaultAcl(res.remainingPath);
}
@Override
public void removeAcl(Path path)
throws IOException {
InodeTree.ResolveResult<FileSystem> res =
fsState.resolve(getUriPath(path), true);
res.targetFileSystem.removeAcl(res.remainingPath);
}
@Override
public void setAcl(Path path, List<AclEntry> aclSpec) throws IOException {
InodeTree.ResolveResult<FileSystem> res =
fsState.resolve(getUriPath(path), true);
res.targetFileSystem.setAcl(res.remainingPath, aclSpec);
}
@Override
public AclStatus getAclStatus(Path path) throws IOException {
InodeTree.ResolveResult<FileSystem> res =
fsState.resolve(getUriPath(path), true);
return res.targetFileSystem.getAclStatus(res.remainingPath);
}
@Override
public void setXAttr(Path path, String name, byte[] value,
EnumSet<XAttrSetFlag> flag) throws IOException {
InodeTree.ResolveResult<FileSystem> res =
fsState.resolve(getUriPath(path), true);
res.targetFileSystem.setXAttr(res.remainingPath, name, value, flag);
}
@Override
public byte[] getXAttr(Path path, String name) throws IOException {
InodeTree.ResolveResult<FileSystem> res =
fsState.resolve(getUriPath(path), true);
return res.targetFileSystem.getXAttr(res.remainingPath, name);
}
@Override
public Map<String, byte[]> getXAttrs(Path path) throws IOException {
InodeTree.ResolveResult<FileSystem> res =
fsState.resolve(getUriPath(path), true);
return res.targetFileSystem.getXAttrs(res.remainingPath);
}
@Override
public Map<String, byte[]> getXAttrs(Path path, List<String> names)
throws IOException {
InodeTree.ResolveResult<FileSystem> res =
fsState.resolve(getUriPath(path), true);
return res.targetFileSystem.getXAttrs(res.remainingPath, names);
}
@Override
public List<String> listXAttrs(Path path) throws IOException {
InodeTree.ResolveResult<FileSystem> res =
fsState.resolve(getUriPath(path), true);
return res.targetFileSystem.listXAttrs(res.remainingPath);
}
@Override
public void removeXAttr(Path path, String name) throws IOException {
InodeTree.ResolveResult<FileSystem> res = fsState.resolve(getUriPath(path),
true);
res.targetFileSystem.removeXAttr(res.remainingPath, name);
}
@Override
public void setVerifyChecksum(final boolean verifyChecksum) {
List<InodeTree.MountPoint<FileSystem>> mountPoints =
fsState.getMountPoints();
for (InodeTree.MountPoint<FileSystem> mount : mountPoints) {
mount.target.targetFileSystem.setVerifyChecksum(verifyChecksum);
}
}
@Override
public long getDefaultBlockSize() {
throw new NotInMountpointException("getDefaultBlockSize");
}
@Override
public short getDefaultReplication() {
throw new NotInMountpointException("getDefaultReplication");
}
@Override
public FsServerDefaults getServerDefaults() throws IOException {
throw new NotInMountpointException("getServerDefaults");
}
@Override
public long getDefaultBlockSize(Path f) {
try {
InodeTree.ResolveResult<FileSystem> res =
fsState.resolve(getUriPath(f), true);
return res.targetFileSystem.getDefaultBlockSize(res.remainingPath);
} catch (FileNotFoundException e) {
throw new NotInMountpointException(f, "getDefaultBlockSize");
}
}
@Override
public short getDefaultReplication(Path f) {
try {
InodeTree.ResolveResult<FileSystem> res =
fsState.resolve(getUriPath(f), true);
return res.targetFileSystem.getDefaultReplication(res.remainingPath);
} catch (FileNotFoundException e) {
throw new NotInMountpointException(f, "getDefaultReplication");
}
}
@Override
public FsServerDefaults getServerDefaults(Path f) throws IOException {
InodeTree.ResolveResult<FileSystem> res =
fsState.resolve(getUriPath(f), true);
return res.targetFileSystem.getServerDefaults(res.remainingPath);
}
@Override
public ContentSummary getContentSummary(Path f) throws IOException {
InodeTree.ResolveResult<FileSystem> res =
fsState.resolve(getUriPath(f), true);
return res.targetFileSystem.getContentSummary(res.remainingPath);
}
@Override
public QuotaUsage getQuotaUsage(Path f) throws IOException {
InodeTree.ResolveResult<FileSystem> res =
fsState.resolve(getUriPath(f), true);
return res.targetFileSystem.getQuotaUsage(res.remainingPath);
}
@Override
public void setWriteChecksum(final boolean writeChecksum) {
List<InodeTree.MountPoint<FileSystem>> mountPoints =
fsState.getMountPoints();
for (InodeTree.MountPoint<FileSystem> mount : mountPoints) {
mount.target.targetFileSystem.setWriteChecksum(writeChecksum);
}
}
@Override
public FileSystem[] getChildFileSystems() {
List<InodeTree.MountPoint<FileSystem>> mountPoints =
fsState.getMountPoints();
Set<FileSystem> children = new HashSet<FileSystem>();
for (InodeTree.MountPoint<FileSystem> mountPoint : mountPoints) {
FileSystem targetFs = mountPoint.target.targetFileSystem;
children.addAll(Arrays.asList(targetFs.getChildFileSystems()));
}
return children.toArray(new FileSystem[]{});
}
public MountPoint[] getMountPoints() {
List<InodeTree.MountPoint<FileSystem>> mountPoints =
fsState.getMountPoints();
MountPoint[] result = new MountPoint[mountPoints.size()];
for ( int i = 0; i < mountPoints.size(); ++i ) {
result[i] = new MountPoint(new Path(mountPoints.get(i).src),
mountPoints.get(i).target.targetDirLinkList);
}
return result;
}
@Override
public Path createSnapshot(Path path, String snapshotName)
throws IOException {
InodeTree.ResolveResult<FileSystem> res = fsState.resolve(getUriPath(path),
true);
return res.targetFileSystem.createSnapshot(res.remainingPath, snapshotName);
}
@Override
public void renameSnapshot(Path path, String snapshotOldName,
String snapshotNewName) throws IOException {
InodeTree.ResolveResult<FileSystem> res = fsState.resolve(getUriPath(path),
true);
res.targetFileSystem.renameSnapshot(res.remainingPath, snapshotOldName,
snapshotNewName);
}
@Override
public void deleteSnapshot(Path path, String snapshotName)
throws IOException {
InodeTree.ResolveResult<FileSystem> res = fsState.resolve(getUriPath(path),
true);
res.targetFileSystem.deleteSnapshot(res.remainingPath, snapshotName);
}
@Override
public void setStoragePolicy(Path src, String policyName) throws IOException {
InodeTree.ResolveResult<FileSystem> res = fsState.resolve(getUriPath(src),
true);
res.targetFileSystem.setStoragePolicy(res.remainingPath, policyName);
}
@Override
public void unsetStoragePolicy(Path src) throws IOException {
InodeTree.ResolveResult<FileSystem> res = fsState.resolve(getUriPath(src),
true);
res.targetFileSystem.unsetStoragePolicy(res.remainingPath);
}
@Override
public BlockStoragePolicySpi getStoragePolicy(Path src) throws IOException {
InodeTree.ResolveResult<FileSystem> res = fsState.resolve(getUriPath(src),
true);
return res.targetFileSystem.getStoragePolicy(res.remainingPath);
}
@Override
public Collection<? extends BlockStoragePolicySpi> getAllStoragePolicies()
throws IOException {
Collection<BlockStoragePolicySpi> allPolicies = new HashSet<>();
for (FileSystem fs : getChildFileSystems()) {
try {
Collection<? extends BlockStoragePolicySpi> policies =
fs.getAllStoragePolicies();
allPolicies.addAll(policies);
} catch (UnsupportedOperationException e) {
// ignored
}
}
return allPolicies;
}
/*
* An instance of this class represents an internal dir of the viewFs
* that is internal dir of the mount table.
* It is a read only mount tables and create, mkdir or delete operations
* are not allowed.
* If called on create or mkdir then this target is the parent of the
* directory in which one is trying to create or mkdir; hence
* in this case the path name passed in is the last component.
* Otherwise this target is the end point of the path and hence
* the path name passed in is null.
*/
static class InternalDirOfViewFs extends FileSystem {
final InodeTree.INodeDir<FileSystem> theInternalDir;
final long creationTime; // of the the mount table
final UserGroupInformation ugi; // the user/group of user who created mtable
final URI myUri;
public InternalDirOfViewFs(final InodeTree.INodeDir<FileSystem> dir,
final long cTime, final UserGroupInformation ugi, URI uri)
throws URISyntaxException {
myUri = uri;
try {
initialize(myUri, new Configuration());
} catch (IOException e) {
throw new RuntimeException("Cannot occur");
}
theInternalDir = dir;
creationTime = cTime;
this.ugi = ugi;
}
static private void checkPathIsSlash(final Path f) throws IOException {
if (f != InodeTree.SlashPath) {
throw new IOException (
"Internal implementation error: expected file name to be /" );
}
}
@Override
public URI getUri() {
return myUri;
}
@Override
public Path getWorkingDirectory() {
throw new RuntimeException (
"Internal impl error: getWorkingDir should not have been called" );
}
@Override
public void setWorkingDirectory(final Path new_dir) {
throw new RuntimeException (
"Internal impl error: getWorkingDir should not have been called" );
}
@Override
public FSDataOutputStream append(final Path f, final int bufferSize,
final Progressable progress) throws IOException {
throw readOnlyMountTable("append", f);
}
@Override
public FSDataOutputStream create(final Path f,
final FsPermission permission, final boolean overwrite,
final int bufferSize, final short replication, final long blockSize,
final Progressable progress) throws AccessControlException {
throw readOnlyMountTable("create", f);
}
@Override
public boolean delete(final Path f, final boolean recursive)
throws AccessControlException, IOException {
checkPathIsSlash(f);
throw readOnlyMountTable("delete", f);
}
@Override
@SuppressWarnings("deprecation")
public boolean delete(final Path f)
throws AccessControlException, IOException {
return delete(f, true);
}
@Override
public BlockLocation[] getFileBlockLocations(final FileStatus fs,
final long start, final long len) throws
FileNotFoundException, IOException {
checkPathIsSlash(fs.getPath());
throw new FileNotFoundException("Path points to dir not a file");
}
@Override
public FileChecksum getFileChecksum(final Path f)
throws FileNotFoundException, IOException {
checkPathIsSlash(f);
throw new FileNotFoundException("Path points to dir not a file");
}
@Override
public FileStatus getFileStatus(Path f) throws IOException {
checkPathIsSlash(f);
return new FileStatus(0, true, 0, 0, creationTime, creationTime,
PERMISSION_555, ugi.getUserName(), ugi.getGroupNames()[0],
new Path(theInternalDir.fullPath).makeQualified(
myUri, ROOT_PATH));
}
@Override
public FileStatus[] listStatus(Path f) throws AccessControlException,
FileNotFoundException, IOException {
checkPathIsSlash(f);
FileStatus[] result = new FileStatus[theInternalDir.children.size()];
int i = 0;
for (Entry<String, INode<FileSystem>> iEntry :
theInternalDir.children.entrySet()) {
INode<FileSystem> inode = iEntry.getValue();
if (inode instanceof INodeLink ) {
INodeLink<FileSystem> link = (INodeLink<FileSystem>) inode;
result[i++] = new FileStatus(0, false, 0, 0,
creationTime, creationTime, PERMISSION_555,
ugi.getUserName(), ugi.getGroupNames()[0],
link.getTargetLink(),
new Path(inode.fullPath).makeQualified(
myUri, null));
} else {
result[i++] = new FileStatus(0, true, 0, 0,
creationTime, creationTime, PERMISSION_555,
ugi.getUserName(), ugi.getGroupNames()[0],
new Path(inode.fullPath).makeQualified(
myUri, null));
}
}
return result;
}
@Override
public boolean mkdirs(Path dir, FsPermission permission)
throws AccessControlException, FileAlreadyExistsException {
if (theInternalDir.isRoot && dir == null) {
throw new FileAlreadyExistsException("/ already exits");
}
// Note dir starts with /
if (theInternalDir.children.containsKey(dir.toString().substring(1))) {
return true; // this is the stupid semantics of FileSystem
}
throw readOnlyMountTable("mkdirs", dir);
}
@Override
public FSDataInputStream open(Path f, int bufferSize)
throws AccessControlException, FileNotFoundException, IOException {
checkPathIsSlash(f);
throw new FileNotFoundException("Path points to dir not a file");
}
@Override
public boolean rename(Path src, Path dst) throws AccessControlException,
IOException {
checkPathIsSlash(src);
checkPathIsSlash(dst);
throw readOnlyMountTable("rename", src);
}
@Override
public boolean truncate(Path f, long newLength) throws IOException {
throw readOnlyMountTable("truncate", f);
}
@Override
public void setOwner(Path f, String username, String groupname)
throws AccessControlException, IOException {
checkPathIsSlash(f);
throw readOnlyMountTable("setOwner", f);
}
@Override
public void setPermission(Path f, FsPermission permission)
throws AccessControlException, IOException {
checkPathIsSlash(f);
throw readOnlyMountTable("setPermission", f);
}
@Override
public boolean setReplication(Path f, short replication)
throws AccessControlException, IOException {
checkPathIsSlash(f);
throw readOnlyMountTable("setReplication", f);
}
@Override
public void setTimes(Path f, long mtime, long atime)
throws AccessControlException, IOException {
checkPathIsSlash(f);
throw readOnlyMountTable("setTimes", f);
}
@Override
public void setVerifyChecksum(boolean verifyChecksum) {
// Noop for viewfs
}
@Override
public FsServerDefaults getServerDefaults(Path f) throws IOException {
throw new NotInMountpointException(f, "getServerDefaults");
}
@Override
public long getDefaultBlockSize(Path f) {
throw new NotInMountpointException(f, "getDefaultBlockSize");
}
@Override
public short getDefaultReplication(Path f) {
throw new NotInMountpointException(f, "getDefaultReplication");
}
@Override
public void modifyAclEntries(Path path, List<AclEntry> aclSpec)
throws IOException {
checkPathIsSlash(path);
throw readOnlyMountTable("modifyAclEntries", path);
}
@Override
public void removeAclEntries(Path path, List<AclEntry> aclSpec)
throws IOException {
checkPathIsSlash(path);
throw readOnlyMountTable("removeAclEntries", path);
}
@Override
public void removeDefaultAcl(Path path) throws IOException {
checkPathIsSlash(path);
throw readOnlyMountTable("removeDefaultAcl", path);
}
@Override
public void removeAcl(Path path) throws IOException {
checkPathIsSlash(path);
throw readOnlyMountTable("removeAcl", path);
}
@Override
public void setAcl(Path path, List<AclEntry> aclSpec) throws IOException {
checkPathIsSlash(path);
throw readOnlyMountTable("setAcl", path);
}
@Override
public AclStatus getAclStatus(Path path) throws IOException {
checkPathIsSlash(path);
return new AclStatus.Builder().owner(ugi.getUserName())
.group(ugi.getGroupNames()[0])
.addEntries(AclUtil.getMinimalAcl(PERMISSION_555))
.stickyBit(false).build();
}
@Override
public void setXAttr(Path path, String name, byte[] value,
EnumSet<XAttrSetFlag> flag) throws IOException {
checkPathIsSlash(path);
throw readOnlyMountTable("setXAttr", path);
}
@Override
public byte[] getXAttr(Path path, String name) throws IOException {
throw new NotInMountpointException(path, "getXAttr");
}
@Override
public Map<String, byte[]> getXAttrs(Path path) throws IOException {
throw new NotInMountpointException(path, "getXAttrs");
}
@Override
public Map<String, byte[]> getXAttrs(Path path, List<String> names)
throws IOException {
throw new NotInMountpointException(path, "getXAttrs");
}
@Override
public List<String> listXAttrs(Path path) throws IOException {
throw new NotInMountpointException(path, "listXAttrs");
}
@Override
public void removeXAttr(Path path, String name) throws IOException {
checkPathIsSlash(path);
throw readOnlyMountTable("removeXAttr", path);
}
@Override
public Path createSnapshot(Path path, String snapshotName)
throws IOException {
checkPathIsSlash(path);
throw readOnlyMountTable("createSnapshot", path);
}
@Override
public void renameSnapshot(Path path, String snapshotOldName,
String snapshotNewName) throws IOException {
checkPathIsSlash(path);
throw readOnlyMountTable("renameSnapshot", path);
}
@Override
public void deleteSnapshot(Path path, String snapshotName)
throws IOException {
checkPathIsSlash(path);
throw readOnlyMountTable("deleteSnapshot", path);
}
@Override
public QuotaUsage getQuotaUsage(Path f) throws IOException {
throw new NotInMountpointException(f, "getQuotaUsage");
}
@Override
public void setStoragePolicy(Path src, String policyName)
throws IOException {
checkPathIsSlash(src);
throw readOnlyMountTable("setStoragePolicy", src);
}
@Override
public void unsetStoragePolicy(Path src) throws IOException {
checkPathIsSlash(src);
throw readOnlyMountTable("unsetStoragePolicy", src);
}
@Override
public BlockStoragePolicySpi getStoragePolicy(Path src) throws IOException {
throw new NotInMountpointException(src, "getStoragePolicy");
}
@Override
public Collection<? extends BlockStoragePolicySpi> getAllStoragePolicies()
throws IOException {
Collection<BlockStoragePolicySpi> allPolicies = new HashSet<>();
for (FileSystem fs : getChildFileSystems()) {
try {
Collection<? extends BlockStoragePolicySpi> policies =
fs.getAllStoragePolicies();
allPolicies.addAll(policies);
} catch (UnsupportedOperationException e) {
// ignored
}
}
return allPolicies;
}
}
}
|
/*
* Copyright 2012-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.auth;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
/**
* AWS credentials provider chain that looks for credentials in this order:
* <ul>
* <li>Environment Variables -
* <code>AWS_ACCESS_KEY_ID</code> and <code>AWS_SECRET_ACCESS_KEY</code>
* (RECOMMENDED since they are recognized by all the AWS SDKs and CLI except for .NET),
* or <code>AWS_ACCESS_KEY</code> and <code>AWS_SECRET_KEY</code> (only recognized by Java SDK)
* </li>
* <li>Java System Properties - aws.accessKeyId and aws.secretKey</li>
* <li>Credential profiles file at the default location (~/.aws/credentials) shared by all AWS SDKs and the AWS CLI</li>
* <li>Credentials delivered through the Amazon EC2 container service if AWS_CONTAINER_CREDENTIALS_RELATIVE_URI" environment variable is set
* and security manager has permission to access the variable,</li>
* <li>Instance profile credentials delivered through the Amazon EC2 metadata service</li>
* <li>Web Identity Token credentials from the environment or container.</li>
* </ul>
*
* @see EnvironmentVariableCredentialsProvider
* @see SystemPropertiesCredentialsProvider
* @see ProfileCredentialsProvider
* @see EC2ContainerCredentialsProviderWrapper
*/
public class DefaultAWSCredentialsProviderChain extends AWSCredentialsProviderChain {
private static final DefaultAWSCredentialsProviderChain INSTANCE
= new DefaultAWSCredentialsProviderChain();
public DefaultAWSCredentialsProviderChain() {
super(new EnvironmentVariableCredentialsProvider(),
new SystemPropertiesCredentialsProvider(),
new ProfileCredentialsProvider(),
WebIdentityTokenCredentialsProvider.create(),
new EC2ContainerCredentialsProviderWrapper());
}
public static DefaultAWSCredentialsProviderChain getInstance() {
return INSTANCE;
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.wicket.examples.authentication1;
import org.apache.wicket.Page;
import org.apache.wicket.RestartResponseAtInterceptPageException;
import org.apache.wicket.Session;
import org.apache.wicket.authorization.IAuthorizationStrategy;
import org.apache.wicket.examples.WicketExampleApplication;
import org.apache.wicket.request.Request;
import org.apache.wicket.request.Response;
import org.apache.wicket.request.component.IRequestableComponent;
/**
* Forms example.
*
* @author Jonathan Locke
*/
public final class SignInApplication extends WicketExampleApplication
{
@Override
public Class<? extends Page> getHomePage()
{
return Home.class;
}
@Override
public Session newSession(Request request, Response response)
{
return new SignInSession(request);
}
@Override
protected void init()
{
super.init();
// Register the authorization strategy
getSecuritySettings().setAuthorizationStrategy(new IAuthorizationStrategy.AllowAllAuthorizationStrategy()
{
@Override
public <T extends IRequestableComponent> boolean isInstantiationAuthorized(
Class<T> componentClass)
{
// Check if the new Page requires authentication (implements the marker interface)
if (AuthenticatedWebPage.class.isAssignableFrom(componentClass))
{
// Is user signed in?
if (((SignInSession)Session.get()).isSignedIn())
{
// okay to proceed
return true;
}
// Intercept the request, but remember the target for later.
// Invoke Component.continueToOriginalDestination() after successful logon to
// continue with the target remembered.
throw new RestartResponseAtInterceptPageException(SignIn.class);
}
// okay to proceed
return true;
}
});
}
}
|
/*
* Copyright 2013 Square, Inc.
* Copyright 2016 PKWARE, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pkware.truth.android.material.textfield;
import com.google.android.material.textfield.TextInputLayout;
import com.google.common.truth.FailureMetadata;
import com.pkware.truth.android.widget.AbstractLinearLayoutSubject;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* Propositions for {@link TextInputLayout} subjects.
*/
public class TextInputLayoutSubject extends AbstractLinearLayoutSubject<TextInputLayout> {
@Nullable
private final TextInputLayout actual;
public TextInputLayoutSubject(@Nonnull FailureMetadata failureMetadata, @Nullable TextInputLayout actual) {
super(failureMetadata, actual);
this.actual = actual;
}
public void hasError(@Nullable String error) {
CharSequence actualError = actual.getError();
String actualErrorString;
if (actualError == null) {
actualErrorString = null;
} else {
actualErrorString = actualError.toString();
}
check("getError()").that(actualErrorString).isEqualTo(error);
}
}
|
package io.minestack.velocity.proxy.server;
import java.util.Collection;
import java.util.Random;
public class RandomConnectionStrategy implements ConnectionStrategy {
private final Random random;
public RandomConnectionStrategy() {
this.random = new Random();
}
@Override
public RegisteredServerGroupServer getServerToConnect(Collection<RegisteredServerGroupServer> servers) {
return servers.stream().skip(this.random.nextInt(servers.size())).findFirst().orElseThrow();
}
}
|
/*
* Copyright 2017 Hippo B.V. (http://www.onehippo.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onehippo.cms7.crisp.core.resource;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import org.onehippo.cms7.crisp.api.resource.AbstractValueMap;
import org.onehippo.cms7.crisp.api.resource.ValueMap;
/**
* An empty, immutable {@link ValueMap} implementation.
*/
public class EmptyValueMap extends AbstractValueMap {
private static final long serialVersionUID = 1L;
/**
* Singleton immutable {@link EmptyValueMap} instance.
*/
private static final ValueMap INSTANCE = new EmptyValueMap();
/**
* Returns the singleton immutable {@link EmptyValueMap} instance.
* @return the singleton immutable {@link EmptyValueMap} instance
*/
public static ValueMap getInstance() {
return INSTANCE;
}
/**
* Default constructor.
*/
private EmptyValueMap() {
}
/**
* {@inheritDoc}
*/
@Override
public int size() {
return 0;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isEmpty() {
return true;
}
/**
* {@inheritDoc}
*/
@Override
public boolean containsKey(Object key) {
return false;
}
/**
* {@inheritDoc}
*/
@Override
public boolean containsValue(Object value) {
return false;
}
/**
* {@inheritDoc}
*/
@Override
public Object get(Object name) {
return null;
}
/**
* {@inheritDoc}
*/
@Override
public Object put(String key, Object value) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
@Override
public Object remove(Object key) {
return null;
}
/**
* {@inheritDoc}
*/
@Override
public void putAll(Map<? extends String, ? extends Object> m) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
@Override
public void clear() {
}
/**
* {@inheritDoc}
*/
@Override
public Set<String> keySet() {
return Collections.emptySet();
}
/**
* {@inheritDoc}
*/
@Override
public Collection<Object> values() {
return Collections.emptyList();
}
/**
* {@inheritDoc}
*/
@Override
public Set<java.util.Map.Entry<String, Object>> entrySet() {
return Collections.emptySet();
}
}
|
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.hive.util;
import com.facebook.presto.common.NotSupportedException;
import com.facebook.presto.common.Page;
import com.facebook.presto.common.io.DataSink;
import com.facebook.presto.common.type.Type;
import com.facebook.presto.orc.DefaultOrcWriterFlushPolicy;
import com.facebook.presto.orc.NoOpOrcWriterStats;
import com.facebook.presto.orc.OrcWriteValidation.OrcWriteValidationMode;
import com.facebook.presto.orc.OrcWriter;
import com.facebook.presto.orc.OrcWriterOptions;
import com.facebook.presto.spi.PrestoException;
import com.google.common.collect.ImmutableMap;
import io.airlift.units.DataSize;
import java.io.Closeable;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.List;
import java.util.Optional;
import java.util.stream.IntStream;
import static com.facebook.presto.orc.DwrfEncryptionProvider.NO_ENCRYPTION;
import static com.facebook.presto.orc.OrcEncoding.ORC;
import static com.facebook.presto.orc.metadata.CompressionKind.LZ4;
import static com.facebook.presto.spi.StandardErrorCode.NOT_SUPPORTED;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static io.airlift.units.DataSize.Unit.BYTE;
import static io.airlift.units.DataSize.Unit.MEGABYTE;
import static org.joda.time.DateTimeZone.UTC;
public class TempFileWriter
implements Closeable
{
private final OrcWriter orcWriter;
public TempFileWriter(List<Type> types, DataSink sink)
{
this.orcWriter = createOrcFileWriter(sink, types);
}
public void writePage(Page page)
{
try {
orcWriter.write(page);
}
catch (IOException e) {
throw new UncheckedIOException(e);
}
}
@Override
public void close()
throws IOException
{
orcWriter.close();
}
public long getWrittenBytes()
{
return orcWriter.getWrittenBytes();
}
private static OrcWriter createOrcFileWriter(DataSink sink, List<Type> types)
{
List<String> columnNames = IntStream.range(0, types.size())
.mapToObj(String::valueOf)
.collect(toImmutableList());
try {
return new OrcWriter(
sink,
columnNames,
types,
ORC,
LZ4,
Optional.empty(),
NO_ENCRYPTION,
OrcWriterOptions.builder()
.withMaxStringStatisticsLimit(new DataSize(0, BYTE))
.withFlushPolicy(DefaultOrcWriterFlushPolicy.builder()
.withStripeMinSize(new DataSize(64, MEGABYTE))
.build())
.withDictionaryMaxMemory(new DataSize(1, MEGABYTE))
.build(),
ImmutableMap.of(),
UTC,
false,
OrcWriteValidationMode.BOTH,
new NoOpOrcWriterStats());
}
catch (NotSupportedException e) {
throw new PrestoException(NOT_SUPPORTED, e.getMessage(), e);
}
}
}
|
/*
* Decompiled with CFR 0.151.
*
* Could not load the following classes:
* net.minecraft.entity.Entity
* net.minecraftforge.common.MinecraftForge
* net.minecraftforge.fml.common.eventhandler.Event
*/
package dev.cuican.staypro.mixin.entity;
import dev.cuican.staypro.Stay;
import dev.cuican.staypro.event.events.client.LandStepEvent;
import dev.cuican.staypro.event.events.client.MoveEvent;
import dev.cuican.staypro.event.events.client.PushEvent;
import dev.cuican.staypro.event.events.client.StepEvent;
import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.entity.Entity;
import net.minecraft.entity.MoverType;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.common.eventhandler.Event;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.ModifyVariable;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(value={Entity.class}, priority=998)
public abstract class MixinEntity {
@Redirect(method={"applyEntityCollision"}, at=@At(value="INVOKE", target="Lnet/minecraft/entity/Entity;addVelocity(DDD)V",ordinal = 0))
public void addVelocityHook(Entity entity, double x, double y, double z) {
PushEvent event = new PushEvent( entity, x, y, z, true);
MinecraftForge.EVENT_BUS.post(event);
if (event.isCanceled()) {
return;
}
entity.motionX += event.x;
entity.motionY += event.y;
entity.motionZ += event.z;
entity.isAirBorne = event.airbone;
}
@Shadow
public void move(MoverType type, double x, double y, double z) {
}
@Inject(method={"move"}, at=@At(value="HEAD"))
public void onMovePre(MoverType type, double x, double y, double z, CallbackInfo ci) {
Entity entity = mc.player;
if (!(entity instanceof EntityPlayerSP)) return;
this.moveEvent = new MoveEvent(type, x, y, z, entity.isSneaking());
Stay.EVENT_BUS.post(moveEvent);
}
@ModifyVariable(method={"move"}, at=@At(value="HEAD"), ordinal=0)
private double onMoveX(double x) {
if (this.moveEvent == null) return x;
return this.moveEvent.getX();
}
@ModifyVariable(method={"move"}, at=@At(value="HEAD"), ordinal=1)
private double onMoveY(double y) {
if (this.moveEvent == null) return y;
return this.moveEvent.getY();
}
@ModifyVariable(method={"move"}, at=@At(value="HEAD"), ordinal=2)
private double onMoveZ(double z) {
if (this.moveEvent == null) return z;
return this.moveEvent.getZ();
}
@Redirect(method={"move"}, at=@At(value="INVOKE", target="net/minecraft/entity/Entity.isSneaking()Z", ordinal=0))
private boolean onMoveSneaking(Entity entity) {
boolean bl;
if (this.moveEvent != null) {
bl = this.moveEvent.isSneaking();
return bl;
}
bl = entity.isSneaking();
return bl;
}
@Inject(method={"move"}, at=@At(value="RETURN"))
public void onMovePost(MoverType type, double x, double y, double z, CallbackInfo ci) {
this.moveEvent = null;
}
@Inject(method={"move"}, at=@At(value="FIELD", target="Lnet/minecraft/entity/Entity;stepHeight:F", shift=At.Shift.BEFORE, ordinal=3))
private void onInjectStepPre(MoverType type, double x, double y, double z, CallbackInfo ci) {
this.cachedStepHeight = this.stepHeight;
this.stepEvent = new StepEvent( this.stepHeight);
Stay.EVENT_BUS.post(this.stepEvent);
}
@Shadow
public float stepHeight;
private StepEvent stepEvent;
private float cachedStepHeight;
@Inject(method={"move"}, at=@At(value="FIELD", target="Lnet/minecraft/entity/Entity;stepHeight:F", ordinal=4, shift=At.Shift.BEFORE), require=1)
private void onInjectStepPre(CallbackInfo ci) {
this.stepHeight = this.stepEvent.getHeight();
}
@Inject(method={"move"}, at=@At(value="INVOKE", target="Lnet/minecraft/profiler/Profiler;endSection()V", shift=At.Shift.BEFORE, ordinal=0))
private void onInjectStepEventPost(CallbackInfo ci) {
this.stepHeight = this.cachedStepHeight;
Stay.EVENT_BUS.post(new StepEvent(this.stepHeight));
}
@Inject(method={"move"}, at=@At(value="FIELD", target="net/minecraft/entity/Entity.onGround:Z", ordinal=1))
private void onStepGround(MoverType type, double x, double y, double z, CallbackInfo ci) {
Entity entity = mc.player;
if (!(entity instanceof EntityPlayerSP)) return;
LandStepEvent event = new LandStepEvent(this.getEntityBoundingBox(), entity.stepHeight);
Stay.EVENT_BUS.post(event);
entity.stepHeight = event.getStepHeight();
}
protected Minecraft mc = Minecraft.getMinecraft();
private MoveEvent moveEvent;
@Shadow
public double motionX;
@Shadow
public double motionY;
@Shadow
public double motionZ;
@Shadow
public abstract AxisAlignedBB getEntityBoundingBox();
}
|
package example.com.pkmnavidemo4.FriendPage;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
public class Cn2Spell {
public static StringBuffer sb = new StringBuffer();
/**
* 获取汉字字符串的首字母,英文字符不变
* 例如:阿飞→af
*/
public static String getPinYinHeadChar(String chines) {
sb.setLength(0);
char[] chars = chines.toCharArray();
HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
for (int i = 0; i < chars.length; i++) {
if (chars[i] > 128) {
try {
sb.append(PinyinHelper.toHanyuPinyinStringArray(chars[i], defaultFormat)[0].charAt(0));
} catch (Exception e) {
e.printStackTrace();
}
} else {
sb.append(chars[i]);
}
}
return sb.toString();
}
/**
* 获取汉字字符串的第一个字母
*/
public static String getPinYinFirstLetter(String str) {
sb.setLength(0);
char c = str.charAt(0);
String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(c);
if (pinyinArray != null) {
sb.append(pinyinArray[0].charAt(0));
} else {
sb.append(c);
}
return sb.toString();
}
/**
* 获取汉字字符串的汉语拼音,英文字符不变
*/
public static String getPinYin(String chines) {
sb.setLength(0);
char[] nameChar = chines.toCharArray();
HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
for (int i = 0; i < nameChar.length; i++) {
if (nameChar[i] > 128) {
try {
sb.append(PinyinHelper.toHanyuPinyinStringArray(nameChar[i], defaultFormat)[0]);
} catch (Exception e) {
e.printStackTrace();
}
} else {
sb.append(nameChar[i]);
}
}
return sb.toString();
}
}
|
package com.macro.mall.model;
import java.io.Serializable;
public class CmsTopicCategory implements Serializable {
private Long id;
private String name;
private String icon;
private Integer subjectCount;
private Integer showStatus;
private Integer sort;
private static final long serialVersionUID = 1L;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public Integer getSubjectCount() {
return subjectCount;
}
public void setSubjectCount(Integer subjectCount) {
this.subjectCount = subjectCount;
}
public Integer getShowStatus() {
return showStatus;
}
public void setShowStatus(Integer showStatus) {
this.showStatus = showStatus;
}
public Integer getSort() {
return sort;
}
public void setSort(Integer sort) {
this.sort = sort;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", name=").append(name);
sb.append(", icon=").append(icon);
sb.append(", subjectCount=").append(subjectCount);
sb.append(", showStatus=").append(showStatus);
sb.append(", sort=").append(sort);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
|
// **********************************************************************
// This file was generated by a TAF parser!
// TAF version 3.0.0.34 by WSRD Tencent.
// Generated from `/usr/local/resin_system.mqq.com/webapps/communication/taf/upload/noahyang/you.jce'
// **********************************************************************
package com.qq.jce.MAAccess;
public final class AddTapAppReqHolder
{
public AddTapAppReqHolder()
{
}
public AddTapAppReqHolder(AddTapAppReq value)
{
this.value = value;
}
public AddTapAppReq value;
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hudi.sink;
import org.apache.hudi.client.HoodieFlinkWriteClient;
import org.apache.hudi.client.WriteStatus;
import org.apache.hudi.common.model.HoodieTableType;
import org.apache.hudi.common.model.WriteOperationType;
import org.apache.hudi.common.table.timeline.HoodieActiveTimeline;
import org.apache.hudi.common.table.timeline.HoodieTimeline;
import org.apache.hudi.common.util.CommitUtils;
import org.apache.hudi.common.util.Option;
import org.apache.hudi.common.util.ValidationUtils;
import org.apache.hudi.configuration.FlinkOptions;
import org.apache.hudi.exception.HoodieException;
import org.apache.hudi.sink.event.CommitAckEvent;
import org.apache.hudi.sink.event.WriteMetadataEvent;
import org.apache.hudi.sink.utils.CoordinatorExecutor;
import org.apache.hudi.sink.utils.HiveSyncContext;
import org.apache.hudi.sink.utils.NonThrownExecutor;
import org.apache.hudi.util.StreamerUtil;
import org.apache.flink.annotation.VisibleForTesting;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.runtime.jobgraph.OperatorID;
import org.apache.flink.runtime.operators.coordination.OperatorCoordinator;
import org.apache.flink.runtime.operators.coordination.OperatorEvent;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static org.apache.hudi.util.StreamerUtil.initTableIfNotExists;
/**
* {@link OperatorCoordinator} for {@link StreamWriteFunction}.
*
* <p>This coordinator starts a new instant when a new checkpoint starts. It commits the instant when all the
* operator tasks write the buffer successfully for a round of checkpoint.
*
* <p>If there is no data for a round of checkpointing, it resets the events buffer and returns early.
*
* @see StreamWriteFunction for the work flow and semantics
*/
public class StreamWriteOperatorCoordinator
implements OperatorCoordinator {
private static final Logger LOG = LoggerFactory.getLogger(StreamWriteOperatorCoordinator.class);
/**
* Config options.
*/
private final Configuration conf;
/**
* Coordinator context.
*/
private final Context context;
/**
* Gateways for sending events to sub tasks.
*/
private transient SubtaskGateway[] gateways;
/**
* Write client.
*/
private transient HoodieFlinkWriteClient writeClient;
/**
* Current REQUESTED instant, for validation.
*/
private volatile String instant = WriteMetadataEvent.BOOTSTRAP_INSTANT;
/**
* Event buffer for one round of checkpointing. When all the elements are non-null and have the same
* write instant, then the instant succeed and we can commit it.
*/
private transient WriteMetadataEvent[] eventBuffer;
/**
* Task number of the operator.
*/
private final int parallelism;
/**
* A single-thread executor to handle all the asynchronous jobs of the coordinator.
*/
private CoordinatorExecutor executor;
/**
* A single-thread executor to handle asynchronous hive sync.
*/
private NonThrownExecutor hiveSyncExecutor;
/**
* Context that holds variables for asynchronous hive sync.
*/
private HiveSyncContext hiveSyncContext;
/**
* A single-thread executor to handle metadata table sync.
*/
private NonThrownExecutor metadataSyncExecutor;
/**
* The table state.
*/
private transient TableState tableState;
/**
* Constructs a StreamingSinkOperatorCoordinator.
*
* @param conf The config options
* @param context The coordinator context
*/
public StreamWriteOperatorCoordinator(
Configuration conf,
Context context) {
this.conf = conf;
this.context = context;
this.parallelism = context.currentParallelism();
}
@Override
public void start() throws Exception {
// initialize event buffer
reset();
this.gateways = new SubtaskGateway[this.parallelism];
this.writeClient = StreamerUtil.createWriteClient(conf);
this.tableState = TableState.create(conf);
// init table, create it if not exists.
initTableIfNotExists(this.conf);
// start the executor
this.executor = new CoordinatorExecutor(this.context, LOG);
// start the executor if required
if (tableState.syncHive) {
initHiveSync();
}
if (tableState.syncMetadata) {
initMetadataSync();
}
}
@Override
public void close() throws Exception {
// teardown the resource
if (writeClient != null) {
writeClient.close();
}
if (executor != null) {
executor.close();
}
if (hiveSyncExecutor != null) {
hiveSyncExecutor.close();
}
this.eventBuffer = null;
}
@Override
public void checkpointCoordinator(long checkpointId, CompletableFuture<byte[]> result) {
executor.execute(
() -> {
try {
result.complete(new byte[0]);
} catch (Throwable throwable) {
// when a checkpoint fails, throws directly.
result.completeExceptionally(
new CompletionException(
String.format("Failed to checkpoint Instant %s for source %s",
this.instant, this.getClass().getSimpleName()), throwable));
}
}, "taking checkpoint %d", checkpointId
);
}
@Override
public void notifyCheckpointComplete(long checkpointId) {
executor.execute(
() -> {
// for streaming mode, commits the ever received events anyway,
// the stream write task snapshot and flush the data buffer synchronously in sequence,
// so a successful checkpoint subsumes the old one(follows the checkpoint subsuming contract)
final boolean committed = commitInstant(this.instant);
if (committed) {
// if async compaction is on, schedule the compaction
if (tableState.scheduleCompaction) {
writeClient.scheduleCompaction(Option.empty());
}
// start new instant.
startInstant();
// sync Hive if is enabled
syncHiveIfEnabled();
// sync metadata if is enabled
syncMetadataIfEnabled();
}
}, "commits the instant %s", this.instant
);
}
@Override
public void resetToCheckpoint(long checkpointID, byte[] checkpointData) {
// no operation
}
@Override
public void handleEventFromOperator(int i, OperatorEvent operatorEvent) {
executor.execute(
() -> {
// no event to handle
ValidationUtils.checkState(operatorEvent instanceof WriteMetadataEvent,
"The coordinator can only handle WriteMetaEvent");
WriteMetadataEvent event = (WriteMetadataEvent) operatorEvent;
if (event.isBootstrap()) {
handleBootstrapEvent(event);
} else if (event.isEndInput()) {
handleEndInputEvent(event);
} else {
handleWriteMetaEvent(event);
}
}, "handle write metadata event for instant %s", this.instant
);
}
@Override
public void subtaskFailed(int i, @Nullable Throwable throwable) {
// reset the event
this.eventBuffer[i] = null;
LOG.warn("Reset the event for task [" + i + "]", throwable);
}
@Override
public void subtaskReset(int i, long l) {
// no operation
}
@Override
public void subtaskReady(int i, SubtaskGateway subtaskGateway) {
this.gateways[i] = subtaskGateway;
}
// -------------------------------------------------------------------------
// Utilities
// -------------------------------------------------------------------------
private void initHiveSync() {
this.hiveSyncExecutor = new NonThrownExecutor(LOG, true);
this.hiveSyncContext = HiveSyncContext.create(conf);
}
private void syncHiveIfEnabled() {
if (tableState.syncHive) {
this.hiveSyncExecutor.execute(this::syncHive, "sync hive metadata for instant %s", this.instant);
}
}
/**
* Sync hoodie table metadata to Hive metastore.
*/
public void syncHive() {
hiveSyncContext.hiveSyncTool().syncHoodieTable();
}
private void initMetadataSync() {
this.metadataSyncExecutor = new NonThrownExecutor(LOG, true);
}
/**
* Sync the write metadata to the metadata table.
*/
private void syncMetadataIfEnabled() {
if (tableState.syncMetadata) {
this.metadataSyncExecutor.execute(this::syncMetadata,
"sync metadata table for instant %s", this.instant);
}
}
/**
* Sync the write metadata to the metadata table.
*/
private void syncMetadata() {
this.writeClient.syncTableMetadata();
}
private void reset() {
this.eventBuffer = new WriteMetadataEvent[this.parallelism];
}
/**
* Checks the buffer is ready to commit.
*/
private boolean allEventsReceived() {
return Arrays.stream(eventBuffer)
.allMatch(event -> event != null && event.isReady(this.instant));
}
private void addEventToBuffer(WriteMetadataEvent event) {
if (this.eventBuffer[event.getTaskID()] != null) {
this.eventBuffer[event.getTaskID()].mergeWith(event);
} else {
this.eventBuffer[event.getTaskID()] = event;
}
}
private void startInstant() {
final String instant = HoodieActiveTimeline.createNewInstantTime();
this.writeClient.startCommitWithTime(instant, tableState.commitAction);
this.instant = instant;
this.writeClient.transitionRequestedToInflight(tableState.commitAction, this.instant);
this.writeClient.upgradeDowngrade(this.instant);
LOG.info("Create instant [{}] for table [{}] with type [{}]", this.instant,
this.conf.getString(FlinkOptions.TABLE_NAME), conf.getString(FlinkOptions.TABLE_TYPE));
}
/**
* Initializes the instant.
*
* <p>Recommits the last inflight instant if the write metadata checkpoint successfully
* but was not committed due to some rare cases.
*
* <p>Starts a new instant, a writer can not flush data buffer
* until it finds a new inflight instant on the timeline.
*/
private void initInstant(String instant) {
HoodieTimeline completedTimeline =
StreamerUtil.createMetaClient(conf).getActiveTimeline().filterCompletedInstants();
executor.execute(() -> {
if (instant.equals("") || completedTimeline.containsInstant(instant)) {
// the last instant committed successfully
reset();
} else {
LOG.info("Recommit instant {}", instant);
commitInstant(instant);
}
if (tableState.syncMetadata) {
// initialize metadata table first if enabled
// condition: the data set timeline has committed instants
syncMetadata();
}
// starts a new instant
startInstant();
}, "initialize instant %s", instant);
}
private void handleBootstrapEvent(WriteMetadataEvent event) {
this.eventBuffer[event.getTaskID()] = event;
if (Arrays.stream(eventBuffer).allMatch(evt -> evt != null && evt.isBootstrap())) {
// start to initialize the instant.
initInstant(event.getInstantTime());
}
}
private void handleEndInputEvent(WriteMetadataEvent event) {
addEventToBuffer(event);
if (allEventsReceived()) {
// start to commit the instant.
commitInstant(this.instant);
// sync Hive if is enabled in batch mode.
syncHiveIfEnabled();
// sync metadata if is enabled in batch mode.
syncMetadataIfEnabled();
}
}
private void handleWriteMetaEvent(WriteMetadataEvent event) {
// the write task does not block after checkpointing(and before it receives a checkpoint success event),
// if it checkpoints succeed then flushes the data buffer again before this coordinator receives a checkpoint
// success event, the data buffer would flush with an older instant time.
ValidationUtils.checkState(
HoodieTimeline.compareTimestamps(this.instant, HoodieTimeline.GREATER_THAN_OR_EQUALS, event.getInstantTime()),
String.format("Receive an unexpected event for instant %s from task %d",
event.getInstantTime(), event.getTaskID()));
addEventToBuffer(event);
}
/**
* The coordinator reuses the instant if there is no data for this round of checkpoint,
* sends the commit ack events to unblock the flushing.
*/
private void sendCommitAckEvents() {
CompletableFuture<?>[] futures = IntStream.range(0, this.parallelism)
.mapToObj(taskID -> this.gateways[taskID].sendEvent(CommitAckEvent.getInstance()))
.toArray(CompletableFuture<?>[]::new);
try {
CompletableFuture.allOf(futures).get();
} catch (Exception e) {
throw new HoodieException("Error while waiting for the commit ack events to finish sending", e);
}
}
/**
* Commits the instant.
*
* @return true if the write statuses are committed successfully.
*/
private boolean commitInstant(String instant) {
if (Arrays.stream(eventBuffer).allMatch(Objects::isNull)) {
// The last checkpoint finished successfully.
return false;
}
List<WriteStatus> writeResults = Arrays.stream(eventBuffer)
.filter(Objects::nonNull)
.map(WriteMetadataEvent::getWriteStatuses)
.flatMap(Collection::stream)
.collect(Collectors.toList());
if (writeResults.size() == 0) {
// No data has written, reset the buffer and returns early
reset();
// Send commit ack event to the write function to unblock the flushing
sendCommitAckEvents();
return false;
}
doCommit(instant, writeResults);
return true;
}
/**
* Performs the actual commit action.
*/
@SuppressWarnings("unchecked")
private void doCommit(String instant, List<WriteStatus> writeResults) {
// commit or rollback
long totalErrorRecords = writeResults.stream().map(WriteStatus::getTotalErrorRecords).reduce(Long::sum).orElse(0L);
long totalRecords = writeResults.stream().map(WriteStatus::getTotalRecords).reduce(Long::sum).orElse(0L);
boolean hasErrors = totalErrorRecords > 0;
if (!hasErrors || this.conf.getBoolean(FlinkOptions.IGNORE_FAILED)) {
HashMap<String, String> checkpointCommitMetadata = new HashMap<>();
if (hasErrors) {
LOG.warn("Some records failed to merge but forcing commit since commitOnErrors set to true. Errors/Total="
+ totalErrorRecords + "/" + totalRecords);
}
final Map<String, List<String>> partitionToReplacedFileIds = tableState.isOverwrite
? writeClient.getPartitionToReplacedFileIds(tableState.operationType, writeResults)
: Collections.emptyMap();
boolean success = writeClient.commit(instant, writeResults, Option.of(checkpointCommitMetadata),
tableState.commitAction, partitionToReplacedFileIds);
if (success) {
reset();
LOG.info("Commit instant [{}] success!", instant);
} else {
throw new HoodieException(String.format("Commit instant [%s] failed!", instant));
}
} else {
LOG.error("Error when writing. Errors/Total=" + totalErrorRecords + "/" + totalRecords);
LOG.error("The first 100 error messages");
writeResults.stream().filter(WriteStatus::hasErrors).limit(100).forEach(ws -> {
LOG.error("Global error for partition path {} and fileID {}: {}",
ws.getGlobalError(), ws.getPartitionPath(), ws.getFileId());
if (ws.getErrors().size() > 0) {
ws.getErrors().forEach((key, value) -> LOG.trace("Error for key:" + key + " and value " + value));
}
});
// Rolls back instant
writeClient.rollback(instant);
throw new HoodieException(String.format("Commit instant [%s] failed and rolled back !", instant));
}
}
@VisibleForTesting
public WriteMetadataEvent[] getEventBuffer() {
return eventBuffer;
}
@VisibleForTesting
public String getInstant() {
return instant;
}
@VisibleForTesting
@SuppressWarnings("rawtypes")
public HoodieFlinkWriteClient getWriteClient() {
return writeClient;
}
@VisibleForTesting
public Context getContext() {
return context;
}
@VisibleForTesting
public void setExecutor(CoordinatorExecutor executor) throws Exception {
if (this.executor != null) {
this.executor.close();
}
this.executor = executor;
}
@VisibleForTesting
public void setMetadataSyncExecutor(NonThrownExecutor executor) throws Exception {
if (this.metadataSyncExecutor != null) {
this.metadataSyncExecutor.close();
}
this.metadataSyncExecutor = executor;
}
// -------------------------------------------------------------------------
// Inner Class
// -------------------------------------------------------------------------
/**
* Provider for {@link StreamWriteOperatorCoordinator}.
*/
public static class Provider implements OperatorCoordinator.Provider {
private final OperatorID operatorId;
private final Configuration conf;
public Provider(OperatorID operatorId, Configuration conf) {
this.operatorId = operatorId;
this.conf = conf;
}
@Override
public OperatorID getOperatorId() {
return this.operatorId;
}
@Override
public OperatorCoordinator create(Context context) {
return new StreamWriteOperatorCoordinator(this.conf, context);
}
}
/**
* Remember some table state variables.
*/
private static class TableState implements Serializable {
private static final long serialVersionUID = 1L;
final WriteOperationType operationType;
final String commitAction;
final boolean isOverwrite;
final boolean scheduleCompaction;
final boolean syncHive;
final boolean syncMetadata;
private TableState(Configuration conf) {
this.operationType = WriteOperationType.fromValue(conf.getString(FlinkOptions.OPERATION));
this.commitAction = CommitUtils.getCommitActionType(this.operationType,
HoodieTableType.valueOf(conf.getString(FlinkOptions.TABLE_TYPE).toUpperCase(Locale.ROOT)));
this.isOverwrite = WriteOperationType.isOverwrite(this.operationType);
this.scheduleCompaction = StreamerUtil.needsScheduleCompaction(conf);
this.syncHive = conf.getBoolean(FlinkOptions.HIVE_SYNC_ENABLED);
this.syncMetadata = conf.getBoolean(FlinkOptions.METADATA_ENABLED);
}
public static TableState create(Configuration conf) {
return new TableState(conf);
}
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ranger.plugin.util;
import java.util.HashMap;
import java.util.Map;
public class StringTokenReplacer {
private final char startChar;
private final char endChar;
private final char escapeChar;
private final String tokenPrefix;
public StringTokenReplacer(char startChar, char endChar, char escapeChar, String tokenPrefix) {
this.startChar = startChar;
this.endChar = endChar;
this.escapeChar = escapeChar;
this.tokenPrefix = tokenPrefix;
}
public String replaceTokens(String value, Map<String, Object> tokens) {
if(tokens == null || tokens.size() < 1 || value == null || value.length() < 1 ||
(value.indexOf(startChar) == -1 && value.indexOf(endChar) == -1 && value.indexOf(escapeChar) == -1)) {
return value;
}
StringBuilder ret = new StringBuilder();
StringBuilder token = null;
for(int i = 0; i < value.length(); i++) {
char c = value.charAt(i);
if(c == escapeChar) {
i++;
if(i < value.length()) {
c = value.charAt(i);
if(token != null) {
token.append(c);
} else {
ret.append(c);
}
}
continue;
}
if(token == null) { // not in token
if(c == startChar) {
token = new StringBuilder();
} else {
ret.append(c);
}
} else { // in token
if(c == endChar) {
String rawToken = token.toString();
if (tokenPrefix.length() == 0 || rawToken.startsWith(tokenPrefix)) {
Object replaced = RangerAccessRequestUtil.getTokenFromContext(tokens, rawToken.substring(tokenPrefix.length()));
if (replaced != null) {
ret.append(replaced.toString());
}
} else {
ret.append(startChar).append(token).append(endChar);
}
token = null;
} else {
token.append(c);
}
}
}
if(token != null) { // if no endChar is found
ret.append(startChar).append(token);
}
return ret.toString();
}
public static void main(String[] args) {
char startChar = '%';
char endChar = '%';
char escapeChar = '\\';
String tokenPrefix = "ranger:";
Map<String, Object> tokens = new HashMap<String, Object>();
tokens.put("USER", "testUser");
tokens.put("COUNTRY", "USA");
tokens.put("STATE", "CA");
tokens.put("CITY", "Santa Clara");
StringTokenReplacer tokenReplacer = new StringTokenReplacer(startChar, endChar, escapeChar, tokenPrefix);
if(args.length == 0) {
args = new String[] {
"/home/%USER%/*",
"/home/%ranger:USER%/*",
"tmp_%USER%",
"tmp_%ranger:USER%",
"%USER%_db",
"%ranger:USER%_db",
"\\%USER_db",
"\\%ranger:USER_db",
"\\%USER%_db",
"\\%ranger:USER%_db",
};
}
for(String str : args) {
System.out.println(str + " ==> " + tokenReplacer.replaceTokens(str, tokens));
}
}}
|
package arrays;
// Selection sorting is better and more efficient than Bubble sorting
public class SelectionSort {
public static void main(String[] args) {
int a[] = {3, 1, -2, 7, 4, 0};
int n = a.length;
for(int i = 0; i < n-1; i++) {
int minIndex = i;
for(int j = i; j < n; j++) {
if(a[j] < a[minIndex]) {
minIndex = j;
}
}
int t = a[i];
a[i] = a[minIndex];
a[minIndex] = t;
}
for(int e: a) {
System.out.print(e+" ");
}
}
}
|
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.util.comparator;
import java.util.Comparator;
/**
* Comparator that adapts Comparables to the Comparator interface.
* Mainly for internal use in other Comparators, when supposed
* to work on Comparables.
*
* @author Keith Donald
* @since 1.2.2
* @see Comparable
*/
public class ComparableComparator<T extends Comparable<T>> implements Comparator<T> {
@SuppressWarnings("rawtypes")
public static final ComparableComparator INSTANCE = new ComparableComparator();
public int compare(T o1, T o2) {
return o1.compareTo(o2);
}
}
|
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */
end_comment
begin_package
DECL|package|org.apache.camel.builder.endpoint.dsl
package|package
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|builder
operator|.
name|endpoint
operator|.
name|dsl
package|;
end_package
begin_import
import|import
name|javax
operator|.
name|annotation
operator|.
name|Generated
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|ExchangePattern
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|builder
operator|.
name|EndpointConsumerBuilder
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|builder
operator|.
name|EndpointProducerBuilder
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|builder
operator|.
name|endpoint
operator|.
name|AbstractEndpointBuilder
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|spi
operator|.
name|ExceptionHandler
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|spi
operator|.
name|HeaderFilterStrategy
import|;
end_import
begin_comment
comment|/** * To use a HTTP Servlet as entry for Camel routes when running in a servlet * container. * * Generated by camel-package-maven-plugin - do not edit this file! */
end_comment
begin_interface
annotation|@
name|Generated
argument_list|(
literal|"org.apache.camel.maven.packaging.EndpointDslMojo"
argument_list|)
DECL|interface|ServletEndpointBuilderFactory
specifier|public
interface|interface
name|ServletEndpointBuilderFactory
block|{
comment|/** * Builder for endpoint for the Servlet component. */
DECL|interface|ServletEndpointBuilder
specifier|public
interface|interface
name|ServletEndpointBuilder
extends|extends
name|EndpointConsumerBuilder
block|{
DECL|method|advanced ()
specifier|default
name|AdvancedServletEndpointBuilder
name|advanced
parameter_list|()
block|{
return|return
operator|(
name|AdvancedServletEndpointBuilder
operator|)
name|this
return|;
block|}
comment|/** * Determines whether or not the raw input stream from Servlet is cached * or not (Camel will read the stream into a in memory/overflow to file, * Stream caching) cache. By default Camel will cache the Servlet input * stream to support reading it multiple times to ensure it Camel can * retrieve all data from the stream. However you can set this option to * true when you for example need to access the raw stream, such as * streaming it directly to a file or other persistent store. * DefaultHttpBinding will copy the request input stream into a stream * cache and put it into message body if this option is false to support * reading the stream multiple times. If you use Servlet to bridge/proxy * an endpoint then consider enabling this option to improve * performance, in case you do not need to read the message payload * multiple times. The http producer will by default cache the response * body stream. If setting this option to true, then the producers will * not cache the response body stream but use the response stream as-is * as the message body. * * The option is a:<code>boolean</code> type. * * Group: common */
DECL|method|disableStreamCache ( boolean disableStreamCache)
specifier|default
name|ServletEndpointBuilder
name|disableStreamCache
parameter_list|(
name|boolean
name|disableStreamCache
parameter_list|)
block|{
name|doSetProperty
argument_list|(
literal|"disableStreamCache"
argument_list|,
name|disableStreamCache
argument_list|)
expr_stmt|;
return|return
name|this
return|;
block|}
comment|/** * Determines whether or not the raw input stream from Servlet is cached * or not (Camel will read the stream into a in memory/overflow to file, * Stream caching) cache. By default Camel will cache the Servlet input * stream to support reading it multiple times to ensure it Camel can * retrieve all data from the stream. However you can set this option to * true when you for example need to access the raw stream, such as * streaming it directly to a file or other persistent store. * DefaultHttpBinding will copy the request input stream into a stream * cache and put it into message body if this option is false to support * reading the stream multiple times. If you use Servlet to bridge/proxy * an endpoint then consider enabling this option to improve * performance, in case you do not need to read the message payload * multiple times. The http producer will by default cache the response * body stream. If setting this option to true, then the producers will * not cache the response body stream but use the response stream as-is * as the message body. * * The option will be converted to a<code>boolean</code> type. * * Group: common */
DECL|method|disableStreamCache ( String disableStreamCache)
specifier|default
name|ServletEndpointBuilder
name|disableStreamCache
parameter_list|(
name|String
name|disableStreamCache
parameter_list|)
block|{
name|doSetProperty
argument_list|(
literal|"disableStreamCache"
argument_list|,
name|disableStreamCache
argument_list|)
expr_stmt|;
return|return
name|this
return|;
block|}
comment|/** * To use a custom HeaderFilterStrategy to filter header to and from * Camel message. * * The option is a: *<code>org.apache.camel.spi.HeaderFilterStrategy</code> type. * * Group: common */
DECL|method|headerFilterStrategy ( HeaderFilterStrategy headerFilterStrategy)
specifier|default
name|ServletEndpointBuilder
name|headerFilterStrategy
parameter_list|(
name|HeaderFilterStrategy
name|headerFilterStrategy
parameter_list|)
block|{
name|doSetProperty
argument_list|(
literal|"headerFilterStrategy"
argument_list|,
name|headerFilterStrategy
argument_list|)
expr_stmt|;
return|return
name|this
return|;
block|}
comment|/** * To use a custom HeaderFilterStrategy to filter header to and from * Camel message. * * The option will be converted to a *<code>org.apache.camel.spi.HeaderFilterStrategy</code> type. * * Group: common */
DECL|method|headerFilterStrategy ( String headerFilterStrategy)
specifier|default
name|ServletEndpointBuilder
name|headerFilterStrategy
parameter_list|(
name|String
name|headerFilterStrategy
parameter_list|)
block|{
name|doSetProperty
argument_list|(
literal|"headerFilterStrategy"
argument_list|,
name|headerFilterStrategy
argument_list|)
expr_stmt|;
return|return
name|this
return|;
block|}
comment|/** * Configure the consumer to work in async mode. * * The option is a:<code>boolean</code> type. * * Group: consumer */
DECL|method|async (boolean async)
specifier|default
name|ServletEndpointBuilder
name|async
parameter_list|(
name|boolean
name|async
parameter_list|)
block|{
name|doSetProperty
argument_list|(
literal|"async"
argument_list|,
name|async
argument_list|)
expr_stmt|;
return|return
name|this
return|;
block|}
comment|/** * Configure the consumer to work in async mode. * * The option will be converted to a<code>boolean</code> type. * * Group: consumer */
DECL|method|async (String async)
specifier|default
name|ServletEndpointBuilder
name|async
parameter_list|(
name|String
name|async
parameter_list|)
block|{
name|doSetProperty
argument_list|(
literal|"async"
argument_list|,
name|async
argument_list|)
expr_stmt|;
return|return
name|this
return|;
block|}
comment|/** * Allows for bridging the consumer to the Camel routing Error Handler, * which mean any exceptions occurred while the consumer is trying to * pickup incoming messages, or the likes, will now be processed as a * message and handled by the routing Error Handler. By default the * consumer will use the org.apache.camel.spi.ExceptionHandler to deal * with exceptions, that will be logged at WARN or ERROR level and * ignored. * * The option is a:<code>boolean</code> type. * * Group: consumer */
DECL|method|bridgeErrorHandler ( boolean bridgeErrorHandler)
specifier|default
name|ServletEndpointBuilder
name|bridgeErrorHandler
parameter_list|(
name|boolean
name|bridgeErrorHandler
parameter_list|)
block|{
name|doSetProperty
argument_list|(
literal|"bridgeErrorHandler"
argument_list|,
name|bridgeErrorHandler
argument_list|)
expr_stmt|;
return|return
name|this
return|;
block|}
comment|/** * Allows for bridging the consumer to the Camel routing Error Handler, * which mean any exceptions occurred while the consumer is trying to * pickup incoming messages, or the likes, will now be processed as a * message and handled by the routing Error Handler. By default the * consumer will use the org.apache.camel.spi.ExceptionHandler to deal * with exceptions, that will be logged at WARN or ERROR level and * ignored. * * The option will be converted to a<code>boolean</code> type. * * Group: consumer */
DECL|method|bridgeErrorHandler ( String bridgeErrorHandler)
specifier|default
name|ServletEndpointBuilder
name|bridgeErrorHandler
parameter_list|(
name|String
name|bridgeErrorHandler
parameter_list|)
block|{
name|doSetProperty
argument_list|(
literal|"bridgeErrorHandler"
argument_list|,
name|bridgeErrorHandler
argument_list|)
expr_stmt|;
return|return
name|this
return|;
block|}
comment|/** * If this option is false the Servlet will disable the HTTP streaming * and set the content-length header on the response. * * The option is a:<code>boolean</code> type. * * Group: consumer */
DECL|method|chunked (boolean chunked)
specifier|default
name|ServletEndpointBuilder
name|chunked
parameter_list|(
name|boolean
name|chunked
parameter_list|)
block|{
name|doSetProperty
argument_list|(
literal|"chunked"
argument_list|,
name|chunked
argument_list|)
expr_stmt|;
return|return
name|this
return|;
block|}
comment|/** * If this option is false the Servlet will disable the HTTP streaming * and set the content-length header on the response. * * The option will be converted to a<code>boolean</code> type. * * Group: consumer */
DECL|method|chunked (String chunked)
specifier|default
name|ServletEndpointBuilder
name|chunked
parameter_list|(
name|String
name|chunked
parameter_list|)
block|{
name|doSetProperty
argument_list|(
literal|"chunked"
argument_list|,
name|chunked
argument_list|)
expr_stmt|;
return|return
name|this
return|;
block|}
comment|/** * Used to only allow consuming if the HttpMethod matches, such as * GET/POST/PUT etc. Multiple methods can be specified separated by * comma. * * The option is a:<code>java.lang.String</code> type. * * Group: consumer */
DECL|method|httpMethodRestrict ( String httpMethodRestrict)
specifier|default
name|ServletEndpointBuilder
name|httpMethodRestrict
parameter_list|(
name|String
name|httpMethodRestrict
parameter_list|)
block|{
name|doSetProperty
argument_list|(
literal|"httpMethodRestrict"
argument_list|,
name|httpMethodRestrict
argument_list|)
expr_stmt|;
return|return
name|this
return|;
block|}
comment|/** * Whether or not the consumer should try to find a target consumer by * matching the URI prefix if no exact match is found. * * The option is a:<code>boolean</code> type. * * Group: consumer */
DECL|method|matchOnUriPrefix (boolean matchOnUriPrefix)
specifier|default
name|ServletEndpointBuilder
name|matchOnUriPrefix
parameter_list|(
name|boolean
name|matchOnUriPrefix
parameter_list|)
block|{
name|doSetProperty
argument_list|(
literal|"matchOnUriPrefix"
argument_list|,
name|matchOnUriPrefix
argument_list|)
expr_stmt|;
return|return
name|this
return|;
block|}
comment|/** * Whether or not the consumer should try to find a target consumer by * matching the URI prefix if no exact match is found. * * The option will be converted to a<code>boolean</code> type. * * Group: consumer */
DECL|method|matchOnUriPrefix (String matchOnUriPrefix)
specifier|default
name|ServletEndpointBuilder
name|matchOnUriPrefix
parameter_list|(
name|String
name|matchOnUriPrefix
parameter_list|)
block|{
name|doSetProperty
argument_list|(
literal|"matchOnUriPrefix"
argument_list|,
name|matchOnUriPrefix
argument_list|)
expr_stmt|;
return|return
name|this
return|;
block|}
comment|/** * If enabled and an Exchange failed processing on the consumer side the * response's body won't contain the exception's stack trace. * * The option is a:<code>boolean</code> type. * * Group: consumer */
DECL|method|muteException (boolean muteException)
specifier|default
name|ServletEndpointBuilder
name|muteException
parameter_list|(
name|boolean
name|muteException
parameter_list|)
block|{
name|doSetProperty
argument_list|(
literal|"muteException"
argument_list|,
name|muteException
argument_list|)
expr_stmt|;
return|return
name|this
return|;
block|}
comment|/** * If enabled and an Exchange failed processing on the consumer side the * response's body won't contain the exception's stack trace. * * The option will be converted to a<code>boolean</code> type. * * Group: consumer */
DECL|method|muteException (String muteException)
specifier|default
name|ServletEndpointBuilder
name|muteException
parameter_list|(
name|String
name|muteException
parameter_list|)
block|{
name|doSetProperty
argument_list|(
literal|"muteException"
argument_list|,
name|muteException
argument_list|)
expr_stmt|;
return|return
name|this
return|;
block|}
comment|/** * To use a custom buffer size on the javax.servlet.ServletResponse. * * The option is a:<code>java.lang.Integer</code> type. * * Group: consumer */
DECL|method|responseBufferSize ( Integer responseBufferSize)
specifier|default
name|ServletEndpointBuilder
name|responseBufferSize
parameter_list|(
name|Integer
name|responseBufferSize
parameter_list|)
block|{
name|doSetProperty
argument_list|(
literal|"responseBufferSize"
argument_list|,
name|responseBufferSize
argument_list|)
expr_stmt|;
return|return
name|this
return|;
block|}
comment|/** * To use a custom buffer size on the javax.servlet.ServletResponse. * * The option will be converted to a<code>java.lang.Integer</code> * type. * * Group: consumer */
DECL|method|responseBufferSize ( String responseBufferSize)
specifier|default
name|ServletEndpointBuilder
name|responseBufferSize
parameter_list|(
name|String
name|responseBufferSize
parameter_list|)
block|{
name|doSetProperty
argument_list|(
literal|"responseBufferSize"
argument_list|,
name|responseBufferSize
argument_list|)
expr_stmt|;
return|return
name|this
return|;
block|}
comment|/** * Name of the servlet to use. * * The option is a:<code>java.lang.String</code> type. * * Group: consumer */
DECL|method|servletName (String servletName)
specifier|default
name|ServletEndpointBuilder
name|servletName
parameter_list|(
name|String
name|servletName
parameter_list|)
block|{
name|doSetProperty
argument_list|(
literal|"servletName"
argument_list|,
name|servletName
argument_list|)
expr_stmt|;
return|return
name|this
return|;
block|}
comment|/** * If enabled and an Exchange failed processing on the consumer side, * and if the caused Exception was send back serialized in the response * as a application/x-java-serialized-object content type. On the * producer side the exception will be deserialized and thrown as is, * instead of the HttpOperationFailedException. The caused exception is * required to be serialized. This is by default turned off. If you * enable this then be aware that Java will deserialize the incoming * data from the request to Java and that can be a potential security * risk. * * The option is a:<code>boolean</code> type. * * Group: consumer */
DECL|method|transferException ( boolean transferException)
specifier|default
name|ServletEndpointBuilder
name|transferException
parameter_list|(
name|boolean
name|transferException
parameter_list|)
block|{
name|doSetProperty
argument_list|(
literal|"transferException"
argument_list|,
name|transferException
argument_list|)
expr_stmt|;
return|return
name|this
return|;
block|}
comment|/** * If enabled and an Exchange failed processing on the consumer side, * and if the caused Exception was send back serialized in the response * as a application/x-java-serialized-object content type. On the * producer side the exception will be deserialized and thrown as is, * instead of the HttpOperationFailedException. The caused exception is * required to be serialized. This is by default turned off. If you * enable this then be aware that Java will deserialize the incoming * data from the request to Java and that can be a potential security * risk. * * The option will be converted to a<code>boolean</code> type. * * Group: consumer */
DECL|method|transferException ( String transferException)
specifier|default
name|ServletEndpointBuilder
name|transferException
parameter_list|(
name|String
name|transferException
parameter_list|)
block|{
name|doSetProperty
argument_list|(
literal|"transferException"
argument_list|,
name|transferException
argument_list|)
expr_stmt|;
return|return
name|this
return|;
block|}
block|}
comment|/** * Advanced builder for endpoint for the Servlet component. */
DECL|interface|AdvancedServletEndpointBuilder
specifier|public
interface|interface
name|AdvancedServletEndpointBuilder
extends|extends
name|EndpointConsumerBuilder
block|{
DECL|method|basic ()
specifier|default
name|ServletEndpointBuilder
name|basic
parameter_list|()
block|{
return|return
operator|(
name|ServletEndpointBuilder
operator|)
name|this
return|;
block|}
comment|/** * To use a custom HttpBinding to control the mapping between Camel * message and HttpClient. * * The option is a: *<code>org.apache.camel.http.common.HttpBinding</code> type. * * Group: common (advanced) */
DECL|method|httpBinding (Object httpBinding)
specifier|default
name|AdvancedServletEndpointBuilder
name|httpBinding
parameter_list|(
name|Object
name|httpBinding
parameter_list|)
block|{
name|doSetProperty
argument_list|(
literal|"httpBinding"
argument_list|,
name|httpBinding
argument_list|)
expr_stmt|;
return|return
name|this
return|;
block|}
comment|/** * To use a custom HttpBinding to control the mapping between Camel * message and HttpClient. * * The option will be converted to a *<code>org.apache.camel.http.common.HttpBinding</code> type. * * Group: common (advanced) */
DECL|method|httpBinding (String httpBinding)
specifier|default
name|AdvancedServletEndpointBuilder
name|httpBinding
parameter_list|(
name|String
name|httpBinding
parameter_list|)
block|{
name|doSetProperty
argument_list|(
literal|"httpBinding"
argument_list|,
name|httpBinding
argument_list|)
expr_stmt|;
return|return
name|this
return|;
block|}
comment|/** * Whether to automatic bind multipart/form-data as attachments on the * Camel Exchange. The options attachmentMultipartBinding=true and * disableStreamCache=false cannot work together. Remove * disableStreamCache to use AttachmentMultipartBinding. This is turn * off by default as this may require servlet specific configuration to * enable this when using Servlet's. * * The option is a:<code>boolean</code> type. * * Group: consumer (advanced) */
DECL|method|attachmentMultipartBinding ( boolean attachmentMultipartBinding)
specifier|default
name|AdvancedServletEndpointBuilder
name|attachmentMultipartBinding
parameter_list|(
name|boolean
name|attachmentMultipartBinding
parameter_list|)
block|{
name|doSetProperty
argument_list|(
literal|"attachmentMultipartBinding"
argument_list|,
name|attachmentMultipartBinding
argument_list|)
expr_stmt|;
return|return
name|this
return|;
block|}
comment|/** * Whether to automatic bind multipart/form-data as attachments on the * Camel Exchange. The options attachmentMultipartBinding=true and * disableStreamCache=false cannot work together. Remove * disableStreamCache to use AttachmentMultipartBinding. This is turn * off by default as this may require servlet specific configuration to * enable this when using Servlet's. * * The option will be converted to a<code>boolean</code> type. * * Group: consumer (advanced) */
DECL|method|attachmentMultipartBinding ( String attachmentMultipartBinding)
specifier|default
name|AdvancedServletEndpointBuilder
name|attachmentMultipartBinding
parameter_list|(
name|String
name|attachmentMultipartBinding
parameter_list|)
block|{
name|doSetProperty
argument_list|(
literal|"attachmentMultipartBinding"
argument_list|,
name|attachmentMultipartBinding
argument_list|)
expr_stmt|;
return|return
name|this
return|;
block|}
comment|/** * Whether to eager check whether the HTTP requests has content if the * content-length header is 0 or not present. This can be turned on in * case HTTP clients do not send streamed data. * * The option is a:<code>boolean</code> type. * * Group: consumer (advanced) */
DECL|method|eagerCheckContentAvailable ( boolean eagerCheckContentAvailable)
specifier|default
name|AdvancedServletEndpointBuilder
name|eagerCheckContentAvailable
parameter_list|(
name|boolean
name|eagerCheckContentAvailable
parameter_list|)
block|{
name|doSetProperty
argument_list|(
literal|"eagerCheckContentAvailable"
argument_list|,
name|eagerCheckContentAvailable
argument_list|)
expr_stmt|;
return|return
name|this
return|;
block|}
comment|/** * Whether to eager check whether the HTTP requests has content if the * content-length header is 0 or not present. This can be turned on in * case HTTP clients do not send streamed data. * * The option will be converted to a<code>boolean</code> type. * * Group: consumer (advanced) */
DECL|method|eagerCheckContentAvailable ( String eagerCheckContentAvailable)
specifier|default
name|AdvancedServletEndpointBuilder
name|eagerCheckContentAvailable
parameter_list|(
name|String
name|eagerCheckContentAvailable
parameter_list|)
block|{
name|doSetProperty
argument_list|(
literal|"eagerCheckContentAvailable"
argument_list|,
name|eagerCheckContentAvailable
argument_list|)
expr_stmt|;
return|return
name|this
return|;
block|}
comment|/** * To let the consumer use a custom ExceptionHandler. Notice if the * option bridgeErrorHandler is enabled then this option is not in use. * By default the consumer will deal with exceptions, that will be * logged at WARN or ERROR level and ignored. * * The option is a:<code>org.apache.camel.spi.ExceptionHandler</code> * type. * * Group: consumer (advanced) */
DECL|method|exceptionHandler ( ExceptionHandler exceptionHandler)
specifier|default
name|AdvancedServletEndpointBuilder
name|exceptionHandler
parameter_list|(
name|ExceptionHandler
name|exceptionHandler
parameter_list|)
block|{
name|doSetProperty
argument_list|(
literal|"exceptionHandler"
argument_list|,
name|exceptionHandler
argument_list|)
expr_stmt|;
return|return
name|this
return|;
block|}
comment|/** * To let the consumer use a custom ExceptionHandler. Notice if the * option bridgeErrorHandler is enabled then this option is not in use. * By default the consumer will deal with exceptions, that will be * logged at WARN or ERROR level and ignored. * * The option will be converted to a *<code>org.apache.camel.spi.ExceptionHandler</code> type. * * Group: consumer (advanced) */
DECL|method|exceptionHandler ( String exceptionHandler)
specifier|default
name|AdvancedServletEndpointBuilder
name|exceptionHandler
parameter_list|(
name|String
name|exceptionHandler
parameter_list|)
block|{
name|doSetProperty
argument_list|(
literal|"exceptionHandler"
argument_list|,
name|exceptionHandler
argument_list|)
expr_stmt|;
return|return
name|this
return|;
block|}
comment|/** * Sets the exchange pattern when the consumer creates an exchange. * * The option is a:<code>org.apache.camel.ExchangePattern</code> type. * * Group: consumer (advanced) */
DECL|method|exchangePattern ( ExchangePattern exchangePattern)
specifier|default
name|AdvancedServletEndpointBuilder
name|exchangePattern
parameter_list|(
name|ExchangePattern
name|exchangePattern
parameter_list|)
block|{
name|doSetProperty
argument_list|(
literal|"exchangePattern"
argument_list|,
name|exchangePattern
argument_list|)
expr_stmt|;
return|return
name|this
return|;
block|}
comment|/** * Sets the exchange pattern when the consumer creates an exchange. * * The option will be converted to a *<code>org.apache.camel.ExchangePattern</code> type. * * Group: consumer (advanced) */
DECL|method|exchangePattern ( String exchangePattern)
specifier|default
name|AdvancedServletEndpointBuilder
name|exchangePattern
parameter_list|(
name|String
name|exchangePattern
parameter_list|)
block|{
name|doSetProperty
argument_list|(
literal|"exchangePattern"
argument_list|,
name|exchangePattern
argument_list|)
expr_stmt|;
return|return
name|this
return|;
block|}
comment|/** * Whitelist of accepted filename extensions for accepting uploaded * files. Multiple extensions can be separated by comma, such as * txt,xml. * * The option is a:<code>java.lang.String</code> type. * * Group: consumer (advanced) */
DECL|method|fileNameExtWhitelist ( String fileNameExtWhitelist)
specifier|default
name|AdvancedServletEndpointBuilder
name|fileNameExtWhitelist
parameter_list|(
name|String
name|fileNameExtWhitelist
parameter_list|)
block|{
name|doSetProperty
argument_list|(
literal|"fileNameExtWhitelist"
argument_list|,
name|fileNameExtWhitelist
argument_list|)
expr_stmt|;
return|return
name|this
return|;
block|}
comment|/** * Specifies whether to enable HTTP OPTIONS for this Servlet consumer. * By default OPTIONS is turned off. * * The option is a:<code>boolean</code> type. * * Group: consumer (advanced) */
DECL|method|optionsEnabled ( boolean optionsEnabled)
specifier|default
name|AdvancedServletEndpointBuilder
name|optionsEnabled
parameter_list|(
name|boolean
name|optionsEnabled
parameter_list|)
block|{
name|doSetProperty
argument_list|(
literal|"optionsEnabled"
argument_list|,
name|optionsEnabled
argument_list|)
expr_stmt|;
return|return
name|this
return|;
block|}
comment|/** * Specifies whether to enable HTTP OPTIONS for this Servlet consumer. * By default OPTIONS is turned off. * * The option will be converted to a<code>boolean</code> type. * * Group: consumer (advanced) */
DECL|method|optionsEnabled ( String optionsEnabled)
specifier|default
name|AdvancedServletEndpointBuilder
name|optionsEnabled
parameter_list|(
name|String
name|optionsEnabled
parameter_list|)
block|{
name|doSetProperty
argument_list|(
literal|"optionsEnabled"
argument_list|,
name|optionsEnabled
argument_list|)
expr_stmt|;
return|return
name|this
return|;
block|}
comment|/** * Specifies whether to enable HTTP TRACE for this Servlet consumer. By * default TRACE is turned off. * * The option is a:<code>boolean</code> type. * * Group: consumer (advanced) */
DECL|method|traceEnabled (boolean traceEnabled)
specifier|default
name|AdvancedServletEndpointBuilder
name|traceEnabled
parameter_list|(
name|boolean
name|traceEnabled
parameter_list|)
block|{
name|doSetProperty
argument_list|(
literal|"traceEnabled"
argument_list|,
name|traceEnabled
argument_list|)
expr_stmt|;
return|return
name|this
return|;
block|}
comment|/** * Specifies whether to enable HTTP TRACE for this Servlet consumer. By * default TRACE is turned off. * * The option will be converted to a<code>boolean</code> type. * * Group: consumer (advanced) */
DECL|method|traceEnabled (String traceEnabled)
specifier|default
name|AdvancedServletEndpointBuilder
name|traceEnabled
parameter_list|(
name|String
name|traceEnabled
parameter_list|)
block|{
name|doSetProperty
argument_list|(
literal|"traceEnabled"
argument_list|,
name|traceEnabled
argument_list|)
expr_stmt|;
return|return
name|this
return|;
block|}
comment|/** * Whether the endpoint should use basic property binding (Camel 2.x) or * the newer property binding with additional capabilities. * * The option is a:<code>boolean</code> type. * * Group: advanced */
DECL|method|basicPropertyBinding ( boolean basicPropertyBinding)
specifier|default
name|AdvancedServletEndpointBuilder
name|basicPropertyBinding
parameter_list|(
name|boolean
name|basicPropertyBinding
parameter_list|)
block|{
name|doSetProperty
argument_list|(
literal|"basicPropertyBinding"
argument_list|,
name|basicPropertyBinding
argument_list|)
expr_stmt|;
return|return
name|this
return|;
block|}
comment|/** * Whether the endpoint should use basic property binding (Camel 2.x) or * the newer property binding with additional capabilities. * * The option will be converted to a<code>boolean</code> type. * * Group: advanced */
DECL|method|basicPropertyBinding ( String basicPropertyBinding)
specifier|default
name|AdvancedServletEndpointBuilder
name|basicPropertyBinding
parameter_list|(
name|String
name|basicPropertyBinding
parameter_list|)
block|{
name|doSetProperty
argument_list|(
literal|"basicPropertyBinding"
argument_list|,
name|basicPropertyBinding
argument_list|)
expr_stmt|;
return|return
name|this
return|;
block|}
comment|/** * If this option is true then IN exchange Body of the exchange will be * mapped to HTTP body. Setting this to false will avoid the HTTP * mapping. * * The option is a:<code>boolean</code> type. * * Group: advanced */
DECL|method|mapHttpMessageBody ( boolean mapHttpMessageBody)
specifier|default
name|AdvancedServletEndpointBuilder
name|mapHttpMessageBody
parameter_list|(
name|boolean
name|mapHttpMessageBody
parameter_list|)
block|{
name|doSetProperty
argument_list|(
literal|"mapHttpMessageBody"
argument_list|,
name|mapHttpMessageBody
argument_list|)
expr_stmt|;
return|return
name|this
return|;
block|}
comment|/** * If this option is true then IN exchange Body of the exchange will be * mapped to HTTP body. Setting this to false will avoid the HTTP * mapping. * * The option will be converted to a<code>boolean</code> type. * * Group: advanced */
DECL|method|mapHttpMessageBody ( String mapHttpMessageBody)
specifier|default
name|AdvancedServletEndpointBuilder
name|mapHttpMessageBody
parameter_list|(
name|String
name|mapHttpMessageBody
parameter_list|)
block|{
name|doSetProperty
argument_list|(
literal|"mapHttpMessageBody"
argument_list|,
name|mapHttpMessageBody
argument_list|)
expr_stmt|;
return|return
name|this
return|;
block|}
comment|/** * If this option is true then IN exchange Form Encoded body of the * exchange will be mapped to HTTP. Setting this to false will avoid the * HTTP Form Encoded body mapping. * * The option is a:<code>boolean</code> type. * * Group: advanced */
DECL|method|mapHttpMessageFormUrlEncodedBody ( boolean mapHttpMessageFormUrlEncodedBody)
specifier|default
name|AdvancedServletEndpointBuilder
name|mapHttpMessageFormUrlEncodedBody
parameter_list|(
name|boolean
name|mapHttpMessageFormUrlEncodedBody
parameter_list|)
block|{
name|doSetProperty
argument_list|(
literal|"mapHttpMessageFormUrlEncodedBody"
argument_list|,
name|mapHttpMessageFormUrlEncodedBody
argument_list|)
expr_stmt|;
return|return
name|this
return|;
block|}
comment|/** * If this option is true then IN exchange Form Encoded body of the * exchange will be mapped to HTTP. Setting this to false will avoid the * HTTP Form Encoded body mapping. * * The option will be converted to a<code>boolean</code> type. * * Group: advanced */
DECL|method|mapHttpMessageFormUrlEncodedBody ( String mapHttpMessageFormUrlEncodedBody)
specifier|default
name|AdvancedServletEndpointBuilder
name|mapHttpMessageFormUrlEncodedBody
parameter_list|(
name|String
name|mapHttpMessageFormUrlEncodedBody
parameter_list|)
block|{
name|doSetProperty
argument_list|(
literal|"mapHttpMessageFormUrlEncodedBody"
argument_list|,
name|mapHttpMessageFormUrlEncodedBody
argument_list|)
expr_stmt|;
return|return
name|this
return|;
block|}
comment|/** * If this option is true then IN exchange Headers of the exchange will * be mapped to HTTP headers. Setting this to false will avoid the HTTP * Headers mapping. * * The option is a:<code>boolean</code> type. * * Group: advanced */
DECL|method|mapHttpMessageHeaders ( boolean mapHttpMessageHeaders)
specifier|default
name|AdvancedServletEndpointBuilder
name|mapHttpMessageHeaders
parameter_list|(
name|boolean
name|mapHttpMessageHeaders
parameter_list|)
block|{
name|doSetProperty
argument_list|(
literal|"mapHttpMessageHeaders"
argument_list|,
name|mapHttpMessageHeaders
argument_list|)
expr_stmt|;
return|return
name|this
return|;
block|}
comment|/** * If this option is true then IN exchange Headers of the exchange will * be mapped to HTTP headers. Setting this to false will avoid the HTTP * Headers mapping. * * The option will be converted to a<code>boolean</code> type. * * Group: advanced */
DECL|method|mapHttpMessageHeaders ( String mapHttpMessageHeaders)
specifier|default
name|AdvancedServletEndpointBuilder
name|mapHttpMessageHeaders
parameter_list|(
name|String
name|mapHttpMessageHeaders
parameter_list|)
block|{
name|doSetProperty
argument_list|(
literal|"mapHttpMessageHeaders"
argument_list|,
name|mapHttpMessageHeaders
argument_list|)
expr_stmt|;
return|return
name|this
return|;
block|}
comment|/** * Sets whether synchronous processing should be strictly used, or Camel * is allowed to use asynchronous processing (if supported). * * The option is a:<code>boolean</code> type. * * Group: advanced */
DECL|method|synchronous (boolean synchronous)
specifier|default
name|AdvancedServletEndpointBuilder
name|synchronous
parameter_list|(
name|boolean
name|synchronous
parameter_list|)
block|{
name|doSetProperty
argument_list|(
literal|"synchronous"
argument_list|,
name|synchronous
argument_list|)
expr_stmt|;
return|return
name|this
return|;
block|}
comment|/** * Sets whether synchronous processing should be strictly used, or Camel * is allowed to use asynchronous processing (if supported). * * The option will be converted to a<code>boolean</code> type. * * Group: advanced */
DECL|method|synchronous (String synchronous)
specifier|default
name|AdvancedServletEndpointBuilder
name|synchronous
parameter_list|(
name|String
name|synchronous
parameter_list|)
block|{
name|doSetProperty
argument_list|(
literal|"synchronous"
argument_list|,
name|synchronous
argument_list|)
expr_stmt|;
return|return
name|this
return|;
block|}
block|}
comment|/** * Servlet (camel-servlet) * To use a HTTP Servlet as entry for Camel routes when running in a servlet * container. * * Category: http * Since: 2.0 * Maven coordinates: org.apache.camel:camel-servlet * * Syntax:<code>servlet:contextPath</code> * * Path parameter: contextPath (required) * The context-path to use */
DECL|method|servlet (String path)
specifier|default
name|ServletEndpointBuilder
name|servlet
parameter_list|(
name|String
name|path
parameter_list|)
block|{
class|class
name|ServletEndpointBuilderImpl
extends|extends
name|AbstractEndpointBuilder
implements|implements
name|ServletEndpointBuilder
implements|,
name|AdvancedServletEndpointBuilder
block|{
specifier|public
name|ServletEndpointBuilderImpl
parameter_list|(
name|String
name|path
parameter_list|)
block|{
name|super
argument_list|(
literal|"servlet"
argument_list|,
name|path
argument_list|)
expr_stmt|;
block|}
block|}
return|return
operator|new
name|ServletEndpointBuilderImpl
argument_list|(
name|path
argument_list|)
return|;
block|}
block|}
end_interface
end_unit
|
package ru.job4j.synchroniz;
import org.junit.Test;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
public class CountTest {
/**
* Класс описывает нить со счетчиком.
*/
private class ThreadCount extends Thread {
private final Count count;
private ThreadCount(final Count count) {
this.count = count;
}
@Override
public void run() {
this.count.increment();
}
}
@Test
public void whenExecute2ThreadThen2() throws InterruptedException {
//Создаем счетчик.
final Count count = new Count();
//Создаем нити.
Thread first = new ThreadCount(count);
Thread second = new ThreadCount(count);
//Запускаем нити.
first.start();
second.start();
//Заставляем главную нить дождаться выполнения наших нитей.
first.join();
second.join();
//Проверяем результат.
assertThat(count.get(), is(2));
}
}
|
package com.whiuk.philip.perfect.helper;
import android.content.Context;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import com.whiuk.philip.perfect.Account;
import com.whiuk.philip.perfect.PerfectMail;
import com.whiuk.philip.perfect.R;
import com.whiuk.philip.perfect.activity.FolderInfoHolder;
import com.whiuk.philip.perfect.activity.MessageInfoHolder;
import com.whiuk.philip.perfect.mail.Address;
import com.whiuk.philip.perfect.mail.Flag;
import com.whiuk.philip.perfect.mail.Message.RecipientType;
import com.whiuk.philip.perfect.mailstore.LocalMessage;
public class MessageHelper {
/**
* If the number of addresses exceeds this value the addresses aren't
* resolved to the names of Android contacts.
*
* <p>
* TODO: This number was chosen arbitrarily and should be determined by
* performance tests.
* </p>
*
* @see #toFriendly(Address[], com.whiuk.philip.perfect.helper.Contacts)
*/
private static final int TOO_MANY_ADDRESSES = 50;
private static MessageHelper sInstance;
public synchronized static MessageHelper getInstance(final Context context) {
if (sInstance == null) {
sInstance = new MessageHelper(context);
}
return sInstance;
}
private Context mContext;
private MessageHelper(final Context context) {
mContext = context;
}
public void populate(final MessageInfoHolder target,
final LocalMessage message,
final FolderInfoHolder folder,
Account account) {
final Contacts contactHelper = PerfectMail.showContactName() ? Contacts.getInstance(mContext) : null;
target.message = message;
target.compareArrival = message.getInternalDate();
target.compareDate = message.getSentDate();
if (target.compareDate == null) {
target.compareDate = message.getInternalDate();
}
target.folder = folder;
target.read = message.isSet(Flag.SEEN);
target.answered = message.isSet(Flag.ANSWERED);
target.forwarded = message.isSet(Flag.FORWARDED);
target.flagged = message.isSet(Flag.FLAGGED);
Address[] addrs = message.getFrom();
if (addrs.length > 0 && account.isAnIdentity(addrs[0])) {
CharSequence to = toFriendly(message.getRecipients(RecipientType.TO), contactHelper);
target.compareCounterparty = to.toString();
target.sender = new SpannableStringBuilder(mContext.getString(R.string.message_to_label)).append(to);
} else {
target.sender = toFriendly(addrs, contactHelper);
target.compareCounterparty = target.sender.toString();
}
if (addrs.length > 0) {
target.senderAddress = addrs[0].getAddress();
} else {
// a reasonable fallback "whomever we were corresponding with
target.senderAddress = target.compareCounterparty;
}
target.uid = message.getUid();
target.account = message.getFolder().getAccountUuid();
target.uri = message.getUri();
}
public CharSequence getDisplayName(Account account, Address[] fromAddrs, Address[] toAddrs) {
final Contacts contactHelper = PerfectMail.showContactName() ? Contacts.getInstance(mContext) : null;
CharSequence displayName;
if (fromAddrs.length > 0 && account.isAnIdentity(fromAddrs[0])) {
CharSequence to = toFriendly(toAddrs, contactHelper);
displayName = new SpannableStringBuilder(
mContext.getString(R.string.message_to_label)).append(to);
} else {
displayName = toFriendly(fromAddrs, contactHelper);
}
return displayName;
}
public boolean toMe(Account account, Address[] toAddrs) {
for (Address address : toAddrs) {
if (account.isAnIdentity(address)) {
return true;
}
}
return false;
}
/**
* Returns the name of the contact this email address belongs to if
* the {@link Contacts contacts} parameter is not {@code null} and a
* contact is found. Otherwise the personal portion of the {@link Address}
* is returned. If that isn't available either, the email address is
* returned.
*
* @param address An {@link com.whiuk.philip.perfect.mail.Address}
* @param contacts A {@link Contacts} instance or {@code null}.
* @return A "friendly" name for this {@link Address}.
*/
public static CharSequence toFriendly(Address address, Contacts contacts) {
return toFriendly(address,contacts,
PerfectMail.showCorrespondentNames(),
PerfectMail.changeContactNameColor(),
PerfectMail.getContactNameColor());
}
public static CharSequence toFriendly(Address[] addresses, Contacts contacts) {
if (addresses == null) {
return null;
}
if (addresses.length >= TOO_MANY_ADDRESSES) {
// Don't look up contacts if the number of addresses is very high.
contacts = null;
}
SpannableStringBuilder sb = new SpannableStringBuilder();
for (int i = 0; i < addresses.length; i++) {
sb.append(toFriendly(addresses[i], contacts));
if (i < addresses.length - 1) {
sb.append(',');
}
}
return sb;
}
/* package, for testing */ static CharSequence toFriendly(Address address, Contacts contacts,
boolean showCorrespondentNames,
boolean changeContactNameColor,
int contactNameColor) {
if (!showCorrespondentNames) {
return address.getAddress();
} else if (contacts != null) {
final String name = contacts.getNameForAddress(address.getAddress());
// TODO: The results should probably be cached for performance reasons.
if (name != null) {
if (changeContactNameColor) {
final SpannableString coloredName = new SpannableString(name);
coloredName.setSpan(new ForegroundColorSpan(contactNameColor),
0,
coloredName.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
);
return coloredName;
} else {
return name;
}
}
}
return (!TextUtils.isEmpty(address.getPersonal())) ? address.getPersonal() : address.getAddress();
}
}
|
/* MIT License
*
* Copyright (c) 2018 Paul Collins
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.stp.games.jme.hud;
// JME3 Dependencies
import com.jme3.math.ColorRGBA;
import com.jme3.texture.Texture2D;
/** @author Paul Collins
* @version v1.0 ~ 04/24/2015
* HISTORY: Version 1.0 Created control HudBoxGrid ~ 04/24/2015
*/
public class HudBoxGrid extends HudGrid {
protected int spacing;
protected int rows;
protected int columns;
public HudBoxGrid(String name, HudStyle style, int size, int spacing, int rows, int columns) {
super (name, style, (columns*size)+(columns*spacing)+spacing, (rows*size)+(rows*spacing)+spacing, size);
this.spacing = spacing;
this.rows = rows;
this.columns = columns;
for (int r = 0; r < rows; r++) {
for (int c = 0; c < columns; c++) {
cells.add(new Cell(cells.getName() + "-cell" + cells.getChildCount(), style, size, size, cells.getChildCount()));
}
}
}
public Cell getCell(int row, int column) {
int index = (row*columns) + column;
if (index >= 0 && index < cells.getChildCount()) {
return (Cell)cells.getChildAt(index);
}
return null;
}
public void set(int row, int column, HudComponent component) {
add(component);
component.setRelative();
component.setLocation(0, 0);
component.setParent(getCell(row, column));
}
public void updateSpacing(int spacing) {
this.spacing = spacing;
setSize((columns*size)+(columns*spacing)+spacing, (rows*size)+(rows*spacing)+spacing);
}
@Override
public void updateSize(int newSize) {
super.updateSize(newSize);
setSize((columns*size)+(columns*spacing)+spacing, (rows*size)+(rows*spacing)+spacing);
}
@Override
public void updateLayout() {
int row = 0;
int col = 0;
for (HudComponent comp : cells.getChildren()) {
int x0 = (col*size) + (col*spacing) + spacing;
int y0 = (row* size) + (row*spacing) + spacing;
comp.setRelative();
comp.setLocation(x0, y0);
comp.setSize(size, size);
col++;
if (col == columns) {
col = 0;
row++;
}
}
}
}
|
/*
* This file is part of the Heritrix web crawler (crawler.archive.org).
*
* Licensed to the Internet Archive (IA) by one or more individual
* contributors.
*
* The IA licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.archive.crawler.restlet;
import java.util.Collection;
import java.util.logging.Logger;
import org.restlet.Context;
import org.restlet.Guard;
import org.restlet.data.ChallengeScheme;
import org.restlet.data.Request;
/**
* Guard that slows and logs failed authentication attempts, to make
* brute-force guessing attacks less feasible.
*
* @contributor gojomo
*/
public class RateLimitGuard extends Guard {
private static final int MIN_MS_BETWEEN_ATTEMPTS = 6000;
private static final Logger logger = Logger.getLogger(RateLimitGuard.class.getName());
protected long lastFailureTime = 0;
public RateLimitGuard(Context context, ChallengeScheme scheme, String realm) throws IllegalArgumentException {
super(context, scheme, realm);
}
public RateLimitGuard(Context context, String realm, Collection<String> baseUris, String serverKey) {
super(context, realm, baseUris, serverKey);
}
@Override
public synchronized int authenticate(Request request) {
int retVal = super.authenticate(request);
if(retVal == AUTHENTICATION_INVALID) {
logger.warning("authentication failure "+request);
// wait until at least LAG has passed from last failure
// holding object lock the whole time, so no other checks
// can happen in parallel
long now = System.currentTimeMillis();
long sleepMs = (lastFailureTime+MIN_MS_BETWEEN_ATTEMPTS)-now;
if(sleepMs>0) {
try {
Thread.sleep(sleepMs);
} catch (InterruptedException e) {
// ignore
}
}
lastFailureTime = now + sleepMs;
}
return retVal;
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.gearpump.sql.rel;
import org.apache.calcite.plan.RelOptCluster;
import org.apache.calcite.plan.RelTraitSet;
import org.apache.calcite.rel.RelCollation;
import org.apache.calcite.rel.RelCollationImpl;
import org.apache.calcite.rel.RelFieldCollation;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rel.core.Sort;
import org.apache.calcite.rex.RexInputRef;
import org.apache.calcite.rex.RexLiteral;
import org.apache.calcite.rex.RexNode;
import org.apache.gearpump.streaming.dsl.javaapi.JavaStream;
import org.apache.gearpump.streaming.dsl.javaapi.JavaStreamApp;
import scala.Tuple2;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
public class GearSortRel extends Sort implements GearRelNode {
private List<Integer> fieldIndices = new ArrayList<>();
private List<Boolean> orientation = new ArrayList<>();
private List<Boolean> nullsFirst = new ArrayList<>();
private int startIndex = 0;
private int count;
public GearSortRel(RelOptCluster cluster, RelTraitSet traits, RelNode child, RelCollation collation,
RexNode offset, RexNode fetch) {
super(cluster, traits, child, collation, offset, fetch);
List<RexNode> fieldExps = getChildExps();
RelCollationImpl collationImpl = (RelCollationImpl) collation;
List<RelFieldCollation> collations = collationImpl.getFieldCollations();
for (int i = 0; i < fieldExps.size(); i++) {
RexNode fieldExp = fieldExps.get(i);
RexInputRef inputRef = (RexInputRef) fieldExp;
fieldIndices.add(inputRef.getIndex());
orientation.add(collations.get(i).getDirection() == RelFieldCollation.Direction.ASCENDING);
RelFieldCollation.NullDirection rawNullDirection = collations.get(i).nullDirection;
if (rawNullDirection == RelFieldCollation.NullDirection.UNSPECIFIED) {
rawNullDirection = collations.get(i).getDirection().defaultNullDirection();
}
nullsFirst.add(rawNullDirection == RelFieldCollation.NullDirection.FIRST);
}
if (fetch == null) {
throw new UnsupportedOperationException("ORDER BY without a LIMIT is not supported!");
}
RexLiteral fetchLiteral = (RexLiteral) fetch;
count = ((BigDecimal) fetchLiteral.getValue()).intValue();
if (offset != null) {
RexLiteral offsetLiteral = (RexLiteral) offset;
startIndex = ((BigDecimal) offsetLiteral.getValue()).intValue();
}
}
@Override
public Sort copy(RelTraitSet traitSet, RelNode newInput, RelCollation newCollation,
RexNode offset, RexNode fetch) {
return new GearSortRel(getCluster(), traitSet, newInput, newCollation, offset, fetch);
}
public static <T extends Number & Comparable> int numberCompare(T a, T b) {
return a.compareTo(b);
}
@Override
public JavaStream<Tuple2<String, Integer>> buildGearPipeline(JavaStreamApp app, JavaStream<Tuple2<String, Integer>> javaStream) throws Exception {
return null;
}
}
|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v7/services/customer_client_link_service.proto
package com.google.ads.googleads.v7.services;
public interface MutateCustomerClientLinkResponseOrBuilder extends
// @@protoc_insertion_point(interface_extends:google.ads.googleads.v7.services.MutateCustomerClientLinkResponse)
com.google.protobuf.MessageOrBuilder {
/**
* <pre>
* A result that identifies the resource affected by the mutate request.
* </pre>
*
* <code>.google.ads.googleads.v7.services.MutateCustomerClientLinkResult result = 1;</code>
* @return Whether the result field is set.
*/
boolean hasResult();
/**
* <pre>
* A result that identifies the resource affected by the mutate request.
* </pre>
*
* <code>.google.ads.googleads.v7.services.MutateCustomerClientLinkResult result = 1;</code>
* @return The result.
*/
com.google.ads.googleads.v7.services.MutateCustomerClientLinkResult getResult();
/**
* <pre>
* A result that identifies the resource affected by the mutate request.
* </pre>
*
* <code>.google.ads.googleads.v7.services.MutateCustomerClientLinkResult result = 1;</code>
*/
com.google.ads.googleads.v7.services.MutateCustomerClientLinkResultOrBuilder getResultOrBuilder();
}
|
package nablarch.test.tool.findbugs.data.methodcall.inherit.method;
public class ClassC extends ClassB {
public void methodC() {
// オーバーライドあり
publishedPublishedOverriddenMethod();
publishedUnpublishedOverriddenMethod();
unpublishedPublishedOverriddenMethod();
unpublishedUnpublishedOverriddenMethod();
// オーバーライドなし
publishedMethodA();
unpublishedMethodA();
}
}
|
/*
* Copyright 2014-2020 Real Logic Limited.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.aeron;
import io.aeron.logbuffer.BufferClaim;
import io.aeron.logbuffer.ExclusiveTermAppender;
import io.aeron.logbuffer.LogBufferDescriptor;
import org.agrona.DirectBuffer;
import org.agrona.MutableDirectBuffer;
import org.agrona.concurrent.UnsafeBuffer;
import org.agrona.concurrent.status.ReadablePosition;
import static io.aeron.logbuffer.LogBufferDescriptor.PARTITION_COUNT;
import static io.aeron.protocol.DataHeaderFlyweight.*;
import static java.nio.ByteOrder.LITTLE_ENDIAN;
/**
* Aeron publisher API for sending messages to subscribers of a given channel and streamId pair. ExclusivePublications
* each get their own session id so multiple can be concurrently active on the same media driver as independent streams.
* <p>
* {@link ExclusivePublication}s are created via the {@link Aeron#addExclusivePublication(String, int)} method,
* and messages are sent via one of the {@link #offer(DirectBuffer)} methods, or a
* {@link #tryClaim(int, BufferClaim)} and {@link BufferClaim#commit()} method combination.
* <p>
* {@link ExclusivePublication}s have the potential to provide greater throughput than the default {@link Publication}
* which supports concurrent access.
* <p>
* The APIs used for tryClaim and offer are non-blocking.
* <p>
* <b>Note:</b> Instances are NOT threadsafe for offer and tryClaim methods but are for the others.
*
* @see Aeron#addExclusivePublication(String, int)
*/
public class ExclusivePublication extends Publication
{
private int termOffset;
private int termId;
private int activePartitionIndex;
private long termBeginPosition;
private final ExclusiveTermAppender[] termAppenders = new ExclusiveTermAppender[PARTITION_COUNT];
ExclusivePublication(
final ClientConductor clientConductor,
final String channel,
final int streamId,
final int sessionId,
final ReadablePosition positionLimit,
final int channelStatusId,
final LogBuffers logBuffers,
final long originalRegistrationId,
final long registrationId)
{
super(
clientConductor,
channel,
streamId,
sessionId,
positionLimit,
channelStatusId,
logBuffers,
originalRegistrationId,
registrationId);
final UnsafeBuffer[] buffers = logBuffers.duplicateTermBuffers();
final UnsafeBuffer logMetaDataBuffer = logBuffers.metaDataBuffer();
for (int i = 0; i < PARTITION_COUNT; i++)
{
termAppenders[i] = new ExclusiveTermAppender(buffers[i], logMetaDataBuffer, i);
}
final int termCount = LogBufferDescriptor.activeTermCount(logMetaDataBuffer);
final int index = LogBufferDescriptor.indexByTermCount(termCount);
activePartitionIndex = index;
final long rawTail = LogBufferDescriptor.rawTail(logMetaDataBuffer, index);
termId = LogBufferDescriptor.termId(rawTail);
termOffset = LogBufferDescriptor.termOffset(rawTail);
termBeginPosition = LogBufferDescriptor.computeTermBeginPosition(termId, positionBitsToShift, initialTermId);
}
public long position()
{
if (isClosed)
{
return CLOSED;
}
return termBeginPosition + termOffset;
}
public long availableWindow()
{
if (isClosed)
{
return CLOSED;
}
return positionLimit.getVolatile() - (termBeginPosition + termOffset);
}
/**
* The current term-id of the publication.
*
* @return the current term-id of the publication.
*/
public int termId()
{
return termId;
}
/**
* The current term-offset of the publication.
*
* @return the current term-offset of the publication.
*/
public int termOffset()
{
return termOffset;
}
/**
* Non-blocking publish of a partial buffer containing a message.
*
* @param buffer containing message.
* @param offset offset in the buffer at which the encoded message begins.
* @param length in bytes of the encoded message.
* @param reservedValueSupplier {@link ReservedValueSupplier} for the frame.
* @return The new stream position, otherwise a negative error value of {@link #NOT_CONNECTED},
* {@link #BACK_PRESSURED}, {@link #ADMIN_ACTION}, {@link #CLOSED}, or {@link #MAX_POSITION_EXCEEDED}.
*/
public long offer(
final DirectBuffer buffer,
final int offset,
final int length,
final ReservedValueSupplier reservedValueSupplier)
{
long newPosition = CLOSED;
if (!isClosed)
{
final long limit = positionLimit.getVolatile();
final ExclusiveTermAppender termAppender = termAppenders[activePartitionIndex];
final long position = termBeginPosition + termOffset;
if (position < limit)
{
final int result;
if (length <= maxPayloadLength)
{
checkPositiveLength(length);
result = termAppender.appendUnfragmentedMessage(
termId, termOffset, headerWriter, buffer, offset, length, reservedValueSupplier);
}
else
{
checkMaxMessageLength(length);
result = termAppender.appendFragmentedMessage(
termId,
termOffset,
headerWriter,
buffer,
offset,
length,
maxPayloadLength,
reservedValueSupplier);
}
newPosition = newPosition(result);
}
else
{
newPosition = backPressureStatus(position, length);
}
}
return newPosition;
}
/**
* Non-blocking publish of a message composed of two parts, e.g. a header and encapsulated payload.
*
* @param bufferOne containing the first part of the message.
* @param offsetOne at which the first part of the message begins.
* @param lengthOne of the first part of the message.
* @param bufferTwo containing the second part of the message.
* @param offsetTwo at which the second part of the message begins.
* @param lengthTwo of the second part of the message.
* @param reservedValueSupplier {@link ReservedValueSupplier} for the frame.
* @return The new stream position, otherwise a negative error value of {@link #NOT_CONNECTED},
* {@link #BACK_PRESSURED}, {@link #ADMIN_ACTION}, {@link #CLOSED}, or {@link #MAX_POSITION_EXCEEDED}.
*/
public long offer(
final DirectBuffer bufferOne,
final int offsetOne,
final int lengthOne,
final DirectBuffer bufferTwo,
final int offsetTwo,
final int lengthTwo,
final ReservedValueSupplier reservedValueSupplier)
{
long newPosition = CLOSED;
if (!isClosed)
{
final long limit = positionLimit.getVolatile();
final ExclusiveTermAppender termAppender = termAppenders[activePartitionIndex];
final long position = termBeginPosition + termOffset;
final int length = validateAndComputeLength(lengthOne, lengthTwo);
if (position < limit)
{
final int result;
if (length <= maxPayloadLength)
{
checkPositiveLength(length);
result = termAppender.appendUnfragmentedMessage(
termId,
termOffset,
headerWriter,
bufferOne, offsetOne, lengthOne,
bufferTwo, offsetTwo, lengthTwo,
reservedValueSupplier);
}
else
{
checkMaxMessageLength(length);
result = termAppender.appendFragmentedMessage(
termId,
termOffset,
headerWriter,
bufferOne, offsetOne, lengthOne,
bufferTwo, offsetTwo, lengthTwo,
maxPayloadLength,
reservedValueSupplier);
}
newPosition = newPosition(result);
}
else
{
newPosition = backPressureStatus(position, length);
}
}
return newPosition;
}
/**
* Non-blocking publish by gathering buffer vectors into a message.
*
* @param vectors which make up the message.
* @param reservedValueSupplier {@link ReservedValueSupplier} for the frame.
* @return The new stream position, otherwise a negative error value of {@link #NOT_CONNECTED},
* {@link #BACK_PRESSURED}, {@link #ADMIN_ACTION}, {@link #CLOSED}, or {@link #MAX_POSITION_EXCEEDED}.
*/
public long offer(final DirectBufferVector[] vectors, final ReservedValueSupplier reservedValueSupplier)
{
final int length = DirectBufferVector.validateAndComputeLength(vectors);
long newPosition = CLOSED;
if (!isClosed)
{
final long limit = positionLimit.getVolatile();
final ExclusiveTermAppender termAppender = termAppenders[activePartitionIndex];
final long position = termBeginPosition + termOffset;
if (position < limit)
{
final int result;
if (length <= maxPayloadLength)
{
result = termAppender.appendUnfragmentedMessage(
termId, termOffset, headerWriter, vectors, length, reservedValueSupplier);
}
else
{
checkMaxMessageLength(length);
result = termAppender.appendFragmentedMessage(
termId,
termOffset,
headerWriter,
vectors,
length,
maxPayloadLength,
reservedValueSupplier);
}
newPosition = newPosition(result);
}
else
{
newPosition = backPressureStatus(position, length);
}
}
return newPosition;
}
/**
* Try to claim a range in the publication log into which a message can be written with zero copy semantics.
* Once the message has been written then {@link BufferClaim#commit()} should be called thus making it
* available.
* <p>
* <b>Note:</b> This method can only be used for message lengths less than MTU length minus header.
* If the claim is held after the publication is closed, or the client dies, then it will be unblocked to reach
* end-of-stream (EOS).
* <pre>{@code
* final BufferClaim bufferClaim = new BufferClaim();
*
* if (publication.tryClaim(messageLength, bufferClaim) > 0L)
* {
* try
* {
* final MutableDirectBuffer buffer = bufferClaim.buffer();
* final int offset = bufferClaim.offset();
*
* // Work with buffer directly or wrap with a flyweight
* }
* finally
* {
* bufferClaim.commit();
* }
* }
* }</pre>
*
* @param length of the range to claim, in bytes..
* @param bufferClaim to be populated if the claim succeeds.
* @return The new stream position, otherwise a negative error value of {@link #NOT_CONNECTED},
* {@link #BACK_PRESSURED}, {@link #ADMIN_ACTION}, {@link #CLOSED}, or {@link #MAX_POSITION_EXCEEDED}.
* @throws IllegalArgumentException if the length is greater than {@link #maxPayloadLength()} within an MTU.
* @see BufferClaim#commit()
* @see BufferClaim#abort()
*/
public long tryClaim(final int length, final BufferClaim bufferClaim)
{
checkPayloadLength(length);
long newPosition = CLOSED;
if (!isClosed)
{
final long limit = positionLimit.getVolatile();
final ExclusiveTermAppender termAppender = termAppenders[activePartitionIndex];
final long position = termBeginPosition + termOffset;
if (position < limit)
{
final int result = termAppender.claim(termId, termOffset, headerWriter, length, bufferClaim);
newPosition = newPosition(result);
}
else
{
newPosition = backPressureStatus(position, length);
}
}
return newPosition;
}
/**
* Append a padding record log of a given length to make up the log to a position.
*
* @param length of the range to claim, in bytes..
* @return The new stream position, otherwise a negative error value of {@link #NOT_CONNECTED},
* {@link #BACK_PRESSURED}, {@link #ADMIN_ACTION}, {@link #CLOSED}, or {@link #MAX_POSITION_EXCEEDED}.
* @throws IllegalArgumentException if the length is greater than {@link #maxMessageLength()}.
*/
public long appendPadding(final int length)
{
checkMaxMessageLength(length);
long newPosition = CLOSED;
if (!isClosed)
{
final long limit = positionLimit.getVolatile();
final ExclusiveTermAppender termAppender = termAppenders[activePartitionIndex];
final long position = termBeginPosition + termOffset;
if (position < limit)
{
checkPositiveLength(length);
final int result = termAppender.appendPadding(termId, termOffset, headerWriter, length);
newPosition = newPosition(result);
}
else
{
newPosition = backPressureStatus(position, length);
}
}
return newPosition;
}
/**
* Offer a block of pre-formatted message fragments directly into the current term.
*
* @param buffer containing the pre-formatted block of message fragments.
* @param offset offset in the buffer at which the first fragment begins.
* @param length in bytes of the encoded block.
* @return The new stream position, otherwise a negative error value of {@link #NOT_CONNECTED},
* {@link #BACK_PRESSURED}, {@link #ADMIN_ACTION}, {@link #CLOSED}, or {@link #MAX_POSITION_EXCEEDED}.
* @throws IllegalArgumentException if the length is greater than remaining size of the current term.
* @throws IllegalArgumentException if the first frame within the block is not properly formatted, i.e. if the
* {@code streamId} is not equal to the value returned by the {@link #streamId()}
* method or if the {@code sessionId} is not equal to the value returned by the
* {@link #sessionId()} method or if the frame type is not equal to the
* {@link io.aeron.protocol.HeaderFlyweight#HDR_TYPE_DATA}.
*/
public long offerBlock(final MutableDirectBuffer buffer, final int offset, final int length)
{
if (isClosed)
{
return CLOSED;
}
if (termOffset >= termBufferLength)
{
rotateTerm();
}
final long limit = positionLimit.getVolatile();
final long position = termBeginPosition + termOffset;
if (position < limit)
{
checkBlockLength(length);
checkFirstFrame(buffer, offset);
final ExclusiveTermAppender termAppender = termAppenders[activePartitionIndex];
final int result = termAppender.appendBlock(termId, termOffset, buffer, offset, length);
return newPosition(result);
}
else
{
return backPressureStatus(position, length);
}
}
private void checkBlockLength(final int length)
{
final int remaining = termBufferLength - termOffset;
if (length > remaining)
{
throw new IllegalArgumentException(
"invalid block length " + length + ", remaining space in term is " + remaining);
}
}
private void checkFirstFrame(final MutableDirectBuffer buffer, final int offset)
{
final int frameType = HDR_TYPE_DATA;
final int blockTermOffset = buffer.getInt(offset + TERM_OFFSET_FIELD_OFFSET, LITTLE_ENDIAN);
final int blockSessionId = buffer.getInt(offset + SESSION_ID_FIELD_OFFSET, LITTLE_ENDIAN);
final int blockStreamId = buffer.getInt(offset + STREAM_ID_FIELD_OFFSET, LITTLE_ENDIAN);
final int blockTermId = buffer.getInt(offset + TERM_ID_FIELD_OFFSET, LITTLE_ENDIAN);
final int blockFrameType = buffer.getShort(offset + TYPE_FIELD_OFFSET, LITTLE_ENDIAN) & 0xFFFF;
if (blockTermOffset != termOffset ||
blockSessionId != sessionId ||
blockStreamId != streamId ||
blockTermId != termId ||
frameType != blockFrameType)
{
throw new IllegalArgumentException("improperly formatted block:" +
" termOffset=" + blockTermOffset + " (expected=" + termOffset + ")," +
" sessionId=" + blockSessionId + " (expected=" + sessionId + ")," +
" streamId=" + blockStreamId + " (expected=" + streamId + ")," +
" termId=" + blockTermId + " (expected=" + termId + ")," +
" frameType=" + blockFrameType + " (expected=" + frameType + ")");
}
}
private long newPosition(final int resultingOffset)
{
if (resultingOffset > 0)
{
termOffset = resultingOffset;
return termBeginPosition + resultingOffset;
}
if ((termBeginPosition + termBufferLength) >= maxPossiblePosition)
{
return MAX_POSITION_EXCEEDED;
}
rotateTerm();
return ADMIN_ACTION;
}
private void rotateTerm()
{
final int nextIndex = LogBufferDescriptor.nextPartitionIndex(activePartitionIndex);
final int nextTermId = termId + 1;
activePartitionIndex = nextIndex;
termOffset = 0;
termId = nextTermId;
termBeginPosition += termBufferLength;
final int termCount = nextTermId - initialTermId;
LogBufferDescriptor.initialiseTailWithTermId(logMetaDataBuffer, nextIndex, nextTermId);
LogBufferDescriptor.activeTermCountOrdered(logMetaDataBuffer, termCount);
}
}
|
package com.farata.lang.invoke.proxy;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;
import com.farata.lang.invoke.spi.AbstractMultiMethodCompiler;
import com.farata.lang.invoke.spi.IntrospectionUtils;
import com.farata.lang.invoke.spi.MultiMethodFactory;
public class ProxyMultiMethodCompiler extends AbstractMultiMethodCompiler {
protected <T,O> MultiMethodFactory<T, O> compileInternal(final Class<T> interfaceClass, final Method interfaceMethod, final Class<O> delegateClass, final List<Method> implementationMethods) {
@SuppressWarnings("unchecked")
final Class<T> proxyClass = (Class<T>)Proxy.getProxyClass(IntrospectionUtils.classLoaderOf(delegateClass), interfaceClass, ProxyMultiMethodDispatch.class);
for (final Method m : implementationMethods) {
m.setAccessible(true);
}
final Constructor<T> proxyConstructor;
try {
proxyConstructor = proxyClass.getConstructor(InvocationHandler.class);
proxyConstructor.setAccessible(true);
} catch (final NoSuchMethodException ex) {
throw new RuntimeException(ex);
}
return new ProxyMultiMethodFactory<T, O>(proxyConstructor, implementationMethods);
}
public static interface ProxyMultiMethodDispatch {};
}
|
package Parser.Commands.Turtle_Command;
import GraphicsBackend.Turtle;
import Parser.BackendController;
import Parser.Commands.Command;
import Parser.Commands.TurtleCommand;
/**
* @author kunalupadya
* @author Louis Lee
* @author Dhanush
*/
public class IsPenDownCommand extends TurtleCommand {
private static final int PEN_DOWN = 1;
private static final int PEN_UP = 0;
public IsPenDownCommand(){
isOutputCommand = true;
setNumParameters(0);
turtleQuery = true;
}
@Override
protected void performAction(BackendController backendController, Turtle turtle) {
setReturnValue(turtle.getMyPen().getPenUp() ? PEN_UP : PEN_DOWN);
}
@Override
public Command copy() {
return new IsPenDownCommand();
}
}
|
/** \brief The mouse listeners for our Othello Program */
package listeners;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import main_components.Board;
import main_components.Color;
import main_components.Controller;
import strategies.Difficulty;
/**
* \brief
* Enables a player to forfeit a game.
* @author Jignesh Chudasama
*/
public class ForfeitListener extends MouseAdapter {
public Controller controller; ///< The Controller in the MVC structure
public Board board; ///< The Model in the MVC structure
/**
* Constructor. Saves the Controller and Board information
* @param controller The Controller in the MVC structure
*/
public ForfeitListener(Controller controller){
this.controller = controller;
this.board = controller.board;
}
/**
* Let's a Player instantly forfeit a game
* @param event the event corresponding to the mouse click
*/
public void mouseClicked(MouseEvent event){
if (board.playerTurn == Color.BLACK){
javax.swing.JOptionPane.showMessageDialog(null, "Black Forfeits. White Wins!");
controller.whiteGamesWon++;
}
else{
javax.swing.JOptionPane.showMessageDialog(null, "White Forfeits. Black Wins!");
controller.blackGamesWon++;
}
controller.reset(Difficulty.EASY);
}
}
|
/*
* Copyright (c) 2012-2020 Cumulocity GmbH
* Copyright (c) 2021 Software AG, Darmstadt, Germany and/or Software AG USA Inc., Reston, VA, USA,
* and/or its subsidiaries and/or its affiliates and/or their licensors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cumulocity.agent.snmp.cucumber.steps;
import cucumber.api.java.en.When;
public class GeneralSteps {
@When("^I wait for (.+) seconds$")
public void startMiloServer(int seconds) throws Exception {
Thread.sleep(1000 * seconds);
}
}
|
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.zeppelin.submarine.job.thread;
import com.google.common.io.Resources;
import com.hubspot.jinjava.Jinjava;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecuteResultHandler;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteException;
import org.apache.commons.exec.ExecuteWatchdog;
import org.apache.commons.exec.LogOutputStream;
import org.apache.commons.exec.PumpStreamHandler;
import org.apache.commons.io.Charsets;
import org.apache.commons.lang3.StringUtils;
import org.apache.zeppelin.interpreter.InterpreterContext;
import org.apache.zeppelin.interpreter.thrift.ParagraphInfo;
import org.apache.zeppelin.submarine.hadoop.HdfsClient;
import org.apache.zeppelin.submarine.commons.SubmarineConstants;
import org.apache.zeppelin.submarine.commons.SubmarineUI;
import org.apache.zeppelin.submarine.commons.SubmarineUtils;
import org.apache.zeppelin.submarine.job.SubmarineJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import static org.apache.zeppelin.submarine.job.SubmarineJobStatus.EXECUTE_SUBMARINE;
import static org.apache.zeppelin.submarine.job.SubmarineJobStatus.EXECUTE_SUBMARINE_ERROR;
import static org.apache.zeppelin.submarine.job.SubmarineJobStatus.EXECUTE_SUBMARINE_FINISHED;
public class JobRunThread extends Thread {
private Logger LOGGER = LoggerFactory.getLogger(JobRunThread.class);
private SubmarineJob submarineJob;
private AtomicBoolean running = new AtomicBoolean(false);
private Lock lockRunning = new ReentrantLock();
public JobRunThread(SubmarineJob submarineJob) {
this.submarineJob = submarineJob;
}
public void run() {
boolean tryLock = lockRunning.tryLock();
if (false == tryLock) {
LOGGER.warn("Can not get JobRunThread lockRunning!");
return;
}
SubmarineUI submarineUI = submarineJob.getSubmarineUI();
try {
InterpreterContext intpContext = submarineJob.getIntpContext();
String noteId = intpContext.getNoteId();
String userName = intpContext.getAuthenticationInfo().getUser();
String jobName = SubmarineUtils.getJobName(userName, noteId);
if (true == running.get()) {
String message = String.format("Job %s already running.", jobName);
submarineUI.outputLog("WARN", message);
LOGGER.warn(message);
return;
}
running.set(true);
Properties properties = submarineJob.getProperties();
HdfsClient hdfsClient = submarineJob.getHdfsClient();
File pythonWorkDir = submarineJob.getPythonWorkDir();
submarineJob.setCurrentJobState(EXECUTE_SUBMARINE);
String algorithmPath = properties.getProperty(
SubmarineConstants.SUBMARINE_ALGORITHM_HDFS_PATH, "");
if (!algorithmPath.startsWith("hdfs://")) {
String message = "Algorithm file upload HDFS path, " +
"Must be `hdfs://` prefix. now setting " + algorithmPath;
submarineUI.outputLog("Configuration error", message);
return;
}
List<ParagraphInfo> paragraphInfos = intpContext.getIntpEventClient()
.getParagraphList(userName, noteId);
String outputMsg = hdfsClient.saveParagraphToFiles(noteId, paragraphInfos,
pythonWorkDir == null ? "" : pythonWorkDir.getAbsolutePath(), properties);
if (!StringUtils.isEmpty(outputMsg)) {
submarineUI.outputLog("Save algorithm file", outputMsg);
}
HashMap jinjaParams = SubmarineUtils.propertiesToJinjaParams(
properties, submarineJob, true);
URL urlTemplate = Resources.getResource(SubmarineJob.SUBMARINE_JOBRUN_TF_JINJA);
String template = Resources.toString(urlTemplate, Charsets.UTF_8);
Jinjava jinjava = new Jinjava();
String submarineCmd = jinjava.render(template, jinjaParams);
// If the first line is a newline, delete the newline
int firstLineIsNewline = submarineCmd.indexOf("\n");
if (firstLineIsNewline == 0) {
submarineCmd = submarineCmd.replaceFirst("\n", "");
}
StringBuffer sbLogs = new StringBuffer(submarineCmd);
submarineUI.outputLog("Submarine submit command", sbLogs.toString());
long timeout = Long.valueOf(properties.getProperty(SubmarineJob.TIMEOUT_PROPERTY,
SubmarineJob.defaultTimeout));
CommandLine cmdLine = CommandLine.parse(SubmarineJob.shell);
cmdLine.addArgument(submarineCmd, false);
DefaultExecutor executor = new DefaultExecutor();
ExecuteWatchdog watchDog = new ExecuteWatchdog(timeout);
executor.setWatchdog(watchDog);
StringBuffer sbLogOutput = new StringBuffer();
executor.setStreamHandler(new PumpStreamHandler(new LogOutputStream() {
@Override
protected void processLine(String line, int level) {
line = line.trim();
if (!StringUtils.isEmpty(line)) {
sbLogOutput.append(line + "\n");
}
}
}));
if (Boolean.valueOf(properties.getProperty(SubmarineJob.DIRECTORY_USER_HOME))) {
executor.setWorkingDirectory(new File(System.getProperty("user.home")));
}
Map<String, String> env = new HashMap<>();
String launchMode = (String) jinjaParams.get(SubmarineConstants.INTERPRETER_LAUNCH_MODE);
if (StringUtils.equals(launchMode, "yarn")) {
// Set environment variables in the submarine interpreter container run on yarn
String javaHome, hadoopHome, hadoopConf;
javaHome = (String) jinjaParams.get(SubmarineConstants.DOCKER_JAVA_HOME);
hadoopHome = (String) jinjaParams.get(SubmarineConstants.DOCKER_HADOOP_HDFS_HOME);
hadoopConf = (String) jinjaParams.get(SubmarineConstants.SUBMARINE_HADOOP_CONF_DIR);
env.put("JAVA_HOME", javaHome);
env.put("HADOOP_HOME", hadoopHome);
env.put("HADOOP_HDFS_HOME", hadoopHome);
env.put("HADOOP_CONF_DIR", hadoopConf);
env.put("YARN_CONF_DIR", hadoopConf);
env.put("CLASSPATH", "`$HADOOP_HDFS_HOME/bin/hadoop classpath --glob`");
env.put("ZEPPELIN_FORCE_STOP", "true");
}
LOGGER.info("Execute EVN: {}, Command: {} ", env.toString(), submarineCmd);
AtomicBoolean cmdLineRunning = new AtomicBoolean(true);
executor.execute(cmdLine, env, new DefaultExecuteResultHandler() {
@Override
public void onProcessComplete(int exitValue) {
String message = String.format(
"jobName %s ProcessComplete exit value is : %d", jobName, exitValue);
LOGGER.info(message);
submarineUI.outputLog("JOR RUN COMPLETE", message);
cmdLineRunning.set(false);
submarineJob.setCurrentJobState(EXECUTE_SUBMARINE_FINISHED);
}
@Override
public void onProcessFailed(ExecuteException e) {
String message = String.format(
"jobName %s ProcessFailed exit value is : %d, exception is : %s",
jobName, e.getExitValue(), e.getMessage());
LOGGER.error(message);
submarineUI.outputLog("JOR RUN FAILED", message);
cmdLineRunning.set(false);
submarineJob.setCurrentJobState(EXECUTE_SUBMARINE_ERROR);
}
});
int loopCount = 100;
while ((loopCount-- > 0) && cmdLineRunning.get() && running.get()) {
Thread.sleep(1000);
}
if (watchDog.isWatching()) {
watchDog.destroyProcess();
Thread.sleep(1000);
}
if (watchDog.isWatching()) {
watchDog.killedProcess();
}
// Check if it has been submitted to YARN
Map<String, Object> jobState = submarineJob.getJobStateByYarn(jobName);
loopCount = 50;
while ((loopCount-- > 0) && !jobState.containsKey("state") && running.get()) {
Thread.sleep(3000);
jobState = submarineJob.getJobStateByYarn(jobName);
}
if (!jobState.containsKey("state")) {
String message = String.format("JOB %s was not submitted to YARN!", jobName);
LOGGER.error(message);
submarineUI.outputLog("JOR RUN FAILED", message);
submarineJob.setCurrentJobState(EXECUTE_SUBMARINE_ERROR);
}
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
submarineJob.setCurrentJobState(EXECUTE_SUBMARINE_ERROR);
submarineUI.outputLog("Exception", e.getMessage());
} finally {
running.set(false);
lockRunning.unlock();
}
}
public void stopRunning() {
try {
running.set(false);
// If can not get the lockRunning, the thread is executed.
boolean tryLock = lockRunning.tryLock();
int loop = 0;
while (false == tryLock && loop++ < 100) {
LOGGER.warn("Can not get the JobRunThread lockRunning [{}] !", loop);
Thread.sleep(500);
tryLock = lockRunning.tryLock();
}
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
} finally {
lockRunning.unlock();
}
}
}
|
/**
* Licensed to Jasig under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Jasig licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a
* copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jasig.portlet.campuslife.athletics.dao;
import org.jasig.portlet.campuslife.athletics.model.feed.xml.AthleticsFeed;
import org.jasig.portlet.campuslife.athletics.model.feed.xml.Sport;
import org.jasig.portlet.campuslife.dao.MockDataService;
public class MockAthleticsDao extends MockDataService<AthleticsFeed> implements
IAthleticsDao {
final static String PACKAGE_NAME = AthleticsFeed.class.getPackage().getName();
@Override
public AthleticsFeed getFeed() {
return this.getData();
}
@Override
public Sport getSport(String sportName) {
for (Sport sport : this.getData().getSport()) {
if (sport.getName().equals(sportName)) {
return sport;
}
}
log.info("Unable to locate sport " + sportName);
return null;
}
@Override
public String getPackageName() {
return PACKAGE_NAME;
}
}
|
/**
*
*/
/**
* @author seven
*
*/
package com.wqwy.zhnm.base.dao.integration;
|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.compute.v2019_03_01;
import java.util.Collection;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.microsoft.rest.ExpandableStringEnum;
/**
* Defines values for ReplicationState.
*/
public final class ReplicationState extends ExpandableStringEnum<ReplicationState> {
/** Static value Unknown for ReplicationState. */
public static final ReplicationState UNKNOWN = fromString("Unknown");
/** Static value Replicating for ReplicationState. */
public static final ReplicationState REPLICATING = fromString("Replicating");
/** Static value Completed for ReplicationState. */
public static final ReplicationState COMPLETED = fromString("Completed");
/** Static value Failed for ReplicationState. */
public static final ReplicationState FAILED = fromString("Failed");
/**
* Creates or finds a ReplicationState from its string representation.
* @param name a name to look for
* @return the corresponding ReplicationState
*/
@JsonCreator
public static ReplicationState fromString(String name) {
return fromString(name, ReplicationState.class);
}
/**
* @return known ReplicationState values
*/
public static Collection<ReplicationState> values() {
return values(ReplicationState.class);
}
}
|
package com.louis.mango.admin.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.louis.mango.admin.model.SysDict;
import com.louis.mango.admin.service.SysDictService;
import com.louis.mango.core.http.HttpResult;
import com.louis.mango.core.page.PageRequest;
/**
* 字典控制器
* @author Louis
* @date Jan 13, 2019
*/
@RestController
@RequestMapping("dict")
public class SysDictController {
@Autowired
private SysDictService sysDictService;
@PreAuthorize("hasAuthority('sys:dict:add') AND hasAuthority('sys:dict:edit')")
@PostMapping(value="/save")
public HttpResult save(@RequestBody SysDict record) {
return HttpResult.ok(sysDictService.save(record));
}
@PreAuthorize("hasAuthority('sys:dict:delete')")
@PostMapping(value="/delete")
public HttpResult delete(@RequestBody List<SysDict> records) {
return HttpResult.ok(sysDictService.delete(records));
}
@PreAuthorize("hasAuthority('sys:dict:view')")
@PostMapping(value="/findPage")
public HttpResult findPage(@RequestBody PageRequest pageRequest) {
return HttpResult.ok(sysDictService.findPage(pageRequest));
}
@PreAuthorize("hasAuthority('sys:dict:view')")
@GetMapping(value="/findByLable")
public HttpResult findByLable(@RequestParam String lable) {
return HttpResult.ok(sysDictService.findByLable(lable));
}
}
|
/*
* Copyright (C) 2017-2019 Dremio Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dremio.service.reflection.refresh;
import static com.dremio.service.accelerator.AccelerationUtils.selfOrEmpty;
import static com.dremio.service.reflection.ReflectionUtils.getId;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.arrow.memory.BufferAllocator;
import org.apache.calcite.rel.RelNode;
import com.dremio.common.exceptions.UserException;
import com.dremio.common.utils.PathUtils;
import com.dremio.exec.planner.acceleration.MaterializationExpander;
import com.dremio.exec.planner.acceleration.StrippingFactory;
import com.dremio.exec.planner.acceleration.UpdateIdWrapper;
import com.dremio.exec.store.RecordWriter;
import com.dremio.io.file.Path;
import com.dremio.proto.model.UpdateId;
import com.dremio.service.job.proto.Acceleration.Substitution;
import com.dremio.service.job.proto.ExtraInfo;
import com.dremio.service.job.proto.JobAttempt;
import com.dremio.service.job.proto.JobId;
import com.dremio.service.job.proto.JobInfo;
import com.dremio.service.job.proto.JobState;
import com.dremio.service.job.proto.JoinAnalysis;
import com.dremio.service.jobs.JobDataClientUtils;
import com.dremio.service.jobs.JobDataFragment;
import com.dremio.service.jobs.JobsProtoUtil;
import com.dremio.service.jobs.JobsService;
import com.dremio.service.jobs.JoinAnalyzer;
import com.dremio.service.namespace.NamespaceException;
import com.dremio.service.namespace.NamespaceService;
import com.dremio.service.namespace.dataset.proto.RefreshMethod;
import com.dremio.service.reflection.DependencyGraph.DependencyException;
import com.dremio.service.reflection.DependencyManager;
import com.dremio.service.reflection.DependencyUtils;
import com.dremio.service.reflection.ExtractedDependencies;
import com.dremio.service.reflection.ReflectionServiceImpl.ExpansionHelper;
import com.dremio.service.reflection.ReflectionUtils;
import com.dremio.service.reflection.proto.DataPartition;
import com.dremio.service.reflection.proto.JobDetails;
import com.dremio.service.reflection.proto.Materialization;
import com.dremio.service.reflection.proto.MaterializationId;
import com.dremio.service.reflection.proto.MaterializationMetrics;
import com.dremio.service.reflection.proto.ReflectionEntry;
import com.dremio.service.reflection.proto.ReflectionId;
import com.dremio.service.reflection.proto.Refresh;
import com.dremio.service.reflection.proto.RefreshDecision;
import com.dremio.service.reflection.store.MaterializationStore;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import io.protostuff.ByteString;
/**
* Handles successful refresh jobs
*/
public class RefreshDoneHandler {
protected static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(RefreshDoneHandler.class);
private final DependencyManager dependencyManager;
private final NamespaceService namespaceService;
private final MaterializationStore materializationStore;
private final Supplier<ExpansionHelper> expansionHelper;
private final Path accelerationBasePath;
private final ReflectionEntry reflection;
private final Materialization materialization;
private final com.dremio.service.job.JobDetails job;
private final JobsService jobsService;
private final BufferAllocator allocator;
public RefreshDoneHandler(
ReflectionEntry entry,
Materialization materialization,
com.dremio.service.job.JobDetails job,
JobsService jobsService,
NamespaceService namespaceService,
MaterializationStore materializationStore,
DependencyManager dependencyManager,
Supplier<ExpansionHelper> expansionHelper,
Path accelerationBasePath,
BufferAllocator allocator) {
this.reflection = Preconditions.checkNotNull(entry, "reflection entry required");
this.materialization = Preconditions.checkNotNull(materialization, "materialization required");
this.job = Preconditions.checkNotNull(job, "jobDetails required");
this.jobsService = Preconditions.checkNotNull(jobsService, "jobsService required");
this.namespaceService = Preconditions.checkNotNull(namespaceService, "namespace service required");
this.dependencyManager = Preconditions.checkNotNull(dependencyManager, "dependencies required");
this.materializationStore = materializationStore;
this.expansionHelper = Preconditions.checkNotNull(expansionHelper, "expansion helper required");
this.accelerationBasePath = Preconditions.checkNotNull(accelerationBasePath, "acceleration base path required");
this.allocator = allocator;
}
/**
* computes various materialization attributes and stats and saves the materialization in the store
* @return refresh decision
* @throws NamespaceException if we fail to access a dataset while updating the dependencies
* @throws IllegalStateException if the materialization is missing refreshes
* @throws DependencyException if cyclic dependency detected
*/
public RefreshDecision handle() throws NamespaceException, DependencyException {
JobAttempt lastAttempt = JobsProtoUtil.getLastAttempt(job);
Preconditions.checkState(lastAttempt.getState() == JobState.COMPLETED,
"Cannot handle job with non completed state %s", lastAttempt.getState());
final RefreshDecision decision = getRefreshDecision(lastAttempt);
final ByteString planBytes = Preconditions.checkNotNull(decision.getLogicalPlan(),
"refresh jobInfo has no logical plan");
updateDependencies(reflection.getId(), lastAttempt.getInfo(), decision, namespaceService, dependencyManager);
failIfNotEnoughRefreshesAvailable(decision);
final JobDetails details = ReflectionUtils.computeJobDetails(lastAttempt);
final boolean dataWritten = Optional.fromNullable(details.getOutputRecords()).or(0L) > 0;
if (dataWritten) {
createAndSaveRefresh(details, decision);
} else {
logger.debug("materialization {} didn't write any data, we won't create a refresh entry", getId(materialization));
}
if (!dataWritten && !decision.getInitialRefresh()) {
// for incremental refresh, if we don't create a refresh entry we still need to copy the materialization fields
// from the previous materialization as it will be owning the same refreshes
Preconditions.checkState(decision.getAccelerationSettings().getMethod() == RefreshMethod.INCREMENTAL,
"non initial refresh only allowed for INCREMENTAL refreshes");
final Materialization lastDone = Preconditions.checkNotNull(
materializationStore.getLastMaterializationDone(materialization.getReflectionId()),
"incremental refresh didn't write any data and previous materializations expired");
materialization.setExpiration(computeExpiration())
.setInitRefreshExecution(details.getJobStart())
.setLastRefreshFromPds(lastDone.getLastRefreshFromPds())
.setLogicalPlan(lastDone.getLogicalPlan())
.setLogicalPlanStrippedHash(decision.getLogicalPlanStrippedHash())
.setStripVersion(StrippingFactory.LATEST_STRIP_VERSION)
.setSeriesId(decision.getSeriesId())
.setSeriesOrdinal(lastDone.getSeriesOrdinal())
.setJoinAnalysis(lastDone.getJoinAnalysis())
.setPartitionList(lastDone.getPartitionList());
} else {
final Optional<Long> oldestDependentMaterialization = dependencyManager.getOldestDependentMaterialization(reflection.getId());
materialization.setExpiration(computeExpiration())
.setInitRefreshExecution(details.getJobStart())
.setLastRefreshFromPds(oldestDependentMaterialization.or(materialization.getInitRefreshSubmit()))
.setLogicalPlan(planBytes)
.setLogicalPlanStrippedHash(decision.getLogicalPlanStrippedHash())
.setStripVersion(StrippingFactory.LATEST_STRIP_VERSION)
.setSeriesId(decision.getSeriesId())
.setSeriesOrdinal(dataWritten ? decision.getSeriesOrdinal() : decision.getSeriesOrdinal() - 1)
.setJoinAnalysis(computeJoinAnalysis())
.setPartitionList(getDataPartitions());
}
materializationStore.save(materialization);
return decision;
}
public static RefreshDecision getRefreshDecision(final JobAttempt jobAttempt) {
if(jobAttempt.getExtraInfoList() == null || jobAttempt.getExtraInfoList().isEmpty()) {
throw new IllegalStateException("No refresh decision found in refresh job.");
}
List<ExtraInfo> extraInfo = jobAttempt.getExtraInfoList().stream()
.filter(i -> RefreshHandler.DECISION_NAME.equals(i.getName()))
.collect(Collectors.toList());
if(extraInfo.size() != 1) {
throw new IllegalStateException(String.format("Expected to have one refresh decision, saw: %d.", extraInfo.size()));
}
return RefreshHandler.ABSTRACT_SERIALIZER.revert(extraInfo.get(0).getData().toByteArray());
}
/**
* throws {@link IllegalStateException} if some refreshes owned by the materialization are missing.
* This can only happen if the materialization somehow took too long to finish and the previous incremental
* materialization was deleted along with its refreshes
*/
private void failIfNotEnoughRefreshesAvailable(final RefreshDecision decision) {
if (decision.getInitialRefresh()) {
return;
}
final int seriesOrdinal = decision.getSeriesOrdinal();
// seriesOrdinal is 0-based so we should expect number of refreshes in the store to be equal to the seriesOrdinal
Iterable<Refresh> refreshes = materializationStore.getRefreshesForSeries(reflection.getId(), decision.getSeriesId());
final int numRefreshes = Iterables.size(refreshes);
Preconditions.checkState(numRefreshes == seriesOrdinal,
"Materialization %s is missing refreshes. Expected %s but only found %s",
getId(materialization), seriesOrdinal, numRefreshes);
}
public static void updateDependencies(final ReflectionId id, final JobInfo info, final RefreshDecision decision,
final NamespaceService namespaceService, final DependencyManager dependencyManager) throws NamespaceException, DependencyException {
final ExtractedDependencies dependencies = DependencyUtils.extractDependencies(namespaceService, info, decision);
if (decision.getInitialRefresh()) {
if (dependencies.isEmpty()) {
throw UserException.reflectionError()
.message("Could not find any physical dependencies for reflection %s most likely " +
"because one of its datasets has a select with options or it's a select from values", id.getId())
.build(logger);
}
dependencyManager.setDependencies(id, dependencies);
} else if (!dependencies.getPlanDependencies().isEmpty()) {
// for incremental refresh, only update the dependencies if planDependencies are not empty, otherwise it's most
// likely an empty incremental refresh
dependencyManager.setDependencies(id, dependencies);
}
}
private void createAndSaveRefresh(final JobDetails details, final RefreshDecision decision) {
final JobId jobId = JobsProtoUtil.toStuff(job.getJobId());
final boolean isFull = decision.getAccelerationSettings().getMethod() == RefreshMethod.FULL;
final UpdateId updateId = isFull ? new UpdateId() : getUpdateId(jobId, jobsService, allocator);
final MaterializationMetrics metrics = ReflectionUtils.computeMetrics(job, jobsService, allocator, jobId);
final List<DataPartition> dataPartitions = ReflectionUtils.computeDataPartitions(JobsProtoUtil.getLastAttempt(job).getInfo());
final List<String> refreshPath = ReflectionUtils.getRefreshPath(jobId, accelerationBasePath, jobsService, allocator);
final boolean isIcebergRefresh = materialization.getIsIcebergDataset() != null && materialization.getIsIcebergDataset();
final String icebergBasePath = ReflectionUtils.getIcebergReflectionBasePath(materialization, refreshPath, isIcebergRefresh);
final Refresh refresh = ReflectionUtils.createRefresh(reflection.getId(), refreshPath, decision.getSeriesId(),
decision.getSeriesOrdinal(), updateId, details, metrics, dataPartitions, isIcebergRefresh, icebergBasePath);
logger.trace("Refresh created: {}", refresh);
materializationStore.save(refresh);
logger.debug("materialization {} was written to {}", ReflectionUtils.getId(materialization), PathUtils.constructFullPath(refreshPath));
}
private List<DataPartition> getDataPartitions() {
return ImmutableList.copyOf(materializationStore.getRefreshes(materialization)
.transformAndConcat(new Function<Refresh, Iterable<DataPartition>>() {
@Override
public Iterable<DataPartition> apply(Refresh input) {
return input.getPartitionList() != null ? input.getPartitionList() : ImmutableList.of();
}
}).toSet());
}
private JoinAnalysis computeJoinAnalysis() {
final JobInfo info = JobsProtoUtil.getLastAttempt(job).getInfo();
if (info.getJoinAnalysis() == null) {
return null;
}
JoinAnalysis joinAnalysis = info.getJoinAnalysis();
if (info.getAcceleration() != null) {
for (Substitution sub : selfOrEmpty(info.getAcceleration().getSubstitutionsList())) {
Materialization usedMaterialization = materializationStore.get(new MaterializationId(sub.getId().getMaterializationId()));
if (usedMaterialization == null) {
continue;
}
try (ExpansionHelper helper = expansionHelper.get()){
RelNode usedMaterializationLogicalPlan = MaterializationExpander.deserializePlan(usedMaterialization.getLogicalPlan().toByteArray(), helper.getConverter());
if (usedMaterialization.getJoinAnalysis() != null) {
joinAnalysis = JoinAnalyzer.merge(joinAnalysis, usedMaterialization.getJoinAnalysis(), usedMaterializationLogicalPlan, usedMaterialization.getId().getId());
}
}
}
}
return joinAnalysis;
}
/**
* @return next updateId
*/
private static UpdateId getUpdateId(final JobId jobId, final JobsService jobsService, BufferAllocator allocator) {
final int fetchLimit = 1000;
UpdateIdWrapper updateIdWrapper = new UpdateIdWrapper();
int offset = 0;
while (true) {
try (final JobDataFragment data = JobDataClientUtils.getJobData(jobsService, allocator, jobId, offset, fetchLimit)) {
if (data.getReturnedRowCount() <= 0) {
break;
}
for (int i = 0; i < data.getReturnedRowCount(); i++) {
byte[] b = (byte[]) data.extractValue(RecordWriter.METADATA_COLUMN, i);
if(b == null) {
throw new IllegalStateException("Didn't find metadata output for job " + jobId.getId());
}
updateIdWrapper.update(UpdateIdWrapper.deserialize(b));
}
offset += data.getReturnedRowCount();
}
}
return updateIdWrapper.getUpdateId();
}
/**
* compute reflection own expiration time.
*
* if the query doesn't depend directly on pds the grace period will be set to Long MAX as the expectation is that
* we will compute a proper expiration time from the dependent reflections
*
* @return expiration time
*/
private long computeExpiration() {
final ReflectionId reflectionId = materialization.getReflectionId();
final long jobStart = materialization.getInitRefreshSubmit();
final Optional<Long> gracePeriod = dependencyManager.getGracePeriod(reflectionId);
final Optional<Long> earliestExpiration = dependencyManager.getEarliestExpiration(reflectionId);
if (gracePeriod.isPresent() && earliestExpiration.isPresent()) {
return Math.min(earliestExpiration.get(), jobStart + gracePeriod.get());
} else if (gracePeriod.isPresent()) {
return jobStart + gracePeriod.get();
} else if (earliestExpiration.isPresent()) {
return earliestExpiration.get();
} else {
throw UserException.reflectionError()
.message("Couldn't compute expiration for materialization %s", materialization.getId().getId())
.build(logger);
}
}
}
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.yarn.server.nodemanager;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;
import org.apache.hadoop.security.Credentials;
import org.apache.hadoop.yarn.api.ContainerManagementProtocol;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.apache.hadoop.yarn.api.records.ContainerId;
import org.apache.hadoop.yarn.api.records.NodeId;
import org.apache.hadoop.yarn.api.records.SplitDataInfo;
import org.apache.hadoop.yarn.server.api.records.NodeHealthStatus;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.application.Application;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.Container;
import org.apache.hadoop.yarn.server.nodemanager.recovery.NMStateStoreService;
import org.apache.hadoop.yarn.server.nodemanager.security.NMContainerTokenSecretManager;
import org.apache.hadoop.yarn.server.nodemanager.security.NMTokenSecretManagerInNM;
import org.apache.hadoop.yarn.server.security.ApplicationACLsManager;
/**
* Context interface for sharing information across components in the
* NodeManager.
*/
public interface Context {
/**
* Return the nodeId. Usable only when the ContainerManager is started.
*
* @return the NodeId
*/
NodeId getNodeId();
/**
* Return the node http-address. Usable only after the Webserver is started.
*
* @return the http-port
*/
int getHttpPort();
ConcurrentMap<ApplicationId, Application> getApplications();
Map<ApplicationId, Credentials> getSystemCredentialsForApps();
ConcurrentMap<ContainerId, Container> getContainers();
NMContainerTokenSecretManager getContainerTokenSecretManager();
NMTokenSecretManagerInNM getNMTokenSecretManager();
NodeHealthStatus getNodeHealthStatus();
ContainerManagementProtocol getContainerManager();
LocalDirsHandlerService getLocalDirsHandler();
ApplicationACLsManager getApplicationACLsManager();
NMStateStoreService getNMStateStore();
boolean getDecommissioned();
void setDecommissioned(boolean isDecommissioned);
}
|
/**
* Copyright (c) 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
package com.facebook.csslayout;
import com.facebook.infer.annotation.Assertions;
import static com.facebook.csslayout.CSSLayout.DIMENSION_HEIGHT;
import static com.facebook.csslayout.CSSLayout.DIMENSION_WIDTH;
import static com.facebook.csslayout.CSSLayout.POSITION_BOTTOM;
import static com.facebook.csslayout.CSSLayout.POSITION_LEFT;
import static com.facebook.csslayout.CSSLayout.POSITION_RIGHT;
import static com.facebook.csslayout.CSSLayout.POSITION_TOP;
/**
* Calculates layouts based on CSS style. See {@link #layoutNode(CSSNode, float, float)}.
*/
public class LayoutEngine {
private static final int CSS_FLEX_DIRECTION_COLUMN =
CSSFlexDirection.COLUMN.ordinal();
private static final int CSS_FLEX_DIRECTION_COLUMN_REVERSE =
CSSFlexDirection.COLUMN_REVERSE.ordinal();
private static final int CSS_FLEX_DIRECTION_ROW =
CSSFlexDirection.ROW.ordinal();
private static final int CSS_FLEX_DIRECTION_ROW_REVERSE =
CSSFlexDirection.ROW_REVERSE.ordinal();
private static final int CSS_POSITION_RELATIVE = CSSPositionType.RELATIVE.ordinal();
private static final int CSS_POSITION_ABSOLUTE = CSSPositionType.ABSOLUTE.ordinal();
private static final int[] leading = {
POSITION_TOP,
POSITION_BOTTOM,
POSITION_LEFT,
POSITION_RIGHT,
};
private static final int[] trailing = {
POSITION_BOTTOM,
POSITION_TOP,
POSITION_RIGHT,
POSITION_LEFT,
};
private static final int[] pos = {
POSITION_TOP,
POSITION_BOTTOM,
POSITION_LEFT,
POSITION_RIGHT,
};
private static final int[] dim = {
DIMENSION_HEIGHT,
DIMENSION_HEIGHT,
DIMENSION_WIDTH,
DIMENSION_WIDTH,
};
private static final int[] leadingSpacing = {
Spacing.TOP,
Spacing.BOTTOM,
Spacing.START,
Spacing.START
};
private static final int[] trailingSpacing = {
Spacing.BOTTOM,
Spacing.TOP,
Spacing.END,
Spacing.END
};
private static boolean isFlexBasisAuto(CSSNode node) {
return CSSConstants.isUndefined(node.style.flexBasis);
}
private static float getFlexGrowFactor(CSSNode node) {
return node.style.flexGrow;
}
private static float getFlexShrinkFactor(CSSNode node) {
return node.style.flexShrink;
}
private static float boundAxisWithinMinAndMax(CSSNode node, int axis, float value) {
float min = CSSConstants.UNDEFINED;
float max = CSSConstants.UNDEFINED;
if (axis == CSS_FLEX_DIRECTION_COLUMN ||
axis == CSS_FLEX_DIRECTION_COLUMN_REVERSE) {
min = node.style.minHeight;
max = node.style.maxHeight;
} else if (axis == CSS_FLEX_DIRECTION_ROW ||
axis == CSS_FLEX_DIRECTION_ROW_REVERSE) {
min = node.style.minWidth;
max = node.style.maxWidth;
}
float boundValue = value;
if (!Float.isNaN(max) && max >= 0.0 && boundValue > max) {
boundValue = max;
}
if (!Float.isNaN(min) && min >= 0.0 && boundValue < min) {
boundValue = min;
}
return boundValue;
}
private static float boundAxis(CSSNode node, int axis, float value) {
float paddingAndBorderAxis =
node.style.padding.getWithFallback(leadingSpacing[axis], leading[axis]) +
node.style.border.getWithFallback(leadingSpacing[axis], leading[axis]) +
node.style.padding.getWithFallback(trailingSpacing[axis], trailing[axis]) +
node.style.border.getWithFallback(trailingSpacing[axis], trailing[axis]);
return Math.max(boundAxisWithinMinAndMax(node, axis, value), paddingAndBorderAxis);
}
private static float getRelativePosition(CSSNode node, int axis) {
float lead = node.style.position.getWithFallback(leadingSpacing[axis], leading[axis]);
if (!Float.isNaN(lead)) {
return lead;
}
float trailingPos = node.style.position.getWithFallback(trailingSpacing[axis], trailing[axis]);
return Float.isNaN(trailingPos) ? 0 : -trailingPos;
}
private static void setPosition(CSSNode node, CSSDirection direction) {
int mainAxis = resolveAxis(getFlexDirection(node), direction);
int crossAxis = getCrossFlexDirection(mainAxis, direction);
node.layout.position[leading[mainAxis]] = node.style.margin.getWithFallback(leadingSpacing[mainAxis], leading[mainAxis]) +
getRelativePosition(node, mainAxis);
node.layout.position[trailing[mainAxis]] = node.style.margin.getWithFallback(trailingSpacing[mainAxis], trailing[mainAxis]) +
getRelativePosition(node, mainAxis);
node.layout.position[leading[crossAxis]] = node.style.margin.getWithFallback(leadingSpacing[crossAxis], leading[crossAxis]) +
getRelativePosition(node, crossAxis);
node.layout.position[trailing[crossAxis]] = node.style.margin.getWithFallback(trailingSpacing[crossAxis], trailing[crossAxis]) +
getRelativePosition(node, crossAxis);
}
private static int resolveAxis(
int axis,
CSSDirection direction) {
if (direction == CSSDirection.RTL) {
if (axis == CSS_FLEX_DIRECTION_ROW) {
return CSS_FLEX_DIRECTION_ROW_REVERSE;
} else if (axis == CSS_FLEX_DIRECTION_ROW_REVERSE) {
return CSS_FLEX_DIRECTION_ROW;
}
}
return axis;
}
private static CSSDirection resolveDirection(CSSNode node, CSSDirection parentDirection) {
CSSDirection direction = node.style.direction;
if (direction == CSSDirection.INHERIT) {
direction = (parentDirection == null ? CSSDirection.LTR : parentDirection);
}
return direction;
}
private static int getFlexDirection(CSSNode node) {
return node.style.flexDirection.ordinal();
}
private static int getCrossFlexDirection(
int axis,
CSSDirection direction) {
if (axis == CSS_FLEX_DIRECTION_COLUMN ||
axis == CSS_FLEX_DIRECTION_COLUMN_REVERSE) {
return resolveAxis(CSS_FLEX_DIRECTION_ROW, direction);
} else {
return CSS_FLEX_DIRECTION_COLUMN;
}
}
private static CSSAlign getAlignItem(CSSNode node, CSSNode child) {
if (child.style.alignSelf != CSSAlign.AUTO) {
return child.style.alignSelf;
}
return node.style.alignItems;
}
private static boolean isMeasureDefined(CSSNode node) {
return node.isMeasureDefined();
}
/*package*/ static void layoutNode(
CSSLayoutContext layoutContext,
CSSNode node,
float availableWidth,
float availableHeight,
CSSDirection parentDirection) {
// Increment the generation count. This will force the recursive routine to visit
// all dirty nodes at least once. Subsequent visits will be skipped if the input
// parameters don't change.
layoutContext.currentGenerationCount++;
CSSMeasureMode widthMeasureMode = CSSMeasureMode.UNDEFINED;
CSSMeasureMode heightMeasureMode = CSSMeasureMode.UNDEFINED;
if (!Float.isNaN(availableWidth)) {
widthMeasureMode = CSSMeasureMode.EXACTLY;
} else if (node.style.dimensions[DIMENSION_WIDTH] >= 0.0) {
float marginAxisRow = (node.style.margin.getWithFallback(leadingSpacing[CSS_FLEX_DIRECTION_ROW], leading[CSS_FLEX_DIRECTION_ROW]) + node.style.margin.getWithFallback(trailingSpacing[CSS_FLEX_DIRECTION_ROW], trailing[CSS_FLEX_DIRECTION_ROW]));
availableWidth = node.style.dimensions[DIMENSION_WIDTH] + marginAxisRow;
widthMeasureMode = CSSMeasureMode.EXACTLY;
} else if (node.style.maxWidth >= 0.0) {
availableWidth = node.style.maxWidth;
widthMeasureMode = CSSMeasureMode.AT_MOST;
}
if (!Float.isNaN(availableHeight)) {
heightMeasureMode = CSSMeasureMode.EXACTLY;
} else if (node.style.dimensions[DIMENSION_HEIGHT] >= 0.0) {
float marginAxisColumn = (node.style.margin.getWithFallback(leadingSpacing[CSS_FLEX_DIRECTION_COLUMN], leading[CSS_FLEX_DIRECTION_COLUMN]) + node.style.margin.getWithFallback(trailingSpacing[CSS_FLEX_DIRECTION_COLUMN], trailing[CSS_FLEX_DIRECTION_COLUMN]));
availableHeight = node.style.dimensions[DIMENSION_HEIGHT] + marginAxisColumn;
heightMeasureMode = CSSMeasureMode.EXACTLY;
} else if (node.style.maxHeight >= 0.0) {
availableHeight = node.style.maxHeight;
heightMeasureMode = CSSMeasureMode.AT_MOST;
}
if (layoutNodeInternal(layoutContext, node, availableWidth, availableHeight, parentDirection, widthMeasureMode, heightMeasureMode, true, "initial")) {
setPosition(node, node.layout.direction);
}
}
/*package*/ static boolean canUseCachedMeasurement(
boolean isTextNode,
float availableWidth,
float availableHeight,
float marginRow,
float marginColumn,
CSSMeasureMode widthMeasureMode,
CSSMeasureMode heightMeasureMode,
CSSCachedMeasurement cachedLayout) {
boolean isHeightSame =
(cachedLayout.heightMeasureMode == CSSMeasureMode.UNDEFINED && heightMeasureMode == CSSMeasureMode.UNDEFINED) ||
(cachedLayout.heightMeasureMode == heightMeasureMode && FloatUtil.floatsEqual(cachedLayout.availableHeight, availableHeight));
boolean isWidthSame =
(cachedLayout.widthMeasureMode == CSSMeasureMode.UNDEFINED && widthMeasureMode == CSSMeasureMode.UNDEFINED) ||
(cachedLayout.widthMeasureMode == widthMeasureMode && FloatUtil.floatsEqual(cachedLayout.availableWidth, availableWidth));
if (isHeightSame && isWidthSame) {
return true;
}
boolean isHeightValid =
(cachedLayout.heightMeasureMode == CSSMeasureMode.UNDEFINED && heightMeasureMode == CSSMeasureMode.AT_MOST && cachedLayout.computedHeight <= (availableHeight - marginColumn)) ||
(heightMeasureMode == CSSMeasureMode.EXACTLY && FloatUtil.floatsEqual(cachedLayout.computedHeight, availableHeight - marginColumn));
if (isWidthSame && isHeightValid) {
return true;
}
boolean isWidthValid =
(cachedLayout.widthMeasureMode == CSSMeasureMode.UNDEFINED && widthMeasureMode == CSSMeasureMode.AT_MOST && cachedLayout.computedWidth <= (availableWidth - marginRow)) ||
(widthMeasureMode == CSSMeasureMode.EXACTLY && FloatUtil.floatsEqual(cachedLayout.computedWidth, availableWidth - marginRow));
if (isHeightSame && isWidthValid) {
return true;
}
if (isHeightValid && isWidthValid) {
return true;
}
// We know this to be text so we can apply some more specialized heuristics.
if (isTextNode) {
if (isWidthSame) {
if (heightMeasureMode == CSSMeasureMode.UNDEFINED) {
// Width is the same and height is not restricted. Re-use cahced value.
return true;
}
if (heightMeasureMode == CSSMeasureMode.AT_MOST &&
cachedLayout.computedHeight < (availableHeight - marginColumn)) {
// Width is the same and height restriction is greater than the cached height. Re-use cached value.
return true;
}
// Width is the same but height restriction imposes smaller height than previously measured.
// Update the cached value to respect the new height restriction.
cachedLayout.computedHeight = availableHeight - marginColumn;
return true;
}
if (cachedLayout.widthMeasureMode == CSSMeasureMode.UNDEFINED) {
if (widthMeasureMode == CSSMeasureMode.UNDEFINED ||
(widthMeasureMode == CSSMeasureMode.AT_MOST &&
cachedLayout.computedWidth <= (availableWidth - marginRow))) {
// Previsouly this text was measured with no width restriction, if width is now restricted
// but to a larger value than the previsouly measured width we can re-use the measurement
// as we know it will fit.
return true;
}
}
}
return false;
}
//
// This is a wrapper around the layoutNodeImpl function. It determines
// whether the layout request is redundant and can be skipped.
//
// Parameters:
// Input parameters are the same as layoutNodeImpl (see below)
// Return parameter is true if layout was performed, false if skipped
//
private static boolean layoutNodeInternal(
CSSLayoutContext layoutContext,
CSSNode node,
float availableWidth,
float availableHeight,
CSSDirection parentDirection,
CSSMeasureMode widthMeasureMode,
CSSMeasureMode heightMeasureMode,
boolean performLayout,
String reason) {
CSSLayout layout = node.layout;
boolean needToVisitNode = (node.isDirty() && layout.generationCount != layoutContext.currentGenerationCount) ||
layout.lastParentDirection != parentDirection;
if (needToVisitNode) {
// Invalidate the cached results.
layout.nextCachedMeasurementsIndex = 0;
layout.cachedLayout.widthMeasureMode = null;
layout.cachedLayout.heightMeasureMode = null;
}
CSSCachedMeasurement cachedResults = null;
// Determine whether the results are already cached. We maintain a separate
// cache for layouts and measurements. A layout operation modifies the positions
// and dimensions for nodes in the subtree. The algorithm assumes that each node
// gets layed out a maximum of one time per tree layout, but multiple measurements
// may be required to resolve all of the flex dimensions.
// We handle nodes with measure functions specially here because they are the most
// expensive to measure, so it's worth avoiding redundant measurements if at all possible.
if (isMeasureDefined(node)) {
float marginAxisRow =
node.style.margin.getWithFallback(leadingSpacing[CSS_FLEX_DIRECTION_ROW], leading[CSS_FLEX_DIRECTION_ROW]) +
node.style.margin.getWithFallback(trailingSpacing[CSS_FLEX_DIRECTION_ROW], trailing[CSS_FLEX_DIRECTION_ROW]);
float marginAxisColumn =
node.style.margin.getWithFallback(leadingSpacing[CSS_FLEX_DIRECTION_COLUMN], leading[CSS_FLEX_DIRECTION_COLUMN]) +
node.style.margin.getWithFallback(trailingSpacing[CSS_FLEX_DIRECTION_COLUMN], trailing[CSS_FLEX_DIRECTION_COLUMN]);
// First, try to use the layout cache.
if (canUseCachedMeasurement(node.isTextNode(), availableWidth, availableHeight, marginAxisRow, marginAxisColumn,
widthMeasureMode, heightMeasureMode, layout.cachedLayout)) {
cachedResults = layout.cachedLayout;
} else {
// Try to use the measurement cache.
for (int i = 0; i < layout.nextCachedMeasurementsIndex; i++) {
if (canUseCachedMeasurement(node.isTextNode(), availableWidth, availableHeight, marginAxisRow, marginAxisColumn,
widthMeasureMode, heightMeasureMode, layout.cachedMeasurements[i])) {
cachedResults = layout.cachedMeasurements[i];
break;
}
}
}
} else if (performLayout) {
if (FloatUtil.floatsEqual(layout.cachedLayout.availableWidth, availableWidth) &&
FloatUtil.floatsEqual(layout.cachedLayout.availableHeight, availableHeight) &&
layout.cachedLayout.widthMeasureMode == widthMeasureMode &&
layout.cachedLayout.heightMeasureMode == heightMeasureMode) {
cachedResults = layout.cachedLayout;
}
} else {
for (int i = 0; i < layout.nextCachedMeasurementsIndex; i++) {
if (FloatUtil.floatsEqual(layout.cachedMeasurements[i].availableWidth, availableWidth) &&
FloatUtil.floatsEqual(layout.cachedMeasurements[i].availableHeight, availableHeight) &&
layout.cachedMeasurements[i].widthMeasureMode == widthMeasureMode &&
layout.cachedMeasurements[i].heightMeasureMode == heightMeasureMode) {
cachedResults = layout.cachedMeasurements[i];
break;
}
}
}
if (!needToVisitNode && cachedResults != null) {
layout.measuredDimensions[DIMENSION_WIDTH] = cachedResults.computedWidth;
layout.measuredDimensions[DIMENSION_HEIGHT] = cachedResults.computedHeight;
} else {
layoutNodeImpl(layoutContext, node, availableWidth, availableHeight, parentDirection, widthMeasureMode, heightMeasureMode, performLayout);
layout.lastParentDirection = parentDirection;
if (cachedResults == null) {
if (layout.nextCachedMeasurementsIndex == CSSLayout.MAX_CACHED_RESULT_COUNT) {
layout.nextCachedMeasurementsIndex = 0;
}
CSSCachedMeasurement newCacheEntry = null;
if (performLayout) {
// Use the single layout cache entry.
newCacheEntry = layout.cachedLayout;
} else {
// Allocate a new measurement cache entry.
newCacheEntry = layout.cachedMeasurements[layout.nextCachedMeasurementsIndex];
if (newCacheEntry == null) {
newCacheEntry = new CSSCachedMeasurement();
layout.cachedMeasurements[layout.nextCachedMeasurementsIndex] = newCacheEntry;
}
layout.nextCachedMeasurementsIndex++;
}
newCacheEntry.availableWidth = availableWidth;
newCacheEntry.availableHeight = availableHeight;
newCacheEntry.widthMeasureMode = widthMeasureMode;
newCacheEntry.heightMeasureMode = heightMeasureMode;
newCacheEntry.computedWidth = layout.measuredDimensions[DIMENSION_WIDTH];
newCacheEntry.computedHeight = layout.measuredDimensions[DIMENSION_HEIGHT];
}
}
if (performLayout) {
node.layout.dimensions[DIMENSION_WIDTH] = node.layout.measuredDimensions[DIMENSION_WIDTH];
node.layout.dimensions[DIMENSION_HEIGHT] = node.layout.measuredDimensions[DIMENSION_HEIGHT];
node.markHasNewLayout();
}
layout.generationCount = layoutContext.currentGenerationCount;
return (needToVisitNode || cachedResults == null);
}
//
// This is the main routine that implements a subset of the flexbox layout algorithm
// described in the W3C CSS documentation: https://www.w3.org/TR/css3-flexbox/.
//
// Limitations of this algorithm, compared to the full standard:
// * Display property is always assumed to be 'flex' except for Text nodes, which
// are assumed to be 'inline-flex'.
// * The 'zIndex' property (or any form of z ordering) is not supported. Nodes are
// stacked in document order.
// * The 'order' property is not supported. The order of flex items is always defined
// by document order.
// * The 'visibility' property is always assumed to be 'visible'. Values of 'collapse'
// and 'hidden' are not supported.
// * The 'wrap' property supports only 'nowrap' (which is the default) or 'wrap'. The
// rarely-used 'wrap-reverse' is not supported.
// * Rather than allowing arbitrary combinations of flexGrow, flexShrink and
// flexBasis, this algorithm supports only the three most common combinations:
// flex: 0 is equiavlent to flex: 0 0 auto
// flex: n (where n is a positive value) is equivalent to flex: n 1 auto
// If POSITIVE_FLEX_IS_AUTO is 0, then it is equivalent to flex: n 0 0
// This is faster because the content doesn't need to be measured, but it's
// less flexible because the basis is always 0 and can't be overriden with
// the width/height attributes.
// flex: -1 (or any negative value) is equivalent to flex: 0 1 auto
// * Margins cannot be specified as 'auto'. They must be specified in terms of pixel
// values, and the default value is 0.
// * The 'baseline' value is not supported for alignItems and alignSelf properties.
// * Values of width, maxWidth, minWidth, height, maxHeight and minHeight must be
// specified as pixel values, not as percentages.
// * There is no support for calculation of dimensions based on intrinsic aspect ratios
// (e.g. images).
// * There is no support for forced breaks.
// * It does not support vertical inline directions (top-to-bottom or bottom-to-top text).
//
// Deviations from standard:
// * Section 4.5 of the spec indicates that all flex items have a default minimum
// main size. For text blocks, for example, this is the width of the widest word.
// Calculating the minimum width is expensive, so we forego it and assume a default
// minimum main size of 0.
// * Min/Max sizes in the main axis are not honored when resolving flexible lengths.
// * The spec indicates that the default value for 'flexDirection' is 'row', but
// the algorithm below assumes a default of 'column'.
//
// Input parameters:
// - node: current node to be sized and layed out
// - availableWidth & availableHeight: available size to be used for sizing the node
// or CSS_UNDEFINED if the size is not available; interpretation depends on layout
// flags
// - parentDirection: the inline (text) direction within the parent (left-to-right or
// right-to-left)
// - widthMeasureMode: indicates the sizing rules for the width (see below for explanation)
// - heightMeasureMode: indicates the sizing rules for the height (see below for explanation)
// - performLayout: specifies whether the caller is interested in just the dimensions
// of the node or it requires the entire node and its subtree to be layed out
// (with final positions)
//
// Details:
// This routine is called recursively to lay out subtrees of flexbox elements. It uses the
// information in node.style, which is treated as a read-only input. It is responsible for
// setting the layout.direction and layout.measured_dimensions fields for the input node as well
// as the layout.position and layout.line_index fields for its child nodes. The
// layout.measured_dimensions field includes any border or padding for the node but does
// not include margins.
//
// The spec describes four different layout modes: "fill available", "max content", "min content",
// and "fit content". Of these, we don't use "min content" because we don't support default
// minimum main sizes (see above for details). Each of our measure modes maps to a layout mode
// from the spec (https://www.w3.org/TR/css3-sizing/#terms):
// - CSS_MEASURE_MODE_UNDEFINED: max content
// - CSS_MEASURE_MODE_EXACTLY: fill available
// - CSS_MEASURE_MODE_AT_MOST: fit content
//
// When calling layoutNodeImpl and layoutNodeInternal, if the caller passes an available size of
// undefined then it must also pass a measure mode of CSS_MEASURE_MODE_UNDEFINED in that dimension.
//
private static void layoutNodeImpl(
CSSLayoutContext layoutContext,
CSSNode node,
float availableWidth,
float availableHeight,
CSSDirection parentDirection,
CSSMeasureMode widthMeasureMode,
CSSMeasureMode heightMeasureMode,
boolean performLayout) {
Assertions.assertCondition(Float.isNaN(availableWidth) ? widthMeasureMode == CSSMeasureMode.UNDEFINED : true, "availableWidth is indefinite so widthMeasureMode must be CSSMeasureMode.UNDEFINED");
Assertions.assertCondition(Float.isNaN(availableHeight) ? heightMeasureMode == CSSMeasureMode.UNDEFINED : true, "availableHeight is indefinite so heightMeasureMode must be CSSMeasureMode.UNDEFINED");
float paddingAndBorderAxisRow = ((node.style.padding.getWithFallback(leadingSpacing[CSS_FLEX_DIRECTION_ROW], leading[CSS_FLEX_DIRECTION_ROW]) + node.style.border.getWithFallback(leadingSpacing[CSS_FLEX_DIRECTION_ROW], leading[CSS_FLEX_DIRECTION_ROW])) + (node.style.padding.getWithFallback(trailingSpacing[CSS_FLEX_DIRECTION_ROW], trailing[CSS_FLEX_DIRECTION_ROW]) + node.style.border.getWithFallback(trailingSpacing[CSS_FLEX_DIRECTION_ROW], trailing[CSS_FLEX_DIRECTION_ROW])));
float paddingAndBorderAxisColumn = ((node.style.padding.getWithFallback(leadingSpacing[CSS_FLEX_DIRECTION_COLUMN], leading[CSS_FLEX_DIRECTION_COLUMN]) + node.style.border.getWithFallback(leadingSpacing[CSS_FLEX_DIRECTION_COLUMN], leading[CSS_FLEX_DIRECTION_COLUMN])) + (node.style.padding.getWithFallback(trailingSpacing[CSS_FLEX_DIRECTION_COLUMN], trailing[CSS_FLEX_DIRECTION_COLUMN]) + node.style.border.getWithFallback(trailingSpacing[CSS_FLEX_DIRECTION_COLUMN], trailing[CSS_FLEX_DIRECTION_COLUMN])));
float marginAxisRow = (node.style.margin.getWithFallback(leadingSpacing[CSS_FLEX_DIRECTION_ROW], leading[CSS_FLEX_DIRECTION_ROW]) + node.style.margin.getWithFallback(trailingSpacing[CSS_FLEX_DIRECTION_ROW], trailing[CSS_FLEX_DIRECTION_ROW]));
float marginAxisColumn = (node.style.margin.getWithFallback(leadingSpacing[CSS_FLEX_DIRECTION_COLUMN], leading[CSS_FLEX_DIRECTION_COLUMN]) + node.style.margin.getWithFallback(trailingSpacing[CSS_FLEX_DIRECTION_COLUMN], trailing[CSS_FLEX_DIRECTION_COLUMN]));
// Set the resolved resolution in the node's layout.
CSSDirection direction = resolveDirection(node, parentDirection);
node.layout.direction = direction;
// For content (text) nodes, determine the dimensions based on the text contents.
if (isMeasureDefined(node)) {
float innerWidth = availableWidth - marginAxisRow - paddingAndBorderAxisRow;
float innerHeight = availableHeight - marginAxisColumn - paddingAndBorderAxisColumn;
if (widthMeasureMode == CSSMeasureMode.EXACTLY && heightMeasureMode == CSSMeasureMode.EXACTLY) {
// Don't bother sizing the text if both dimensions are already defined.
node.layout.measuredDimensions[DIMENSION_WIDTH] = boundAxis(node, CSS_FLEX_DIRECTION_ROW, availableWidth - marginAxisRow);
node.layout.measuredDimensions[DIMENSION_HEIGHT] = boundAxis(node, CSS_FLEX_DIRECTION_COLUMN, availableHeight - marginAxisColumn);
} else if (innerWidth <= 0 || innerHeight <= 0) {
// Don't bother sizing the text if there's no horizontal or vertical space.
node.layout.measuredDimensions[DIMENSION_WIDTH] = boundAxis(node, CSS_FLEX_DIRECTION_ROW, 0);
node.layout.measuredDimensions[DIMENSION_HEIGHT] = boundAxis(node, CSS_FLEX_DIRECTION_COLUMN, 0);
} else {
// Measure the text under the current constraints.
MeasureOutput measureDim = node.measure(
layoutContext.measureOutput,
innerWidth,
widthMeasureMode,
innerHeight,
heightMeasureMode
);
node.layout.measuredDimensions[DIMENSION_WIDTH] = boundAxis(node, CSS_FLEX_DIRECTION_ROW,
(widthMeasureMode == CSSMeasureMode.UNDEFINED || widthMeasureMode == CSSMeasureMode.AT_MOST) ?
measureDim.width + paddingAndBorderAxisRow :
availableWidth - marginAxisRow);
node.layout.measuredDimensions[DIMENSION_HEIGHT] = boundAxis(node, CSS_FLEX_DIRECTION_COLUMN,
(heightMeasureMode == CSSMeasureMode.UNDEFINED || heightMeasureMode == CSSMeasureMode.AT_MOST) ?
measureDim.height + paddingAndBorderAxisColumn :
availableHeight - marginAxisColumn);
}
return;
}
// For nodes with no children, use the available values if they were provided, or
// the minimum size as indicated by the padding and border sizes.
int childCount = node.getChildCount();
if (childCount == 0) {
node.layout.measuredDimensions[DIMENSION_WIDTH] = boundAxis(node, CSS_FLEX_DIRECTION_ROW,
(widthMeasureMode == CSSMeasureMode.UNDEFINED || widthMeasureMode == CSSMeasureMode.AT_MOST) ?
paddingAndBorderAxisRow :
availableWidth - marginAxisRow);
node.layout.measuredDimensions[DIMENSION_HEIGHT] = boundAxis(node, CSS_FLEX_DIRECTION_COLUMN,
(heightMeasureMode == CSSMeasureMode.UNDEFINED || heightMeasureMode == CSSMeasureMode.AT_MOST) ?
paddingAndBorderAxisColumn :
availableHeight - marginAxisColumn);
return;
}
// If we're not being asked to perform a full layout, we can handle a number of common
// cases here without incurring the cost of the remaining function.
if (!performLayout) {
// If we're being asked to size the content with an at most constraint but there is no available width,
// the measurement will always be zero.
if (widthMeasureMode == CSSMeasureMode.AT_MOST && availableWidth <= 0 &&
heightMeasureMode == CSSMeasureMode.AT_MOST && availableHeight <= 0) {
node.layout.measuredDimensions[DIMENSION_WIDTH] = boundAxis(node, CSS_FLEX_DIRECTION_ROW, 0);
node.layout.measuredDimensions[DIMENSION_HEIGHT] = boundAxis(node, CSS_FLEX_DIRECTION_COLUMN, 0);
return;
}
if (widthMeasureMode == CSSMeasureMode.AT_MOST && availableWidth <= 0) {
node.layout.measuredDimensions[DIMENSION_WIDTH] = boundAxis(node, CSS_FLEX_DIRECTION_ROW, 0);
node.layout.measuredDimensions[DIMENSION_HEIGHT] = boundAxis(node, CSS_FLEX_DIRECTION_COLUMN, Float.isNaN(availableHeight) ? 0 : (availableHeight - marginAxisColumn));
return;
}
if (heightMeasureMode == CSSMeasureMode.AT_MOST && availableHeight <= 0) {
node.layout.measuredDimensions[DIMENSION_WIDTH] = boundAxis(node, CSS_FLEX_DIRECTION_ROW, Float.isNaN(availableWidth) ? 0 : (availableWidth - marginAxisRow));
node.layout.measuredDimensions[DIMENSION_HEIGHT] = boundAxis(node, CSS_FLEX_DIRECTION_COLUMN, 0);
return;
}
// If we're being asked to use an exact width/height, there's no need to measure the children.
if (widthMeasureMode == CSSMeasureMode.EXACTLY && heightMeasureMode == CSSMeasureMode.EXACTLY) {
node.layout.measuredDimensions[DIMENSION_WIDTH] = boundAxis(node, CSS_FLEX_DIRECTION_ROW, availableWidth - marginAxisRow);
node.layout.measuredDimensions[DIMENSION_HEIGHT] = boundAxis(node, CSS_FLEX_DIRECTION_COLUMN, availableHeight - marginAxisColumn);
return;
}
}
// STEP 1: CALCULATE VALUES FOR REMAINDER OF ALGORITHM
int mainAxis = resolveAxis(getFlexDirection(node), direction);
int crossAxis = getCrossFlexDirection(mainAxis, direction);
boolean isMainAxisRow = (mainAxis == CSS_FLEX_DIRECTION_ROW || mainAxis == CSS_FLEX_DIRECTION_ROW_REVERSE);
CSSJustify justifyContent = node.style.justifyContent;
boolean isNodeFlexWrap = (node.style.flexWrap == CSSWrap.WRAP);
CSSNode firstAbsoluteChild = null;
CSSNode currentAbsoluteChild = null;
float leadingPaddingAndBorderMain = (node.style.padding.getWithFallback(leadingSpacing[mainAxis], leading[mainAxis]) + node.style.border.getWithFallback(leadingSpacing[mainAxis], leading[mainAxis]));
float trailingPaddingAndBorderMain = (node.style.padding.getWithFallback(trailingSpacing[mainAxis], trailing[mainAxis]) + node.style.border.getWithFallback(trailingSpacing[mainAxis], trailing[mainAxis]));
float leadingPaddingAndBorderCross = (node.style.padding.getWithFallback(leadingSpacing[crossAxis], leading[crossAxis]) + node.style.border.getWithFallback(leadingSpacing[crossAxis], leading[crossAxis]));
float paddingAndBorderAxisMain = ((node.style.padding.getWithFallback(leadingSpacing[mainAxis], leading[mainAxis]) + node.style.border.getWithFallback(leadingSpacing[mainAxis], leading[mainAxis])) + (node.style.padding.getWithFallback(trailingSpacing[mainAxis], trailing[mainAxis]) + node.style.border.getWithFallback(trailingSpacing[mainAxis], trailing[mainAxis])));
float paddingAndBorderAxisCross = ((node.style.padding.getWithFallback(leadingSpacing[crossAxis], leading[crossAxis]) + node.style.border.getWithFallback(leadingSpacing[crossAxis], leading[crossAxis])) + (node.style.padding.getWithFallback(trailingSpacing[crossAxis], trailing[crossAxis]) + node.style.border.getWithFallback(trailingSpacing[crossAxis], trailing[crossAxis])));
CSSMeasureMode measureModeMainDim = isMainAxisRow ? widthMeasureMode : heightMeasureMode;
CSSMeasureMode measureModeCrossDim = isMainAxisRow ? heightMeasureMode : widthMeasureMode;
// STEP 2: DETERMINE AVAILABLE SIZE IN MAIN AND CROSS DIRECTIONS
float availableInnerWidth = availableWidth - marginAxisRow - paddingAndBorderAxisRow;
float availableInnerHeight = availableHeight - marginAxisColumn - paddingAndBorderAxisColumn;
float availableInnerMainDim = isMainAxisRow ? availableInnerWidth : availableInnerHeight;
float availableInnerCrossDim = isMainAxisRow ? availableInnerHeight : availableInnerWidth;
// STEP 3: DETERMINE FLEX BASIS FOR EACH ITEM
CSSNode child;
int i;
float childWidth;
float childHeight;
CSSMeasureMode childWidthMeasureMode;
CSSMeasureMode childHeightMeasureMode;
for (i = 0; i < childCount; i++) {
child = node.getChildAt(i);
if (performLayout) {
// Set the initial position (relative to the parent).
CSSDirection childDirection = resolveDirection(child, direction);
setPosition(child, childDirection);
}
// Absolute-positioned children don't participate in flex layout. Add them
// to a list that we can process later.
if (child.style.positionType == CSSPositionType.ABSOLUTE) {
// Store a private linked list of absolutely positioned children
// so that we can efficiently traverse them later.
if (firstAbsoluteChild == null) {
firstAbsoluteChild = child;
}
if (currentAbsoluteChild != null) {
currentAbsoluteChild.nextChild = child;
}
currentAbsoluteChild = child;
child.nextChild = null;
} else {
if (isMainAxisRow && (child.style.dimensions[dim[CSS_FLEX_DIRECTION_ROW]] >= 0.0)) {
// The width is definite, so use that as the flex basis.
child.layout.computedFlexBasis = Math.max(child.style.dimensions[DIMENSION_WIDTH], ((child.style.padding.getWithFallback(leadingSpacing[CSS_FLEX_DIRECTION_ROW], leading[CSS_FLEX_DIRECTION_ROW]) + child.style.border.getWithFallback(leadingSpacing[CSS_FLEX_DIRECTION_ROW], leading[CSS_FLEX_DIRECTION_ROW])) + (child.style.padding.getWithFallback(trailingSpacing[CSS_FLEX_DIRECTION_ROW], trailing[CSS_FLEX_DIRECTION_ROW]) + child.style.border.getWithFallback(trailingSpacing[CSS_FLEX_DIRECTION_ROW], trailing[CSS_FLEX_DIRECTION_ROW]))));
} else if (!isMainAxisRow && (child.style.dimensions[dim[CSS_FLEX_DIRECTION_COLUMN]] >= 0.0)) {
// The height is definite, so use that as the flex basis.
child.layout.computedFlexBasis = Math.max(child.style.dimensions[DIMENSION_HEIGHT], ((child.style.padding.getWithFallback(leadingSpacing[CSS_FLEX_DIRECTION_COLUMN], leading[CSS_FLEX_DIRECTION_COLUMN]) + child.style.border.getWithFallback(leadingSpacing[CSS_FLEX_DIRECTION_COLUMN], leading[CSS_FLEX_DIRECTION_COLUMN])) + (child.style.padding.getWithFallback(trailingSpacing[CSS_FLEX_DIRECTION_COLUMN], trailing[CSS_FLEX_DIRECTION_COLUMN]) + child.style.border.getWithFallback(trailingSpacing[CSS_FLEX_DIRECTION_COLUMN], trailing[CSS_FLEX_DIRECTION_COLUMN]))));
} else if (!isFlexBasisAuto(child) && !Float.isNaN(availableInnerMainDim)) {
// If the basis isn't 'auto', it is assumed to be zero.
child.layout.computedFlexBasis = Math.max(child.style.flexBasis, ((child.style.padding.getWithFallback(leadingSpacing[mainAxis], leading[mainAxis]) + child.style.border.getWithFallback(leadingSpacing[mainAxis], leading[mainAxis])) + (child.style.padding.getWithFallback(trailingSpacing[mainAxis], trailing[mainAxis]) + child.style.border.getWithFallback(trailingSpacing[mainAxis], trailing[mainAxis]))));
} else {
// Compute the flex basis and hypothetical main size (i.e. the clamped flex basis).
childWidth = CSSConstants.UNDEFINED;
childHeight = CSSConstants.UNDEFINED;
childWidthMeasureMode = CSSMeasureMode.UNDEFINED;
childHeightMeasureMode = CSSMeasureMode.UNDEFINED;
if ((child.style.dimensions[dim[CSS_FLEX_DIRECTION_ROW]] >= 0.0)) {
childWidth = child.style.dimensions[DIMENSION_WIDTH] + (child.style.margin.getWithFallback(leadingSpacing[CSS_FLEX_DIRECTION_ROW], leading[CSS_FLEX_DIRECTION_ROW]) + child.style.margin.getWithFallback(trailingSpacing[CSS_FLEX_DIRECTION_ROW], trailing[CSS_FLEX_DIRECTION_ROW]));
childWidthMeasureMode = CSSMeasureMode.EXACTLY;
}
if ((child.style.dimensions[dim[CSS_FLEX_DIRECTION_COLUMN]] >= 0.0)) {
childHeight = child.style.dimensions[DIMENSION_HEIGHT] + (child.style.margin.getWithFallback(leadingSpacing[CSS_FLEX_DIRECTION_COLUMN], leading[CSS_FLEX_DIRECTION_COLUMN]) + child.style.margin.getWithFallback(trailingSpacing[CSS_FLEX_DIRECTION_COLUMN], trailing[CSS_FLEX_DIRECTION_COLUMN]));
childHeightMeasureMode = CSSMeasureMode.EXACTLY;
}
// According to the spec, if the main size is not definite and the
// child's inline axis is parallel to the main axis (i.e. it's
// horizontal), the child should be sized using "UNDEFINED" in
// the main size. Otherwise use "AT_MOST" in the cross axis.
if (!isMainAxisRow && Float.isNaN(childWidth) && !Float.isNaN(availableInnerWidth)) {
childWidth = availableInnerWidth;
childWidthMeasureMode = CSSMeasureMode.AT_MOST;
}
// The W3C spec doesn't say anything about the 'overflow' property,
// but all major browsers appear to implement the following logic.
if (node.style.overflow == CSSOverflow.HIDDEN) {
if (isMainAxisRow && Float.isNaN(childHeight) && !Float.isNaN(availableInnerHeight)) {
childHeight = availableInnerHeight;
childHeightMeasureMode = CSSMeasureMode.AT_MOST;
}
}
// If child has no defined size in the cross axis and is set to stretch, set the cross
// axis to be measured exactly with the available inner width
if (!isMainAxisRow &&
!Float.isNaN(availableInnerWidth) &&
!(child.style.dimensions[dim[CSS_FLEX_DIRECTION_ROW]] >= 0.0) &&
widthMeasureMode == CSSMeasureMode.EXACTLY &&
getAlignItem(node, child) == CSSAlign.STRETCH) {
childWidth = availableInnerWidth;
childWidthMeasureMode = CSSMeasureMode.EXACTLY;
}
if (isMainAxisRow &&
!Float.isNaN(availableInnerHeight) &&
!(child.style.dimensions[dim[CSS_FLEX_DIRECTION_COLUMN]] >= 0.0) &&
heightMeasureMode == CSSMeasureMode.EXACTLY &&
getAlignItem(node, child) == CSSAlign.STRETCH) {
childHeight = availableInnerHeight;
childHeightMeasureMode = CSSMeasureMode.EXACTLY;
}
// Measure the child
layoutNodeInternal(layoutContext, child, childWidth, childHeight, direction, childWidthMeasureMode, childHeightMeasureMode, false, "measure");
child.layout.computedFlexBasis = Math.max(isMainAxisRow ? child.layout.measuredDimensions[DIMENSION_WIDTH] : child.layout.measuredDimensions[DIMENSION_HEIGHT], ((child.style.padding.getWithFallback(leadingSpacing[mainAxis], leading[mainAxis]) + child.style.border.getWithFallback(leadingSpacing[mainAxis], leading[mainAxis])) + (child.style.padding.getWithFallback(trailingSpacing[mainAxis], trailing[mainAxis]) + child.style.border.getWithFallback(trailingSpacing[mainAxis], trailing[mainAxis]))));
}
}
}
// STEP 4: COLLECT FLEX ITEMS INTO FLEX LINES
// Indexes of children that represent the first and last items in the line.
int startOfLineIndex = 0;
int endOfLineIndex = 0;
// Number of lines.
int lineCount = 0;
// Accumulated cross dimensions of all lines so far.
float totalLineCrossDim = 0;
// Max main dimension of all the lines.
float maxLineMainDim = 0;
while (endOfLineIndex < childCount) {
// Number of items on the currently line. May be different than the difference
// between start and end indicates because we skip over absolute-positioned items.
int itemsOnLine = 0;
// sizeConsumedOnCurrentLine is accumulation of the dimensions and margin
// of all the children on the current line. This will be used in order to
// either set the dimensions of the node if none already exist or to compute
// the remaining space left for the flexible children.
float sizeConsumedOnCurrentLine = 0;
float totalFlexGrowFactors = 0;
float totalFlexShrinkScaledFactors = 0;
i = startOfLineIndex;
// Maintain a linked list of the child nodes that can shrink and/or grow.
CSSNode firstRelativeChild = null;
CSSNode currentRelativeChild = null;
// Add items to the current line until it's full or we run out of items.
while (i < childCount) {
child = node.getChildAt(i);
child.lineIndex = lineCount;
if (child.style.positionType != CSSPositionType.ABSOLUTE) {
float outerFlexBasis = child.layout.computedFlexBasis + (child.style.margin.getWithFallback(leadingSpacing[mainAxis], leading[mainAxis]) + child.style.margin.getWithFallback(trailingSpacing[mainAxis], trailing[mainAxis]));
// If this is a multi-line flow and this item pushes us over the available size, we've
// hit the end of the current line. Break out of the loop and lay out the current line.
if (sizeConsumedOnCurrentLine + outerFlexBasis > availableInnerMainDim && isNodeFlexWrap && itemsOnLine > 0) {
break;
}
sizeConsumedOnCurrentLine += outerFlexBasis;
itemsOnLine++;
if ((child.style.positionType == CSSPositionType.RELATIVE && (child.style.flexGrow != 0 || child.style.flexShrink != 0))) {
totalFlexGrowFactors += getFlexGrowFactor(child);
// Unlike the grow factor, the shrink factor is scaled relative to the child
// dimension.
totalFlexShrinkScaledFactors += getFlexShrinkFactor(child) * child.layout.computedFlexBasis;
}
// Store a private linked list of children that need to be layed out.
if (firstRelativeChild == null) {
firstRelativeChild = child;
}
if (currentRelativeChild != null) {
currentRelativeChild.nextChild = child;
}
currentRelativeChild = child;
child.nextChild = null;
}
i++;
endOfLineIndex++;
}
// If we don't need to measure the cross axis, we can skip the entire flex step.
boolean canSkipFlex = !performLayout && measureModeCrossDim == CSSMeasureMode.EXACTLY;
// In order to position the elements in the main axis, we have two
// controls. The space between the beginning and the first element
// and the space between each two elements.
float leadingMainDim = 0;
float betweenMainDim = 0;
// STEP 5: RESOLVING FLEXIBLE LENGTHS ON MAIN AXIS
// Calculate the remaining available space that needs to be allocated.
// If the main dimension size isn't known, it is computed based on
// the line length, so there's no more space left to distribute.
float remainingFreeSpace = 0;
if (!Float.isNaN(availableInnerMainDim)) {
remainingFreeSpace = availableInnerMainDim - sizeConsumedOnCurrentLine;
} else if (sizeConsumedOnCurrentLine < 0) {
// availableInnerMainDim is indefinite which means the node is being sized based on its content.
// sizeConsumedOnCurrentLine is negative which means the node will allocate 0 pixels for
// its content. Consequently, remainingFreeSpace is 0 - sizeConsumedOnCurrentLine.
remainingFreeSpace = -sizeConsumedOnCurrentLine;
}
float originalRemainingFreeSpace = remainingFreeSpace;
float deltaFreeSpace = 0;
if (!canSkipFlex) {
float childFlexBasis;
float flexShrinkScaledFactor;
float flexGrowFactor;
float baseMainSize;
float boundMainSize;
// Do two passes over the flex items to figure out how to distribute the remaining space.
// The first pass finds the items whose min/max constraints trigger, freezes them at those
// sizes, and excludes those sizes from the remaining space. The second pass sets the size
// of each flexible item. It distributes the remaining space amongst the items whose min/max
// constraints didn't trigger in pass 1. For the other items, it sets their sizes by forcing
// their min/max constraints to trigger again.
//
// This two pass approach for resolving min/max constraints deviates from the spec. The
// spec (https://www.w3.org/TR/css-flexbox-1/#resolve-flexible-lengths) describes a process
// that needs to be repeated a variable number of times. The algorithm implemented here
// won't handle all cases but it was simpler to implement and it mitigates performance
// concerns because we know exactly how many passes it'll do.
// First pass: detect the flex items whose min/max constraints trigger
float deltaFlexShrinkScaledFactors = 0;
float deltaFlexGrowFactors = 0;
currentRelativeChild = firstRelativeChild;
while (currentRelativeChild != null) {
childFlexBasis = currentRelativeChild.layout.computedFlexBasis;
if (remainingFreeSpace < 0) {
flexShrinkScaledFactor = getFlexShrinkFactor(currentRelativeChild) * childFlexBasis;
// Is this child able to shrink?
if (flexShrinkScaledFactor != 0) {
baseMainSize = childFlexBasis +
remainingFreeSpace / totalFlexShrinkScaledFactors * flexShrinkScaledFactor;
boundMainSize = boundAxis(currentRelativeChild, mainAxis, baseMainSize);
if (baseMainSize != boundMainSize) {
// By excluding this item's size and flex factor from remaining, this item's
// min/max constraints should also trigger in the second pass resulting in the
// item's size calculation being identical in the first and second passes.
deltaFreeSpace -= boundMainSize - childFlexBasis;
deltaFlexShrinkScaledFactors -= flexShrinkScaledFactor;
}
}
} else if (remainingFreeSpace > 0) {
flexGrowFactor = getFlexGrowFactor(currentRelativeChild);
// Is this child able to grow?
if (flexGrowFactor != 0) {
baseMainSize = childFlexBasis +
remainingFreeSpace / totalFlexGrowFactors * flexGrowFactor;
boundMainSize = boundAxis(currentRelativeChild, mainAxis, baseMainSize);
if (baseMainSize != boundMainSize) {
// By excluding this item's size and flex factor from remaining, this item's
// min/max constraints should also trigger in the second pass resulting in the
// item's size calculation being identical in the first and second passes.
deltaFreeSpace -= boundMainSize - childFlexBasis;
deltaFlexGrowFactors -= flexGrowFactor;
}
}
}
currentRelativeChild = currentRelativeChild.nextChild;
}
totalFlexShrinkScaledFactors += deltaFlexShrinkScaledFactors;
totalFlexGrowFactors += deltaFlexGrowFactors;
remainingFreeSpace += deltaFreeSpace;
// Second pass: resolve the sizes of the flexible items
deltaFreeSpace = 0;
currentRelativeChild = firstRelativeChild;
while (currentRelativeChild != null) {
childFlexBasis = currentRelativeChild.layout.computedFlexBasis;
float updatedMainSize = childFlexBasis;
if (remainingFreeSpace < 0) {
flexShrinkScaledFactor = getFlexShrinkFactor(currentRelativeChild) * childFlexBasis;
// Is this child able to shrink?
if (flexShrinkScaledFactor != 0) {
updatedMainSize = boundAxis(currentRelativeChild, mainAxis, childFlexBasis +
remainingFreeSpace / totalFlexShrinkScaledFactors * flexShrinkScaledFactor);
}
} else if (remainingFreeSpace > 0) {
flexGrowFactor = getFlexGrowFactor(currentRelativeChild);
// Is this child able to grow?
if (flexGrowFactor != 0) {
updatedMainSize = boundAxis(currentRelativeChild, mainAxis, childFlexBasis +
remainingFreeSpace / totalFlexGrowFactors * flexGrowFactor);
}
}
deltaFreeSpace -= updatedMainSize - childFlexBasis;
if (isMainAxisRow) {
childWidth = updatedMainSize + (currentRelativeChild.style.margin.getWithFallback(leadingSpacing[CSS_FLEX_DIRECTION_ROW], leading[CSS_FLEX_DIRECTION_ROW]) + currentRelativeChild.style.margin.getWithFallback(trailingSpacing[CSS_FLEX_DIRECTION_ROW], trailing[CSS_FLEX_DIRECTION_ROW]));
childWidthMeasureMode = CSSMeasureMode.EXACTLY;
if (!Float.isNaN(availableInnerCrossDim) &&
!(currentRelativeChild.style.dimensions[dim[CSS_FLEX_DIRECTION_COLUMN]] >= 0.0) &&
heightMeasureMode == CSSMeasureMode.EXACTLY &&
getAlignItem(node, currentRelativeChild) == CSSAlign.STRETCH) {
childHeight = availableInnerCrossDim;
childHeightMeasureMode = CSSMeasureMode.EXACTLY;
} else if (!(currentRelativeChild.style.dimensions[dim[CSS_FLEX_DIRECTION_COLUMN]] >= 0.0)) {
childHeight = availableInnerCrossDim;
childHeightMeasureMode = Float.isNaN(childHeight) ? CSSMeasureMode.UNDEFINED : CSSMeasureMode.AT_MOST;
} else {
childHeight = currentRelativeChild.style.dimensions[DIMENSION_HEIGHT] + (currentRelativeChild.style.margin.getWithFallback(leadingSpacing[CSS_FLEX_DIRECTION_COLUMN], leading[CSS_FLEX_DIRECTION_COLUMN]) + currentRelativeChild.style.margin.getWithFallback(trailingSpacing[CSS_FLEX_DIRECTION_COLUMN], trailing[CSS_FLEX_DIRECTION_COLUMN]));
childHeightMeasureMode = CSSMeasureMode.EXACTLY;
}
} else {
childHeight = updatedMainSize + (currentRelativeChild.style.margin.getWithFallback(leadingSpacing[CSS_FLEX_DIRECTION_COLUMN], leading[CSS_FLEX_DIRECTION_COLUMN]) + currentRelativeChild.style.margin.getWithFallback(trailingSpacing[CSS_FLEX_DIRECTION_COLUMN], trailing[CSS_FLEX_DIRECTION_COLUMN]));
childHeightMeasureMode = CSSMeasureMode.EXACTLY;
if (!Float.isNaN(availableInnerCrossDim) &&
!(currentRelativeChild.style.dimensions[dim[CSS_FLEX_DIRECTION_ROW]] >= 0.0) &&
widthMeasureMode == CSSMeasureMode.EXACTLY &&
getAlignItem(node, currentRelativeChild) == CSSAlign.STRETCH) {
childWidth = availableInnerCrossDim;
childWidthMeasureMode = CSSMeasureMode.EXACTLY;
} else if (!(currentRelativeChild.style.dimensions[dim[CSS_FLEX_DIRECTION_ROW]] >= 0.0)) {
childWidth = availableInnerCrossDim;
childWidthMeasureMode = Float.isNaN(childWidth) ? CSSMeasureMode.UNDEFINED : CSSMeasureMode.AT_MOST;
} else {
childWidth = currentRelativeChild.style.dimensions[DIMENSION_WIDTH] + (currentRelativeChild.style.margin.getWithFallback(leadingSpacing[CSS_FLEX_DIRECTION_ROW], leading[CSS_FLEX_DIRECTION_ROW]) + currentRelativeChild.style.margin.getWithFallback(trailingSpacing[CSS_FLEX_DIRECTION_ROW], trailing[CSS_FLEX_DIRECTION_ROW]));
childWidthMeasureMode = CSSMeasureMode.EXACTLY;
}
}
boolean requiresStretchLayout = !(currentRelativeChild.style.dimensions[dim[crossAxis]] >= 0.0) &&
getAlignItem(node, currentRelativeChild) == CSSAlign.STRETCH;
// Recursively call the layout algorithm for this child with the updated main size.
layoutNodeInternal(layoutContext, currentRelativeChild, childWidth, childHeight, direction, childWidthMeasureMode, childHeightMeasureMode, performLayout && !requiresStretchLayout, "flex");
currentRelativeChild = currentRelativeChild.nextChild;
}
}
remainingFreeSpace = originalRemainingFreeSpace + deltaFreeSpace;
// STEP 6: MAIN-AXIS JUSTIFICATION & CROSS-AXIS SIZE DETERMINATION
// At this point, all the children have their dimensions set in the main axis.
// Their dimensions are also set in the cross axis with the exception of items
// that are aligned "stretch". We need to compute these stretch values and
// set the final positions.
// If we are using "at most" rules in the main axis, we won't distribute
// any remaining space at this point.
if (measureModeMainDim == CSSMeasureMode.AT_MOST) {
remainingFreeSpace = 0;
}
// Use justifyContent to figure out how to allocate the remaining space
// available in the main axis.
if (justifyContent != CSSJustify.FLEX_START) {
if (justifyContent == CSSJustify.CENTER) {
leadingMainDim = remainingFreeSpace / 2;
} else if (justifyContent == CSSJustify.FLEX_END) {
leadingMainDim = remainingFreeSpace;
} else if (justifyContent == CSSJustify.SPACE_BETWEEN) {
remainingFreeSpace = Math.max(remainingFreeSpace, 0);
if (itemsOnLine > 1) {
betweenMainDim = remainingFreeSpace / (itemsOnLine - 1);
} else {
betweenMainDim = 0;
}
} else if (justifyContent == CSSJustify.SPACE_AROUND) {
// Space on the edges is half of the space between elements
betweenMainDim = remainingFreeSpace / itemsOnLine;
leadingMainDim = betweenMainDim / 2;
}
}
float mainDim = leadingPaddingAndBorderMain + leadingMainDim;
float crossDim = 0;
for (i = startOfLineIndex; i < endOfLineIndex; ++i) {
child = node.getChildAt(i);
if (child.style.positionType == CSSPositionType.ABSOLUTE &&
!Float.isNaN(child.style.position.getWithFallback(leadingSpacing[mainAxis], leading[mainAxis]))) {
if (performLayout) {
// In case the child is position absolute and has left/top being
// defined, we override the position to whatever the user said
// (and margin/border).
child.layout.position[pos[mainAxis]] =
(Float.isNaN(child.style.position.getWithFallback(leadingSpacing[mainAxis], leading[mainAxis])) ?
0 :
child.style.position.getWithFallback(leadingSpacing[mainAxis], leading[mainAxis])) +
node.style.border.getWithFallback(leadingSpacing[mainAxis], leading[mainAxis]) +
child.style.margin.getWithFallback(leadingSpacing[mainAxis], leading[mainAxis]);
}
} else {
if (performLayout) {
// If the child is position absolute (without top/left) or relative,
// we put it at the current accumulated offset.
child.layout.position[pos[mainAxis]] += mainDim;
}
// Now that we placed the element, we need to update the variables.
// We need to do that only for relative elements. Absolute elements
// do not take part in that phase.
if (child.style.positionType == CSSPositionType.RELATIVE) {
if (canSkipFlex) {
// If we skipped the flex step, then we can't rely on the measuredDims because
// they weren't computed. This means we can't call getDimWithMargin.
mainDim += betweenMainDim + (child.style.margin.getWithFallback(leadingSpacing[mainAxis], leading[mainAxis]) + child.style.margin.getWithFallback(trailingSpacing[mainAxis], trailing[mainAxis])) + child.layout.computedFlexBasis;
crossDim = availableInnerCrossDim;
} else {
// The main dimension is the sum of all the elements dimension plus
// the spacing.
mainDim += betweenMainDim + (child.layout.measuredDimensions[dim[mainAxis]] + child.style.margin.getWithFallback(leadingSpacing[mainAxis], leading[mainAxis]) + child.style.margin.getWithFallback(trailingSpacing[mainAxis], trailing[mainAxis]));
// The cross dimension is the max of the elements dimension since there
// can only be one element in that cross dimension.
crossDim = Math.max(crossDim, (child.layout.measuredDimensions[dim[crossAxis]] + child.style.margin.getWithFallback(leadingSpacing[crossAxis], leading[crossAxis]) + child.style.margin.getWithFallback(trailingSpacing[crossAxis], trailing[crossAxis])));
}
}
}
}
mainDim += trailingPaddingAndBorderMain;
float containerCrossAxis = availableInnerCrossDim;
if (measureModeCrossDim == CSSMeasureMode.UNDEFINED || measureModeCrossDim == CSSMeasureMode.AT_MOST) {
// Compute the cross axis from the max cross dimension of the children.
containerCrossAxis = boundAxis(node, crossAxis, crossDim + paddingAndBorderAxisCross) - paddingAndBorderAxisCross;
if (measureModeCrossDim == CSSMeasureMode.AT_MOST) {
containerCrossAxis = Math.min(containerCrossAxis, availableInnerCrossDim);
}
}
// If there's no flex wrap, the cross dimension is defined by the container.
if (!isNodeFlexWrap && measureModeCrossDim == CSSMeasureMode.EXACTLY) {
crossDim = availableInnerCrossDim;
}
// Clamp to the min/max size specified on the container.
crossDim = boundAxis(node, crossAxis, crossDim + paddingAndBorderAxisCross) - paddingAndBorderAxisCross;
// STEP 7: CROSS-AXIS ALIGNMENT
// We can skip child alignment if we're just measuring the container.
if (performLayout) {
for (i = startOfLineIndex; i < endOfLineIndex; ++i) {
child = node.getChildAt(i);
if (child.style.positionType == CSSPositionType.ABSOLUTE) {
// If the child is absolutely positioned and has a top/left/bottom/right
// set, override all the previously computed positions to set it correctly.
if (!Float.isNaN(child.style.position.getWithFallback(leadingSpacing[crossAxis], leading[crossAxis]))) {
child.layout.position[pos[crossAxis]] =
(Float.isNaN(child.style.position.getWithFallback(leadingSpacing[crossAxis], leading[crossAxis])) ?
0 :
child.style.position.getWithFallback(leadingSpacing[crossAxis], leading[crossAxis])) +
node.style.border.getWithFallback(leadingSpacing[crossAxis], leading[crossAxis]) +
child.style.margin.getWithFallback(leadingSpacing[crossAxis], leading[crossAxis]);
} else {
child.layout.position[pos[crossAxis]] = leadingPaddingAndBorderCross +
child.style.margin.getWithFallback(leadingSpacing[crossAxis], leading[crossAxis]);
}
} else {
float leadingCrossDim = leadingPaddingAndBorderCross;
// For a relative children, we're either using alignItems (parent) or
// alignSelf (child) in order to determine the position in the cross axis
CSSAlign alignItem = getAlignItem(node, child);
// If the child uses align stretch, we need to lay it out one more time, this time
// forcing the cross-axis size to be the computed cross size for the current line.
if (alignItem == CSSAlign.STRETCH) {
childWidth = child.layout.measuredDimensions[DIMENSION_WIDTH] + (child.style.margin.getWithFallback(leadingSpacing[CSS_FLEX_DIRECTION_ROW], leading[CSS_FLEX_DIRECTION_ROW]) + child.style.margin.getWithFallback(trailingSpacing[CSS_FLEX_DIRECTION_ROW], trailing[CSS_FLEX_DIRECTION_ROW]));
childHeight = child.layout.measuredDimensions[DIMENSION_HEIGHT] + (child.style.margin.getWithFallback(leadingSpacing[CSS_FLEX_DIRECTION_COLUMN], leading[CSS_FLEX_DIRECTION_COLUMN]) + child.style.margin.getWithFallback(trailingSpacing[CSS_FLEX_DIRECTION_COLUMN], trailing[CSS_FLEX_DIRECTION_COLUMN]));
boolean isCrossSizeDefinite = false;
if (isMainAxisRow) {
isCrossSizeDefinite = (child.style.dimensions[dim[CSS_FLEX_DIRECTION_COLUMN]] >= 0.0);
childHeight = crossDim;
} else {
isCrossSizeDefinite = (child.style.dimensions[dim[CSS_FLEX_DIRECTION_ROW]] >= 0.0);
childWidth = crossDim;
}
// If the child defines a definite size for its cross axis, there's no need to stretch.
if (!isCrossSizeDefinite) {
childWidthMeasureMode = Float.isNaN(childWidth) ? CSSMeasureMode.UNDEFINED : CSSMeasureMode.EXACTLY;
childHeightMeasureMode = Float.isNaN(childHeight) ? CSSMeasureMode.UNDEFINED : CSSMeasureMode.EXACTLY;
layoutNodeInternal(layoutContext, child, childWidth, childHeight, direction, childWidthMeasureMode, childHeightMeasureMode, true, "stretch");
}
} else if (alignItem != CSSAlign.FLEX_START) {
float remainingCrossDim = containerCrossAxis - (child.layout.measuredDimensions[dim[crossAxis]] + child.style.margin.getWithFallback(leadingSpacing[crossAxis], leading[crossAxis]) + child.style.margin.getWithFallback(trailingSpacing[crossAxis], trailing[crossAxis]));
if (alignItem == CSSAlign.CENTER) {
leadingCrossDim += remainingCrossDim / 2;
} else { // CSSAlign.FLEX_END
leadingCrossDim += remainingCrossDim;
}
}
// And we apply the position
child.layout.position[pos[crossAxis]] += totalLineCrossDim + leadingCrossDim;
}
}
}
totalLineCrossDim += crossDim;
maxLineMainDim = Math.max(maxLineMainDim, mainDim);
// Reset variables for new line.
lineCount++;
startOfLineIndex = endOfLineIndex;
endOfLineIndex = startOfLineIndex;
}
// STEP 8: MULTI-LINE CONTENT ALIGNMENT
if (lineCount > 1 && performLayout && !Float.isNaN(availableInnerCrossDim)) {
float remainingAlignContentDim = availableInnerCrossDim - totalLineCrossDim;
float crossDimLead = 0;
float currentLead = leadingPaddingAndBorderCross;
CSSAlign alignContent = node.style.alignContent;
if (alignContent == CSSAlign.FLEX_END) {
currentLead += remainingAlignContentDim;
} else if (alignContent == CSSAlign.CENTER) {
currentLead += remainingAlignContentDim / 2;
} else if (alignContent == CSSAlign.STRETCH) {
if (availableInnerCrossDim > totalLineCrossDim) {
crossDimLead = (remainingAlignContentDim / lineCount);
}
}
int endIndex = 0;
for (i = 0; i < lineCount; ++i) {
int startIndex = endIndex;
int j;
// compute the line's height and find the endIndex
float lineHeight = 0;
for (j = startIndex; j < childCount; ++j) {
child = node.getChildAt(j);
if (child.style.positionType != CSSPositionType.RELATIVE) {
continue;
}
if (child.lineIndex != i) {
break;
}
if ((child.layout.measuredDimensions[dim[crossAxis]] >= 0.0)) {
lineHeight = Math.max(lineHeight,
child.layout.measuredDimensions[dim[crossAxis]] + (child.style.margin.getWithFallback(leadingSpacing[crossAxis], leading[crossAxis]) + child.style.margin.getWithFallback(trailingSpacing[crossAxis], trailing[crossAxis])));
}
}
endIndex = j;
lineHeight += crossDimLead;
if (performLayout) {
for (j = startIndex; j < endIndex; ++j) {
child = node.getChildAt(j);
if (child.style.positionType != CSSPositionType.RELATIVE) {
continue;
}
CSSAlign alignContentAlignItem = getAlignItem(node, child);
if (alignContentAlignItem == CSSAlign.FLEX_START) {
child.layout.position[pos[crossAxis]] = currentLead + child.style.margin.getWithFallback(leadingSpacing[crossAxis], leading[crossAxis]);
} else if (alignContentAlignItem == CSSAlign.FLEX_END) {
child.layout.position[pos[crossAxis]] = currentLead + lineHeight - child.style.margin.getWithFallback(trailingSpacing[crossAxis], trailing[crossAxis]) - child.layout.measuredDimensions[dim[crossAxis]];
} else if (alignContentAlignItem == CSSAlign.CENTER) {
childHeight = child.layout.measuredDimensions[dim[crossAxis]];
child.layout.position[pos[crossAxis]] = currentLead + (lineHeight - childHeight) / 2;
} else if (alignContentAlignItem == CSSAlign.STRETCH) {
child.layout.position[pos[crossAxis]] = currentLead + child.style.margin.getWithFallback(leadingSpacing[crossAxis], leading[crossAxis]);
// TODO(prenaux): Correctly set the height of items with indefinite
// (auto) crossAxis dimension.
}
}
}
currentLead += lineHeight;
}
}
// STEP 9: COMPUTING FINAL DIMENSIONS
node.layout.measuredDimensions[DIMENSION_WIDTH] = boundAxis(node, CSS_FLEX_DIRECTION_ROW, availableWidth - marginAxisRow);
node.layout.measuredDimensions[DIMENSION_HEIGHT] = boundAxis(node, CSS_FLEX_DIRECTION_COLUMN, availableHeight - marginAxisColumn);
// If the user didn't specify a width or height for the node, set the
// dimensions based on the children.
if (measureModeMainDim == CSSMeasureMode.UNDEFINED) {
// Clamp the size to the min/max size, if specified, and make sure it
// doesn't go below the padding and border amount.
node.layout.measuredDimensions[dim[mainAxis]] = boundAxis(node, mainAxis, maxLineMainDim);
} else if (measureModeMainDim == CSSMeasureMode.AT_MOST) {
node.layout.measuredDimensions[dim[mainAxis]] = Math.max(
Math.min(availableInnerMainDim + paddingAndBorderAxisMain,
boundAxisWithinMinAndMax(node, mainAxis, maxLineMainDim)),
paddingAndBorderAxisMain);
}
if (measureModeCrossDim == CSSMeasureMode.UNDEFINED) {
// Clamp the size to the min/max size, if specified, and make sure it
// doesn't go below the padding and border amount.
node.layout.measuredDimensions[dim[crossAxis]] = boundAxis(node, crossAxis, totalLineCrossDim + paddingAndBorderAxisCross);
} else if (measureModeCrossDim == CSSMeasureMode.AT_MOST) {
node.layout.measuredDimensions[dim[crossAxis]] = Math.max(
Math.min(availableInnerCrossDim + paddingAndBorderAxisCross,
boundAxisWithinMinAndMax(node, crossAxis, totalLineCrossDim + paddingAndBorderAxisCross)),
paddingAndBorderAxisCross);
}
// STEP 10: SIZING AND POSITIONING ABSOLUTE CHILDREN
currentAbsoluteChild = firstAbsoluteChild;
while (currentAbsoluteChild != null) {
// Now that we know the bounds of the container, perform layout again on the
// absolutely-positioned children.
if (performLayout) {
childWidth = CSSConstants.UNDEFINED;
childHeight = CSSConstants.UNDEFINED;
if ((currentAbsoluteChild.style.dimensions[dim[CSS_FLEX_DIRECTION_ROW]] >= 0.0)) {
childWidth = currentAbsoluteChild.style.dimensions[DIMENSION_WIDTH] + (currentAbsoluteChild.style.margin.getWithFallback(leadingSpacing[CSS_FLEX_DIRECTION_ROW], leading[CSS_FLEX_DIRECTION_ROW]) + currentAbsoluteChild.style.margin.getWithFallback(trailingSpacing[CSS_FLEX_DIRECTION_ROW], trailing[CSS_FLEX_DIRECTION_ROW]));
} else {
// If the child doesn't have a specified width, compute the width based on the left/right offsets if they're defined.
if (!Float.isNaN(currentAbsoluteChild.style.position.getWithFallback(leadingSpacing[CSS_FLEX_DIRECTION_ROW], leading[CSS_FLEX_DIRECTION_ROW])) &&
!Float.isNaN(currentAbsoluteChild.style.position.getWithFallback(trailingSpacing[CSS_FLEX_DIRECTION_ROW], trailing[CSS_FLEX_DIRECTION_ROW]))) {
childWidth = node.layout.measuredDimensions[DIMENSION_WIDTH] -
(node.style.border.getWithFallback(leadingSpacing[CSS_FLEX_DIRECTION_ROW], leading[CSS_FLEX_DIRECTION_ROW]) + node.style.border.getWithFallback(trailingSpacing[CSS_FLEX_DIRECTION_ROW], trailing[CSS_FLEX_DIRECTION_ROW])) -
((Float.isNaN(currentAbsoluteChild.style.position.getWithFallback(leadingSpacing[CSS_FLEX_DIRECTION_ROW], leading[CSS_FLEX_DIRECTION_ROW])) ?
0 :
currentAbsoluteChild.style.position.getWithFallback(leadingSpacing[CSS_FLEX_DIRECTION_ROW], leading[CSS_FLEX_DIRECTION_ROW])) +
(Float.isNaN(currentAbsoluteChild.style.position.getWithFallback(trailingSpacing[CSS_FLEX_DIRECTION_ROW], trailing[CSS_FLEX_DIRECTION_ROW])) ?
0 :
currentAbsoluteChild.style.position.getWithFallback(trailingSpacing[CSS_FLEX_DIRECTION_ROW], trailing[CSS_FLEX_DIRECTION_ROW])));
childWidth = boundAxis(currentAbsoluteChild, CSS_FLEX_DIRECTION_ROW, childWidth);
}
}
if ((currentAbsoluteChild.style.dimensions[dim[CSS_FLEX_DIRECTION_COLUMN]] >= 0.0)) {
childHeight = currentAbsoluteChild.style.dimensions[DIMENSION_HEIGHT] + (currentAbsoluteChild.style.margin.getWithFallback(leadingSpacing[CSS_FLEX_DIRECTION_COLUMN], leading[CSS_FLEX_DIRECTION_COLUMN]) + currentAbsoluteChild.style.margin.getWithFallback(trailingSpacing[CSS_FLEX_DIRECTION_COLUMN], trailing[CSS_FLEX_DIRECTION_COLUMN]));
} else {
// If the child doesn't have a specified height, compute the height based on the top/bottom offsets if they're defined.
if (!Float.isNaN(currentAbsoluteChild.style.position.getWithFallback(leadingSpacing[CSS_FLEX_DIRECTION_COLUMN], leading[CSS_FLEX_DIRECTION_COLUMN])) &&
!Float.isNaN(currentAbsoluteChild.style.position.getWithFallback(trailingSpacing[CSS_FLEX_DIRECTION_COLUMN], trailing[CSS_FLEX_DIRECTION_COLUMN]))) {
childHeight = node.layout.measuredDimensions[DIMENSION_HEIGHT] -
(node.style.border.getWithFallback(leadingSpacing[CSS_FLEX_DIRECTION_COLUMN], leading[CSS_FLEX_DIRECTION_COLUMN]) + node.style.border.getWithFallback(trailingSpacing[CSS_FLEX_DIRECTION_COLUMN], trailing[CSS_FLEX_DIRECTION_COLUMN])) -
((Float.isNaN(currentAbsoluteChild.style.position.getWithFallback(leadingSpacing[CSS_FLEX_DIRECTION_COLUMN], leading[CSS_FLEX_DIRECTION_COLUMN])) ?
0 :
currentAbsoluteChild.style.position.getWithFallback(leadingSpacing[CSS_FLEX_DIRECTION_COLUMN], leading[CSS_FLEX_DIRECTION_COLUMN])) +
(Float.isNaN(currentAbsoluteChild.style.position.getWithFallback(trailingSpacing[CSS_FLEX_DIRECTION_COLUMN], trailing[CSS_FLEX_DIRECTION_COLUMN])) ?
0 :
currentAbsoluteChild.style.position.getWithFallback(trailingSpacing[CSS_FLEX_DIRECTION_COLUMN], trailing[CSS_FLEX_DIRECTION_COLUMN])));
childHeight = boundAxis(currentAbsoluteChild, CSS_FLEX_DIRECTION_COLUMN, childHeight);
}
}
// If we're still missing one or the other dimension, measure the content.
if (Float.isNaN(childWidth) || Float.isNaN(childHeight)) {
childWidthMeasureMode = Float.isNaN(childWidth) ? CSSMeasureMode.UNDEFINED : CSSMeasureMode.EXACTLY;
childHeightMeasureMode = Float.isNaN(childHeight) ? CSSMeasureMode.UNDEFINED : CSSMeasureMode.EXACTLY;
// According to the spec, if the main size is not definite and the
// child's inline axis is parallel to the main axis (i.e. it's
// horizontal), the child should be sized using "UNDEFINED" in
// the main size. Otherwise use "AT_MOST" in the cross axis.
if (!isMainAxisRow && Float.isNaN(childWidth) && !Float.isNaN(availableInnerWidth)) {
childWidth = availableInnerWidth;
childWidthMeasureMode = CSSMeasureMode.AT_MOST;
}
// The W3C spec doesn't say anything about the 'overflow' property,
// but all major browsers appear to implement the following logic.
if (node.style.overflow == CSSOverflow.HIDDEN) {
if (isMainAxisRow && Float.isNaN(childHeight) && !Float.isNaN(availableInnerHeight)) {
childHeight = availableInnerHeight;
childHeightMeasureMode = CSSMeasureMode.AT_MOST;
}
}
layoutNodeInternal(layoutContext, currentAbsoluteChild, childWidth, childHeight, direction, childWidthMeasureMode, childHeightMeasureMode, false, "abs-measure");
childWidth = currentAbsoluteChild.layout.measuredDimensions[DIMENSION_WIDTH] + (currentAbsoluteChild.style.margin.getWithFallback(leadingSpacing[CSS_FLEX_DIRECTION_ROW], leading[CSS_FLEX_DIRECTION_ROW]) + currentAbsoluteChild.style.margin.getWithFallback(trailingSpacing[CSS_FLEX_DIRECTION_ROW], trailing[CSS_FLEX_DIRECTION_ROW]));
childHeight = currentAbsoluteChild.layout.measuredDimensions[DIMENSION_HEIGHT] + (currentAbsoluteChild.style.margin.getWithFallback(leadingSpacing[CSS_FLEX_DIRECTION_COLUMN], leading[CSS_FLEX_DIRECTION_COLUMN]) + currentAbsoluteChild.style.margin.getWithFallback(trailingSpacing[CSS_FLEX_DIRECTION_COLUMN], trailing[CSS_FLEX_DIRECTION_COLUMN]));
}
layoutNodeInternal(layoutContext, currentAbsoluteChild, childWidth, childHeight, direction, CSSMeasureMode.EXACTLY, CSSMeasureMode.EXACTLY, true, "abs-layout");
if (!Float.isNaN(currentAbsoluteChild.style.position.getWithFallback(trailingSpacing[mainAxis], trailing[mainAxis])) &&
Float.isNaN(currentAbsoluteChild.style.position.getWithFallback(leadingSpacing[mainAxis], leading[mainAxis]))) {
currentAbsoluteChild.layout.position[leading[mainAxis]] =
node.layout.measuredDimensions[dim[mainAxis]] -
currentAbsoluteChild.layout.measuredDimensions[dim[mainAxis]] -
(Float.isNaN(currentAbsoluteChild.style.position.getWithFallback(trailingSpacing[mainAxis], trailing[mainAxis])) ? 0 : currentAbsoluteChild.style.position.getWithFallback(trailingSpacing[mainAxis], trailing[mainAxis]));
}
if (!Float.isNaN(currentAbsoluteChild.style.position.getWithFallback(trailingSpacing[crossAxis], trailing[crossAxis])) &&
Float.isNaN(currentAbsoluteChild.style.position.getWithFallback(leadingSpacing[crossAxis], leading[crossAxis]))) {
currentAbsoluteChild.layout.position[leading[crossAxis]] =
node.layout.measuredDimensions[dim[crossAxis]] -
currentAbsoluteChild.layout.measuredDimensions[dim[crossAxis]] -
(Float.isNaN(currentAbsoluteChild.style.position.getWithFallback(trailingSpacing[crossAxis], trailing[crossAxis])) ? 0 : currentAbsoluteChild.style.position.getWithFallback(trailingSpacing[crossAxis], trailing[crossAxis]));
}
}
currentAbsoluteChild = currentAbsoluteChild.nextChild;
}
// STEP 11: SETTING TRAILING POSITIONS FOR CHILDREN
if (performLayout) {
boolean needsMainTrailingPos = false;
boolean needsCrossTrailingPos = false;
if (mainAxis == CSS_FLEX_DIRECTION_ROW_REVERSE ||
mainAxis == CSS_FLEX_DIRECTION_COLUMN_REVERSE) {
needsMainTrailingPos = true;
}
if (crossAxis == CSS_FLEX_DIRECTION_ROW_REVERSE ||
crossAxis == CSS_FLEX_DIRECTION_COLUMN_REVERSE) {
needsCrossTrailingPos = true;
}
// Set trailing position if necessary.
if (needsMainTrailingPos || needsCrossTrailingPos) {
for (i = 0; i < childCount; ++i) {
child = node.getChildAt(i);
if (needsMainTrailingPos) {
child.layout.position[trailing[mainAxis]] =
node.layout.measuredDimensions[dim[mainAxis]] -
child.layout.measuredDimensions[dim[mainAxis]] -
child.layout.position[pos[mainAxis]];
}
if (needsCrossTrailingPos) {
child.layout.position[trailing[crossAxis]] =
node.layout.measuredDimensions[dim[crossAxis]] -
child.layout.measuredDimensions[dim[crossAxis]] -
child.layout.position[pos[crossAxis]];
}
}
}
}
}
}
|
package com.atguigu.gmall.pms.dao;
import com.atguigu.gmall.pms.entity.AttrGroupEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* 属性分组
*
* @author wangguoquan
* @email 872448085@qq.com
* @date 2020-02-18 19:57:56
*/
@Mapper
public interface AttrGroupDao extends BaseMapper<AttrGroupEntity> {
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.iotdb.db.metadata.idtable;
import org.apache.iotdb.commons.exception.MetadataException;
import org.apache.iotdb.commons.utils.TestOnly;
import org.apache.iotdb.db.metadata.idtable.entry.DiskSchemaEntry;
import org.apache.iotdb.db.metadata.idtable.entry.SchemaEntry;
import org.apache.iotdb.tsfile.file.metadata.enums.CompressionType;
import org.apache.iotdb.tsfile.file.metadata.enums.TSDataType;
import org.apache.iotdb.tsfile.file.metadata.enums.TSEncoding;
import org.apache.iotdb.tsfile.utils.ReadWriteIOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/** store id table schema in append only file */
public class AppendOnlyDiskSchemaManager implements IDiskSchemaManager {
private static final String FILE_NAME = "SeriesKeyMapping.meta";
// file version to distinguish different id table file
private static final String FILE_VERSION = "AppendOnly_V1";
File dataFile;
FileOutputStream outputStream;
long loc;
private static final Logger logger = LoggerFactory.getLogger(AppendOnlyDiskSchemaManager.class);
public AppendOnlyDiskSchemaManager(File dir) {
try {
initFile(dir);
outputStream = new FileOutputStream(dataFile, true);
// we write file version to new file
if (loc == 0) {
ReadWriteIOUtils.write(FILE_VERSION, outputStream);
}
} catch (IOException e) {
logger.error(e.getMessage());
throw new IllegalArgumentException("can't initialize disk schema manager at " + dataFile);
}
}
private void initFile(File dir) throws IOException {
// create dirs
if (dir.mkdirs()) {
logger.info(
"ID table create storage group system dir {} doesn't exist, create it",
dir.getParentFile());
}
dataFile = new File(dir, FILE_NAME);
if (dataFile.exists()) {
loc = dataFile.length();
if (!checkFileConsistency(loc)) {
throw new IOException("File corruption");
}
} else {
logger.debug("create new file for id table: " + dir.getName());
boolean createRes = dataFile.createNewFile();
if (!createRes) {
throw new IOException(
"create new file for id table failed. Path is: " + dataFile.getPath());
}
loc = 0;
}
}
private boolean checkFileConsistency(long pos) {
// empty file
if (pos == 0) {
return true;
}
// file length is smaller than one int
if (pos <= Integer.BYTES) {
return false;
}
try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(dataFile))) {
// check file version
String version = ReadWriteIOUtils.readString(inputStream);
if (!FILE_VERSION.equals(version)) {
logger.error("File version isn't right, need: {}, actual: {} ", FILE_VERSION, version);
return false;
}
} catch (Exception e) {
logger.error("File check failed" + e);
return false;
}
return true;
}
@Override
public long serialize(DiskSchemaEntry schemaEntry) {
long beforeLoc = loc;
try {
loc += schemaEntry.serialize(outputStream);
} catch (IOException e) {
logger.error("failed to serialize schema entry: " + schemaEntry);
throw new IllegalArgumentException("can't serialize disk entry of " + schemaEntry);
}
return beforeLoc;
}
@Override
public void recover(IDTable idTable) {
long loc = 0;
try (FileInputStream inputStream = new FileInputStream(dataFile)) {
// read file version
ReadWriteIOUtils.readString(inputStream);
while (inputStream.available() > 0) {
DiskSchemaEntry cur = DiskSchemaEntry.deserialize(inputStream);
SchemaEntry schemaEntry =
new SchemaEntry(
TSDataType.deserialize(cur.type),
TSEncoding.deserialize(cur.encoding),
CompressionType.deserialize(cur.compressor),
loc);
idTable.putSchemaEntry(cur.deviceID, cur.measurementName, schemaEntry, cur.isAligned);
loc += cur.entrySize;
}
} catch (IOException | MetadataException e) {
logger.info("Last entry is incomplete, we will recover as much as we can.");
try {
outputStream.getChannel().truncate(loc);
} catch (IOException ioException) {
logger.error("Failed at truncate file.", ioException);
}
this.loc = loc;
}
}
@TestOnly
public Collection<DiskSchemaEntry> getAllSchemaEntry() throws IOException {
List<DiskSchemaEntry> res = new ArrayList<>();
try (FileInputStream inputStream = new FileInputStream(dataFile)) {
// read file version
ReadWriteIOUtils.readString(inputStream);
// for test, we read at most 1000 entries.
int maxCount = 1000;
while (maxCount > 0) {
try {
maxCount--;
DiskSchemaEntry cur = DiskSchemaEntry.deserialize(inputStream);
res.add(cur);
} catch (IOException e) {
logger.debug("read finished");
break;
}
}
}
return res;
}
@Override
public void close() throws IOException {
try {
outputStream.close();
} catch (IOException e) {
logger.error("close schema file failed");
throw e;
}
}
}
|
/*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2021 DBeaver Corp and others
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jkiss.dbeaver.model.struct.cache;
import org.jkiss.code.NotNull;
import org.jkiss.code.Nullable;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.dbeaver.model.struct.DBSObject;
/**
* Basic objects cache.
*/
public abstract class BasicObjectCache<OWNER extends DBSObject, OBJECT extends DBSObject> extends AbstractObjectCache<OWNER, OBJECT> {
@Nullable
@Override
public OBJECT getObject(@NotNull DBRProgressMonitor monitor, @Nullable OWNER owner, @NotNull String name) throws DBException {
if (!isFullyCached()) {
getAllObjects(monitor, owner);
}
return getCachedObject(name);
}
}
|
package com.javaone.onepet.Alarm;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import com.javaone.onepet.Alarm.Model.AlarmModel;
import com.javaone.onepet.Alarm.data.MyAlarmDataBase;
import com.javaone.onepet.MainActivity;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Random;
public class AlarmService extends Service{
private static final int ONE_DAY_TIME = 1000*60*60*24;
private static final int CONFIG_ONE = 0;
private static final int CONFIG_TWO = 1;
private static AlarmManager alarmManager;
private MyBinder myBinder = new MyBinder();
@Nullable
@Override
public IBinder onBind(Intent intent) {
return myBinder;
}
@Override
public void onCreate() {
Log.d("Service","启动服务");
super.onCreate();
}
@Override
public void onDestroy() {
Intent service = new Intent(this,AlarmService.class);
this.startService(service);
Log.d("Service","重启服务");
super.onDestroy();
}
public static class MyBinder extends Binder {
private String[] mTimeSplit;
private int mHour;
private int mMinute;
public void setSingleAlarm(Context context, String time, int id) {
mTimeSplit = time.split(":");
mHour = Integer.parseInt(mTimeSplit[0]);
mMinute = Integer.parseInt(mTimeSplit[1]);
Calendar c = Calendar.getInstance();
c.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH),
c.get(Calendar.DAY_OF_MONTH), mHour, mMinute, 0);
long mTimeInfo = c.getTimeInMillis();
long actualTime = mTimeInfo > System.currentTimeMillis()
? mTimeInfo : mTimeInfo + ONE_DAY_TIME;
alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
int flagDayOfWeek = 0;
alarmManager.set(AlarmManager.RTC_WAKEUP, actualTime, getIntent(CONFIG_ONE, context, id, flagDayOfWeek));
Log.d("Service", "单次闹钟设置完成");
}
public void setEverydayAlarm(Context context, String time, int id) {
mTimeSplit = time.split(":");
mHour = Integer.parseInt(mTimeSplit[0]);
mMinute = Integer.parseInt(mTimeSplit[1]);
Calendar c = Calendar.getInstance();
c.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH),
c.get(Calendar.DAY_OF_MONTH), mHour, mMinute, 0);
long mTimeInfo = c.getTimeInMillis();
long actualTime = mTimeInfo > System.currentTimeMillis()
? mTimeInfo : mTimeInfo + ONE_DAY_TIME;
alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
int flagDayOfWeek = 0;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
alarmManager.setExact(AlarmManager.RTC_WAKEUP, actualTime,
getIntent(CONFIG_ONE, context, id, flagDayOfWeek));
Log.d("Service", "每日闹钟,调用了setExact()");
} else {
alarmManager.set(AlarmManager.RTC_WAKEUP, actualTime,
getIntent(CONFIG_ONE, context, id, flagDayOfWeek));
Log.d("Service", "每日闹钟,调用了set()");
}
Log.d("Service","每日闹钟设置完成");
}
public void setDiyAlarm(Context context, String repeat, String time,
int id, String repeatCode) {
List<Integer> dayOfWeekList = loadDayOfWeek(repeat, repeatCode);
mTimeSplit = time.split(":");
mHour = Integer.parseInt(mTimeSplit[0]);
mMinute = Integer.parseInt(mTimeSplit[1]);
Calendar c = Calendar.getInstance();
c.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH),
c.get(Calendar.DAY_OF_MONTH), mHour, mMinute, 0);
long mTimeInfo = c.getTimeInMillis();
long actualTime = mTimeInfo > System.currentTimeMillis()
? mTimeInfo : mTimeInfo + ONE_DAY_TIME;
int currentDayOfWeek = Calendar.getInstance().get(Calendar.DAY_OF_WEEK); //今天是星期几
Log.d("Service", "今天是" + currentDayOfWeek);
for (int j = 0; j < dayOfWeekList.size(); j++) {
int flagDayOfWeek = dayOfWeekList.get(j);
Log.d("Service", "第"+(j+1)+"次循环,这次的目标是: "+flagDayOfWeek);
if (currentDayOfWeek == flagDayOfWeek) {
setAlarm(actualTime, context, id, flagDayOfWeek);
Log.d("Service","已设置,目标与今天相同,是" + flagDayOfWeek);
} else if (currentDayOfWeek < flagDayOfWeek) {
int gapDay = flagDayOfWeek - currentDayOfWeek;
long realTime = actualTime + gapDay * ONE_DAY_TIME;
setAlarm(realTime, context, id, flagDayOfWeek);
Log.d("Service", "已设置,目标小于今天,是" + flagDayOfWeek);
} else if (currentDayOfWeek > flagDayOfWeek) {
int gapDay = 7 - currentDayOfWeek + flagDayOfWeek;
long realTime = gapDay * ONE_DAY_TIME + actualTime;
setAlarm(realTime, context, id, flagDayOfWeek);
Log.d("Service", "已设置,目标大于今天,是" + flagDayOfWeek);
}
}
dayOfWeekList.clear();
Log.d("Service","自定义闹钟设置完成!");
}
@NonNull
private List<Integer> loadDayOfWeek(String repeat, String repeatCode) {
List<Integer> dayOfWeekList = new ArrayList<>();
if (repeat.equals("周一至周五")) {
for (int i = 2; i < 7; i++) {
dayOfWeekList.add(i);
}
} else if (repeat.equals("周六周日")) {
dayOfWeekList.add(1);
dayOfWeekList.add(7);
} else {
if (repeatCode!=null){
String[] splitCode = repeatCode.split(",");
for (int i = 0; i < splitCode.length; i++) {
dayOfWeekList.add(Integer.parseInt(splitCode[i]));
Log.d("Service", "获取到自定义dayOfWeek");
}
}
}
return dayOfWeekList;
}
private void setAlarm(long realTime, Context context, int id, int flagDayOfWeek) {
alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
alarmManager.setExact(AlarmManager.RTC_WAKEUP, realTime,
getIntent(CONFIG_TWO, context, id, flagDayOfWeek));
} else {
alarmManager.set(AlarmManager.RTC_WAKEUP, realTime,
getIntent(CONFIG_TWO, context, id + flagDayOfWeek, flagDayOfWeek));
}
}
public void cancelAlarm(AlarmModel alarm,int id,Context context){
if (alarm==null){
Log.d("alarm null","null");
}
Log.d("id ", String.valueOf(id));
String repeat = alarm.getRepeatType();
AlarmManager alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE);
if (repeat.equals("每天")||repeat.equals("只响一次")){
PendingIntent pi = PendingIntent.getBroadcast(context, id,
new Intent(context, MyAlarmReceiver.class), 0);
alarmManager.cancel(pi);
}else {
List<Integer> flagDayOfWeek = loadDayOfWeek(repeat,alarm.getRepeatCode());
for (int i = 0;i<flagDayOfWeek.size();i++){
PendingIntent pi = getIntent(CONFIG_TWO,context,id,flagDayOfWeek.get(i));
alarmManager.cancel(pi);
Log.d("Service","取消id是"+id+" 星期"+flagDayOfWeek+"的闹钟");
}
}
}
private PendingIntent getIntent(int config, Context context, int id, int flagDayOfWeek) {
Intent intent = new Intent(context, MyAlarmReceiver.class);
intent.putExtra(MyAlarmReceiver.ID_FLAG, Integer.toString(id));
switch (config) {
case CONFIG_ONE:
return PendingIntent.getBroadcast(context,
id+flagDayOfWeek, intent, PendingIntent.FLAG_CANCEL_CURRENT);
case CONFIG_TWO:
return PendingIntent.getBroadcast(context,
id+flagDayOfWeek, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
return null;
}
}
public static class RebootReceiver extends BroadcastReceiver {
private String mTime,mRepeat,mActive,mRepeatCode;
private int mID;
private AlarmService.MyBinder binder = new MyBinder();
@Override
public void onReceive(final Context context, Intent intent) {
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")){
Log.d("RebootReceiver","接收到开机广播");
Random rand = new Random();
int i = rand.nextInt(100);
if(i < 50)
return;
MyAlarmDataBase db = new MyAlarmDataBase(context);
List<AlarmModel> alarm = db.getAllAlarms();
for (AlarmModel am : alarm) {
mTime = am.getTime();
mRepeat = am.getRepeatType();
mID = am.getID();
mActive = am.getActive();
if (mRepeat.equals("自定义")){
mRepeatCode = am.getRepeatCode();
}
if (mActive.equals("true")){
switch (mRepeat) {
case "只响一次":
binder.setSingleAlarm(context, mTime, mID);
break;
case "每天":
binder.setEverydayAlarm(context, mTime, mID);
break;
default:
binder.setDiyAlarm(context, mRepeat, mTime, mID,mRepeatCode);
}
Log.v("RebootReceiver","完成重启后闹钟设置");
}
}
Intent startIntent = new Intent(context, MainActivity.class);
startIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(startIntent);
}
}
}
}
|
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.opensearch.plugins;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
import org.opensearch.common.io.stream.NamedWriteableRegistry;
import org.opensearch.common.network.NetworkService;
import org.opensearch.common.settings.ClusterSettings;
import org.opensearch.common.settings.Settings;
import org.opensearch.common.util.BigArrays;
import org.opensearch.common.util.PageCacheRecycler;
import org.opensearch.common.util.concurrent.ThreadContext;
import org.opensearch.common.xcontent.NamedXContentRegistry;
import org.opensearch.http.HttpServerTransport;
import org.opensearch.indices.breaker.CircuitBreakerService;
import org.opensearch.threadpool.ThreadPool;
import org.opensearch.transport.Transport;
import org.opensearch.transport.TransportInterceptor;
/**
* Plugin for extending network and transport related classes
*/
public interface NetworkPlugin {
/**
* Returns a list of {@link TransportInterceptor} instances that are used to intercept incoming and outgoing
* transport (inter-node) requests. This must not return <code>null</code>
*
* @param namedWriteableRegistry registry of all named writeables registered
* @param threadContext a {@link ThreadContext} of the current nodes or clients {@link ThreadPool} that can be used to set additional
* headers in the interceptors
*/
default List<TransportInterceptor> getTransportInterceptors(NamedWriteableRegistry namedWriteableRegistry,
ThreadContext threadContext) {
return Collections.emptyList();
}
/**
* Returns a map of {@link Transport} suppliers.
* See {@link org.opensearch.common.network.NetworkModule#TRANSPORT_TYPE_KEY} to configure a specific implementation.
*/
default Map<String, Supplier<Transport>> getTransports(Settings settings, ThreadPool threadPool, PageCacheRecycler pageCacheRecycler,
CircuitBreakerService circuitBreakerService,
NamedWriteableRegistry namedWriteableRegistry, NetworkService networkService) {
return Collections.emptyMap();
}
/**
* Returns a map of {@link HttpServerTransport} suppliers.
* See {@link org.opensearch.common.network.NetworkModule#HTTP_TYPE_SETTING} to configure a specific implementation.
*/
default Map<String, Supplier<HttpServerTransport>> getHttpTransports(Settings settings, ThreadPool threadPool, BigArrays bigArrays,
PageCacheRecycler pageCacheRecycler,
CircuitBreakerService circuitBreakerService,
NamedXContentRegistry xContentRegistry,
NetworkService networkService,
HttpServerTransport.Dispatcher dispatcher,
ClusterSettings clusterSettings) {
return Collections.emptyMap();
}
}
|
package com.thegreatgooo.eclipse.prettier.css;
import org.eclipse.core.commands.operations.OperationHistoryFactory;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorReference;
import org.eclipse.ui.IPartListener2;
import org.eclipse.ui.IStartup;
import org.eclipse.ui.IWindowListener;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchPartReference;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.FileEditorInput;
import org.eclipse.ui.texteditor.ITextEditor;
import com.thegreatgooo.eclipse.prettier.css.handlers.FormattingListener;
public class Startup implements IStartup {
@Override
public void earlyStartup() {
FormattingListener formattingListener = new FormattingListener();
Display.getDefault().asyncExec(() -> {
PlatformUI.getWorkbench().addWindowListener(new IWindowListener() {
@Override
public void windowOpened(IWorkbenchWindow window) {
registerWindow(window, formattingListener);
}
@Override
public void windowDeactivated(IWorkbenchWindow window) {
}
@Override
public void windowClosed(IWorkbenchWindow window) {
}
@Override
public void windowActivated(IWorkbenchWindow window) {
}
});
OperationHistoryFactory.getOperationHistory().addOperationHistoryListener(formattingListener);
IWorkbenchWindow[] windows = PlatformUI.getWorkbench().getWorkbenchWindows();
for (IWorkbenchWindow iWorkbenchWindow : windows) {
registerWindow(iWorkbenchWindow, formattingListener);
for (IWorkbenchPage workbenchPage : iWorkbenchWindow.getPages()) {
for (IEditorReference editorReference : workbenchPage.getEditorReferences()) {
registerListenersForPart(formattingListener, editorReference.getEditor(false));
}
}
}
});
}
private void registerWindow(IWorkbenchWindow window, FormattingListener formattingListener) {
IWorkbenchPage activePage = window.getActivePage();
activePage.addPartListener(new IPartListener2() {
public void partHidden(IWorkbenchPartReference partRef) {
unRegisterListenersForPart(formattingListener, partRef.getPart(false));
}
public void partVisible(IWorkbenchPartReference partRef) {
registerListenersForPart(formattingListener, partRef.getPart(false));
}
});
}
private void registerListenersForPart(FormattingListener formattingListener, IWorkbenchPart workbenchPart) {
if (workbenchPart instanceof IEditorPart
&& isSupportedExtension(((IEditorPart) workbenchPart).getEditorInput())) {
IEditorPart editorPart = (IEditorPart) workbenchPart;
IEditorInput input = editorPart.getEditorInput();
if (editorPart instanceof ITextEditor && input instanceof FileEditorInput) {
formattingListener.registerEditor((ITextEditor) editorPart);
}
}
}
private void unRegisterListenersForPart(FormattingListener formattingListener, IWorkbenchPart workbenchPart) {
if (workbenchPart instanceof IEditorPart) {
IEditorPart editorPart = (IEditorPart) workbenchPart;
IEditorInput input = editorPart.getEditorInput();
if (editorPart instanceof ITextEditor && input instanceof FileEditorInput) {
formattingListener.unRegisterEditor((ITextEditor) editorPart);
}
}
}
private boolean isSupportedExtension(IEditorInput editorInput) {
return editorInput instanceof FileEditorInput
&& "css".equals(((FileEditorInput) editorInput).getFile().getFileExtension());
}
}
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Márcio M. Noda
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package br.com.devmedia.cleancode.modelo.cliente.converter;
import br.com.devmedia.cleancode.modelo.cliente.Cpf;
import org.junit.Before;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class CpfJpaConverterTest {
private final String CPF_ESPERADO = "97785537852";
private CpfJpaConverter cpfJpaConverter;
@Before
public void setUp() {
cpfJpaConverter = new CpfJpaConverter();
}
@Test
public void deve_converter_string_para_cpf() {
Cpf cpf = cpfJpaConverter.convertToEntityAttribute(CPF_ESPERADO);
assertThat(cpf).isNotNull().isEqualTo(Cpf.valueOf(CPF_ESPERADO));
}
@Test
public void deve_converter_cpf_para_string() {
String cpf = cpfJpaConverter.convertToDatabaseColumn(Cpf.valueOf(CPF_ESPERADO));
assertThat(cpf).isNotNull().isEqualTo(CPF_ESPERADO);
}
}
|
/*
* Copyright (c) 2009-2019, United States Government, as represented by the Secretary of Health and Human Services.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of the United States Government nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE UNITED STATES GOVERNMENT BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package gov.hhs.fha.nhinc.docrepository.adapter;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import gov.hhs.fha.nhinc.docrepository.adapter.model.DocumentMetadata;
import gov.hhs.fha.nhinc.docrepository.adapter.model.DocumentQueryParams;
import gov.hhs.fha.nhinc.docrepository.adapter.service.DocumentService;
import gov.hhs.fha.nhinc.largefile.LargeFileUtils;
import ihe.iti.xds_b._2007.ProvideAndRegisterDocumentSetRequestType;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.activation.DataHandler;
import oasis.names.tc.ebxml_regrep.xsd.rim._3.ClassificationType;
import oasis.names.tc.ebxml_regrep.xsd.rim._3.InternationalStringType;
import oasis.names.tc.ebxml_regrep.xsd.rim._3.LocalizedStringType;
import oasis.names.tc.ebxml_regrep.xsd.rim._3.SlotType1;
import oasis.names.tc.ebxml_regrep.xsd.rim._3.ValueListType;
import org.junit.Test;
/**
* @author jsmith
*
*/
public class AdapterComponentDocRepositoryHelperTest {
@Test
public void testGetDocumentMap() throws IOException {
AdapterComponentDocRepositoryHelper docRepoHelper = new AdapterComponentDocRepositoryHelper();
ProvideAndRegisterDocumentSetRequestType body = mock(ProvideAndRegisterDocumentSetRequestType.class);
List<ProvideAndRegisterDocumentSetRequestType.Document> docList = new ArrayList<>();
ProvideAndRegisterDocumentSetRequestType.Document doc = new ProvideAndRegisterDocumentSetRequestType.Document();
final String ID = "MOCK_ID";
final String VALUE = "MOCK_VALUE";
DataHandler dataHandler = LargeFileUtils.getInstance().convertToDataHandler(VALUE);
doc.setId(ID);
doc.setValue(dataHandler);
docList.add(doc);
when(body.getDocument()).thenReturn(docList);
HashMap<String, DataHandler> docMap = docRepoHelper.getDocumentMap(body);
assertEquals(docMap.get(ID), dataHandler);
}
/**
* Test for extractClassifcationMetadata(List<ClassificationType, String, String, int).
*/
@Test
public void testExtractClassificationMetadata() {
final String CLASS_VALUE = "Classfication value";
final String CLASS_SCHEME_NAME = "classificationSchemeName";
AdapterComponentDocRepositoryHelper docRepoHelper = new AdapterComponentDocRepositoryHelper() {
@Override
String extractMetadataFromSlots(List<SlotType1> documentSlots, String slotName, int valueIndex) {
return CLASS_VALUE;
}
};
List<ClassificationType> classifications = new ArrayList<>();
ClassificationType classType = mock(ClassificationType.class);
classifications.add(classType);
when(classType.getClassificationScheme()).thenReturn(CLASS_SCHEME_NAME);
String result = docRepoHelper.extractClassificationMetadata(classifications, CLASS_SCHEME_NAME, "slotName", 0);
assertEquals(result, CLASS_VALUE);
}
@Test
public void testExtractPatientInfo() {
final String PATIENT_NAME = "John Doe";
final String SLOT_PATIENT_NAME = "John Doe <Patient Information>";
final String EXPECTED_RESULT = "<Patient Information>";
List<SlotType1> documentSlots = new ArrayList<>();
SlotType1 slot = mock(SlotType1.class);
documentSlots.add(slot);
ValueListType valueListType = mock(ValueListType.class);
List<String> valueList = new ArrayList<>();
valueList.add(SLOT_PATIENT_NAME);
when(slot.getName()).thenReturn(DocRepoConstants.XDS_SOURCE_PATIENT_INFO_SLOT);
when(slot.getValueList()).thenReturn(valueListType);
when(valueListType.getValue()).thenReturn(valueList);
AdapterComponentDocRepositoryHelper docRepoHelper = new AdapterComponentDocRepositoryHelper();
String result = docRepoHelper.extractPatientInfo(documentSlots, PATIENT_NAME);
assertEquals(result, EXPECTED_RESULT);
}
/**
* Test for extractClassificationMetadata(List<ClassificationType>, String, String).
*/
@Test
public void testExtractClassificationMetadata2() {
AdapterComponentDocRepositoryHelper docRepoHelper = new AdapterComponentDocRepositoryHelper();
String result;
List<ClassificationType> classifications = new ArrayList();
ClassificationType classificationType = mock(ClassificationType.class);
classifications.add(classificationType);
InternationalStringType internationalString = mock(InternationalStringType.class);
LocalizedStringType localizedString = new LocalizedStringType();
final String VALUE = "classification Value";
localizedString.setValue(VALUE);
List<LocalizedStringType> localizedList = new ArrayList();
localizedList.add(localizedString);
final String CLASSIFICATION_SCHEME = "classificationScheme";
when(classificationType.getClassificationScheme()).thenReturn(CLASSIFICATION_SCHEME);
when(classificationType.getName()).thenReturn(internationalString);
when(internationalString.getLocalizedString()).thenReturn(localizedList);
result = docRepoHelper.extractClassificationMetadata(classifications, CLASSIFICATION_SCHEME,
DocRepoConstants.XDS_NAME);
assertEquals(result, VALUE);
when(classificationType.getNodeRepresentation()).thenReturn(VALUE);
result = docRepoHelper.extractClassificationMetadata(classifications, CLASSIFICATION_SCHEME,
DocRepoConstants.XDS_NODE_REPRESENTATION);
assertEquals(result, VALUE);
when(classificationType.getClassifiedObject()).thenReturn(VALUE);
result = docRepoHelper.extractClassificationMetadata(classifications, CLASSIFICATION_SCHEME,
DocRepoConstants.XDS_CLASSIFIED_OBJECT);
assertEquals(result, VALUE);
result = docRepoHelper.extractClassificationMetadata(classifications, CLASSIFICATION_SCHEME,
DocRepoConstants.XDS_CLASSIFICATION_ID);
assertEquals(result, VALUE);
}
@Test
public void testQueryRepositoryByPatientId() {
AdapterComponentDocRepositoryHelper docRepoHelper = new AdapterComponentDocRepositoryHelper();
final String SPATID = "sPatId";
final String SDOCID = "Doc ID 1";
final String SCLASSCODE = "sClassCode";
final String ESTATUS = "sStatus";
final String DOC_UNIQUE_ID = "Doc ID 1";
final long DOC_ID = 12345;
DocumentService docService = mock(DocumentService.class);
List<DocumentMetadata> documents = new ArrayList<>();
DocumentMetadata doc = mock(DocumentMetadata.class);
documents.add(doc);
when(docService.documentQuery(any(DocumentQueryParams.class))).thenReturn(documents);
when(doc.getDocumentUniqueId()).thenReturn(DOC_UNIQUE_ID);
when(doc.getDocumentid()).thenReturn(DOC_ID);
long result = docRepoHelper.queryRepositoryByPatientId(SPATID, SDOCID, SCLASSCODE, ESTATUS, docService);
assertEquals(result, DOC_ID);
}
}
|
/*
* Copyright (c) 2014, Cloudera, Inc. All Rights Reserved.
*
* Cloudera, Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for
* the specific language governing permissions and limitations under the
* License.
*/
package com.cloudera.oryx.ml.mllib.als;
import java.util.HashMap;
import java.util.Map;
import com.typesafe.config.Config;
import com.cloudera.oryx.common.settings.ConfigUtils;
import com.cloudera.oryx.lambda.AbstractBatchIT;
public abstract class AbstractALSIT extends AbstractBatchIT {
@Override
protected Config getConfig() {
Map<String,String> overlayConfig = new HashMap<>();
overlayConfig.put("als.hyperparams.iterations", "10");
overlayConfig.put("als.hyperparams.features", "10");
overlayConfig.put("als.hyperparams.implicit", "true");
overlayConfig.put("als.hyperparams.lambda", "0.001");
overlayConfig.put("als.hyperparams.alpha", "1.0");
return ConfigUtils.overlayOn(overlayConfig, super.getConfig());
}
}
|
package org.omg.PortableServer;
/**
* org/omg/PortableServer/_ServantActivatorStub.java .
* Generated by the IDL-to-Java compiler (portable), version "3.2"
* from /HUDSON/workspace/8-2-build-linux-amd64/jdk8u192/11895/corba/src/share/classes/org/omg/PortableServer/poa.idl
* Saturday, October 6, 2018 6:46:22 AM PDT
*/
/**
* When the POA has the RETAIN policy it uses servant
* managers that are ServantActivators.
*/
public class _ServantActivatorStub extends org.omg.CORBA.portable.ObjectImpl implements org.omg.PortableServer.ServantActivator
{
final public static java.lang.Class _opsClass = ServantActivatorOperations.class;
/**
* This operation is invoked by the POA whenever the
* POA receives a request for an object that is not
* currently active, assuming the POA has the
* USE_SERVANT_MANAGER and RETAIN policies.
* @param oid object Id associated with the object on
* the request was made.
* @param adapter object reference for the POA in which
* the object is being activated.
* @return Servant corresponding to oid is created or
* located by the user supplied servant manager.
* @exception ForwardRequest to indicate to the ORB
* that it is responsible for delivering
* the current request and subsequent
* requests to the object denoted in the
* forward_reference member of the exception.
*/
public org.omg.PortableServer.Servant incarnate (byte[] oid, org.omg.PortableServer.POA adapter) throws org.omg.PortableServer.ForwardRequest
{
org.omg.CORBA.portable.ServantObject $so = _servant_preinvoke ("incarnate", _opsClass);
ServantActivatorOperations $self = (ServantActivatorOperations) $so.servant;
try {
return $self.incarnate (oid, adapter);
} finally {
_servant_postinvoke ($so);
}
} // incarnate
/**
* This operation is invoked whenever a servant for
* an object is deactivated, assuming the POA has
* the USE_SERVANT_MANAGER and RETAIN policies.
* @param oid object Id associated with the object
* being deactivated.
* @param adapter object reference for the POA in which
* the object was active.
* @param serv contains reference to the servant
* associated with the object being deactivated.
* @param cleanup_in_progress if TRUE indicates that
* destroy or deactivate is called with
* etherealize_objects param of TRUE. FALSE
* indicates that etherealize was called due to
* other reasons.
* @param remaining_activations indicates whether the
* Servant Manager can destroy a servant. If
* set to TRUE, the Servant Manager should wait
* until all invocations in progress have
* completed.
*/
public void etherealize (byte[] oid, org.omg.PortableServer.POA adapter, org.omg.PortableServer.Servant serv, boolean cleanup_in_progress, boolean remaining_activations)
{
org.omg.CORBA.portable.ServantObject $so = _servant_preinvoke ("etherealize", _opsClass);
ServantActivatorOperations $self = (ServantActivatorOperations) $so.servant;
try {
$self.etherealize (oid, adapter, serv, cleanup_in_progress, remaining_activations);
} finally {
_servant_postinvoke ($so);
}
} // etherealize
// Type-specific CORBA::Object operations
private static String[] __ids = {
"IDL:omg.org/PortableServer/ServantActivator:2.3",
"IDL:omg.org/PortableServer/ServantManager:1.0"};
public String[] _ids ()
{
return (String[])__ids.clone ();
}
private void readObject (java.io.ObjectInputStream s) throws java.io.IOException
{
String str = s.readUTF ();
String[] args = null;
java.util.Properties props = null;
org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props);
try {
org.omg.CORBA.Object obj = orb.string_to_object (str);
org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl) obj)._get_delegate ();
_set_delegate (delegate);
} finally {
orb.destroy() ;
}
}
private void writeObject (java.io.ObjectOutputStream s) throws java.io.IOException
{
String[] args = null;
java.util.Properties props = null;
org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props);
try {
String str = orb.object_to_string (this);
s.writeUTF (str);
} finally {
orb.destroy() ;
}
}
} // class _ServantActivatorStub
|
/*
* Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
*
* @summary converted from VM Testbase vm/mlvm/indy/stress/java/volatileCallSiteDekker.
* VM Testbase keywords: [feature_mlvm, nonconcurrent]
* VM Testbase readme:
* DESCRIPTION
* The test tries to detect a stale handle in VolatileCallSite due to store-after-load reordering in
* modern CPU.
* The current Oracle Hotspot JVM implementation uses an internal mutex when relinking a call site,
* which serves as memory barrier between store and load in this test, so I never saw it failing.
*
* @library /vmTestbase
* /test/lib
*
* @comment build actor
* @build vm.mlvm.indy.stress.java.volatileCallSiteDekker.Actor
*
* @run driver jdk.test.lib.FileInstaller . .
*
* @comment build test class and indify classes
* @build vm.mlvm.share.DekkerTest
* @run driver vm.mlvm.share.IndifiedClassesBuilder
*
* @run main/othervm
* vm.mlvm.share.DekkerTest
* -actorClass vm.mlvm.indy.stress.java.volatileCallSiteDekker.Actor
* -iterations 100000
* -runs 30
*/
|
package fr.syncrase.ecosyst.cucumber;
import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;
import org.junit.runner.RunWith;
@RunWith(Cucumber.class)
@CucumberOptions(plugin = "pretty", features = "src/test/features")
class CucumberIT {}
|
package mcjty.lostcities.dimensions.world;
import mcjty.lostcities.config.LandscapeType;
import mcjty.lostcities.dimensions.world.driver.IPrimerDriver;
import mcjty.lostcities.dimensions.world.terraingen.LostCitiesTerrainGenerator;
/**
* A heightmap for a chunk
*/
public class ChunkHeightmap {
private byte heightmap[] = new byte[16*16];
public ChunkHeightmap(IPrimerDriver driver, LandscapeType type, int groundLevel, char baseChar) {
char air = LostCitiesTerrainGenerator.airChar;
if (type == LandscapeType.CAVERN) {
// Here we try to find the height inside the cavern itself. Ignoring the top layer
int base = Math.max(groundLevel - 20, 1);
for (int x = 0; x < 16; x++) {
for (int z = 0; z < 16; z++) {
int y = base;
driver.current(x, y, z);
while (y < 100 && driver.getBlock() != air) {
y++;
driver.incY();
}
if (y >= 100) {
y = 128;
} else {
while (y > 0 && driver.getBlock() == air) {
y--;
driver.decY();
}
}
heightmap[z * 16 + x] = (byte) y;
}
}
} else if (type == LandscapeType.SPACE) {
// Here we ignore the glass from the spheres
for (int x = 0; x < 16; x++) {
for (int z = 0; z < 16; z++) {
int y = 255;
driver.current(x, y, z);
while (y > 0 && driver.getBlock() != baseChar) {
y--;
driver.decY();
}
heightmap[z * 16 + x] = (byte) y;
}
}
} else {
for (int x = 0; x < 16; x++) {
for (int z = 0; z < 16; z++) {
int y = 255;
driver.current(x, y, z);
while (y > 0 && driver.getBlock() == air) {
y--;
driver.decY();
}
heightmap[z * 16 + x] = (byte) y;
}
}
}
}
public int getHeight(int x, int z) {
return heightmap[z*16+x] & 0xff;
}
public int getAverageHeight() {
int cnt = 0;
int y = 0;
int yy;
yy = getHeight(2, 2);
if (yy > 5) {
y += yy;
cnt++;
}
yy = getHeight(13, 2);
if (yy > 5) {
y += yy;
cnt++;
}
yy = getHeight(2, 13);
if (yy > 5) {
y += yy;
cnt++;
}
yy = getHeight(13, 13);
if (yy > 5) {
y += yy;
cnt++;
}
yy = getHeight(8, 8);
if (yy > 5) {
y += yy;
cnt++;
}
if (cnt > 0) {
return y / cnt;
} else {
return 0;
}
}
public int getMinimumHeight() {
int y = 255;
int yy;
yy = getHeight(2, 2);
if (yy < y) {
y = yy;
}
yy = getHeight(13, 2);
if (yy < y) {
y = yy;
}
yy = getHeight(2, 13);
if (yy < y) {
y = yy;
}
yy = getHeight(13, 13);
if (yy < y) {
y = yy;
}
yy = getHeight(8, 8);
if (yy < y) {
y = yy;
}
return y;
}
}
|
/**
*
* @author Jarid Bredemeier
*
*/
public class PriorityQueue {
}
|
/*
* Copyright (c) 2020, Zoinkwiz
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.questhelper.panel;
import com.questhelper.Icon;
import com.questhelper.QuestHelperConfig;
import com.questhelper.QuestHelperPlugin;
import com.questhelper.QuestHelperQuest;
import com.questhelper.questhelpers.Quest;
import com.questhelper.questhelpers.QuestHelper;
import com.questhelper.steps.QuestStep;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ItemEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.plaf.basic.BasicButtonUI;
import lombok.extern.slf4j.Slf4j;
import net.runelite.api.Client;
import net.runelite.api.Item;
import net.runelite.api.QuestState;
import net.runelite.client.ui.ColorScheme;
import net.runelite.client.ui.DynamicGridLayout;
import net.runelite.client.ui.PluginPanel;
import net.runelite.client.ui.components.IconTextField;
import net.runelite.client.util.ImageUtil;
import net.runelite.client.util.LinkBrowser;
import net.runelite.client.util.SwingUtil;
import net.runelite.client.util.Text;
@Slf4j
public class QuestHelperPanel extends PluginPanel
{
private final QuestOverviewPanel questOverviewPanel;
private final FixedWidthPanel questOverviewWrapper = new FixedWidthPanel();
private JPanel allQuestsCompletedPanel = new JPanel();
private JPanel searchQuestsPanel;
private final JPanel allDropdownSections = new JPanel();
private final JComboBox<Enum> filterDropdown, difficultyDropdown, orderDropdown;
private final IconTextField searchBar = new IconTextField();
private final FixedWidthPanel questListPanel = new FixedWidthPanel();
private final FixedWidthPanel questListWrapper = new FixedWidthPanel();
private final JScrollPane scrollableContainer;
private final int DROPDOWN_HEIGHT = 20;
// private boolean settingsPanelActive = false;
private boolean questActive = false;
private final ArrayList<QuestSelectPanel> questSelectPanels = new ArrayList<>();
QuestHelperPlugin questHelperPlugin;
private static final ImageIcon DISCORD_ICON;
private static final ImageIcon GITHUB_ICON;
private static final ImageIcon PATREON_ICON;
private static final ImageIcon SETTINGS_ICON;
static
{
DISCORD_ICON = Icon.DISCORD.getIcon(img -> ImageUtil.resizeImage(img, 16, 16));
GITHUB_ICON = Icon.GITHUB.getIcon(img -> ImageUtil.resizeImage(img, 16, 16));
PATREON_ICON = Icon.PATREON.getIcon(img -> ImageUtil.resizeImage(img, 16, 16));
SETTINGS_ICON = Icon.SETTINGS.getIcon(img -> ImageUtil.resizeImage(img, 16, 16));
}
public QuestHelperPanel(QuestHelperPlugin questHelperPlugin)
{
super(false);
this.questHelperPlugin = questHelperPlugin;
setBackground(ColorScheme.DARK_GRAY_COLOR);
setLayout(new BorderLayout());
/* Setup overview panel */
JPanel titlePanel = new JPanel();
titlePanel.setBorder(new EmptyBorder(10, 10, 10, 10));
titlePanel.setLayout(new BorderLayout());
JLabel title = new JLabel();
title.setText("Quest Helper");
title.setForeground(Color.WHITE);
titlePanel.add(title, BorderLayout.WEST);
// Options
final JPanel viewControls = new JPanel(new GridLayout(1, 3, 10, 0));
viewControls.setBackground(ColorScheme.DARK_GRAY_COLOR);
// Settings
// TODO: Removed until the Runelite API allows for a link to the actual config panel
// JButton settingsBtn = new JButton();
// SwingUtil.removeButtonDecorations(settingsBtn);
// settingsBtn.setIcon(SETTINGS_ICON);
// settingsBtn.setToolTipText("Change your settings");
// settingsBtn.setBackground(ColorScheme.DARK_GRAY_COLOR);
// settingsBtn.setUI(new BasicButtonUI());
// settingsBtn.addActionListener((ev) -> {
// if (settingsPanelActive)
// {
// settingsBtn.setBackground(ColorScheme.LIGHT_GRAY_COLOR);
// deactivateSettings();
// }
// else
// {
// settingsBtn.setBackground(ColorScheme.DARK_GRAY_COLOR);
// activateSettings();
// }
// });
// settingsBtn.addMouseListener(new java.awt.event.MouseAdapter()
// {
// public void mouseEntered(java.awt.event.MouseEvent evt)
// {
// settingsBtn.setBackground(ColorScheme.DARK_GRAY_HOVER_COLOR);
// }
//
// public void mouseExited(java.awt.event.MouseEvent evt)
// {
// if (settingsPanelActive)
// {
// settingsBtn.setBackground(ColorScheme.LIGHT_GRAY_COLOR);
// }
// else
// {
// settingsBtn.setBackground(ColorScheme.DARK_GRAY_COLOR);
// }
// }
// });
// viewControls.add(settingsBtn);
// Discord button
JButton discordBtn = new JButton();
SwingUtil.removeButtonDecorations(discordBtn);
discordBtn.setIcon(DISCORD_ICON);
discordBtn.setToolTipText("Get help with the Quest Helper or make suggestions on Discord");
discordBtn.setBackground(ColorScheme.DARK_GRAY_COLOR);
discordBtn.setUI(new BasicButtonUI());
discordBtn.addActionListener((ev) -> LinkBrowser.browse("https://discord.gg/XCfwNnz6RB"));
discordBtn.addMouseListener(new java.awt.event.MouseAdapter()
{
public void mouseEntered(java.awt.event.MouseEvent evt)
{
discordBtn.setBackground(ColorScheme.DARK_GRAY_HOVER_COLOR);
}
public void mouseExited(java.awt.event.MouseEvent evt)
{
discordBtn.setBackground(ColorScheme.DARK_GRAY_COLOR);
}
});
viewControls.add(discordBtn);
// GitHub button
JButton githubBtn = new JButton();
SwingUtil.removeButtonDecorations(githubBtn);
githubBtn.setIcon(GITHUB_ICON);
githubBtn.setToolTipText("Report issues or contribute on GitHub");
githubBtn.setBackground(ColorScheme.DARK_GRAY_COLOR);
githubBtn.setUI(new BasicButtonUI());
githubBtn.addActionListener((ev) -> LinkBrowser.browse("https://github.com/Zoinkwiz/quest-helper"));
githubBtn.addMouseListener(new java.awt.event.MouseAdapter()
{
public void mouseEntered(java.awt.event.MouseEvent evt)
{
githubBtn.setBackground(ColorScheme.DARK_GRAY_HOVER_COLOR);
}
public void mouseExited(java.awt.event.MouseEvent evt)
{
githubBtn.setBackground(ColorScheme.DARK_GRAY_COLOR);
}
});
viewControls.add(githubBtn);
// Patreon button
JButton patreonBtn = new JButton();
SwingUtil.removeButtonDecorations(patreonBtn);
patreonBtn.setIcon(PATREON_ICON);
patreonBtn.setToolTipText("Support development on Patreon");
patreonBtn.setBackground(ColorScheme.DARK_GRAY_COLOR);
patreonBtn.setUI(new BasicButtonUI());
patreonBtn.addActionListener((ev) -> LinkBrowser.browse("https://www.patreon.com/zoinkwiz"));
patreonBtn.addMouseListener(new java.awt.event.MouseAdapter()
{
public void mouseEntered(java.awt.event.MouseEvent evt)
{
patreonBtn.setBackground(ColorScheme.DARK_GRAY_HOVER_COLOR);
}
public void mouseExited(java.awt.event.MouseEvent evt)
{
patreonBtn.setBackground(ColorScheme.DARK_GRAY_COLOR);
}
});
viewControls.add(patreonBtn);
titlePanel.add(viewControls, BorderLayout.EAST);
JLabel questsCompletedLabel = new JLabel();
questsCompletedLabel.setForeground(Color.GRAY);
questsCompletedLabel.setText("<html><body style='text-align:left'>Please log in to see available quests" +
".</body></html>");
allQuestsCompletedPanel.setLayout(new BorderLayout());
allQuestsCompletedPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
allQuestsCompletedPanel.add(questsCompletedLabel);
allQuestsCompletedPanel.setVisible(false);
/* Search bar */
searchBar.setIcon(IconTextField.Icon.SEARCH);
searchBar.setPreferredSize(new Dimension(PluginPanel.PANEL_WIDTH - 20, 30));
searchBar.setBackground(ColorScheme.DARKER_GRAY_COLOR);
searchBar.setHoverBackgroundColor(ColorScheme.DARK_GRAY_HOVER_COLOR);
searchBar.getDocument().addDocumentListener(new DocumentListener()
{
@Override
public void insertUpdate(DocumentEvent e)
{
onSearchBarChanged();
}
@Override
public void removeUpdate(DocumentEvent e)
{
onSearchBarChanged();
}
@Override
public void changedUpdate(DocumentEvent e)
{
onSearchBarChanged();
}
});
searchQuestsPanel = new JPanel();
searchQuestsPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
searchQuestsPanel.setLayout(new BorderLayout(0, BORDER_OFFSET));
searchQuestsPanel.add(searchBar, BorderLayout.CENTER);
searchQuestsPanel.add(allQuestsCompletedPanel, BorderLayout.SOUTH);
questListPanel.setBorder(new EmptyBorder(8, 10, 0, 10));
questListPanel.setLayout(new DynamicGridLayout(0, 1, 0, 5));
questListPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
showMatchingQuests("");
// Filters
filterDropdown = makeNewDropdown(QuestHelperConfig.QuestFilter.values(), "filterListBy");
JPanel filtersPanel = makeDropdownPanel(filterDropdown, "Filters");
filtersPanel.setPreferredSize(new Dimension(PANEL_WIDTH, DROPDOWN_HEIGHT));
difficultyDropdown = makeNewDropdown(Quest.Difficulty.values(), "questDifficulty");
JPanel difficultyPanel = makeDropdownPanel(difficultyDropdown, "Difficulty");
difficultyPanel.setPreferredSize(new Dimension(PANEL_WIDTH, DROPDOWN_HEIGHT));
orderDropdown = makeNewDropdown(QuestHelperConfig.QuestOrdering.values(), "orderListBy");
JPanel orderPanel = makeDropdownPanel(orderDropdown, "Ordering");
orderPanel.setPreferredSize(new Dimension(PANEL_WIDTH, DROPDOWN_HEIGHT));
allDropdownSections.setBorder(new EmptyBorder(0, 0, 10, 0));
allDropdownSections.setLayout(new BorderLayout(0, BORDER_OFFSET));
allDropdownSections.add(filtersPanel, BorderLayout.NORTH);
allDropdownSections.add(difficultyPanel, BorderLayout.CENTER);
allDropdownSections.add(orderPanel, BorderLayout.SOUTH);
searchQuestsPanel.add(allDropdownSections, BorderLayout.NORTH);
// Wrapper
questListWrapper.setLayout(new BorderLayout());
questListWrapper.add(questListPanel, BorderLayout.NORTH);
scrollableContainer = new JScrollPane(questListWrapper);
scrollableContainer.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
JPanel introDetailsPanel = new JPanel();
introDetailsPanel.setLayout(new BorderLayout());
introDetailsPanel.add(titlePanel, BorderLayout.NORTH);
introDetailsPanel.add(searchQuestsPanel, BorderLayout.CENTER);
add(introDetailsPanel, BorderLayout.NORTH);
add(scrollableContainer, BorderLayout.CENTER);
/* Layout */
questOverviewPanel = new QuestOverviewPanel(questHelperPlugin);
questOverviewWrapper.setLayout(new BorderLayout());
questOverviewWrapper.add(questOverviewPanel, BorderLayout.NORTH);
}
private void onSearchBarChanged()
{
final String text = searchBar.getText();
if ((questOverviewPanel.currentQuest == null || !text.isEmpty()))
{
scrollableContainer.setViewportView(questListWrapper);
questSelectPanels.forEach(questListPanel::remove);
showMatchingQuests(text);
}
else
{
scrollableContainer.setViewportView(questOverviewWrapper);
}
revalidate();
}
private JComboBox<Enum> makeNewDropdown(Enum[] values, String key)
{
JComboBox<Enum> dropdown = new JComboBox<>(values);
dropdown.setFocusable(false);
dropdown.setForeground(Color.WHITE);
dropdown.setRenderer(new DropdownRenderer());
dropdown.addItemListener(e ->
{
if (e.getStateChange() == ItemEvent.SELECTED)
{
Enum source = (Enum) e.getItem();
questHelperPlugin.getConfigManager().setConfiguration("questhelper", key,
source);
}
});
return dropdown;
}
private JPanel makeDropdownPanel(JComboBox dropdown, String name)
{
// Filters
JLabel filterName = new JLabel(name);
filterName.setForeground(Color.WHITE);
JPanel filtersPanel = new JPanel();
filtersPanel.setLayout(new BorderLayout());
filtersPanel.setMinimumSize(new Dimension(PANEL_WIDTH, 0));
filtersPanel.add(filterName, BorderLayout.CENTER);
filtersPanel.add(dropdown, BorderLayout.EAST);
return filtersPanel;
}
private void showMatchingQuests(String text)
{
if (text.isEmpty())
{
questSelectPanels.forEach(questListPanel::add);
return;
}
final String[] searchTerms = text.toLowerCase().split(" ");
questSelectPanels.forEach(listItem ->
{
if (Text.matchesSearchTerms(Arrays.asList(searchTerms), listItem.getKeywords()))
{
questListPanel.add(listItem);
}
});
}
public void refresh(List<QuestHelper> questHelpers, boolean loggedOut,
Map<QuestHelperQuest, QuestState> completedQuests, QuestHelperConfig.QuestFilter... questFilters)
{
questSelectPanels.forEach(questListPanel::remove);
questSelectPanels.clear();
filterDropdown.setSelectedItem(questHelperPlugin.getConfig().filterListBy());
difficultyDropdown.setSelectedItem(questHelperPlugin.getConfig().difficulty());
orderDropdown.setSelectedItem(questHelperPlugin.getConfig().orderListBy());
if (questFilters.length > 0)
{
for (QuestHelperConfig.QuestFilter questFilter : questFilters)
{
List<QuestHelper> filterList = questHelpers.stream()
.filter(questFilter)
.collect(Collectors.toList());
if (filterList.size() != 0)
{
questSelectPanels.add(new QuestSelectPanel(questFilter.getDisplayName()));
}
for (QuestHelper questHelper : filterList)
{
QuestState questState = completedQuests.getOrDefault(questHelper.getQuest(), QuestState.NOT_STARTED);
questSelectPanels.add(new QuestSelectPanel(questHelperPlugin, this, questHelper, questState));
}
}
}
else
{
for (QuestHelper questHelper : questHelpers)
{
QuestState questState = completedQuests.getOrDefault(questHelper.getQuest(), QuestState.NOT_STARTED);
questSelectPanels.add(new QuestSelectPanel(questHelperPlugin, this, questHelper, questState));
}
}
Set<QuestHelperQuest> quests = completedQuests.keySet();
boolean hasMoreQuests = quests.stream().anyMatch(q -> completedQuests.get(q) != QuestState.FINISHED);
if (questSelectPanels.isEmpty() && hasMoreQuests)
{
allQuestsCompletedPanel.removeAll();
JLabel noMatch = new JLabel();
noMatch.setForeground(Color.GRAY);
if (loggedOut)
{
noMatch.setText("<html><body style='text-align:left'>Log in to see available quests</body></html>");
}
else
{
noMatch.setText("<html><body style='text-align:left'>No quests are available that match your current filters</body></html>");
}
allQuestsCompletedPanel.add(noMatch);
}
allQuestsCompletedPanel.setVisible(questSelectPanels.isEmpty());
repaint();
revalidate();
showMatchingQuests(searchBar.getText() != null ? searchBar.getText() : "");
}
public void addQuest(QuestHelper quest, boolean isActive)
{
questActive = true;
allDropdownSections.setVisible(false);
scrollableContainer.setViewportView(questOverviewWrapper);
questOverviewPanel.addQuest(quest, isActive);
repaint();
revalidate();
}
public void updateSteps()
{
questOverviewPanel.updateSteps();
}
public void updateHighlight(Client client, QuestStep newStep)
{
questOverviewPanel.updateHighlight(client, newStep);
repaint();
revalidate();
}
public void updateLocks()
{
questOverviewPanel.updateLocks();
repaint();
revalidate();
}
public void removeQuest()
{
questActive = false;
allDropdownSections.setVisible(true);
scrollableContainer.setViewportView(questListWrapper);
questOverviewPanel.removeQuest();
repaint();
revalidate();
}
private void activateSettings()
{
// settingsPanelActive = true;
// scrollableContainer.setViewportView(configPanel);
searchQuestsPanel.setVisible(false);
repaint();
revalidate();
}
private void deactivateSettings()
{
// settingsPanelActive = false;
if (questActive && searchBar.getText().isEmpty())
{
scrollableContainer.setViewportView(questOverviewWrapper);
}
else
{
scrollableContainer.setViewportView(questListWrapper);
}
searchQuestsPanel.setVisible(true);
repaint();
revalidate();
}
public void emptyBar()
{
searchBar.setText("");
}
public void updateItemRequirements(Client client, List<Item> bankItems)
{
questOverviewPanel.updateRequirements(client, bankItems);
}
}
|
/**
* Jakarta Bean Validation TCK
*
* License: Apache License, Version 2.0
* See the license.txt file in the root directory or <http://www.apache.org/licenses/LICENSE-2.0>.
*/
package org.hibernate.beanvalidation.tck.tests.validation.groupconversion.containerelement;
import jakarta.validation.groups.Default;
/**
* @author Gunnar Morling
*/
public interface Complete extends Default, Complex {
}
|
/* Copyright 2002-2022 CS GROUP
* Licensed to CS GROUP (CS) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* This package provides initial orbit determination methods.
*
* <p>
* Initial orbit determination methods are used to compute
* an initial orbit from a small number of observations.
* The computed orbit can then be used, for instance, as a
* first guess to initialize an orbit determination engine.
* </p>
*/
package org.orekit.estimation.iod;
|
/*
* Copyright (c) 2008-2015, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.transaction.impl.xa;
import com.hazelcast.transaction.TransactionContext;
import com.hazelcast.transaction.impl.Transaction;
public final class TransactionAccessor {
private TransactionAccessor() {
}
public static Transaction getTransaction(TransactionContext ctx) {
if (ctx instanceof XATransactionContextImpl) {
XATransactionContextImpl ctxImp = (XATransactionContextImpl) ctx;
return ctxImp.getTransaction();
}
throw new IllegalArgumentException();
}
}
|
/*
* Copyright 2019 Wultra s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.getlime.security.powerauth.app.nextstep.converter;
import io.getlime.security.powerauth.app.nextstep.repository.model.entity.AuthenticationEntity;
import io.getlime.security.powerauth.lib.nextstep.model.entity.AuthenticationDetail;
/**
* Converter for authentications.
*
* @author Roman Strobl, roman.strobl@wultra.com
*/
public class AuthenticationConverter {
/**
* Convert authentication from entity to detail.
* @param authentication Authentication entity.
* @return Authentication detail.
*/
public AuthenticationDetail fromEntity(AuthenticationEntity authentication) {
final AuthenticationDetail authenticationDetail = new AuthenticationDetail();
authenticationDetail.setAuthenticationType(authentication.getAuthenticationType());
if (authentication.getCredential() != null) {
authenticationDetail.setCredentialName(authentication.getCredential().getCredentialDefinition().getName());
}
if (authentication.getOtp() != null) {
authenticationDetail.setOtpName(authentication.getOtp().getOtpDefinition().getName());
}
authenticationDetail.setAuthenticationResult(authentication.getResult());
authenticationDetail.setCredentialAuthenticationResult(authentication.getResultCredential());
authenticationDetail.setOtpAuthenticationResult(authentication.getResultOtp());
authenticationDetail.setTimestampCreated(authentication.getTimestampCreated());
return authenticationDetail;
}
}
|
copyright ibm corporation rights reserved program accompanying materials terms eclipse license accompanies distribution http eclipse org legal epl html contributors ibm corporation initial api implementation org eclipse jdt internal refactoring reorg org eclipse ltk core refactoring refactoring org eclipse jdt internal i java help context ids ijavahelpcontextids org eclipse jdt internal java plugin images javapluginimages org eclipse jdt internal refactoring refactoring messages refactoringmessages rename source folder wizard renamesourcefolderwizard rename refactoring wizard renamerefactoringwizard rename source folder wizard renamesourcefolderwizard refactoring refactoring refactoring refactoring messages refactoringmessages rename source folder renamesourcefolder default page title defaultpagetitle refactoring messages refactoringmessages rename source folder renamesourcefolder input page inputpage description java plugin images javapluginimages desc wizban ref actor refactor i java help context ids ijavahelpcontextids rename source folder wizard
|
/*
* Copyright © 2012 Karl J. Ots. All Rights Reserved.
*/
package org.kjots.lib.gwt.event.webMessage.client.dom;
import org.kjots.lib.gwt.js.util.client.JSON;
import org.kjots.lib.gwt.js.util.client.JsAny;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArray;
/**
* Window.
* <p>
* Created: 6th August 2012.
*
* @author <a href="mailto:kjots@kjots.org">Karl J. Ots <kjots@kjots.org></a>
* @since 1.1
*/
public class Window extends JavaScriptObject {
/** The logger for this class. */
private static final Logger logger = LoggerFactory.getLogger("org.kjots.lib.gwt.event.webMessage.client.dom.Window");
/**
* Retrieve the global window object.
*
* @return The global window object.
*/
public static native Window get() /*-{
return window;
}-*/;
/**
* Retrieve the GWT <code>$wnd</code> object.
*
* @return The GWT <code>$wnd</code> object.
*/
public static native Window getWnd() /*-{
return $wnd;
}-*/;
/**
* Log the posting of the given message.
*
* @param message The message.
* @param targetOrigin The target origin.
* @param transfer The transfer.
*/
static void logPostMessage(Window window, JsAny<?> message, String targetOrigin, JsArray<JavaScriptObject> transfer) {
if (logger.isDebugEnabled()) {
logger.debug("Posting message: window={}, message={}, targetOrigin={}, transfer={}", new Object[] {
window.getUrl(),
JSON.stringify(message),
targetOrigin,
transfer
});
}
}
/**
* Post the given message with the given target origin and transfer.
*
* @param message The message.
* @param targetOrigin The target origin.
* @param transfer The transfer.
*/
public final void postMessage(JsAny<?> message, String targetOrigin, JavaScriptObject... transfer) {
JsArray<JavaScriptObject> jsTransfer = JavaScriptObject.createArray().cast();
for (JavaScriptObject jso : transfer) {
jsTransfer.push(jso);
}
this.postMessage(message, targetOrigin, jsTransfer);
}
/**
* Post the given message with the given target origin and transfer.
*
* @param message The message.
* @param targetOrigin The target origin.
* @param transfer The transfer.
*/
public final native void postMessage(JsAny<?> message, String targetOrigin, JsArray<JavaScriptObject> transfer) /*-{
@org.kjots.lib.gwt.event.webMessage.client.dom.Window::logPostMessage(Lorg/kjots/lib/gwt/event/webMessage/client/dom/Window;Lorg/kjots/lib/gwt/js/util/client/JsAny;Ljava/lang/String;Lcom/google/gwt/core/client/JsArray;)(this, message, targetOrigin, transfer);
this.postMessage(message.value, targetOrigin, transfer);
}-*/;
/**
* Add the given message event listener.
*
* @param listener The message event listener.
*/
public final native void addMessageEventListener(MessageEventListener listener) /*-{
this.addEventListener("message", listener, false);
}-*/;
/**
* Remove the given message event listener.
*
* @param listener The message event listener.
*/
public final native void removeMessageEventListener(MessageEventListener listener) /*-{
this.removeEventListener("message", listener, false);
}-*/;
/**
* Retrieve the URL of the window object.
*
* @return The URL.
*/
public final native String getUrl() /*-{
return this.location.href;
}-*/;
/**
* Construct a new Window.
*/
protected Window() {
}
}
|
package io.josemyduarte.cliques.finder.social.github;
public class GithubRuntimeException extends RuntimeException {
public GithubRuntimeException(String message, Throwable cause) {
super(message, cause);
}
}
|
package mono.androidx.core.view.accessibility;
public class AccessibilityManagerCompat_AccessibilityStateChangeListenerImplementor
extends java.lang.Object
implements
mono.android.IGCUserPeer,
androidx.core.view.accessibility.AccessibilityManagerCompat.AccessibilityStateChangeListener
{
/** @hide */
public static final String __md_methods;
static {
__md_methods =
"n_onAccessibilityStateChanged:(Z)V:GetOnAccessibilityStateChanged_ZHandler:AndroidX.Core.View.Accessibility.AccessibilityManagerCompat/IAccessibilityStateChangeListenerInvoker, Xamarin.AndroidX.Core\n" +
"";
mono.android.Runtime.register ("AndroidX.Core.View.Accessibility.AccessibilityManagerCompat+IAccessibilityStateChangeListenerImplementor, Xamarin.AndroidX.Core", AccessibilityManagerCompat_AccessibilityStateChangeListenerImplementor.class, __md_methods);
}
public AccessibilityManagerCompat_AccessibilityStateChangeListenerImplementor ()
{
super ();
if (getClass () == AccessibilityManagerCompat_AccessibilityStateChangeListenerImplementor.class)
mono.android.TypeManager.Activate ("AndroidX.Core.View.Accessibility.AccessibilityManagerCompat+IAccessibilityStateChangeListenerImplementor, Xamarin.AndroidX.Core", "", this, new java.lang.Object[] { });
}
public void onAccessibilityStateChanged (boolean p0)
{
n_onAccessibilityStateChanged (p0);
}
private native void n_onAccessibilityStateChanged (boolean p0);
private java.util.ArrayList refList;
public void monodroidAddReference (java.lang.Object obj)
{
if (refList == null)
refList = new java.util.ArrayList ();
refList.add (obj);
}
public void monodroidClearReferences ()
{
if (refList != null)
refList.clear ();
}
}
|
package com.zpj.fragmentation.demo.demo_zhihu.ui.fragment.first;
import android.os.Bundle;
import androidx.annotation.Nullable;
import android.view.View;
import android.widget.Toast;
import com.zpj.fragmentation.demo.R;
import com.zpj.fragmentation.demo.demo_zhihu.base.BaseMainFragment;
import com.zpj.fragmentation.demo.demo_zhihu.ui.fragment.first.child.FirstHomeFragment;
/**
* Created by YoKeyword on 16/6/3.
*/
public class ZhihuFirstFragment extends BaseMainFragment {
public static ZhihuFirstFragment newInstance() {
Bundle args = new Bundle();
ZhihuFirstFragment fragment = new ZhihuFirstFragment();
fragment.setArguments(args);
return fragment;
}
@Override
protected int getLayoutId() {
return R.layout.zhihu_fragment_first;
}
@Override
protected void initView(View view, @Nullable Bundle savedInstanceState) {
}
@Override
public void onLazyInitView(@Nullable Bundle savedInstanceState) {
super.onLazyInitView(savedInstanceState);
if (findChildFragment(FirstHomeFragment.class) == null) {
loadRootFragment(R.id.fl_first_container, FirstHomeFragment.newInstance());
}
}
@Override
public void onSupportInvisible() {
super.onSupportInvisible();
for (int i = 0; i < 5; i++) {
final int index = i;
postOnSupportVisible(new Runnable() {
@Override
public void run() {
Toast.makeText(context, "ZhihuFirstFragment visible" + index, Toast.LENGTH_SHORT).show();
}
});
}
}
}
|
/*
* This file is part of SpongeAPI, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package net.legacyfabric.fabric.impl.command.lib.sponge.args;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import net.minecraft.text.LiteralText;
import net.minecraft.text.Text;
import net.legacyfabric.fabric.api.command.v2.lib.sponge.CommandMessageFormatting;
import net.legacyfabric.fabric.api.command.v2.lib.sponge.args.ArgumentParseException;
import net.legacyfabric.fabric.api.command.v2.lib.sponge.args.CommandArgs;
import net.legacyfabric.fabric.api.command.v2.lib.sponge.args.CommandContext;
import net.legacyfabric.fabric.api.command.v2.lib.sponge.args.CommandElement;
import net.legacyfabric.fabric.api.permission.v1.PermissibleCommandSource;
import net.legacyfabric.fabric.api.util.TriState;
public class ChoicesCommandElement extends CommandElement {
public static final int CUTOFF = 5;
private final Supplier<Collection<String>> keySupplier;
private final Function<String, ?> valueSupplier;
private final TriState choicesInUsage;
public ChoicesCommandElement(Text key, Supplier<Collection<String>> keySupplier, Function<String, ?> valueSupplier, TriState choicesInUsage) {
super(key);
this.keySupplier = keySupplier;
this.valueSupplier = valueSupplier;
this.choicesInUsage = choicesInUsage;
}
@Override
public Object parseValue(PermissibleCommandSource source, CommandArgs args) throws ArgumentParseException {
Object value = this.valueSupplier.apply(args.next());
if (value == null) {
throw args.createError(new LiteralText(String.format("Argument was not a valid choice. Valid choices: %s", this.keySupplier.get().toString())));
}
return value;
}
@Override
public List<String> complete(PermissibleCommandSource src, CommandArgs args, CommandContext context) {
final String prefix = args.nextIfPresent().orElse("");
return Collections.unmodifiableList(this.keySupplier.get().stream().filter((input) -> input.startsWith(prefix)).collect(Collectors.toList()));
}
@Override
public Text getUsage(PermissibleCommandSource commander) {
Collection<String> keys = this.keySupplier.get();
if (this.choicesInUsage == TriState.TRUE || (this.choicesInUsage == TriState.DEFAULT && keys.size() <= CUTOFF)) {
final Text build = new LiteralText("");
build.append(CommandMessageFormatting.LT_TEXT);
for (Iterator<String> it = keys.iterator(); it.hasNext(); ) {
build.append(new LiteralText(it.next()));
if (it.hasNext()) {
build.append(CommandMessageFormatting.PIPE_TEXT);
}
}
build.append(CommandMessageFormatting.GT_TEXT);
return new LiteralText(build.getString());
}
return super.getUsage(commander);
}
}
|
package net.xpece.android.app;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.util.SparseArray;
import android.view.ViewGroup;
/**
* https://github.com/ksoichiro/Android-ObservableScrollView/blob/master/library/src/main/java/com/github/ksoichiro/android/observablescrollview/CacheFragmentStatePagerAdapter.java
*
* @deprecated Don't use fragments in ViewPager. It's a pain.
*/
@Deprecated
public abstract class CacheFragmentStatePagerAdapter extends FragmentStatePagerAdapter {
private static final String STATE_SUPER_STATE = "superState";
private static final String STATE_PAGES = "pages";
private static final String STATE_PAGE_INDEX_PREFIX = "pageIndex:";
private static final String STATE_PAGE_KEY_PREFIX = "page:";
private FragmentManager mFm;
private SparseArray<Fragment> mPages;
private Fragment mCurrentFragment = null;
private OnPrimaryItemChangedListener mPrimaryItemListener = null;
public CacheFragmentStatePagerAdapter(FragmentManager fm) {
super(fm);
mPages = new SparseArray<Fragment>();
mFm = fm;
}
@Override
public Parcelable saveState() {
Parcelable p = super.saveState();
Bundle bundle = new Bundle();
bundle.putParcelable(STATE_SUPER_STATE, p);
bundle.putInt(STATE_PAGES, mPages.size());
if (0 < mPages.size()) {
for (int i = 0; i < mPages.size(); i++) {
int position = mPages.keyAt(i);
bundle.putInt(createCacheIndex(i), position);
Fragment f = mPages.get(position);
mFm.putFragment(bundle, createCacheKey(position), f);
}
}
return bundle;
}
@Override
public void restoreState(Parcelable state, ClassLoader loader) {
Bundle bundle = (Bundle) state;
int pages = bundle.getInt(STATE_PAGES);
if (0 < pages) {
for (int i = 0; i < pages; i++) {
int position = bundle.getInt(createCacheIndex(i));
Fragment f = mFm.getFragment(bundle, createCacheKey(position));
mPages.put(position, f);
}
}
Parcelable p = bundle.getParcelable(STATE_SUPER_STATE);
super.restoreState(p, loader);
}
/**
* Get a new Fragment instance.
* Each fragments are automatically cached in this method,
* so you don't have to do it by yourself.
* If you want to implement instantiation of Fragments,
* you should override {@link #createItem(int)} instead.
* <p/>
* {@inheritDoc}
*
* @param position position of the item in the adapter
* @return fragment instance
*/
@Override
public Fragment getItem(int position) {
Fragment f = createItem(position);
// We should cache fragments manually to access to them later
mPages.put(position, f);
return f;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
if (0 <= mPages.indexOfKey(position)) {
mPages.remove(position);
}
super.destroyItem(container, position, object);
}
/**
* Get the item at the specified position in the adapter.
*
* @param position position of the item in the adapter
* @return fragment instance
*/
public Fragment getItemAt(int position) {
return mPages.get(position);
}
/**
* Create a new Fragment instance.
* This is called inside {@link #getItem(int)}.
*
* @param position position of the item in the adapter
* @return fragment instance
*/
protected abstract Fragment createItem(int position);
/**
* Create an index string for caching Fragment pages.
*
* @param index index of the item in the adapter
* @return key string for caching Fragment pages
*/
protected String createCacheIndex(int index) {
return STATE_PAGE_INDEX_PREFIX + index;
}
/**
* Create a key string for caching Fragment pages.
*
* @param position position of the item in the adapter
* @return key string for caching Fragment pages
*/
protected String createCacheKey(int position) {
return STATE_PAGE_KEY_PREFIX + position;
}
@Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
super.setPrimaryItem(container, position, object);
if (mCurrentFragment != object) {
Fragment newFragment = (Fragment) object;
if (mPrimaryItemListener != null) {
mPrimaryItemListener.onPrimaryItemChanged(mCurrentFragment, newFragment);
}
mCurrentFragment = newFragment;
}
}
public void setOnPrimaryItemChangedListener(OnPrimaryItemChangedListener listener) {
mPrimaryItemListener = listener;
}
}
|
package com.toparchy.molecule.permission.data;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import com.toparchy.molecule.permission.model.entity.MemberEntity;
@ApplicationScoped
public class MemberEntityRepository {
@Inject
private EntityManager moleculeEm;
public MemberEntity findById(String id) {
return moleculeEm.find(MemberEntity.class, id);
}
}
|
package com.macro.mall.common.api;
/**
* Universal return object
* Created by macro on 2019/4/19.
*/
public class CommonResult<T> {
private long code;
private String message;
private T data;
protected CommonResult() {
}
protected CommonResult(long code, String message, T data) {
this.code = code;
this.message = message;
this.data = data;
}
/**
* Success Return result
*
* @param data Fetched data
*/
public static <T> CommonResult<T> success(T data) {
return new CommonResult<T>(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMessage(), data);
}
/**
* Success Return result
*
* @param data Fetched data
* @param message Information
*/
public static <T> CommonResult<T> success(T data, String message) {
return new CommonResult<T>(ResultCode.SUCCESS.getCode(), message, data);
}
/**
* Return result
* @param errorCode error code
*/
public static <T> CommonResult<T> failed(IErrorCode errorCode) {
return new CommonResult<T>(errorCode.getCode(), errorCode.getMessage(), null);
}
/**
* Return result on failure
* @param errorCode Error code
* @param message Error message
*/
public static <T> CommonResult<T> failed(IErrorCode errorCode,String message) {
return new CommonResult<T>(errorCode.getCode(), message, null);
}
/**
* Return result on failure
* @param message Prompt information
*/
public static <T> CommonResult<T> failed(String message) {
return new CommonResult<T>(ResultCode.FAILED.getCode(), message, null);
}
/**
* Return result
*/
public static <T> CommonResult<T> failed() {
return failed(ResultCode.FAILED);
}
/**
* parameter verification
*/
public static <T> CommonResult<T> validateFailed() {
return failed(ResultCode.VALIDATE_FAILED);
}
/**
* parameter verification
* @param message Information
*/
public static <T> CommonResult<T> validateFailed(String message) {
return new CommonResult<T>(ResultCode.VALIDATE_FAILED.getCode(), message, null);
}
/**
* Return result not logged in
*/
public static <T> CommonResult<T> unauthorized(T data) {
return new CommonResult<T>(ResultCode.UNAUTHORIZED.getCode(), ResultCode.UNAUTHORIZED.getMessage(), data);
}
/**
* Unauthorized Return result
*/
public static <T> CommonResult<T> forbidden(T data) {
return new CommonResult<T>(ResultCode.FORBIDDEN.getCode(), ResultCode.FORBIDDEN.getMessage(), data);
}
public long getCode() {
return code;
}
public void setCode(long code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
|
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.perforce.test;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DaemonExecutor;
import org.apache.commons.exec.DefaultExecuteResultHandler;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteException;
import org.apache.commons.exec.ExecuteResultHandler;
import org.apache.commons.exec.ProcessDestroyer;
import org.apache.commons.exec.PumpStreamHandler;
import org.apache.commons.exec.ShutdownHookProcessDestroyer;
import javax.annotation.Nonnull;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Arrays;
import java.util.HashMap;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicLong;
public class TestServer {
public static final String DEFAULT_P4_PORT = "11666";
private static final Charset P4D_ENCODING = Charset.forName("UTF-8");
private static final String CASE_INSENSITIVE_ARG = "-C0";
private static final String CASE_SENSITIVE_ARG = "-C1";
private static AtomicLong serverCount = new AtomicLong(Math.round(Math.random() * 1000));
private final File outDir;
private final ProcessDestroyer processDestroyer = new ShutdownHookProcessDestroyer();
private String version = "r17.1";
private String user = "luser";
private final String port;
private int monitor = 3;
private boolean proxy;
private boolean unicode = false;
private boolean caseSensitive = false;
@Nonnull
private ExecuteStatus status = ExecuteStatus.createDummy();
public TestServer() {
this(DEFAULT_P4_PORT);
}
public TestServer(@Nonnull String port) {
this(new File("p4d.d-" + serverCount.incrementAndGet()), port);
}
public TestServer(@Nonnull File outDir) {
this(outDir, DEFAULT_P4_PORT);
}
public TestServer(@Nonnull File outDir, @Nonnull String port) {
this.port = port;
this.outDir = outDir;
System.out.println("Using test server directory " + outDir);
}
protected void finalize() throws Throwable {
delete();
super.finalize();
}
public File getRootDir() {
return outDir;
}
public String getPathToRoot() {
return outDir.getAbsolutePath();
}
public void setP4dVersion(String version) {
ensureNotRunning();
this.version = version;
}
public void setUnicode(boolean unicode) {
ensureNotRunning();
this.unicode = unicode;
}
@SuppressWarnings("WeakerAccess")
public void setCaseSensitive(boolean set) {
this.caseSensitive = set;
}
public ExecutableSpecification getServerExecutableSpecification() {
return codeline -> {
if ("main".equals(codeline)) {
setP4dVersion("r17.1");
} else if (codeline.startsWith("p")) {
setP4dVersion("r" + codeline.substring(1));
} else {
setP4dVersion(codeline);
}
};
}
public synchronized void initialize() throws IOException {
initialize(null, null, null);
}
public synchronized void initialize(ClassLoader cl, String initialDepotResource, String checkpointResource)
throws IOException {
ensureNotRunning();
delete();
File p4d = P4ExtFileUtils.extractP4d(outDir, version);
if (initialDepotResource == null) {
// Perform an initial startup of the server to initialize the database
// This will create a checkpoint, and the empty file system will force
// the creation of the initial depot files.
execNoError("-jc");
} else {
P4ExtFileUtils.extractResource(cl, initialDepotResource, p4d.getParentFile(), true);
}
if (unicode) {
execNoError("-xi");
}
if (checkpointResource != null) {
File outfile = new File(p4d.getParentFile(), "checkpoint.gz");
P4ExtFileUtils.extractResource(cl, checkpointResource, outfile, false);
execNoError("-z", "-jr", outfile.getAbsolutePath());
}
if (initialDepotResource != null && checkpointResource != null) {
// upgrade the server files.
execNoError("-xu");
}
}
public boolean isAlive() {
return status.isRunning();
}
@Nonnull
public String getLocalUrl() {
return "p4java://localhost:" + port;
}
@Nonnull
public String getRSHURL()
throws IOException {
File p4d = P4ExtFileUtils.extractP4d(outDir, version);
StringBuilder ret = new StringBuilder("p4jrsh://");
ret
.append(p4d.getAbsolutePath())
.append(" -r ")
.append(getPathToRoot())
.append(' ');
if (caseSensitive) {
ret.append(CASE_SENSITIVE_ARG);
} else {
ret.append(CASE_INSENSITIVE_ARG);
}
ret.append(" -L log -i --java");
return ret.toString();
}
public void rotateJournal() throws Exception {
exec(new String[]{"-jj"}, true, null);
}
protected void exec(String[] args, boolean block, HashMap<String, String> environment) throws Exception {
File p4d = P4ExtFileUtils.extractP4d(outDir, version);
CommandLine cmdLine = new CommandLine(p4d);
cmdLine.addArgument("-C0");
cmdLine.addArgument("-r");
cmdLine.addArgument(outDir.getAbsolutePath());
for (String arg : args) {
cmdLine.addArgument(arg);
}
DefaultExecutor executor = new DefaultExecutor();
if (block) {
executor.execute(cmdLine, environment);
} else {
DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
executor.execute(cmdLine, environment, resultHandler);
}
}
/**
* Start the server in the background. This should only be used by tests that
* need to test explicit socket connections. Most tests should use the
* RSH connection.
*
* @throws IOException on error
*/
public synchronized void startAsync()
throws IOException {
if (!outDir.exists() && !outDir.mkdirs()) {
throw new IOException("could not create output dir " + outDir);
}
final File p4d = P4ExtFileUtils.extractP4d(outDir, version);
try {
status.with(() -> {
ensureNotRunning();
CommandLine cmdLine = createBaseCmdLine(p4d);
cmdLine
// disable journal
.addArgument("-J")
.addArgument("off")
// set logging level
.addArgument("-v")
.addArgument("subsystem=" + monitor);
DaemonExecutor executor = new DaemonExecutor();
final ExecuteStatus newStatus = new ExecuteStatus();
executor.setProcessDestroyer(new ProcessDestroyer() {
@Override
public boolean add(Process process) {
newStatus.setProcess(process);
return processDestroyer.add(process);
}
@Override
public boolean remove(Process process) {
newStatus.setProcess(null);
return processDestroyer.remove(process);
}
@Override
public int size() {
return processDestroyer.size();
}
});
// default - log is pumped to stderr.
PumpStreamHandler streamHandler = new PumpStreamHandler(status.out, status.log);
executor.setStreamHandler(streamHandler);
executor.execute(cmdLine, newStatus);
System.err.println("Starting new p4d process: " + cmdLine);
status = newStatus;
return null;
});
waitForStartup();
} catch (IOException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private void waitForStartup()
throws InterruptedException {
// TODO need to correctly wait for the server to start. This is a terrible way.
// But then, we should really be using the rsh connection method, not the
// async method.
Thread.sleep(1000L);
}
// Stop the server and delete the directory.
public void delete()
throws IOException {
delete(true);
}
public void delete(boolean failIfCantDelete)
throws IOException {
stopServer();
if (outDir.exists()) {
Files.walkFileTree(outDir.toPath(), new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
final File basicFile = file.toFile();
boolean removed = basicFile.delete();
// int attemptCount = 4;
int attemptCount = 10; // 10 seconds. Still a very, very long wait, but much shorter than before.
while (basicFile.exists() && --attemptCount >= 0) {
if (! file.toFile().canWrite()) {
boolean setState = basicFile.setWritable(true);
if (!setState) {
System.err.println("Temporary test file is read-only and could not make it writable: " +
file.toAbsolutePath());
if (failIfCantDelete) {
throw new IOException("could not make file writable: " + file.toAbsolutePath());
}
return FileVisitResult.CONTINUE;
}
} else {
System.err.println("Failed to remove " + file.toAbsolutePath() + "; trying again");
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
throw new IOException("interrupted by another thread", e);
}
}
removed = basicFile.delete();
}
if (!removed && failIfCantDelete) {
throw new IOException("could not delete " + file.toAbsolutePath());
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc)
throws IOException {
if (!dir.toFile().delete()) {
if (failIfCantDelete) {
throw new IOException("Could not delete " + dir.toAbsolutePath());
}
System.err.println("Failed to delete test directory " + dir.toAbsolutePath());
}
return FileVisitResult.CONTINUE;
}
});
if (outDir.exists() && !outDir.delete() && failIfCantDelete) {
throw new IOException("Could not delete " + outDir);
}
}
}
public String getUser() {
return user;
}
public String getPort() {
return port;
}
/*
public void setPort(String port) {
ensureNotRunning();
this.port = port;
}
public String getProxyPort() {
return port;
}
*/
public void setMonitor(int monitor) {
ensureNotRunning();
this.monitor = monitor;
}
@SuppressWarnings("ResultOfMethodCallIgnored")
public void importRecord(String journalRecord)
throws IOException {
// Really, should use "p4 pull" or "p4 replicate"
File tmp = File.createTempFile("journal", ".jnl");
try {
try (FileWriter out = new FileWriter(tmp)) {
out.write(journalRecord + "\n");
out.flush();
}
execNoError("-jr", tmp.getAbsolutePath());
} finally {
tmp.delete();
}
}
public String getLog() {
return new String(status.log.toByteArray(), P4D_ENCODING);
}
@SuppressWarnings("WeakerAccess")
public InputStream getLogAsInputStream() {
return new ByteArrayInputStream(status.log.toByteArray());
}
public Reader getLogAsReader() {
try {
status.log.flush();
} catch (IOException e) {
// ignore
}
return new InputStreamReader(getLogAsInputStream(), P4D_ENCODING);
}
public void setProxy(boolean proxy) {
this.proxy = proxy;
}
public synchronized void stopServer() {
try {
System.err.println("Stopping server");
status.with(() -> {
if (status.isRunning()) {
System.err.println("Stopping server for realsies.");
if (status.process != null) {
status.process.destroy();
}
status.waitFor(1000000L);
status = ExecuteStatus.createDummy();
}
return null;
});
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@SuppressWarnings("WeakerAccess")
public void execNoError(String... args) throws IOException {
int res = exec(args);
if (res != 0) {
throw new IOException("Execution of p4d " +
Arrays.asList(args) +
" caused result code " + res);
}
}
/**
* Call and wait execution of the p4d server.
*
* @param args p4d arguments
* @return status code
* @throws IOException on error
*/
public int exec(String... args)
throws IOException {
try {
return status.with(() -> {
ensureNotRunning();
return innerExec(args);
});
} catch (IOException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private synchronized void ensureNotRunning() {
if (status.isRunning()) {
throw new IllegalStateException("Server is actively running; cannot run another command.");
}
}
private int innerExec(String... args)
throws IOException {
File p4d = P4ExtFileUtils.extractP4d(outDir, version);
CommandLine cmdLine = createBaseCmdLine(p4d);
for (String arg : args) {
cmdLine.addArgument(arg);
}
DefaultExecutor executor = new DefaultExecutor();
// default - log is pumped to stderr.
PumpStreamHandler streamHandler = new PumpStreamHandler(status.out, status.log);
executor.setStreamHandler(streamHandler);
executor.setProcessDestroyer(processDestroyer);
return executor.execute(cmdLine);
}
@Nonnull
private CommandLine createBaseCmdLine(@Nonnull File p4d) {
CommandLine cmdLine = new CommandLine(p4d);
cmdLine
.addArgument("-r")
.addArgument(getPathToRoot())
.addArgument("-p")
.addArgument(port);
if (caseSensitive) {
cmdLine.addArgument(CASE_SENSITIVE_ARG);
} else {
cmdLine.addArgument(CASE_INSENSITIVE_ARG);
}
return cmdLine;
}
public boolean hasProcessError() {
return status.hasProcessError();
}
public Throwable getProcessError() {
return status.getProcessError();
}
private static class ExecuteStatus implements ExecuteResultHandler {
private final Object sync = new Object();
private boolean running = true;
private int exitCode = 0;
private ExecuteException error;
private Process process;
public ByteArrayOutputStream out = new ByteArrayOutputStream();
public ByteArrayOutputStream log = new ByteArrayOutputStream();
static ExecuteStatus create() {
return new ExecuteStatus();
}
static ExecuteStatus createDummy() {
ExecuteStatus ret = new ExecuteStatus();
ret.running = false;
return ret;
}
void setProcess(Process process) {
synchronized (sync) {
this.process = process;
}
}
public <T> T with(Callable<T> c)
throws Exception {
synchronized (sync) {
return c.call();
}
}
public boolean isRunning() {
synchronized (sync) {
return running;
}
}
@Override
public void onProcessComplete(int exitValue) {
synchronized (sync) {
running = false;
exitCode = exitValue;
sync.notifyAll();
}
}
@Override
public void onProcessFailed(ExecuteException e) {
synchronized (sync) {
running = false;
error = e;
sync.notifyAll();
}
}
void waitFor(long timeoutMs)
throws InterruptedException {
long end = System.currentTimeMillis() + timeoutMs;
synchronized (sync) {
while (running && System.currentTimeMillis() < end) {
sync.wait(timeoutMs);
}
if (running) {
throw new IllegalStateException("Could not stop server after " + timeoutMs + "ms");
}
}
}
boolean hasProcessError() {
return error != null;
}
ExecuteException getProcessError() {
return error;
}
}
}
|
/*
* Copyright 2009-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ibatis.executor;
import static org.apache.ibatis.executor.ExecutionPlaceholder.EXECUTION_PLACEHOLDER;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.cache.impl.PerpetualCache;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;
import org.apache.ibatis.logging.jdbc.ConnectionLogger;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.ParameterMode;
import org.apache.ibatis.mapping.StatementType;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.factory.ObjectFactory;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.LocalCacheScope;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.transaction.Transaction;
import org.apache.ibatis.type.TypeHandlerRegistry;
/**
* @author Clinton Begin
*/
/**
* 执行器基类
*/
public abstract class BaseExecutor implements Executor
{
private static final Log log = LogFactory.getLog(BaseExecutor.class);
protected Transaction transaction;
protected Executor wrapper;
//延迟加载队列(线程安全)
protected ConcurrentLinkedQueue<DeferredLoad> deferredLoads;
//本地缓存机制(Local Cache)防止循环引用(circular references)和加速重复嵌套查询(一级缓存)
//本地缓存
protected PerpetualCache localCache;
//本地输出参数缓存
protected PerpetualCache localOutputParameterCache;
protected Configuration configuration;
//查询堆栈
protected int queryStack = 0;
private boolean closed;
protected BaseExecutor(Configuration configuration, Transaction transaction)
{
this.transaction = transaction;
this.deferredLoads = new ConcurrentLinkedQueue<DeferredLoad>();
this.localCache = new PerpetualCache("LocalCache");
this.localOutputParameterCache = new PerpetualCache("LocalOutputParameterCache");
this.closed = false;
this.configuration = configuration;
this.wrapper = this;
}
@Override
public Transaction getTransaction()
{
if (closed)
{
throw new ExecutorException("Executor was closed.");
}
return transaction;
}
@Override
public void close(boolean forceRollback)
{
try
{
try
{
rollback(forceRollback);
} finally
{
if (transaction != null)
{
transaction.close();
}
}
} catch (SQLException e)
{
// Ignore. There's nothing that can be done at this point.
log.warn("Unexpected exception on closing transaction. Cause: " + e);
} finally
{
transaction = null;
deferredLoads = null;
localCache = null;
localOutputParameterCache = null;
closed = true;
}
}
@Override
public boolean isClosed()
{
return closed;
}
//SqlSession.update/insert/delete会调用此方法
@Override
public int update(MappedStatement ms, Object parameter) throws SQLException
{
ErrorContext.instance().resource(ms.getResource()).activity("executing an update").object(ms.getId());
if (closed)
{
throw new ExecutorException("Executor was closed.");
}
//先清局部缓存,再更新,如何更新交由子类,模板方法模式
clearLocalCache();
return doUpdate(ms, parameter);
}
@Override
public List<BatchResult> flushStatements() throws SQLException
{
return flushStatements(false);
}
//刷新语句,Batch用
public List<BatchResult> flushStatements(boolean isRollBack) throws SQLException
{
if (closed)
{
throw new ExecutorException("Executor was closed.");
}
return doFlushStatements(isRollBack);
}
//SqlSession.selectList会调用此方法
@Override
public <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException
{
//得到绑定sql
BoundSql boundSql = ms.getBoundSql(parameter);
//创建缓存Key
CacheKey key = createCacheKey(ms, parameter, rowBounds, boundSql);
//查询
return query(ms, parameter, rowBounds, resultHandler, key, boundSql);
}
@SuppressWarnings("unchecked")
@Override
public <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException
{
ErrorContext.instance().resource(ms.getResource()).activity("executing a query").object(ms.getId());
//如果已经关闭,报错
if (closed)
{
throw new ExecutorException("Executor was closed.");
}
//先清局部缓存,再查询.但仅查询堆栈为0,才清。为了处理递归调用
if (queryStack == 0 && ms.isFlushCacheRequired())
{
clearLocalCache();
}
List<E> list;
try
{
//加一,这样递归调用到上面的时候就不会再清局部缓存了
queryStack++;
//先根据cachekey从localCache去查
list = resultHandler == null ? (List<E>) localCache.getObject(key) : null;
if (list != null)
{
//若查到localCache缓存,处理localOutputParameterCache
handleLocallyCachedOutputParameters(ms, key, parameter, boundSql);
} else
{
//从数据库查
list = queryFromDatabase(ms, parameter, rowBounds, resultHandler, key, boundSql);
}
} finally
{
//清空堆栈
queryStack--;
}
if (queryStack == 0)
{
//延迟加载队列中所有元素
for (DeferredLoad deferredLoad : deferredLoads)
{
deferredLoad.load();
}
// issue #601
//清空延迟加载队列
deferredLoads.clear();
if (configuration.getLocalCacheScope() == LocalCacheScope.STATEMENT)
{
// issue #482
//如果是STATEMENT,清本地缓存
clearLocalCache();
}
}
return list;
}
//延迟加载,DefaultResultSetHandler.getNestedQueryMappingValue调用.属于嵌套查询,比较高级.
@Override
public void deferLoad(MappedStatement ms, MetaObject resultObject, String property, CacheKey key, Class<?> targetType)
{
if (closed)
{
throw new ExecutorException("Executor was closed.");
}
DeferredLoad deferredLoad = new DeferredLoad(resultObject, property, key, localCache, configuration, targetType);
//如果能加载,则立刻加载,否则加入到延迟加载队列中
if (deferredLoad.canLoad())
{
deferredLoad.load();
} else
{
//这里怎么又new了一个新的,性能有点问题
deferredLoads.add(new DeferredLoad(resultObject, property, key, localCache, configuration, targetType));
}
}
//创建缓存Key
@Override
public CacheKey createCacheKey(MappedStatement ms, Object parameterObject, RowBounds rowBounds, BoundSql boundSql)
{
if (closed)
{
throw new ExecutorException("Executor was closed.");
}
CacheKey cacheKey = new CacheKey();
//MyBatis 对于其 Key 的生成采取规则为:[mappedStementId + offset + limit + SQL + queryParams + environment]生成一个哈希码
cacheKey.update(ms.getId());
cacheKey.update(Integer.valueOf(rowBounds.getOffset()));
cacheKey.update(Integer.valueOf(rowBounds.getLimit()));
cacheKey.update(boundSql.getSql());
List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
TypeHandlerRegistry typeHandlerRegistry = ms.getConfiguration().getTypeHandlerRegistry();
// mimic DefaultParameterHandler logic
//模仿DefaultParameterHandler的逻辑,不再重复,请参考DefaultParameterHandler
for (int i = 0; i < parameterMappings.size(); i++)
{
ParameterMapping parameterMapping = parameterMappings.get(i);
if (parameterMapping.getMode() != ParameterMode.OUT)
{
Object value;
String propertyName = parameterMapping.getProperty();
if (boundSql.hasAdditionalParameter(propertyName))
{
value = boundSql.getAdditionalParameter(propertyName);
} else if (parameterObject == null)
{
value = null;
} else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass()))
{
value = parameterObject;
} else
{
MetaObject metaObject = configuration.newMetaObject(parameterObject);
value = metaObject.getValue(propertyName);
}
cacheKey.update(value);
}
}
if (configuration.getEnvironment() != null)
{
// issue #176
cacheKey.update(configuration.getEnvironment().getId());
}
return cacheKey;
}
@Override
public boolean isCached(MappedStatement ms, CacheKey key)
{
return localCache.getObject(key) != null;
}
@Override
public void commit(boolean required) throws SQLException
{
if (closed)
{
throw new ExecutorException("Cannot commit, transaction is already closed");
}
clearLocalCache();
flushStatements();
if (required)
{
transaction.commit();
}
}
@Override
public void rollback(boolean required) throws SQLException
{
if (!closed)
{
try
{
clearLocalCache();
flushStatements(true);
} finally
{
if (required)
{
transaction.rollback();
}
}
}
}
@Override
public void clearLocalCache()
{
if (!closed)
{
localCache.clear();
localOutputParameterCache.clear();
}
}
protected abstract int doUpdate(MappedStatement ms, Object parameter)
throws SQLException;
protected abstract List<BatchResult> doFlushStatements(boolean isRollback)
throws SQLException;
//query-->queryFromDatabase-->doQuery
protected abstract <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql)
throws SQLException;
protected void closeStatement(Statement statement)
{
if (statement != null)
{
try
{
statement.close();
} catch (SQLException e)
{
// ignore
}
}
}
private void handleLocallyCachedOutputParameters(MappedStatement ms, CacheKey key, Object parameter, BoundSql boundSql)
{
//处理存储过程的OUT参数
if (ms.getStatementType() == StatementType.CALLABLE)
{
final Object cachedParameter = localOutputParameterCache.getObject(key);
if (cachedParameter != null && parameter != null)
{
final MetaObject metaCachedParameter = configuration.newMetaObject(cachedParameter);
final MetaObject metaParameter = configuration.newMetaObject(parameter);
for (ParameterMapping parameterMapping : boundSql.getParameterMappings())
{
if (parameterMapping.getMode() != ParameterMode.IN)
{
final String parameterName = parameterMapping.getProperty();
final Object cachedValue = metaCachedParameter.getValue(parameterName);
metaParameter.setValue(parameterName, cachedValue);
}
}
}
}
}
//从数据库查
private <E> List<E> queryFromDatabase(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException
{
List<E> list;
//先向缓存中放入占位符???
localCache.putObject(key, EXECUTION_PLACEHOLDER);
try
{
list = doQuery(ms, parameter, rowBounds, resultHandler, boundSql);
} finally
{
//最后删除占位符
localCache.removeObject(key);
}
//加入缓存
localCache.putObject(key, list);
//如果是存储过程,OUT参数也加入缓存
if (ms.getStatementType() == StatementType.CALLABLE)
{
localOutputParameterCache.putObject(key, parameter);
}
return list;
}
protected Connection getConnection(Log statementLog) throws SQLException
{
Connection connection = transaction.getConnection();
if (statementLog.isDebugEnabled())
{
//如果需要打印Connection的日志,返回一个ConnectionLogger(代理模式, AOP思想)
return ConnectionLogger.newInstance(connection, statementLog, queryStack);
} else
{
return connection;
}
}
@Override
public void setExecutorWrapper(Executor wrapper)
{
this.wrapper = wrapper;
}
//延迟加载
private static class DeferredLoad
{
private final MetaObject resultObject;
private final String property;
private final Class<?> targetType;
private final CacheKey key;
private final PerpetualCache localCache;
private final ObjectFactory objectFactory;
private final ResultExtractor resultExtractor;
// issue #781
public DeferredLoad(MetaObject resultObject,
String property,
CacheKey key,
PerpetualCache localCache,
Configuration configuration,
Class<?> targetType)
{
this.resultObject = resultObject;
this.property = property;
this.key = key;
this.localCache = localCache;
this.objectFactory = configuration.getObjectFactory();
this.resultExtractor = new ResultExtractor(configuration, objectFactory);
this.targetType = targetType;
}
public boolean canLoad()
{
//缓存中找到,且不为占位符,代表可以加载
return localCache.getObject(key) != null && localCache.getObject(key) != EXECUTION_PLACEHOLDER;
}
//加载
public void load()
{
@SuppressWarnings("unchecked")
// we suppose we get back a List
List<Object> list = (List<Object>) localCache.getObject(key);
//调用ResultExtractor.extractObjectFromList
Object value = resultExtractor.extractObjectFromList(list, targetType);
resultObject.setValue(property, value);
}
}
}
|
/**
* This file is part of Magma, licensed under the MIT License (MIT).
*
* Copyright (c) 2013-2014 ObsidianBox <http://obsidianbox.org/>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.obsidianbox.magma.block;
import java.util.List;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.block.BlockFence;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.client.resources.I18n;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IIcon;
import org.obsidianbox.magma.addon.Addon;
import org.obsidianbox.magma.lang.Languages;
public class SimpleFence extends BlockFence {
private final Addon addon;
private final String identifier;
private IIcon bottomIcon, sideIcon, topIcon;
public SimpleFence(Addon addon, String identifier, String displayName, Material material, boolean showInCreativeTab) {
super("", material);
this.addon = addon;
this.identifier = identifier;
setBlockName(addon.getDescription().getIdentifier() + ".tile.block." + identifier);
setBlockTextureName(addon.getDescription().getIdentifier() + ":fences/" + identifier);
addon.getGame().getLanguages().put(addon, Languages.ENGLISH_AMERICAN, "tile.block." + identifier + ".name", displayName);
if (showInCreativeTab) {
setCreativeTab(addon.getGame().getTabs());
}
GameRegistry.registerBlock(this, addon.getDescription().getIdentifier() + "_" + identifier);
}
@Override
@SuppressWarnings({"unchecked", "rawtypes"})
public void getSubBlocks(Item item, CreativeTabs tab, List list) {
list.add(new ItemStack(item, 1, 0));
}
@Override
public IIcon getIcon(int side, int type) {
switch (side) {
case 0:
return bottomIcon;
case 1:
return topIcon;
default:
return sideIcon;
}
}
@SideOnly(Side.CLIENT)
@Override
public void registerBlockIcons(IIconRegister icon) {
bottomIcon = icon.registerIcon(getTextureName() + "_bottom");
sideIcon = icon.registerIcon(getTextureName() + "_side");
topIcon = icon.registerIcon(getTextureName() + "_top");
}
public final Addon getAddon() {
return addon;
}
public final String getIdentifier() {
return identifier;
}
@Override
public final String getLocalizedName() {
return I18n.format(getUnlocalizedName() + ".name");
}
@Override
public final String getUnlocalizedName() {
return addon.getDescription().getIdentifier() + ".tile.block." + identifier;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof SimpleFence)) {
return false;
}
final SimpleFence that = (SimpleFence) o;
return addon.equals(that.addon) && identifier.equals(that.identifier);
}
@Override
public int hashCode() {
int result = addon.hashCode();
result = 31 * result + identifier.hashCode();
return result;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.